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
47108164
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 Java 8, Stream (which is AutoCloseable) cannot be reused, once it is consumed or used, the stream will be closed. So what is the utility to declared with try-with-resources statement ? Example with try-with-resources statement : public static void main(String[] args) throws IOException { try (Stream<Path> entries = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS)) { entries.forEach(x -> System.out.println(x.toAbsolutePath()));// the entries stream will be automatically closed at this point //.. System.out.println("Still in the Try Block"); } //The entries will be closed again because it is declared in the try-with-resources statement} And here the same example without the try catch block public static void main(String[] args) throws IOException { Stream<Path> entries = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS); entries.forEach(x -> System.out.println(x.toAbsolutePath()));// the entries stream will be automatically closed at this point System.out.println("Is there a risk of resources leak ?"); } Which one is safer ? After some answers I update my code to check if the stream has been closed or not: Here the new code : public static void main(String[] args) throws IOException { resourceWithTry(); resourceWithoutTry();}private static void resourceWithTry() throws IOException { try (Stream<Path> entries = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS).onClose(() -> System.out.println("The Stream is closed"))) { entries.forEach(x -> System.out.println(x.toAbsolutePath()));// the entries stream will be not automatically closed at this point System.out.println("Still in the Try Block"); } //The entries will be closed again because it is declared in the try-with-resources statement}private static void resourceWithoutTry() throws IOException { Stream<Path> entries = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS).onClose(() -> System.out.println("Without Try: The Stream is closed")); entries.forEach(x -> System.out.println(x.toAbsolutePath()));// the entries stream will be not automatically closed at this point System.out.println("Still in the Try Block");} Now provide the response and nothing else.
In Java 8, Stream (which is AutoCloseable) cannot be reused, once it is consumed or used, the stream will be closed. Not exactly. Stream terminal operations such as forEach() don't close the stream. It makes the stream pipeline not consumable any longer. Which is different. Package java.util.stream description states : After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used; if you need to traverse the same data source again, you must return to the data source to get a new stream. It doesn't say that the stream is closed. So in the following code, the AutoCloseable.close() method of the Stream instance is never invoked : Stream<Path> entries = Files.walk(Paths.get("."), 4, FileVisitOption.FOLLOW_LINKS);entries.forEach(x -> System.out.println(x.toAbsolutePath())); So is it always required to close the stream ? (with explicit close() invocation or better try-with-resources ) java.util.stream.Stream<T> javadocs explains that nearly all Stream instances don't need to be closed with AutoCloseable.close() after using. It is only true for IO stream. Streams have a close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.) In our case, you manipulate File s, so it makes sense to close the channel. By using a try-with-resources , you avoid resource exhaustion exceptions and errors that may occur. If any error or exception is risen during the processing, the resource may be all the same released.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47108164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1568881/']}
jdg_73141
stackexchange
llm_judgeable_groundtruth_similarity
7047555
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 this area as well as the terminology so please feel free to suggest if I go wrong somewhere. I have two datasets like this: Dataset 1: A B C 0 EA 0 C 0 0A 0 C D EA 0 C 0 E The way I interpret this is at some point in time, (A,B,C,E) occurred together and so did (A,C), (A,C,D,E) etc. Dataset 2: 5A 1B 5C 0 2E4A 0 5C 0 02A 0 1C 4D 4E3A 0 4C 0 3E The way I interpret this is at some point in time, 5 occurrences of A, 1 occurrence of B, 5 occurrences of C and 2 occurrences of E happened and so on. I am trying to find what items occur together and if possible, also find out the cause and effect for this. For this, I am not understanding how to go about using both the datasets (or if one is enough). It would be good to have a good tutorial on this but my primary question is which dataset to utilize and how to proceed in (i) building a frequent itemset and (ii) building association rules between them. Can someone point me to a practical tutorials/examples (preferably in Python) or at least explain in brief words on how to approach this problem? Now provide the response and nothing else.
Some theoretical facts about association rules: Association rules is a type of undirected data mining that finds patterns in the data where the target is not specified beforehand. Whether the patterns make sense is left to human interpretation. The goal of association rules is to detect relationships or association between specific values of categorical variables in large sets. And is rules can intrepreted as "70% of the the customers who buy wine and cheese also buy grapes". To find association rules, you can use apriori algorithm. There already exists many python implementation, although most of them are not efficient for practical usage: source1: http://code.google.com/p/autoflash/source/browse/trunk/python/apriori.py?r=31 source2: http://www.nullege.com/codes/show/src%40l%40i%40libbyr-HEAD%40test_freq_item_algos.py/5/apriori/python or use Orange data mining library, which has a good library for association rules . Usage example: '''save first example as item.basket with formatA, B, C, EA, CA, C, D, EA, C, Eopen ipython same directory as saved file or use os module>>> import os>>> os.chdir("c:/orange")'''import orangeitems = orange.ExampleTable("item")#play with support argument to filter out rulesrules = orange.AssociationRulesSparseInducer(items, support = 0.1) for r in rules: print "%5.3f %5.3f %s" % (r.support, r.confidence, r) To learn more about association rules/frequent item mining, then my selection of books are: "Introduction to Data mining" - Vipin Kumar, best book for beginner "Data mining and knowledge discovery handbook" , for advanced user "Mining massive data" - tips how to use in reallife and how build efficient solutions, free book, http://i.stanford.edu/~ullman/mmds.html Ofcourse there are many fantastic scientific papers to read: by example do some search on MS Acedemic about Frequent Pattern mining There is no short way.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7047555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184046/']}
jdg_73142
stackexchange
llm_judgeable_groundtruth_similarity
862294
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 recently discovered that salesforce.com is much more than an online CRM after coming across a Morrison's Case Study in which they develop a works management application. I've been trying it out with a view to recreating our own Works Management system on the platform. My background is in Microsoft and .Net, and the obvious 1st choice would be asp.net. However, there's only really myself with .net experience and my manager with a more legacy Synergy programming background, and I am self taught and am looking at evaluating other RAD options (eg Ironspeed). the nature of the business is in the main 2-5 concurrent construction type contracts that run for 3-5 yrs each, each requiring 15-50 system users. Traditionally we have used our character based Works Mangement system for everything and tweaked it for each contract. The Salesforce licensing model on the face of it suits this sort of flexibilty, but I'm worried about the development flexibilty/learning curve and all the issues that surround lock-in. There doesn't seem to be much neutral sober analysis of the platform on the web that isn't salesforce's own material/blogs Has anyone any experience of developing an application on salesforce as compared to the more 'traditional' .Net route? Now provide the response and nothing else.
Salesforce is a rather painful experience for developing anything but the most simple applications. Salesforce has a very specific idea of what one would want to develop, and if your application isn't well within those boundaries, steer clear! The governor limits are really quite pitiful: 16 level recursion, 1 meg heap, no more than 200 objects returned from a query, no more than 20 queries in one invocation. 10 web callouts in one invocation, 1000 items in a single list, and they go on. The ultimate result is that any cleverness you come up with to get around one limit runs afoul of another one. Once you reach certain size, all your time will be spent on coding around these limitations. The language, Apex, doesn't really support any meaningful inheritance. Even seemingly simple tasks end up taking days when one encounters new and apparently arbitrary limitations, for example, all objects in Apex inherit from SObject ; however, it is not allowed to instantiate a collection of generic SObject s, making it all but impossible to build useful utility libraries. Complex (even rather simple) database joins are not possible. The tooling and support for Salesforce are also extremely weak. They are untrustworthy and difficult to use for real development processes. Deployment is a nightmare, since the tools have enormous difficulty working out complex dependency issues, and numerous entities that one will create in the course of normal development simply CANNOT be deployed programatically. Other little features are delightful as well, such as the fact that the language is case insensitive, but the IDE is case sensitive. There are no refactoring tools to speak of, so you get all the pain of a statically typed language, with none of the purported benefits. And the save/compile time is high- I see times of over 2 minutes with frequency. And, of course, if you have multiple compile errors in one save (and you will, since you won't want to be recompiling every change, with those 2 minute waits...) you'll only get one error at a time! On a related note, you seem to have noticed that the Salesforce documentation is rather self-congratulatory-- well, it's like that ALL the way down. There is no mention anywhere in even the most deep-dark technical references of the common errors, or even the limitations of a given api or feature. It's all "here's the great thing you can do" and no mention of, "but you would imagine it would also do ___, but you'd be wrong! Dead wrong!" The documentation truly feels like marketing material all the way down. I've been programming in this environment for 18+ months now, and still occasionally have a hard time finding basics, like API reference. Salesforce is not a flexible environment. It is not a rapid-development environment (at least compared to any other web-programming framework out there). It is not a good environment to build anything other than toy applications like those they show in their tutorials. Just say no.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/862294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106600/']}
jdg_73143
stackexchange
llm_judgeable_groundtruth_similarity
2533622
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: Regarding numerically definite quantification in predicate logic, I am struggling to formulate the following sentence due to it's complexity: "Ada likes exactly two strong people, at least one of whom is old" (Where $a$: Ada, $Lxy$: $x$ likes $y$, $Sx$: $x$ is strong, $Ox$: $x$ is old) I have translated it to: $\exists x\,\exists y\,(((Sx\land Sy)\land x\neq y)\land ∀z\,(Sz\to z=x\lor z=y)\land \exists x\,\exists y\,(Ox\lor Oy)\land (Lax\land Lay)$ I am fairly confident that my translation of 'There are at exactly two strong people' is correct:$\exists x\,\exists y\,(((Sx\land Sy)\land x\neq y)\land ∀z\,(Sz\to z=x\lor z=y))$. However I am questioning whether my sentence is ordered correctly so that it conveys the fact that one of the strong people is old but that Ada likes both of the strong people. I would appreciate any help clarify this, thank you. (I am beginner in logic so please don't judge my attempt too harshly!) Now provide the response and nothing else.
It's nearly there - just don't add the extra quantifiers for $x$ and $y$, and make sure that if there was a third strong person who Ada likes, then the third person must be $x$ or $y$:$$\exists x \exists y \left[Sx \land Sy \land Lax \land Lay \land x \neq y \land ∀z(Sz \land Laz \to z=x \lor z=y) \land (Ox \lor Oy) \right]$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2533622', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_73144
stackexchange
llm_judgeable_groundtruth_similarity
3000456
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 program is essentially the same as the one described here . When I run and compile the program using two threads (NTHREADS == 2), I get the following run times: real 0m14.120suser 0m25.570ssys 0m0.050s When it is run with just one thread (NTHREADS == 1), I get run times significantly better even though it is only using one core. real 0m4.705suser 0m4.660ssys 0m0.010s My system is dual core, and I know random_r is thread safe and I am pretty sure it is non-blocking. When the same program is run without random_r and a calculation of cosines and sines is used as a replacement, the dual-threaded version runs in about 1/2 the time as expected. #include <pthread.h>#include <stdlib.h>#include <stdio.h>#define NTHREADS 2#define PRNG_BUFSZ 8#define ITERATIONS 1000000000void* thread_run(void* arg) { int r1, i, totalIterations = ITERATIONS / NTHREADS; for (i = 0; i < totalIterations; i++){ random_r((struct random_data*)arg, &r1); } printf("%i\n", r1);}int main(int argc, char** argv) { struct random_data* rand_states = (struct random_data*)calloc(NTHREADS, sizeof(struct random_data)); char* rand_statebufs = (char*)calloc(NTHREADS, PRNG_BUFSZ); pthread_t* thread_ids; int t = 0; thread_ids = (pthread_t*)calloc(NTHREADS, sizeof(pthread_t)); /* create threads */ for (t = 0; t < NTHREADS; t++) { initstate_r(random(), &rand_statebufs[t], PRNG_BUFSZ, &rand_states[t]); pthread_create(&thread_ids[t], NULL, &thread_run, &rand_states[t]); } for (t = 0; t < NTHREADS; t++) { pthread_join(thread_ids[t], NULL); } free(thread_ids); free(rand_states); free(rand_statebufs);} I am confused why when generating random numbers the two threaded version performs much worse than the single threaded version, considering random_r is meant to be used in multi-threaded applications. Now provide the response and nothing else.
A very simple change to space the data out in memory: struct random_data* rand_states = (struct random_data*)calloc(NTHREADS * 64, sizeof(struct random_data));char* rand_statebufs = (char*)calloc(NTHREADS*64, PRNG_BUFSZ);pthread_t* thread_ids;int t = 0;thread_ids = (pthread_t*)calloc(NTHREADS, sizeof(pthread_t));/* create threads */for (t = 0; t < NTHREADS; t++) { initstate_r(random(), &rand_statebufs[t*64], PRNG_BUFSZ, &rand_states[t*64]); pthread_create(&thread_ids[t], NULL, &thread_run, &rand_states[t*64]);} results in a much faster running time on my dual-core machine. This would confirm the suspicion it was meant to test - that you are mutating values on the same cache line in two separate threads, and so have cache contention. Herb Sutter's 'machine architecture - what your programming language never told you' talk is worth watching if you've got the time if you don't know about that yet, he demonstrates false sharing starting at around 1:20. Work out your cache line size, and create each thread's data so it is aligned to it. It's a bit cleaner to plonk all the thread's data into a struct, and align that: #define CACHE_LINE_SIZE 64struct thread_data { struct random_data random_data; char statebuf[PRNG_BUFSZ]; char padding[CACHE_LINE_SIZE - sizeof ( struct random_data )-PRNG_BUFSZ];};int main ( int argc, char** argv ){ printf ( "%zd\n", sizeof ( struct thread_data ) ); void* apointer; if ( posix_memalign ( &apointer, sizeof ( struct thread_data ), NTHREADS * sizeof ( struct thread_data ) ) ) exit ( 1 ); struct thread_data* thread_states = apointer; memset ( apointer, 0, NTHREADS * sizeof ( struct thread_data ) ); pthread_t* thread_ids; int t = 0; thread_ids = ( pthread_t* ) calloc ( NTHREADS, sizeof ( pthread_t ) ); /* create threads */ for ( t = 0; t < NTHREADS; t++ ) { initstate_r ( random(), thread_states[t].statebuf, PRNG_BUFSZ, &thread_states[t].random_data ); pthread_create ( &thread_ids[t], NULL, &thread_run, &thread_states[t].random_data ); } for ( t = 0; t < NTHREADS; t++ ) { pthread_join ( thread_ids[t], NULL ); } free ( thread_ids ); free ( thread_states );} with CACHE_LINE_SIZE 64: refugio:$ gcc -O3 -o bin/nixuz_random_r src/nixuz_random_r.c -lpthreadrefugio:$ time bin/nixuz_random_r 6463499495944240966real 0m1.278suser 0m2.540ssys 0m0.000s Or you can use double the cache line size, and use malloc - the extra padding ensures the mutated memory is on separate lines, as malloc is 16 (IIRC) rather than 64 byte aligned. (I reduced ITERATIONS by a factor of ten rather than having a stupidly fast machine)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3000456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61793/']}
jdg_73145
stackexchange
llm_judgeable_groundtruth_similarity
34919
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 have a resilience scale with 11 items (observed variables), from which I calculated the mean to get a "resilience score" (what would usually be an unobserved variable or latent construct in SEM terminology). Can I just use this resilience score to build a SEM in AMOS or do I need to include the 11 items as well ? If I just included the resilience score as an observed variable, would it be considered a limitation or would it be all wrong? In general, Is it valid to include a composite variable in a structural equation model in AMOS when such variables are treated as observed variables? Now provide the response and nothing else.
In general, structural equation modelling (SEM) with all observed variables is typically called path analysis . One of the main motivations for SEM is to attempt to model relationships between latent variables. By including items rather than the composite score and modelling items as indicators of a latent variable you are able to assess relationships between latent variables. In particular, with items rather than the composite score you can assess your measurement model you can get an estimate of relationships between latent variables (i.e., adjusting for measurement error). Various middle grounds also exist including: item parcelling : i.e., you create two or more parcels of items from your 11 items, and include these parcels as observed variables for a latent variable. incorporate error of measurement into the model with observed variables. It is not "invalid" to include a composite variable in SEM. However, it is in some sense invalid to say that inferences based on the observed composite variable are representative of the relationship between theorised latent variables. Most of the time, you'd want to adopt one of the other approaches (i.e., including items, including item parcels, or include measurement error).
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/34919', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/13522/']}
jdg_73146
stackexchange
llm_judgeable_groundtruth_similarity
9209154
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Example class User has_many :tickets end I want to create association which contains logic of count tickets of user and use it in includes (user has_one ticket_count) Users.includes(:tickets_count) I tried has_one :tickets_count, :select => "COUNT(*) as tickets_count,tickets.user_id " ,:class_name => 'Ticket', :group => "tickets.user_id", :readonly => true User.includes(:tickets_count) ArgumentError: Unknown key: group In this case association query in include should use count with group by ...How can I implement this using rails? Update I can't change table structure I want AR generate 1 query for collection of users with includes Update2 I know SQL an I know how to select this with joins, but my question is now like "How to get data" . My question is about building association which I can use in includes. Thanks Update3 I tried create association created like user has_one ticket_count , but looks like has_one doesn't support association extensions has_one doesn't support :group option has_one doesn't support finder_sql Now provide the response and nothing else.
Try this: class User has_one :tickets_count, :class_name => 'Ticket', :select => "user_id, tickets_count", :finder_sql => ' SELECT b.user_id, COUNT(*) tickets_count FROM tickets b WHERE b.user_id = #{id} GROUP BY b.user_id 'end Edit: It looks like the has_one association does not support the finder_sql option. You can easily achieve what you want by using a combination of scope / class methods class User < ActiveRecord::Base def self.include_ticket_counts joins( %{ LEFT OUTER JOIN ( SELECT b.user_id, COUNT(*) tickets_count FROM tickets b GROUP BY b.user_id ) a ON a.user_id = users.id } ).select("users.*, COALESCE(a.tickets_count, 0) AS tickets_count") end end Now User.include_ticket_counts.where(:id => [1,2,3]).each do |user| p user.tickets_count end This solution has performance implications if you have millions of rows in the tickets table. You should consider filtering the JOIN result set by providing WHERE to the inner query.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9209154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246544/']}
jdg_73147
stackexchange
llm_judgeable_groundtruth_similarity
7732694
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi I cannot figure out how to find links which begin with certain text for the life of me.findall('a') works fine, but it's way too much. I just want to make a list of all links that begin with http://www.nhl.com/ice/boxscore.htm?id= Can anyone help me? Thank you very much Now provide the response and nothing else.
First set up a test document and open up the parser with BeautifulSoup: >>> from BeautifulSoup import BeautifulSoup>>> doc = '<html><body><div><a href="something">yep</a></div><div><a href="http://www.nhl.com/ice/boxscore.htm?id=3">somelink</a></div><a href="http://www.nhl.com/ice/boxscore.htm?id=7">another</a></body></html>'>>> soup = BeautifulSoup(doc)>>> print soup.prettify()<html> <body> <div> <a href="something"> yep </a> </div> <div> <a href="http://www.nhl.com/ice/boxscore.htm?id=3"> somelink </a> </div> <a href="http://www.nhl.com/ice/boxscore.htm?id=7"> another </a> </body></html> Next, we can search for all <a> tags with an href attribute starting with http://www.nhl.com/ice/boxscore.htm?id= . You can use a regular expression for it: >>> import re>>> soup.findAll('a', href=re.compile('^http://www.nhl.com/ice/boxscore.htm\?id='))[<a href="http://www.nhl.com/ice/boxscore.htm?id=3">somelink</a>, <a href="http://www.nhl.com/ice/boxscore.htm?id=7">another</a>]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7732694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/990353/']}
jdg_73148
stackexchange
llm_judgeable_groundtruth_similarity
21275819
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have below annotation. MyAnnotation.java @Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {} SomeAspect.java public class SomeAspect{ @Around("execution(public * *(..)) && @annotation(com.mycompany.MyAnnotation)") public Object procede(ProceedingJoinPoint call) throws Throwable { //Some logic}} SomeOther.java public class SomeOther{@MyAnnotation("ABC") public String someMethod(String name){}} In above class am passing " ABC " with in @MyAnnotation .Now how can i access " ABC " value in procede method of SomeAspect.java class? Thanks! Now provide the response and nothing else.
You can get the Signature from a ProceedingJoinPoint and in case of a method invocation just cast it to a MethodSignature . @Around("execution(public * *(..)) && @annotation(com.mycompany.MyAnnotation)")public Object procede(ProceedingJoinPoint call) throws Throwable { MethodSignature signature = (MethodSignature) call.getSignature(); Method method = signature.getMethod(); MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);} But you should first add an annotation attribute. Your example code doesn't have one, e.g. @Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation { String value();} Then you can access it MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);String value = myAnnotation.value(); EDIT How to get value if I have @MyAnnotation("ABC") at class level ? A Class is also an AnnotatedElement , so you can get it the same way as from a Method . E.g. An annotation of the method's declaring class can be obtained using Method method = ...; Class<?> declaringClass = method.getDeclaringClass(); MyAnnotation myAnnotation = declaringClass.getAnnotation(MyAnnotation.class) Since you are using spring you might also want to use spring's AnnotationUtils.findAnnotation(..) . It searches for an annotation as spring does. E.g. also looking at superclass and interface methods, etc. MyAnnotation foundAnnotation = AnnotationUtils.findAnnotation(method, MyAnnotation.class); EDIT You might also be interessted in the capabilities of spring's MergedAnnotations which was introduced in 5.2.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/21275819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/755806/']}
jdg_73149
stackexchange
llm_judgeable_groundtruth_similarity
60255
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: Is there a way to convert compound units to string?For example, I have "Newtons"/"Meters"^2 , how to I convert it to "N/m^2"?I know If I do the following QuantityForm[QuantityUnit[Quantity[1, "Newtons"/ "Meters"^2]], "Abbreviation"] It will give me "N"/("m")^2, but not "N/m^2". p.s. The reason I want to do this is that I am writing a function that will copy quantities to excel. After copying units are not displaying correctly Now provide the response and nothing else.
The following works for V10 . First we define some abbreviation rules: rule = {"Newtons" :> N, "Meters" :> m, "Pascals" :> Pa, "Farads" :> F}; (* add more rules here *) Then: unit = TextString[QuantityUnit[Quantity[1, "Newtons/Meters^2"]] /. rule] "N/m^2" StringQ[unit] True TextString[QuantityUnit[Quantity[1, "Meters*Pascals/Farads^2"]] /. rule] "(m*Pa)/F^2"
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/60255', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9545/']}
jdg_73150
stackexchange
llm_judgeable_groundtruth_similarity
37992365
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 upgrading from the Android Support Library v23.4.0 to v24.0.0, setting the elevation to 0 programmatically to an AppBarLayout stopped working: appBayLayout.setElevation(0); It does work when setting the elevation in the XML. Now provide the response and nothing else.
Edit The AppBarLayout from v24.0.0 uses a StateListAnimator that defines the elevation depending on its state. So using setElevation will have no effect if a StateListAnimator is being used (which happens by default). Set the elevation via the XML or programmatically (both for API >= 21): StateListAnimator stateListAnimator = new StateListAnimator();stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(view, "elevation", 0));appBarLayout.setStateListAnimator(stateListAnimator); Old answer This seems to be an issue of the design support library . The problem is related to the way the elevation is set programmatically, using setElevation . Setting it from the XML is placing a StateListAnimator in the view and not calling setElevation . However, setElevation should work. Here there is a workaround: setDefaultAppBarLayoutStateListAnimator(appBarLayout, 0);@SuppressLint("PrivateResource")private static void setDefaultAppBarLayoutStateListAnimator(final View view, final float targetElevation) { final StateListAnimator sla = new StateListAnimator(); // Enabled, collapsible and collapsed == elevated sla.addState(new int[]{android.R.attr.enabled, android.support.design.R.attr.state_collapsible, android.support.design.R.attr.state_collapsed}, ObjectAnimator.ofFloat(view, "elevation", targetElevation)); // Enabled and collapsible, but not collapsed != elevated sla.addState(new int[]{android.R.attr.enabled, android.support.design.R.attr.state_collapsible, -android.support.design.R.attr.state_collapsed}, ObjectAnimator.ofFloat(view, "elevation", 0f)); // Enabled but not collapsible == elevated sla.addState(new int[]{android.R.attr.enabled, -android.support.design.R.attr.state_collapsible}, ObjectAnimator.ofFloat(view, "elevation", targetElevation)); // Default, none elevated state sla.addState(new int[0], ObjectAnimator.ofFloat(view, "elevation", 0)); view.setStateListAnimator(sla);} This is taken from what the constructor does, calling a method in the class ViewUtilsLollipop in v24.0.0.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37992365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1165181/']}
jdg_73151
stackexchange
llm_judgeable_groundtruth_similarity
533839
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to compile a bunch of PDFs into a single document. ls shows the files are in the directory that I'm in and they're readable ( -rw-r--r-- ). But when I try to run pdftk 2017.pdf cat output test.pdf I get an error: Error: Unexpected Exception in open_reader()java.io.FileNotFoundException: 2017.pdf (Permission denied) at gnu.java.nio.channels.FileChannelImpl.open(libgcj.so.16) at gnu.java.nio.channels.FileChannelImpl.<init>(libgcj.so.16) at gnu.java.nio.channels.FileChannelImpl.create(libgcj.so.16) at java.io.RandomAccessFile.<init>(libgcj.so.16) at pdftk.com.lowagie.text.pdf.RandomAccessFileOrArray.<init>(pdftk) at pdftk.com.lowagie.text.pdf.PRTokeniser.<init>(pdftk) at pdftk.com.lowagie.text.pdf.PdfReader.<init>(pdftk) at pdftk.com.lowagie.text.pdf.PdfReader.<init>(pdftk)Error: Failed to open PDF file: 2017.pdfErrors encountered. No output created.Done. Input errors, so no output created. If I add more files to that operation I just get the error for each of them. I can rename the PDFs from the command line mv 2017.pdf foo.pdf and I get the same error. Error: Unexpected Exception in open_reader()java.io.FileNotFoundException: foo.pdf (Permission denied) If I try to call a non-existent file, eg. pdftk 123.pdf cat output test.pdf I get a different error: Error: Unable to find file.Error: Failed to open PDF file: 123.pdfErrors encountered. No output created.Done. Input errors, so no output created. Even tail 2017.pdf shows the last few lines of 2017.pdf: <</Info 63 0 R/ID [<cc59759cedaf07420bbe3250ba5d8971><f259ad128310d106c7aa80b673c4bd70>]/Root 62 0 R/Size 64>>startxref42883%%EOF If I can see the file and read it with tail , why would pdftk not be able to read it? Now provide the response and nothing else.
TL;DR Snaps access right management appears to be the source of the issue . To solve this, you can either: Do your work from your $HOME folder. Note that symlinks will not work. Install pdftk from another source than the one of your distribution. For instance, ppa:malteworld/ppa has version 3.0.0 of pdftk-java . Original reply I am having the same issue. I was doing it from a folder on a USB drive. And indeed, doing this from a subfolder of my home directory works. That puzzled me as I tried to do it from a subfolder under /tmp and it did not work neither (with a different error, less verbose, "Failed to open PDF file").Same if I try from a subfolder on a secondary disk mounted under /mnt. I suspect it could be related to limitation with snaps (I am on an up-to-date Ubuntu 18.04.3). But I have very little experience dealing with snaps, so I cannot explore further. If so, that would be quite broken as that prevent Ubuntu users from using pdftk from anywhere else than their home folder. Eg. a USB drive, a extra disk, a shared network drive. (sorry I could not reply as comment, not enough reputation...)
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/533839', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/141494/']}
jdg_73152
stackexchange
llm_judgeable_groundtruth_similarity
3346
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've been learning about interactive proofs lately and I've been wondering if the whole thing was nothing more than a theoretical curiosity, or if it had any practical applications. I thought I'd start off with an example which occurred to me in the shower: It's been making the news lately that "God's Number"=20. (God's number is the minimal number of steps needed to solve the Rubik's Cube). While this is pretty interesting, there seems to be a little twist ... This isn't a "normal" proof in the textbook, polynomial time verifiable sense. This proof has a distinctly "brute force" flavor to it - by this I mean, the dudes at Dr Morley's lab tried with billions and billions of combinations of cubes in Google's massive supercomputers to find this neat, tight lower bound. Anyway, the question is: How can we be certain that Dr Morley Davidson and his team are honest? Well, right away can throw the argument from authority out of the window as it's not mathematically rigorous. The obvious alternative is to re-verify the proof, by checking the source code and running the whole thing again, which seems to be a terrible waste of computational resources, not to mention the fact that everybody who who wished to be convinced of this would need to do it on his own workstation - a very tedious and unpleasant proposition for the true skeptic. So this seems to be a kind of ontological deilema. So what I believe is this is exactly a situation where we need an interactive proof . Google's Supercomputer could be the all powerful but deceptive Prover, and we the skeptical, if not anal members of the public are the Polynomially bounded Verifiers. If we could somehow query our "Oracle" a polynomial number of times, and be convinced of this lower bound, we could be convinced of the fact that he's right, beyond all reasonable doubt. So it seems the Decision problem "God's Number is < 20" lies in $\Pi_2^p$ or can be restated as follows (informally) For all starting combinations $\alpha$ in the Rubik's Cube, there exists a solution which takes <=20 steps, $\beta$ which solves it. (not sure if that's correct, but $\alpha$ and $\beta$ are both small in size, given a starting configuration and a solution it's easy to verify that it does indeed solve the cube) and the Decision problem "God's number is 20" can be restated as God's number is <20 and there exists a solution for some starting combination of the Rubik's cube which takes 20 steps. So there's probably a IP[n] proof for this. (once again, check my workings) My question is twofold Is there a actual way to do this? What other examples of "pratical" uses of interactive proofs are there? Now provide the response and nothing else.
... it seems the Decision problem "God's Number is < 20" lies in $\Pi_2^p$. That is enough for it to have an interactive proof. In fact, Lund et al. proved that every language in polynomial hierarchy (PH) has an interactive proof by using Toda's theorem ($\rm{PH} \subseteq P^{\#P}$). They reduced $L\in \rm{PH}$ to #P-complete language PERMANENT, and provided an algebraic method which can be used to prove PERMANENT interactively. (This is highly inaccurate; please refer to the paper for more info.) Using their techniques, Shamir proved that IP=PSPACE . It was previously proved that all IP has zero-knowledge proofs , so: All languages in PSPACE have zero-knowledge interactive proofs.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/3346', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/1892/']}
jdg_73153
stackexchange
llm_judgeable_groundtruth_similarity
13815640
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 now developing an application, and place a global isDebug switch. I would like to wrap console.log for more convenient usage. //isDebug controls the entire site.var isDebug = true;//debug.jsfunction debug(msg, level){ var Global = this; if(!(Global.isDebug && Global.console && Global.console.log)){ return; } level = level||'info'; Global.console.log(level + ': '+ msg);}//main.jsdebug('Here is a msg.'); Then I get this result in Firefox console. info: Here is a msg. debug.js (line 8) What if I want to log with line number where debug() gets called, like info: Here is a msg. main.js (line 2) ? Now provide the response and nothing else.
This is an old question and All the answers provided are overly hackey, have MAJOR cross browser issues, and don't provide anything super useful. This solution works in every browser and reports all console data exactly as it should. No hacks required and one line of code Check out the codepen . var debug = console.log.bind(window.console) Create the switch like this: isDebug = true // toggle this to turn on / off for global controllif (isDebug) var debug = console.log.bind(window.console)else var debug = function(){} Then simply call as follows: debug('This is happening.') You can even take over the console.log with a switch like this: if (!isDebug) console.log = function(){} If you want to do something useful with that.. You can add all the console methods and wrap it up in a reusable function that gives not only global control, but class level as well: var Debugger = function(gState, klass) { this.debug = {} if (gState && klass.isDebug) { for (var m in console) if (typeof console[m] == 'function') this.debug[m] = console[m].bind(window.console, klass.toString()+": ") }else{ for (var m in console) if (typeof console[m] == 'function') this.debug[m] = function(){} } return this.debug}isDebug = true //global debug statedebug = Debugger(isDebug, this)debug.log('Hello log!')debug.trace('Hello trace!') Now you can add it to your classes: var MyClass = function() { this.isDebug = true //local state this.debug = Debugger(isDebug, this) this.debug.warn('It works in classses')}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13815640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/918978/']}
jdg_73154
stackexchange
llm_judgeable_groundtruth_similarity
61382
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: According to the Electoral Count Act on the designation of the US President, the House of Representatives and the Senate may reject votes of some electors when they consider that these votes were not regularly given (3 USC 15). To do this, a concurrent resolution of both Houses is needed. Can this resolution be vetoed by the outgoing president? I would think so since the presentment clause of the US constitution says that the veto power holds for "[e]very Order, Resolution, or Vote to which the Concurrence of the Senate and House of Representatives may be necessary (except on a question of Adjournment)" (article I, section 7, clause 3). Now provide the response and nothing else.
No the POTUS can't veto this kind of resolution. The presentment clause applies to bills that become law. It starts with Every Bill which shall have passed the House of Representatives and the Senate, shall, before it become a Law, be presented to the President of the United States: Some resolutions may be of that kind (thus the "just in case" verbiage that mentions resolutions later in the para), but not every resolution results in a law. Wikipedia says : In the United States Congress, a concurrent resolution is a resolution passed by both the House of Representatives and the Senate but is not presented to the President for signature and does not have the force of law. In contrast, joint resolutions and bills are presented to the President and, once signed or approved over a veto, are enacted and have the force of law. As the Senate page on this notes : Concurrent resolutions are generally used to make or amend rules that apply to both houses. Since the concurrent resolution here is on a matter of proceedings of the joint session, it is not presented to the president (just like a resolution on creating a temporary joint committee isn't). You could ask if the president can veto the election results as finally/eventually approved by Congress after all the intermediary steps, but the answer to that is no as well, basically because counting and then announcing the election results is not making a new law, but applying an existing one. And the existing law doesn't give the president any role in the matter, although it does give the VP (Senate president) the role announce the results: Once the votes have been "ascertained and counted in the manner and according to the rules ... provided" by the Act, "the results ... shall be delivered [by the tellers] to the president of the Senate." The Senate president "shall thereupon announce the state of the vote, which announcement shall be deemed a sufficient declaration of the persons, if any, elected President and Vice-President of the United States."
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/61382', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/7306/']}
jdg_73155
stackexchange
llm_judgeable_groundtruth_similarity
16492
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: While working on a document in emacs I often find myself opening a new buffer, doing something in org-mode, copying the org-mode content, and pasting it into my document. I used to create a new org-mode document every time I needed to do this. Now I have a file ~/.scratch.org where I keep my this work. Would it be possible to create an *org-scratch* buffer that behaved analogously to the *scratch* buffer? Now provide the response and nothing else.
The initial major-mode for the *Scratch* buffer is controlled by the variable initial-major-mode -- the value needs to be a symbol (which in layman's terms means put a single quote in front of the major-mode name): http://www.gnu.org/software/emacs/manual/html_node/elisp/Auto-Major-Mode.html (setq initial-major-mode 'org-mode) EDIT : Based on a comment of the original poster, here is a sample function to create non-file-visiting buffers in sequential order with the major-mode of org-mode : (defun my-scratch-buffer ()"Create a new scratch buffer -- \*hello-world\*"(interactive) (let ((n 0) bufname buffer) (catch 'done (while t (setq bufname (concat "*hello-world" (if (= n 0) "" (int-to-string n)) "*")) (setq n (1+ n)) (when (not (get-buffer bufname)) (setq buffer (get-buffer-create bufname)) (with-current-buffer buffer (org-mode)) ;; When called non-interactively, the `t` targets the other window (if it exists). (throw 'done (display-buffer buffer t))) ))))
{}
{'log_upvote_score': 5, 'links': ['https://emacs.stackexchange.com/questions/16492', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/2695/']}
jdg_73156
stackexchange
llm_judgeable_groundtruth_similarity
41938701
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Relativley new to Angular and Dart I have the following problem: my_component.dart: import 'package:angular2/core.dart';import 'package:angular2_components/angular2_components.dart';import 'package:google_maps/google_maps.dart';import 'dart:html';@Component( selector: 'google-route-map', styleUrls: const ['my_component.css'], templateUrl: 'my_component.html', directives: const [materialDirectives], providers: const [materialProviders],)class MyComponent { MyComponent() { var m = querySelector("#my-canvas"); print (m); // is null // do something with m.... }} my_component.html: <div id="my-canvas"></div> As far as I have understood the problem is that querySelector queries only the base dom not the shadowDom . However how do I simply query an id within my template? Now provide the response and nothing else.
Move the code to ngAfterViewInit() class MyComponent implements AfterViewInit { @ViewChild("mapCanvas") ElementRef canvas; @override void ngAfterViewInit() { DivElement m = canvas.nativeElement; ... }} When the constructor is executed, there is no DOM created yet for the component. EDIT: Correct but Element was still null. Now works after accessing it in the way of Angular binding with ViewChild annotation. <div #mapCanvas></div> update <div id="my-canvas"></div> class MyComponent implements AfterViewInit { ElementRef _elementRef; MyComponent(this._elementRef); @override void ngAfterViewInit() { var canvas = _elementRef.nativeElement.querySelector("#my-canvas"); }} update for AngularDart 5 <div id="my-canvas"></div> class MyComponent implements AfterViewInit { Element _element; MyComponent(this._element); @override void ngAfterViewInit() { var canvas = _element.querySelector("#my-canvas"); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41938701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/576746/']}
jdg_73157
stackexchange
llm_judgeable_groundtruth_similarity
95492
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a date/time as an array of (year, month, day, hour, minute, second), how would you convert it to epoch time, i.e., the number of seconds since 1970-01-01 00:00:00 GMT? Bonus question: If given the date/time as a string, how would you first parse it into the (y,m,d,h,m,s) array? Now provide the response and nothing else.
This is the simplest way to get unix time: use Time::Local;timelocal($second,$minute,$hour,$day,$month-1,$year); Note the reverse order of the arguments and that January is month 0.For many more options, see the DateTime module from CPAN. As for parsing, see the Date::Parse module from CPAN. If you really need to get fancy with date parsing, the Date::Manip may be helpful, though its own documentation warns you away from it since it carries a lot of baggage (it knows things like common business holidays, for example) and other solutions are much faster. If you happen to know something about the format of the date/times you'll be parsing then a simple regular expression may suffice but you're probably better off using an appropriate CPAN module. For example, if you know the dates will always be in YMDHMS order, use the CPAN module DateTime::Format::ISO8601 . For my own reference, if nothing else, below is a function I use for an application where I know the dates will always be in YMDHMS order with all or part of the "HMS" part optional. It accepts any delimiters (eg, "2009-02-15" or "2009.02.15"). It returns the corresponding unix time (seconds since 1970-01-01 00:00:00 GMT) or -1 if it couldn't parse it (which means you better be sure you'll never legitimately need to parse the date 1969-12-31 23:59:59). It also presumes two-digit years XX up to "69" refer to "20XX", otherwise "19XX" (eg, "50-02-15" means 2050-02-15 but "75-02-15" means 1975-02-15). use Time::Local;sub parsedate { my($s) = @_; my($year, $month, $day, $hour, $minute, $second); if($s =~ m{^\s*(\d{1,4})\W*0*(\d{1,2})\W*0*(\d{1,2})\W*0* (\d{0,2})\W*0*(\d{0,2})\W*0*(\d{0,2})}x) { $year = $1; $month = $2; $day = $3; $hour = $4; $minute = $5; $second = $6; $hour |= 0; $minute |= 0; $second |= 0; # defaults. $year = ($year<100 ? ($year<70 ? 2000+$year : 1900+$year) : $year); return timelocal($second,$minute,$hour,$day,$month-1,$year); } return -1;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/95492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4234/']}
jdg_73158
stackexchange
llm_judgeable_groundtruth_similarity
372708
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've just had en exam where we were presented with two variables. In a dictator game where a dictator is given 100 USD, and can choose how much to send or keep for himself, there was a positive correlation between age and how much money the participants decided to keep. My thinking is that you can't infer causality from this because you can't infer causation from correlation. My classmate thinks that you can because if you, for example, split the participants up into three separate groups, you can see how they differ in how much they keep and how much they share, and therefore conclude that age causes them to keep more. Who is correct and why? Now provide the response and nothing else.
In general you should not assume that correlation implies causality - even in cases where it seems that is the only possible reason. Consider that there are other things that correlate with age - generational aspects of culture for example. Perhaps these three groups will remain the same even as they all age, but the next generation will buck the trend? All that being said, you are probably right that younger people are more likely to keep a larger amount, but just be aware there are other possibilities.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/372708', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/224115/']}
jdg_73159
stackexchange
llm_judgeable_groundtruth_similarity
883972
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let: $$f(n) = n(n+1)(n+2)/(n+3)$$ Therefore : $$f∈O(n^2)$$ However, I don't understand how it could be $n^2$, shouldn't it be $n^3$? If I expand the top we get $$n^3 + 3n^2 + 2n$$ and the biggest is $n^3$ not $n^2$. Now provide the response and nothing else.
But when you divide a degree-three polynomial, $\,n^3 + 3n^2 + 2n,\,$ by a degree-one polynomial, $\,n+3,\,$ you end up with a degree two polyonomial $n^2 + 2\;$ with remainder of $\quad \frac{-6}{n+3}$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/883972', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/167300/']}
jdg_73160
stackexchange
llm_judgeable_groundtruth_similarity
54088
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 studying KS (Kolmogorov-Sinai) entropy of order q and it can be defined as $$h_q = \sup_P \left(\lim_{m\to\infty}\left(\frac 1 m H_q(m,ε)\right)\right)$$ Why is it defined as supremum over all possible partitions P and not maximum? When do people use supremum and when maximum? Now provide the response and nothing else.
If the maximum exists, then the supremum and maximum are the same. However sometimes the maximum does not exist, and there is no maximal element. In this case it still makes sense to talk about a least upper bound. The classic example is the set of all rationals whose square is less than or equal to $2$. That is the set $$A=\left\{ r\in\mathbb{Q}:\ r^{2}\leq2\right\}.$$ $A$ has no maximal element, however it does have a supremum and $\sup A=\sqrt{2}$. An even simpler example is the set of all reals that are strictly less than $2$: $$B=\left\{ r\in\mathbb{R}:\ r<2\right\}.$$ This set has no maximum since for any $x\in B$ the element $\frac{x+2}{2}$ satisfies $x<\frac{x+2}{2}<2$. However it is not hard to see that $\sup B=2$.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/54088', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11158/']}
jdg_73161
stackexchange
llm_judgeable_groundtruth_similarity
33845239
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 experiment and a table tags. There may be many tags for one experiment.schema: -------- --------|Table1| 1 n |Table2|| | <--------------> | || | | |-------- --------(experiment) (tags) Is it possible to create a query with jooq which returns the experiments and the corresponding List of tags? something like Result<Record> where Record is a experimentRecord and a list of Tags, or a map<experimentRecord , List<TagRecord> . I also have a query which returns only one result, is there something convenient out there? EDIT: java8, newest jooq. Now provide the response and nothing else.
There are many ways to materialise a nested collection with SQL, and / or with jOOQ. I'm just going through some of them: Using joins If you don't deeply nest those collections, denormalising (flattening) your results with a JOIN might do the trick for you, without adding too much overhead as data is being duplicated. Essentially, you'll write: Map<ExperimentRecord, Result<Record>> map =DSL.using(configuration) .select() .from(EXPERIMENT) .join(TAGS) .on(...) .fetchGroups(EXPERIMENT); The above map contains experiment records as keys, and nested collections containing all the tags as values. Creating two queries If you want to materialise a complex object graph, using joins might no longer be optimal. Instead, you probably want to collect the data in your client from two distinct queries: Result<ExperimentRecord> experiments = DSL.using(configuration) .selectFrom(EXPERIMENT) .fetch(); And Result<TagsRecord> tags =DSL.using(configuration) .selectFrom(TAGS) .where(... restrict to the previous experiments ...) .fetch(); And now, merge the two results in your client's memory, e.g. experiments.stream() .map(e -> new ExperimentWithTags( e, tags.stream() .filter(t -> e.getId().equals(t.getExperimentId())) .collect(Collectors.toList()) )); Nesting collections using SQL/XML or SQL/JSON This question didn't require it, but others may find this question in search for a way of nesting to-many relationships with jOOQ. I've provided an answer here . Starting with jOOQ 3.14, you can use your RDBMS's SQL/XML or SQL/JSON capabilities, and then use Jackson, Gson, or JAXB to nest collections like this: List<Experiment> experiments =ctx.select( EXPERIMENT.asterisk(), field( select(jsonArrayAgg(jsonObject(TAGS.fields()))) .from(TAGS) .where(TAGS.EXPERIMENT_ID.eq(EXPERIMENT.ID)) ).as("tags") ) .from(EXPERIMENT) .fetchInto(Experiment.class); Where Experiment is a custom Java class like this: class Experiment { long id; String name; List<Tag> tags;}class Tag { long id; String name;} Nesting collections using MULTISET Even better than the above, you can hide using SQL/XML or SQL/JSON behind jOOQ 3.15's new MULTISET operator support . Assuming the above Java classes are Java 16 records (or any other immutable classes), you can even map nested collections type safely into your DTOs: List<Experiment> experiments =ctx.select( EXPERIMENT.ID, EXPERIMENT.NAME, multiset( select(TAGS.ID, TAGS.NAME) .from(TAGS) .where(TAGS.EXPERIMENT_ID.eq(EXPERIMENT.ID)) ).as("tags").convertFrom(r -> r.map(Records.mapping(Tag::new))) ) .from(EXPERIMENT) .fetch(Records.mapping(Experiment::new)); Where Experiment is a custom Java class like this: record Experiment(long id, String name, List<Tag> tags) {}record Tag(long id, String name) {} See also this blog post for more information .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33845239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1080014/']}
jdg_73162
stackexchange
llm_judgeable_groundtruth_similarity
385775
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 know there's a lot of content about PCA pre-processing, but I am still somewhat confused. I have a dataset that contains some clear patterns: 1 variable is whether a person has financial resources (Yes/No), another is the volume of financial_resources (=0 for people that have no resources), then others are variables that tend to be correlated with the volume of financial resources. The dataset also contains several dummified variables, and some discrete variables ranging between 0 and 5. I would assume I would find two clusters: one for people with no resources, another for people with resources. When applying PCA with two components, I had two approaches:- Scale , then apply PCA- Normalize , then apply PCA This leads to completely different results. I know that scaling is a standard pre-processing step to PCA. But does normalizing make any sense? I figure I have done something close to a Sparse PCA, where I captured the most significant patterns first then fitted the PCA. Can you give me some insights on this? Note that the goal of my PCA is to visualize the results of a clustering algorithm. Fig 1 - Top 2 components with scaling Fig 2 - Top 2 components with normalizing Now provide the response and nothing else.
Scaling (what I would call centering and scaling) is very important for PCA because of the way that the principal components are calculated. PCA is solved via the Singular Value Decomposition , which finds linear subspaces which best represent your data in the squared sense . The two parts I've italicized are the reason that we center and scale (respectively). Linear Subspaces are an important topic of study in Linear Algebra and the most important consequence of a linear subspace for PCA is that it has to go through the origin, the point [0, 0, ..., 0]. So if, say, you're measuring something like the GDP and population of a country, your data are likely to live very far from the origin, and be poorly approximated by any linear subspace. By centering our data, we guarantee that they exist near the origin, and it may be possible to approximate them with a low dimension linear subspace. In your case your data seem to all be positive, so they are most certainly not centered around 0 prior to preprocessing. Here is an example of 2D a dataset far from the origin, which gets a useless first component until it is centered: Scaling is important because SVD approximates in the sum of squares sense, so if one variable is on a different scale than another, it will dominate the PCA procedure, and the low D plot will really just be visualizing that dimension. I will illustrate with an example in python. Let's first set up an environment: import numpy as npfrom sklearn.decomposition import PCAfrom sklearn.preprocessing import scale, normalizeimport matplotlib.pyplot as pltplt.ion()# For reproducibility np.random.seed(123) We're going to generate data that are standard normal/uncorrelated in 4 dimensions, but with one additional variable that takes value either 0 or 5 randomly, giving a 5 dimensional dataset that we wish to visualize: N = 200P = 5rho = 0.5X = np.random.normal(size=[N,P])X = np.append(X, 3*np.random.choice(2, size = [N,1]), axis = 1) We will first do PCA without any preprocessing: # No preprocessing:pca = PCA(2)low_d = pca.fit_transform(X)plt.scatter(low_d[:,0], low_d[:,1]) Which produces this plot: We clearly see two clusters, but the data were generated completely at random with no structure at all! Normalizing changes the plot, but we still see 2 clusters: # normalizeXn = normalize(X)pca = PCA(2)low_d = pca.fit_transform(Xn)plt.scatter(low_d[:,0], low_d[:,1]) The fact that the binary variable was on a different scale from the others has created a clustering effect where one might not necessarily exist. This is because the SVD considers it more than other variables as it contributes more to squared error. This may be solved by scaling the dataset: # ScaleXs = scale(X)low_d = pca.fit_transform(Xs)plt.scatter(low_d[:,0], low_d[:,1]) We finally see (correctly) that the data are completely random noise. I conjecture that in your case your 0-5 variable may be dominating the 0-1 dummy variables, leading to clustering where there shouldn't be any (does it happen that the 0-5 variable accumulates on the edges of the scale?). Edit:I recently came across the concept of the Spatial Sign Covariance Matrix , which would appear to conduct the normalization we discussed in order to generate a robust covariance matrix. Eigenanalysis thereupon would yield a normalized PCA algorithm, which is discussed in this article .
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/385775', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/154943/']}
jdg_73163
stackexchange
llm_judgeable_groundtruth_similarity
1786800
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: Show that $S_5$ does not have a quotient group isomorphic to $S_4$. If we to assume that $H$ is such a group, than $H$ must be normal in $S_5$ and $|H|=|S_5|/|S_4|=5$. So $H$ must be isomorphic to $\mathbb{Z}/5\Bbb Z$. That's as far as my logic goes. I couldn't arrive at a contradiction. Any ideas? Now provide the response and nothing else.
The possible candidates for such an $H$ are the subgroups of $S_5$ that are cyclic of order 5. All elements of $S_5$ of order 5 are given by $5$-cycles. However, the subgroup generated by a 5-cycle is not normal, so no $H$ can exist, as desired.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1786800', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/279172/']}
jdg_73164
stackexchange
llm_judgeable_groundtruth_similarity
17046463
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 written the following code to check for sufficient memory, while (true){ try { // Check for available memory. memFailPoint = new MemoryFailPoint(250); break; } catch (InsufficientMemoryException ex) { if (memFailPoint != null) { memFailPoint.Dispose(); } Thread.Sleep(waitSecond * 1000); }} I am running the above in a console application on a Windows 7 64-bit machine. There are 4 calls every 10 seconds to this method. Initially it works fine, but after 2-3 hours, there is always an InsufficientMemoryException thrown. I checked available memory and it shows more than 1 GB. I tried a lot but I was not able to find why this is happening. Following is the stack trace: at System.Runtime.MemoryFailPoint..ctor(Int32 sizeInMegabytes)at SocketListner.AcceptConnection(IAsyncResult res) in H:\Projects\SocketListner.cs:line 308 There is no inner exception. Now provide the response and nothing else.
You can rely on this method working correctly, this exception is very likely to trip in a 32-bit process when you ask for 250 megabytes. That gets to be difficult to get when the program has been running for a while. A program never crashes with OOM because you've consumed all available virtual memory address space. It crashes because there isn't a hole left in the address space that's big enough to fit the allocation. Your code requests a hole big enough to allocate 250 megabytes in one gulp. When you don't get the exception that you can be sure that this allocation will not fail. But 250 megabytes is rather a lot, that's a really big array. And is very likely to fail due to a problem called "address space fragmentation". In other words, a program typically starts out with several very large holes, the largest about 600 megabytes. Holes available between the allocations made to store code and data that's used by the .NET runtime and unmanaged Windows DLLs. As the program allocates more memory, those holes get smaller. It is likely to release some memory but that doesn't reproduce a big hole. You typically get two holes, roughly half the size of the original, with an allocation somewhere in the middle that cuts the original big hole in two. This is called fragmentation , a 32-bit process that allocates and releases a lot of memory ends up fragmenting the virtual memory address space so the biggest hole that's still available after a while gets smaller, around 90 megabytes is fairly typical. Asking for 250 megabytes is almost guaranteed to fail. You will need to aim lower. You no doubt expected it to work differently, ensuring that the sum of allocations adding up to 250 megabytes is guaranteed to work. This however is not how MemoryFailPoint works, it only checks for the largest possible allocation. Needless to say perhaps, this makes it less than useful. I otherwise do sympathize with the .NET framework programmers, getting it to work the way we'd like it is both expensive and cannot actually provide a guarantee since the size of an allocation matters most. Virtual memory is a plentiful resource that's incredibly cheap. But getting close to consuming it all is very troublesome. Once you consume a gigabyte of it then OOM striking at random is starting to get likely. Don't forget the easy fix for this problem, you are running on a 64-bit operating system. So just changing the EXE platform target to AnyCPU gets you gobs and gobs of virtual address space. Depends on the OS edition but a terabyte is possible. It still fragments but you just don't care anymore, the holes are huge. Last but not least, visible in the comments, this problem has nothing to do with RAM. Virtual memory is quite unrelated to how much RAM you have. It is the operating system's job to map virtual memory addresses to physical addresses in RAM, it does so dynamically. Accessing a memory location may trip a page fault, the OS will allocate RAM for the page. And the reverse happens, the OS will unmap RAM for a page when it is needed elsewhere. You can never run out of RAM, the machine will slow down to a crawl before that can happen. The SysInternals' VMMap utility is nice to see what your program's virtual address space looks like, albeit that you tend to drown in the info for a large process.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17046463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/252975/']}
jdg_73165
stackexchange
llm_judgeable_groundtruth_similarity
2596992
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 you access a RecordSet variable inside a Script Task? Now provide the response and nothing else.
On the script tab, make sure you put the variable in either the readonlyvariables or readwritevariables text boxes. Here is a simple script that I use to format the errors in a data flow (saved in a RecordSet Variable) into the body of an email. Basically I read the recordset varialbe into a datatable and process it row by row with the for loops. After this task completes I examine the value of uvErrorEmailNeeded to determine if there is anything to email using a conditional process flow connector. You will also need to add a reference to system.xml in your vb script. This is in SQL 2005. Imports SystemImports System.DataImports System.MathImports Microsoft.SqlServer.Dts.RuntimeImports System.XmlImports System.Data.OleDbPublic Class ScriptMain Public Sub Main() Dim oleDA As New OleDbDataAdapter Dim dt As New DataTable Dim col As DataColumn Dim row As DataRow Dim sMsg As String Dim sHeader As String oleDA.Fill(dt, Dts.Variables("uvErrorTable").Value) If dt.Rows.Count > 0 Then Dts.Variables("uvErrorEmailNeeded").Value = True For Each col In dt.Columns sHeader = sHeader & col.ColumnName & vbTab Next sHeader = sHeader & vbCrLf For Each row In dt.Rows For Each col In dt.Columns sMsg = sMsg & row(col.Ordinal).ToString & vbTab Next sMsg = sMsg & vbCrLf Next Dts.Variables("uvMessageBody").Value = "Error task. Error list follows:" & vbCrLf & sHeader & sMsg & vbCrLf & vbCrLf End If Dts.TaskResult = Dts.Results.Success End SubEnd Class
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2596992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/68654/']}
jdg_73166
stackexchange
llm_judgeable_groundtruth_similarity
50061163
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 example I have two models a user and a post. A post belongs_to a user and a user has many posts #spec/factories/post.rbFactoryBot.define do factory :post do user body Faker::Movie.quote posted_at "2018-04-03 13:33:05" endend#spec/factories/user.rbFactoryBot.define do factory :user do first_name 'Jake' endend Using Rspec in a test I want to do this: user = create(:user, first_name: 'Barry') #id 1post = create(:post, user: user) I would expect that the user_id of post to be 1 however it is creating another user prior and the user_id is 2. How can you specify the association when you are creating the object with factory_bot / factory_girl? Now provide the response and nothing else.
You should use explicit associations instead of implicit ones: #spec/factories/post.rbFactoryBot.define do factory :post do association :user # <<<--- here the change body Faker::Movie.quote posted_at "2018-04-03 13:33:05" endend#spec/factories/user.rbFactoryBot.define do factory :user do first_name 'Jake' endend https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#associations
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50061163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1044281/']}
jdg_73167
stackexchange
llm_judgeable_groundtruth_similarity
26681059
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 images that are 480px wide by 640px high. I want to display them as circles on a webpage 150px wide using CSS. But I want to see the centre of the image. So take 80px of the top and bottom of the original image produces the square with the image I want to see. I then want to make that into a circle. Everything I try stretches the image as most examples are to use a square image to start with. Can any one help Now provide the response and nothing else.
You can set the image as the background of an element, set its background-size to cover , and then use border-radius to round the edges. This works with images of any aspect ratio, and will scale the image to fill the container without stretching/distorting it. #avatar { /* This image is 687 wide by 1024 tall, similar to your aspect ratio */ background-image: url('http://i.stack.imgur.com/Dj7eP.jpg'); /* make a square container */ width: 150px; height: 150px; /* fill the container, preserving aspect ratio, and cropping to fit */ background-size: cover; /* center the image vertically and horizontally */ background-position: top center; /* round the edges to a circle with border radius 1/2 container size */ border-radius: 50%;} <div id="avatar"></div>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26681059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3086854/']}
jdg_73168
stackexchange
llm_judgeable_groundtruth_similarity
24244733
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could someone explain why once is used method c(T*) and next time d<>(int*) ? methods c and d seems identical to me and I cannot figure out why is not the same type of method called. #include <iostream>using namespace std;template<typename T>void c(T){ cout <<"(T)" << endl; }template<>void c<>(int*){ cout <<"(int*)" << endl; }template<typename T>void c(T*){ cout <<"(T*)" << endl; }template<typename T>void d(T){ cout <<"(T)" << endl; }template<typename T>void d(T*){ cout <<"(T*)" << endl; }template<>void d<>(int*){ cout <<"(int*)" << endl; }int main(){ int i; c(&i); d(&i); return 0;} Output: (T*)(int*) Now provide the response and nothing else.
You just stumbled on an ugly part of C++. The overload resolution pass, during compilation, is about finding the best overload for the current code. It is executed on a set of function and function templates that was selected by the look-up phase, and aims at identifying one (and only one) overload that is better than others. For function templates, they are segregated in two groups: "base" function templates specialized function templates and the overload resolution process has two steps: Pick the best match among the regular function and "base" function templates If a "base" function template is selected by step 1., pick the best specialization (if any matches, otherwise use the "base") In both of your examples, the best "base" function is c(T*) and d(T*) , so this is the second step that differ. Why ? Because, to be a specialization of a function template, said function template has to be declared first . Thus: c<>(int*) is a specialization of c(T) d<>(int*) is a specialization of d(T*) and therefore, when c(T*) is picked in step 1., then there is no better specialization whilst when d(T*) is picked, d<>(int*) is a better specialization. Because this is tricky, the recommendation by experts... is NOT to use function template specialization. It just mixes weirdly with function template overload.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24244733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3117006/']}
jdg_73169
stackexchange
llm_judgeable_groundtruth_similarity
61749480
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 today tried to create my first airflow DAG: from datetime import timedeltafrom airflow import DAGfrom airflow.operators.bash_operator import BashOperatorfrom airflow.operators.dummy_operator import DummyOperatorfrom airflow.operators.python_operator import PythonOperatorfrom airflow.utils.dates import days_agodefault_args = { 'owner': 'default_user', 'start_date': days_ago(2), 'depends_on_past': True, # With this set to true, the pipeline won't run if the previous day failed 'email': ['[email protected]'], 'email_on_failure': True, # upon failure this pipeline will send an email to your email set above 'email_on_retry': False, 'retries': 5, 'retry_delay': timedelta(minutes=30),}dag = DAG( 'basic_dag_2', default_args=default_args, schedule_interval=timedelta(days=1),)def my_func(): print('Hello from my_func')bashtask = BashOperator( task_id='print_date', bash_command='date', dag=dag,)dummy_task = DummyOperator(task_id='dummy_task', retries=3)python_task = PythonOperator(task_id='python_task', python_callable=my_func)dummy_task.set_downstream(bashtask)python_task.set_downstream(bashtask) My Airflow is running properly on Python3.6.8, but when I try to import the dagbag into airflow it throws this exception and I rly don't know why: [2020-05-11 17:11:15,601] {scheduler_job.py:1576} WARNING - No viable dags retrieved from /root/airflow/dags/first_dag.py[2020-05-11 17:11:15,616] {scheduler_job.py:162} INFO - Processing /root/airflow/dags/first_dag.py took 0.031 seconds[2020-05-11 17:12:05,647] {scheduler_job.py:154} INFO - Started process (PID=26569) to work on /root/airflow/dags/first_dag.py[2020-05-11 17:12:05,653] {scheduler_job.py:1562} INFO - Processing file /root/airflow/dags/first_dag.py for tasks to queue[2020-05-11 17:12:05,654] {logging_mixin.py:112} INFO - [2020-05-11 17:12:05,654] {dagbag.py:396} INFO - Filling up the DagBag from /root/airflow/dags/first_dag.py[2020-05-11 17:12:05,666] {logging_mixin.py:112} INFO - [2020-05-11 17:12:05,662] {dagbag.py:239} ERROR - Failed to import: /root/airflow/dags/first_dag.pyTraceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/airflow/models/dagbag.py", line 236, in process_file m = imp.load_source(mod_name, filepath) File "/usr/lib64/python3.6/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 684, in _load File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/root/airflow/dags/first_dag.py", line 34, in <module> dag=dag, File "/usr/local/lib/python3.6/site-packages/airflow/utils/decorators.py", line 98, in wrapper result = func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/airflow/operators/bash_operator.py", line 70, in __init__ super(BashOperator, self).__init__(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/airflow/utils/decorators.py", line 98, in wrapper result = func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/airflow/models/baseoperator.py", line 422, in __init__ self.dag = dag File "/usr/local/lib/python3.6/site-packages/airflow/models/baseoperator.py", line 548, in dag dag.add_task(self) File "/usr/local/lib/python3.6/site-packages/airflow/models/dag.py", line 1301, in add_task raise AirflowException("Task is missing the start_date parameter")airflow.exceptions.AirflowException: Task is missing the start_date parameter I thought that I should give my Operators also an start_date, but they should also use the date from their DAG. Now provide the response and nothing else.
That is because two of your tasks have not been assigned to the DAG which contains the start_date in default_args . dummy_task = DummyOperator(task_id='dummy_task', retries=3, dag=dag)python_task = PythonOperator(task_id='python_task', python_callable=my_func, dag=dag) Note you can use DAG object as a context manager as mentioned in https://airflow.apache.org/docs/stable/concepts.html#context-manager to avoid repeating dag=dag for all tasks: Example: with DAG( 'basic_dag_2', default_args=default_args, schedule_interval=timedelta(days=1),) as dag: bashtask = BashOperator( task_id='print_date', bash_command='date', ) dummy_task = DummyOperator(task_id='dummy_task', retries=3) python_task = PythonOperator(task_id='python_task', python_callable=my_func) dummy_task.set_downstream(bashtask) python_task.set_downstream(bashtask)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61749480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11346290/']}
jdg_73170
stackexchange
llm_judgeable_groundtruth_similarity
74511594
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: C++ standard allows constexpr volatile variables per defect report 1688 , which was resolved in September 2013: The combination is intentionally permitted and could be used in some circumstances to force constant initialization. It looks though that the intention was to allow only constinit volatile , which was not available before C++20. Still the current compilers diverge in treatment of constexpr volatile in certain circumstances. For example, this program initializes one such variable by the other one: int main() { constexpr volatile int i = 0; constexpr volatile int j = i; return j;} It is accepted in GCC and MSVC, but Clang complains: error: constexpr variable 'j' must be initialized by a constant expression constexpr volatile int j = i; ^ ~note: read of volatile-qualified type 'const volatile int' is not allowed in a constant expression constexpr volatile int j = i; Online demo: https://gcc.godbolt.org/z/43ee65Peq Which compiler is right here and why? Now provide the response and nothing else.
Clang is correct. The initialization of j from i requires that an lvalue-to-rvalue conversion be performed on i , but according to [expr.const]/5.9, an lvalue-to-rvalue conversion on a volatile glvalue is never permitted inside a constant expression. Since i is a constexpr variable, it must be initialized by a constant expression. I have no idea why GCC and MSVC choose not to enforce this rule, other than that all C++ compilers are perpetually short-staffed and can't implement everything they're expected to.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/74511594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7325599/']}
jdg_73171
stackexchange
llm_judgeable_groundtruth_similarity
463707
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 haven't play enough with this and usually use mocks, but I wonder what are the differences between this two and when to use one or the other on Rhino Mocks. Update: I also found the answer to my question in Ayende's words : The difference between stubs and mocks You can get the actual definition of the these terms in this article: Mocks Aren't Stubs . I want to focus on the difference from the point of view of Rhino Mocks. A mock is an object that we can set expectations on, and which will verify that the expected actions have indeed occurred. A stub is an object that you use in order to pass to the code under test. You can setup expectations on it, so it would act in certain ways, but those expectations will never be verified. A stub's properties will automatically behave like normal properties, and you can't set expectations on them. If you want to verify the behavior of the code under test, you will use a mock with the appropriate expectation, and verify that. If you want just to pass a value that may need to act in a certain way, but isn't the focus of this test, you will use a stub. IMPORTANT: A stub will never cause a test to fail. Now provide the response and nothing else.
As per this ... Put simply there is a difference between Mock and Stub objects and RhinoMocks recognizes that allowing us to write tests that better state their purpose. Mock objects are used to define expectations i.e: In this scenario I expect method A() to be called with such and such parameters. Mocks record and verify such expectations. Stubs, on the other hand have a different purpose: they do not record or verify expectations, but rather allow us to “replace” the behavior, state of the “fake”object in order to utilize a test scenario ...
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/463707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1560/']}
jdg_73172
stackexchange
llm_judgeable_groundtruth_similarity
29111
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a bash script, and need to ask user for his password and pass it to openssl . Whilst openssl can read the password itself, I need for two runs of the program and don't want to ask the user twice. Here is the script: cp file{,.old}read -sp 'Enter password. ' PASS; echoexport PASS# decode | edit | encodeopenssl enc -d -aes-256-cbc -k "$PASS" -in file.old | \ sed ... | openssl enc -e -aes-256-cbc -k "$PASS" -out fileunset PASS This is not safe as the password is easily available by looking at the command line; somebody can read it using ps , for example. openssl can read a password from an environment variable, so I can replace -k "$PASS" with -pass env:PASS , but it's still not safe; the environment variables of any process can be read freely (again, ps can do it). So, how can I safely pass the password to the two openssl instances? Now provide the response and nothing else.
Pass the password on a separate file descriptor from the input (twice, once for encryption and once for decryption). Do not export PASS to the environment. read -sp 'Enter password. ' PASSprintf '%s\n' "$PASS" |openssl enc -d -aes-256-cbc -kfile /dev/stdin -in file.old |sed ... | { printf '%s\n' "$PASS" | openssl enc -e -aes-256-cbc -kfile /dev/stdin -in /dev/fd/3 -out file;} 3<&0 If your system doesn't have /dev/fd , you can use the -pass argument to tell openssl to read the passphrase from an open file descriptor. printf '%s\n' "$PASS" | { printf '%s\n' "$PASS" | openssl enc -d -aes-256-cbc -pass fd:0 -in file.old | tr a-z A-Z | tee /dev/tty | { openssl enc -e -aes-256-cbc -pass fd:3 -out file; }} 3<&0
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/29111', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']}
jdg_73173
stackexchange
llm_judgeable_groundtruth_similarity
4008279
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 structure: public enum MyTypes{ Type1 = 1, Type2 = 2, Type3 = 3}public abstract class class1{ int id; string name; MyType type;}public class class2 : class1{}public class class3 : class1{}public class class4 : class1{} now what I want to do is to make a generic method , I want to give it the type of object say class 3 and it will create object from class 3 and define it's variables and return it to be able to add it to a list of class1 like that private class1 myFunction (MyType t , int id , string name){ T obj = new T(); obj.type = t ; obj.id = id ; obj.name = name; return obj;} how to create this generic method ? please Help me as soon as you can Thanks in Advance Now provide the response and nothing else.
As Danny Chen says in his answer, you will have to modify your class definitions a little for it to work, then you could do something like the following: public T myFunction<T>(int id, string name) where T : class1, new(){ T obj = new T(); obj.id = id; obj.name = name; return obj;} This generic method requires type parameter T to be derived from class1 and also to have a parameter-less constructor -- that's what the where T : class1, new() means. Since id and name properties are defined through the class1 base class, you can then set these to whatever was passed into myFunction via its parameters. Some more things to note about class1 : Consider making class1 an interface instead of an abstract class, as it doesn't contain any functionality. id , name , type need to be public if you actually want to be able to access them. Usually, fields aren't actually exposed as public . Consider using properties instead for that purpose.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4008279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/458700/']}
jdg_73174
stackexchange
llm_judgeable_groundtruth_similarity
2639243
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: For simplicity's sake, let the Earth be a perfect sphere. Imagine you are drawing an equilateral triangle over its surface. How long should its sides be, for the sum of its angles to be 180.1 degrees? Now provide the response and nothing else.
The area of a spherical triangle is exactly $ER^2$ where $E$ is the angular excess. In our case $E=\frac{\pi}{1800}$, so the given triangle covers $\frac{1}{7200}$ of Earth's surface. Assuming $R=1$, l'Huilier's formula (page 184 of my notes) relates the angular excess / the area to the semiperimeter / the side lengths through$$ \tan\frac{E}{4}=\sqrt{\tan\frac{s}{2}\tan\frac{s-a}{2}\tan\frac{s-b}{2}\tan\frac{s-c}{2}} $$and in our case we have $a=b=c=\ell$ and $s=\frac{3}{2}\ell$, so $$ E = \frac{\pi}{1800} = 4\arctan\sqrt{\tan\frac{3\ell}{4}\tan^3\frac{\ell}{4}} $$and by solving$$ \tan\frac{3\ell}{4}\tan^3\frac{\ell}{4}=\tan^2\frac{\pi}{7200} $$we get that $\ell$ is approximately $6.347\%$ of the radius $R$. For Earth, $R =6\ 371$ km, and $\ell = 404.377$ km.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2639243', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/528859/']}
jdg_73175
stackexchange
llm_judgeable_groundtruth_similarity
31645341
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to create a heredoc that does not become subject to variable expansion? e.g. cat <<-EOF > somefile.shDo not print current value of $1 instead evaluate it later.EOF Update I am aware of escaping by \ . My actual heredoc has many variables in it - and it is error prone and tedious to escape all of them. Now provide the response and nothing else.
Quote the delimiter: cat <<-"EOF" > somefile.shDo not print current value of $1 instead evaluate it later.EOF This results in: $ cat somefile.sh Do not print current value of $1 instead evaluate it later. Documentation The format of here-documents is: <<[-]word here-document delimiter No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \ is ignored, and \ must be used to quote the characters \, $, and `. If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion. [Emphasis added.]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31645341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1056563/']}
jdg_73176
stackexchange
llm_judgeable_groundtruth_similarity
29390663
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Noob here, I'm trying to compile this segment of code from Bjarne Stroustrup's 'The C++ Programming Language' but CodeBlocks keeps throwing me this error. The code is about range checking an array held in a vector function. Here is the code: #include <iostream>#include <vector>#include <array>using namespace std;int i = 1000;template<class T> class Vec : public vector<T>{public: Vec() : vector<T>() { } T& operator[] (int i) {return at(i); } const T& operator[] (int i) const {return at(i); } //The at() operation is a vector subscript operation //that throws an exception of type out_of_range //if its argument is out of the vector's range.};Vec<Entry> phone_book(1000);int main(){ return 0;} The errors returned are: there are no arguments to 'at' that depend on a template parameter, so a declaration of 'at' must be available note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated In member function 'const T& operator[] (int i) const': there are no arguments to 'at' that depend on a template parameter, so a declaration of 'at' must be available 'Entry' was not declared in this scope template argument 1 is invalid invalid type in declaration before '(' token Can someone explain this to me? Also, how would I implement this if I were to not use 'using namespace std;' Now provide the response and nothing else.
Replace at with vector<T>::at or this->at . Rules for how functions are looked up in templates are tighter now than when C++ was being originally designed. Now, methods in dependent bases are only looked up if you this-> , otherwise it is assumed to be a global function (or a non-dependent base/class local/etc). This can help avoid nasty surprises in practice, where what you thought was a method call becomes a global one, or a global call becomes a method call. It also allows earlier checking of template method bodies.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29390663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4628738/']}
jdg_73177
stackexchange
llm_judgeable_groundtruth_similarity
40444540
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible in CSS to add color to a black & white image using a filter? I'm talking about using filters like it's possible in Photoshop, and an even better example would be the ones in Microsoft PowerPoint. What I'm trying to do is this:I have an image file of a black icon.I want to add a filter to it such that everything in the image (the background is transparent) will have the color I choose by using the filter, such that I'd be able to have the icon in whatever color I want.Like I said in the title, it's a PNG image, so as far as I know, I can't use SVG filters. How can I do this? I'm trying to write a theme for a website using the original icons, and I'm stuck on this. Update: I want to use the original PNG images. I'm not going to replace them with SVGs, or pre-edited PNGs. Thanks a lot in advance! Now provide the response and nothing else.
You can do it with CSS filters, though I wouldn’t recommend that at all: .colorizable { filter: /* for demonstration purposes; originals not entirely black */ contrast(1000%) /* black to white */ invert(100%) /* white to off-white */ sepia(100%) /* off-white to yellow */ saturate(10000%) /* do whatever you want with yellow */ hue-rotate(90deg);}.example-clip { display: block; height: 20px; margin: 1em; object-fit: none; object-position: 0 0; width: 300px;}.original { filter: contrast(1000%);}body { background: #333;} <img class="colorizable example-clip" src="https://cdn.sstatic.net/Sites/stackoverflow/img/wmd-buttons.svg" /><img class="original example-clip" src="https://cdn.sstatic.net/Sites/stackoverflow/img/wmd-buttons.svg" />
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40444540', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5094787/']}
jdg_73178
stackexchange
llm_judgeable_groundtruth_similarity
190083
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: When doing an Nmap scan from an external network, what open ports should be an instant red flag?For example, if I was in the open internet and scanned www.somewebsite.com, besides port 22 , what other open ports should I be on the lookout for? Now provide the response and nothing else.
To echo gameOver's comment and elaborate further, simply detecting that a port is open is interesting but I wouldn't see it as an immediate 'red flag'. Perhaps a better approach might be to run Nmap with the -sV or -sC flags which will either run a service/version scan or launch the default NSE (Nmap Scripting Engine) scripts against the target port that you've deemed interesting, provided you have the proper authorization to do so. So, for example let's say you discovered that port 21 is open, which is interesting, but it only becomes a potential attack vector when you can enumerate the service running behind it. Once you discover the specific service you can begin searching CVEs and gain a better understanding if there is a vulnerability tied to it. By running a script-scan, the NSE will test your specific port in question and will output its findings, this might include (for port 21) an anonymous FTP login misconfiguration that allows for read/write access. Now, after further enumeration of the service running behind port 21, you have a potential attack vector. As a final note, there are some known ports where specific types of malware have a history of using, but these can also be false positives as I could simply run my SSH client out of TCP port 31337. You might see this port as open and immediately think Back Orifice! Instead I'm just running SSH using an unusual port to do so. Sources: https://nmap.org/nsedoc/scripts/
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/190083', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/173015/']}
jdg_73179
stackexchange
llm_judgeable_groundtruth_similarity
82642
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I evaluate $$\int_{-\infty}^\infty {\exp(ixk)\over -x^2+2ixa+a^2+b^2} dx,$$ where $k\in \mathbb R, a>0$? Would Fourier transforms simplify anything? I know very little about complex analysis, so I am guessing there is a rather simple way to evaluate this? Thanks. Now provide the response and nothing else.
You can evaluate this using the residue theorem . The integrand has simple poles at $x_\pm=\mathrm ia\pm b$ (which you can find by setting the denominator zero and solving the quadratic equation). You can find the residues at the poles by multiplying the integrand by $x-x_\pm$ and then substituting $x_\pm$, which yields $$\left.-\frac{\exp(\mathrm ixk)}{x-(\mathrm ia\mp b)}\right|_{x=\mathrm ia\pm b}=\mp\exp(-ka)\frac{\exp(\pm\mathrm ikb)}{2b}\;.$$ If $k\gt 0$, You can complete the integral by a half circle at infinity in the upper half-plane (which contains the poles), since the integrand decays quadratically with $x\to\pm\infty$ and exponentially with $x\to\mathrm i\infty$, so the contribution from this half circle vanishes. Thus by the residue theorem the given integral is $2\pi\mathrm i$ times the sum of the residues, that is, $$2\pi\mathrm i\left(-\exp(-ka)\frac{\exp(\mathrm ikb)}{2b}+\exp(-ka)\frac{\exp(-\mathrm ikb)}{2b}\right)=2\pi\exp(-ka)\frac{\sin(kb)}b\;.$$ If $k\le0$, you can complete the integral by a half circle at infinity in the lower half-plane, since the integrand decays quadratically (or exponentially for $k\lt0$) and the perimeter of the half circle increases linearly. There are no poles in the lower half-plane, so in this case the integral is zero.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/82642', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19544/']}
jdg_73180
stackexchange
llm_judgeable_groundtruth_similarity
89504
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'm looking for a quick way to compute the Pontryagin dual group of the n-dimensional torus $\mathbb{T}^n$ (with $\mathbb{T} := \mathbb{R} / \mathbb{Z}$). The only way I know is from "Dikran Dikranjan - Introduction to Topological Groups" and is very tedious. I thought so: $\mathbb{T}^n$ is compact then $\widehat{\mathbb{T}^n}$ has the discrete topology. The set $E$ of all the functions $\mathbb{T}^n \to \mathbb{C} : x \mapsto e^{2 \pi a \cdot x}$ with $a \in \mathbb{Z}^d$ is a subset of $\widehat{\mathbb{T}^d}$ which separates the points of $\mathbb{T}^d$ (I mean: forany $x,y \in \mathbb{T}^d$ with $x \neq y$ exists some $\chi \in E$ such that $\chi(x) \neq \chi(y)$. Now I was hoping that Stone-Weierstass theorem could help me to prove that $E$ is dense in $\widehat{\mathbb{T}^d}$ and so that $\widehat{\mathbb{T}^d} = E$, because $\widehat{\mathbb{T}^d}$ is discrete. However I don't know how to apply Stone-Weierstass theorem in this case. I thank you for any ideas! Now provide the response and nothing else.
The key case is the 1-dimensional torus. We want to show every continuous homomorphism $\chi \colon {\mathbf R}/{\mathbf Z} \rightarrow {\mathbf T}$ has the form $x \bmod {\mathbf Z} \mapsto e^{2\pi inx}$ for some integer $n$. Any character of ${\mathbf R}/{\mathbf Z}$ can be pulled back to a character of ${\mathbf R}$ by composing with the canonical map ${\mathbf R} \rightarrow {\mathbf R}/{\mathbf Z}$. Let $\chi' \colon {\mathbf R} \rightarrow {\mathbf T}$ be the resulting character of ${\mathbf R}$, i.e., $\chi'(x) = \chi(x \bmod {\mathbf Z})$. All continuous homomorphisms ${\mathbf R} \rightarrow {\mathbf T}$ have the form $x \mapsto e^{2\pi ixy}$ for some real number $y$. Accepting this for a moment, we'd have $\chi'(x) = e^{2\pi ixy}$ for some $y$. Thus $\chi(x \bmod {\mathbf Z}) = e^{2\pi ixy}$. Taking $x = 1$, we get $1 = e^{2\pi iy}$. Therefore $y$ is an integer. Writing $y$ as $n$, for psychological purposes, $\chi(x \bmod {\mathbf Z}) = e^{2\pi inx}$ for an integer $n$, which is what you wanted. Our task now is to compute the characters of ${\mathbf R}$. For this I like the method from Conway's "A Course in Functional Analysis". For any continuous homomorphism $\gamma \colon {\mathbf R} \rightarrow {\mathbf T}$, we want to show $\gamma(x) = e^{2\pi ixy}$ for some real number $y$. We will use differential equations. Because $\gamma(0) = 1$, by continuity $\int_0^a \gamma(t)dt \approx a$ for small positive $a$, so $\int_0^a\gamma(t)dt \not= 0$ for an appropriate $a$. Fixing such $a$, for all real $x$ we have $$\int_x^{x+a} \gamma(t)dt = \int_0^a \gamma(t+x)dt = \int_0^a \gamma(t)\gamma(x)dt = \gamma(x)\int_0^a \gamma(t)dt.$$ Therefore$$\gamma(x) = \frac{\int_x^{x+a} \gamma(t)dt}{\int_0^a\gamma(t)dt}.$$The right side, by the fundamental theorem of calculus, is a differentiable function of $x$, and therefore $$\gamma'(x) = \frac{\gamma(x+a) - \gamma(x)}{\int_0^a\gamma(t)dt} = \frac{\gamma(a)-1}{\int_0^a\gamma(t)dt}\gamma(x), $$so $\gamma'(x) = s\gamma(x)$ for a complex number $s$. By the theory of ODE, $\gamma(x) = Ce^{sx}$. Since $\gamma(0) = 1$, we have $C = 1$, so $\gamma(x) = e^{sx}$. Since $|\gamma(x)| = 1$, we have $e^{{\rm Re}(s)x} = 1$ for all real $x$, so ${\rm Re}(s) = 0$. Write $s = 2\pi iy$ for a real number $y$ and we're done. I don't think you're going to find a 2-line proof of the computation of the character group of ${\mathbf R}/{\mathbf Z}$ or ${\mathbf R}$ because you need to get exponential functions from somewhere. Above we get them from our knowledge of solutions to the most basic first-order ODE, and to bring in an ODE we needed a clever idea to see that the a priori continuous function $\gamma$ is in fact differentiable.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/89504', 'https://mathoverflow.net', 'https://mathoverflow.net/users/21706/']}
jdg_73181
stackexchange
llm_judgeable_groundtruth_similarity
20781
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider a random sample from a distribution with the p.d.f. (for some $c > 0$) \begin{equation} f(x) = cx^2 (1 − x), \text{if } 0 < x < 1; \end{equation} \begin{equation} 0, \text{ elsewhere}. \end{equation} What is an approximate distribution of $\bar{X}_n$ ? For a sample of size 45, find approximate mean and variance for $\bar{X}_n$ ? Find an approximate distribution of $\bar{X}^3_n$. How should I go about solving this problem ? More importantly, I'd like to have an intuition of this question. I'm new to statistics so more details would help me more. This may be naive/dumb but we know that we are taking a sample from uniform distribution and why would we want to find its distribution again and how is it leading to an another distribution ? I'm very confused. Now provide the response and nothing else.
First of all, the p.d.f $f$ corresponds to a beta distribution with parameters $\alpha=3$ and $\beta=2$ (hence, not a uniform distribution). Now, by the central limit theorem, $\frac{{\sum\nolimits_{i = 1}^n {X_i } - n \mu }}{{\sigma \sqrt n }}$ converges in distribution to the ${\rm N}(0,1)$ distribution, where $\mu = {\rm E}(X_1)$ and $\sigma^2 = {\rm Var}(X_1)$. This means that, for $n$ sufficiently large (for example, $n=45$), we may write $\sum\nolimits_{i = 1}^n {X_i } \approx n \mu + \sigma \sqrt n Z$, where $Z \sim {\rm N}(0,1)$. Dividing by $n$ thus gives $\bar X_n \approx \mu + (\sigma/{\sqrt{n}})Z$. Thus, $\bar X_n$ is approximated by the normal distribution with mean $\mu$ and small variance $\sigma^2/n$ (this is exactly the distribution of the right-hand side, $\mu + (\sigma/{\sqrt{n}})Z$). As for the mean and variance of $\bar X_n$, this is a simple exercise, and you should be able to show that the mean is $\mu$ and the variance is $\sigma^2/n$. Finally, to find approximate distribution of $\bar X_n^3$, you may use the approximation $\bar X_n \approx \mu + (\sigma/{\sqrt{n}})Z$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/20781', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6335/']}
jdg_73182
stackexchange
llm_judgeable_groundtruth_similarity
20433364
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 make something like this: if(day==1 || day==11 || day==21 || day==31 || day==41 ......){ result="dan";}else{ result="dana";} How can i do that with every number that ends with one and of course without writing all numbers? Now provide the response and nothing else.
Just check the remainder of division by 10: if (day % 10 == 1) { result = "dan";} else { result = "dana";} % is the "Modulo" or "Modulus" Operator, unless you're using JavaScript, in which case it is a simple remainder operator ( not a true modulo ). It divides the two numbers, and returns the remainder.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20433364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2766386/']}
jdg_73183
stackexchange
llm_judgeable_groundtruth_similarity
35616661
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 refer to below question, but with a bit difference. I need to only get line that has "abc" when there is "efg" matching at different line. And I only need the latest matched "abc" line before "efg" is matched... How to find patterns across multiple lines using grep? blah blah..blah blah..blah abc blah1blah blah..blah blah..blah abc blah2blah blah..blah efg1 blah blahblah efg2 blah blahblah blah..blah blah..blah abc blah3blah blah..blah blah..blah abc blah4blah blah..blah blah blahblah abc blah5blah blah..blah blah..blah abc blah6blah blah..blah efg3 blah blahblah efg4 blah blahblah abc blah7blah blah..blah blah..blah abc blah8blah blah.. Expected output blah abc blah2blah abc blah6 Now provide the response and nothing else.
You cannot update glibc on Centos 6 safely. However you can install 2.14 alongside 2.12 easily, then use it to compile projects etc. Here is how: mkdir ~/glibc_install; cd ~/glibc_installwget http://ftp.gnu.org/gnu/glibc/glibc-2.14.tar.gztar zxvf glibc-2.14.tar.gzcd glibc-2.14mkdir buildcd build../configure --prefix=/opt/glibc-2.14make -j4sudo make installexport LD_LIBRARY_PATH=/opt/glibc-2.14/lib
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35616661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3663854/']}
jdg_73184
stackexchange
llm_judgeable_groundtruth_similarity
846235
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: X and Y are iid with density $f(x)=\frac{1}{(1+x)^2}I_{(0,\infty)}$. Find $P(Z\le z)$ where $Z=XY+X+Y+1$ my effort:$P(Z\le z)=P((x+1)(y+1)\le z)=P(x\le \frac{z}{y+1}-1)=\int_{0}^{\infty}\int_{0}^{\frac{z}{y+1}-1}\frac{1}{(1+x)^2}dxdy=\int_{0}^{\infty}1-\frac{y+1}{z}dy=...?$ If I integrate it once more the result is $\infty$, which is obviously wrong - where have I done a mistake? Now provide the response and nothing else.
Note that $y = \dfrac{z}{x+1}-1 \le z-1$ for any value of $x \ge 0$. So, the bounds for the integrals should be $0 \le y \le z-1$ and $0 \le x \le \dfrac{z}{y+1}-1$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/846235', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/46355/']}
jdg_73185
stackexchange
llm_judgeable_groundtruth_similarity
36503224
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 navigation controller intermittently will freeze on push. It seems to add the new view controller onto the stack, but the animation never takes place. I also have two other containers that hold view controllers on the screen, and I can interact with both of them just fine after the navigation controller freezes. The really interesting thing is if I try to push another view controller onto the navigation controller's stack, I noticed that there is an extra view controller on top of the stack (the view controller that I pushed initially that froze the navigation controller). So if I'm on the home screen (we'll call it VC-Home) and I try to push a new view (VC-1) and it freezes, then I try to push a new view (VC-2), this is what I see in the current stack before the push: { [VC-Home, VC-1] } and after pushViewController is called, it remains the same; VC-2 is not added to the stack. From what I can tell, the navigation controller starts the animation by making the previous view controller inactive before the animation begins, but then the animation never takes place, leaving the navigation controller in a frozen state. I'm creating the new view controller from a storyboard by calling UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ViewController") so I don't think there's any issues there. I'm also not overriding pushViewController on the navigation bar. Some unique things about my app is that it is very high-res image heavy (using SDWebImage to manage that) and I always have three containers on the screen at once (one navigation controller, one view controller for search, and one interactive gutter/side/slideout menu). CPU usage is low and memory usage is normal (steadily around 60-70MB on device when freezes occur). Are there any ideas with what might be causing this or any debugging tips that could help me discover the real problem? Update There's no unique code for the UINavigationController since I'm just pushing using pushViewController(). Here's the code that calls it: func didSelectItem(profile: SimpleProfile) { let vc = UIStoryboard.profileViewController() vc.profile = profile navigationController?.pushViewController(vc, animated: true)} The ViewController that I pushed has the following code in viewDidLoad: override func viewDidLoad() { super.viewDidLoad() button.roundView() if let type = profile?.profileType { //load multiple view controllers into a view pager based on type let viewControllers = ProfileTypeTabAdapter.produceViewControllersBasedOnType(type) loadViewPagerViews(viewControllers) let topInset = headerView.bounds.height + tabScrollView.contentSize.height if let viewPager = viewPager { for view in viewPager.views { if let tempView = view as? PagingChildViewController { tempView.profile = fullProfile tempView.parentVCDelegate = self tempView.topInset = topInset } } } }}func loadViewPagerViews(viewControllers: [UIViewController]) { viewPager?.views = viewControllers viewPager?.delegate = self //loading views into paging scroll view (using PureLayout to create constraints) let _ = subviews.map { $0.removeFromSuperview() } var i = 0 for item in views { addSubview(item.view) item.view.autoSetDimensionsToSize(CGSize(width: tabWidth, height: tabHeight)) if i == 0 { item.view.autoPinEdgeToSuperviewEdge(.Leading) } else if let previousView = views[i-1].view { item.view.autoPinEdge(.Leading, toEdge: .Trailing, ofView: previousView) } if i == views.count { item.view.autoPinEdgeToSuperviewEdge(.Trailing) } i += 1 } contentSize = CGSize(width: Double(i)*Double(tabWidth), height: Double(tabHeight))} Update 2 I finally got it to freeze again. The app was in the background and I brought it back and tried pushing a view controller on the stack when it froze. I noticed an animation was taking place. I have a scrollview at the top of the page that pages through its content every 10 seconds (think of the app stores top banner). On this freeze, I noticed that the banner was mid-animation. Here's the scrolling function from the my UIScrollView that gets called every 10 seconds: func moveToNextItem() { let pageWidth: CGFloat = CGRectGetWidth(frame) let maxWidth: CGFloat = pageWidth * CGFloat(max(images.count, profileImages.count)) let contentOffset: CGFloat = self.contentOffset.x let slideToX = contentOffset + pageWidth //if this is the end of the line, stop the timer if contentOffset + pageWidth == maxWidth { timer?.invalidate() timer = nil return } scrollRectToVisible(CGRectMake(slideToX, 0, pageWidth, CGRectGetHeight(frame)), animated: true)} I don't recall ever having a push stop because of an animation/scroll taking place, but I could be wrong. I've also rechecked the stack and the same situation as described above is still the case where [VC-Home, VC-1] is the stack and VC-2 is not pushed on. I've also gone through VC-1's variables and everything has loaded (data calls and image loads). Update 3 This is getting stranger by the second. I've overriden pushViewController so I can put a breakpoint in there and do some debugging based on Alessandro Ornano's response. If I push a view controller unsuccessfully, then send my app to the background, put a breakpoint into the pushViewController call, and bring the app back, the breakpoint is immediately hit a number of times. If I then continue past all the hits, the next view controller suddenly becomes visible and the last view controller I tried to push is now on the stack as the last view controller. This means that the one that I see is still disabled, which essentially puts me in the same position as before. Now provide the response and nothing else.
We have faced the same problem couple of weeks back. And for our problem we narrowed it down to left-edge pop gesture recogniser . You can try and check if you can reproduce this problem using below steps Try using the left edge pop gesture when there are no view controllers below it (i.e on root view controllers, your VC-Home controller) Try clicking on any UI elements after this. If you are able to reproduce the freeze, try disabling the interactivePopGestureRecognizer when the view controller stack have only one view controller. Refer to this question for more details. Below is the code from the link for ease of reference. - (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animate{ if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]){ if (self.viewControllers.count > 1) { self.interactivePopGestureRecognizer.enabled = YES; } else { self.interactivePopGestureRecognizer.enabled = NO; } }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36503224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1102687/']}
jdg_73186
stackexchange
llm_judgeable_groundtruth_similarity
240848
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was reading this question on Stack Exchange Workplace community and it indicates that an IT team was able to prevent a user from turning their laptop on (power on). My laptop access has been shut off (IT somehow remotely shut it down,it won't power on), company cell doesn't work, can't access e-mail viawebmail. I know that an IT system administrator can prevent a user from logging in. But, is this possible? If it is, what are technologies that can be used to do something like this? Linked question: https://workplace.stackexchange.com/q/166838/86347 Now provide the response and nothing else.
Out-of-band management Intel Management Engine and amd DASH are separate microprocessors that remotely manage enterprise PCs. They run with Ring -3 privilege on the machine and run outside of host OS. It can lock stolen devices, remotely erase data, track location, wake on LAN and wake on wireless LAN , control host OS and detect third party live USB boots. It is capable of accessing any memory region without the main x86 CPU knowing about the existence of these accesses. It also runs a TCP/IP server on your network interface and packets entering and leaving your machine on certain ports bypass any firewall running on your system. [1] As it requires a power source, in enterprise Desktops, keeping the switch on is enough for motherboard to draw power as shutting down the host OS does not shut down the AC power supply to the power supply unit of the motherboard. There is no way to disable it from UEFI. Removing the microprocessor or modifying its firmware which is stored in UEFI will prevent system to boot. Disabling secure boot or using custom UEFI keys will not disable its firmware verification. This is how Intel verifies it, amd's implementation could be different: The ME firmware is verified by a secret boot ROM embedded in the chipset that first checks that the SHA256 checksum of the public key matches the one from the factory, and then verifies the RSA signature of the firmware payload by recalculating it and comparing to the stored signature. This means that there is no obvious way to bypass the signature checking, since the checking is done by code stored in a ROM buried in silicon, even though we have the public key and signature. [1] Once stolen devices are locked, they don't respond to power button signal. In old motherboards with BIOS, they used to respond but immediately shut themselves down. Consumer PCs also have Intel Management Engine microprocessor and Intel Management Engine Interface driver pre-installed in Windows but Intel Active Management Technology software is not installed by OEMs in consumer PCs. Can it be reversed, or will this brick the device? If the device is locked by the remote administrator, it can unlock it using wake on LAN and a specific unlock instruction to the chip. This is how my organisation used to handle enterprise laptops with sensitive data. The chip is bounded with its firmware in UEFI, hardcoded with chipmaker's public key and is probably hardwired to the motherboard in order to brick the device if chip is removed. Intel is secretive about its implementation. That didn't stop researchers to partially disable it from its firmware: Disable Intel’s Backdoor On Modern Hardware (2020) Researchers discovered an undocumented configuration setting that can used to disable the Intel ME master controller that has been likened to a backdoor. (2017) Out-of-band management [1] Intel x86s hide another CPU that can take over your machine (you can't audit it)
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/240848', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/176981/']}
jdg_73187
stackexchange
llm_judgeable_groundtruth_similarity
23019384
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a pretty common problem but I haven't yet found the exact question and answer I'm looking for. I have one table that has a FK pointing to its own PK, to enable an arbitrarily deep hierarchy, like the classic tblEmployee that has a column Manager that is a FK with the PK tblEmployee.EmployeeID. Let's say in my app, the user Creates new employees Alice and Dave, with no manager because they're the CEO and President. So tblEmployee.Manager is NULL for those two records. Create new employee Bob, with Alice as manager. Then create Charles with Bob as his manager. Their Manager fields contain the Primary Key value of another record in tblEmployee . Edit employee record for Alice, meaning to assign Dave has her manager (which would be fine) but accidentally set Alice's manager to be Charles, who is two levels down from Alice in the tree. Now the table is in a circular reference instead of a proper tree. What is the best way to make sure that Step 3 cannot be done in an application? I just need to make sure that it will refuse to do that last SQL update, and instead show some error message. I'm not picky about whether it's a database constraint in SQL Server (has to work in 2008 or 2012) or with some kind of validation routine in the business logic layer of my C# app. Now provide the response and nothing else.
You can do this with a CHECK CONSTRAINT that validates manager id is not a cycle. You can't have complex queries in a check constraint, but if you wrap it in a function first you can: create function CheckManagerCycle( @managerID int )returns intasbegin declare @cycleExists bit set @cycleExists = 0 ;with cte as ( select E.* from tblEmployee E where ID = @managerID union all select E.* from tblEmployee E join cte on cte.ManagerID = E.ID and E.ID <> @managerID ) select @cycleExists = count(*) from cte E where E.ManagerID = @managerID return @cycleExists;end Then you can use a constraint like this: alter table tblEmployeeADD CONSTRAINT chkManagerRecursive CHECK ( dbo.CheckManagerCycle(ManagerID) = 0 ) This will prevent adding or updating records to create a cycle from any source. Edit: An important note: check constraints are validated on the columns they reference. I originally coded this to check cycles on the Employee ID, rather than the Manager ID. However, that did not work because it only triggered on changes to the ID column. This version does work because it is triggered any time the ManagerID changes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23019384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241201/']}
jdg_73188
stackexchange
llm_judgeable_groundtruth_similarity
13064406
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 plot real-time graph, with time axis, but I have found the LineChart constructor only has the signature. LineChart(Axis<X> xAxis, Axis<Y> yAxis) I think embedding jfree chart in javafx is not a proper solution. I want a few of the jfree features in a javafx LineChart , is this possible? Now provide the response and nothing else.
Download Ensemble sample from http://www.oracle.com/technetwork/java/javafx/samples/index.html There are several examples in it for dynamic charts, e.g. "Advanced Stock Line Chart". You can take a look at their source code directly in the application. To show time on axis you can use string and DateFormatter: BarChart<String, Number> chart = new BarChart<>(new CategoryAxis(), new NumberAxis()); final XYChart.Series<String, Number> series1 = new XYChart.Series<>(); chart.getData().addAll(series1); SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); Date date = new Date(); for (int i = 0; i <= 10; i += 1) { date.setTime(date.getTime() + i * 11111); series1.getData().add(new XYChart.Data(dateFormat.format(date), Math.random() * 500)); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13064406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/868300/']}
jdg_73189
stackexchange
llm_judgeable_groundtruth_similarity
2229835
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to figure out if it's possible to define a linear transformation for every pair of n dimensional vector spaces. My thought process has led me to a possible contradiction to this in using the zero vector. Is it possible to map the zero vector to any other vector? Now provide the response and nothing else.
Is it possible to map the zero vector to any other vector? No, that's not possible. It follows from the (definition of) linearity, that the zero vector must be mapped to the zero vector. Let $T:V \to W$ be a linear transformation between vector spaces $V$ and $W$ over some field $K$, then you have for any scalar $\alpha \in K$ and ${\bf 0_V} \in V$:$$T\left(\alpha \cdot{\bf 0_V}\right)=\alpha \,T\left({\bf 0_V}\right)\implies T\left({\bf 0_V}\right)=T\left(0 \cdot{\bf 0_V}\right)=0 \,T\left({\bf 0_V}\right)= {\bf 0_W}$$ I'm trying to figure out if it's possible to define a linear transformation for every pair of n dimensional vectors. I assume you meant to say: define a linear transformation between two arbitrary $n$-dimensional vector spaces (over the same field - see comment by celtschk below). The answer is then yes and the dimensions needn't even be the same... With the notation above, define $T$ as:$$T : V \to W : {\bf v} \mapsto {\bf 0_W}$$The transformation that trivially maps every element ${\bf v} \in V$ to the zero vector ${\bf 0_W} \in W$. You can easily verify that this is indeed a linear transformation, though perhaps a boring one :-).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2229835', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/388463/']}
jdg_73190
stackexchange
llm_judgeable_groundtruth_similarity
133012
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: eight 300GB SAS drives are available. Can ESX be put on one disk as RAID-0 and others as RAID-5 ? so that in the event of disk failure data (VMs) are safe.if os disk RAID-0 fails could that be installed on replacement disk and still be able to keep VMs running? if not RAID-1 for OS is only option for OS disk? please suggest any other RAID options. All: many thanks for your responses. the question that remains is which RAID? my situation: at max handle 1 disk failure be more storage efficient (less disk cost) better I/O write perf if esxi 4 can handle locking better (Chopper) then why not RAID-6 or 5 for all 8 disks instead of separating OS and data volumes? does this provide ability replace failed disk and continue since OS is now mixed up with data? How good is RAID-50? is it better than RAID-5? Now provide the response and nothing else.
What's wrong with just R10'ing all 8 drives into a single logical disk (LD) of ~1.2TB, it'll be faster and a lot more resilient than your R0+R5 suggestion and gives you the same available space as Tom's R1+R6 suggestion (sorry Tom, you know I love you right). There's no need to have the OS on a different disk than the VMs at all, especially if you're using v4 as it handles locking much better. EDIT FOLLOWING QUESTION EDIT Basically you can't have it all, let's look at your newly-added criteria; You're happy to live with loss of drives if more than 1 disk fails - well fair enough, in that case anything but R0 will work for you. You want as much space as possible - given we've ruled out R0 then R5 will clearly give you the most space, followed by R6 then R10. You want good write performance - well R6 is significantly slower than R5 which in turn is slower than R10. If you have a single logical disk array for both the OS and VMs then losing the LD will kill your host, but then so would losing a VM-only logical disk - all your VMs would stop if either LD failed. The difference would be you wouldn't have to reinstall ESX/i again if you only lost a VM-only LD, but then again reinstalling the OS doesn't take long at all, plus it can be backed up. Given you'll lose 600GB if your R1 one them then I'd stick with either R10 or R5 myself.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/133012', 'https://serverfault.com', 'https://serverfault.com/users/32465/']}
jdg_73191
stackexchange
llm_judgeable_groundtruth_similarity
3607691
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 structure of my entities: @MappedSuperclasspublic abstract class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqGenerator") private Long id;}@MappedSuperclass@Inheritance(strategy = InheritanceType.SINGLE_TABLE)@SequenceGenerator(name = "seqGenerator", sequenceName = "DICTIONARY_SEQ")public abstract class Intermed extends BaseEntity {}@Entitypublic class MyEntity1 extends Intermed {}@Entitypublic class MyEntity2 extends Intermed {} And I got following exception: Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [context/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unknown Id.generator: seqGenerator When I change @MappedSuperclass to @Entity on Intermed class, everything works OK. Are there any problems with using @MappedSuperclass and @SequenceGenerator? Or I have missed something? Now provide the response and nothing else.
Here is what the JPA 1.0 spec says about the SequenceGenerator annotation: 9.1.37 SequenceGenerator Annotation The SequenceGenerator annotation defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation. A sequence generator may be specified on the entity class or on the primary key field or property . The scope of the generator name is global to the persistence unit (across all generator types). And a mapped superclass is not an entity. So according to the way I read the spec, what you want to do is not possible. Either make the Intermed class an entity or put the SequenceGenerator on the sub classes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3607691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59692/']}
jdg_73192
stackexchange
llm_judgeable_groundtruth_similarity
46737
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to derive the internal energy of a gas which obeys the van der Waals equation. I have however encountered some problems. I calculate the integral of $dU$ from $V=0,T=0$ to $V=V, T=\infty$ to $V=V,T=T$. I can calculate the work: $$\left(p+\left(\frac{a}{n}\right)^2\right)(V-nb)=nRT \implies p=\frac{nRT}{V-nb}-\frac{an^2}{V^2}$$ For the second part of the path $V$ is constant so $W=0$. $$W=-\int\limits_\infty^V p\textrm dV=\int\limits_V^\infty \frac{nRT}{V-nb}-\frac{an^2}{V^2} \textrm dV\\=nRT\ln(V-nb)|_V^\infty+\frac{an^2}{V}|_V^\infty\\=\infty-\infty +\frac{an^2}{\infty}-\frac{an^2}{V}=-\frac{an^2}{V}$$ I know I haven't been mathematically rigorous but that is not really important to me at the moment. I think this is right. I can't however think of how i should calculate the heat involved in following this path. Any help on how to do this is appreciated. EDIT : I see now that the work I calculated is wrong as well as $$nRT\ln(V-nb)|_V^\infty\neq\infty-\infty$$ Now provide the response and nothing else.
You and Lubos are integrating the expression $dU = -pdV$ for a constant composition system, but this expression is only valid for constant entropy $S$. During integration you maintain $T$ constant, but the latter is not equivalent to $S$ constant. If you chose a representation $(T,V)$ then $$dU = \left( \frac{\partial U}{\partial T}\right)_V dT + \left( \frac{\partial U}{\partial V}\right)_T dV$$ and you can integrate for the special case of constant $T$, but then $({\partial U}/{\partial V})_T$ is not $(-p)$, as you assumed above. The value of this partial derivative can be obtained from the Helmholtz equation $({\partial U}/{\partial V})_T = T^2 [{\partial}/{\partial T} (p/T)]_V$. Integration gives $$U(T,V,N) = U_0(T,V_0,N) + \int_{V_0}^V T^2 \left( \frac{\partial}{\partial T} \frac{p}{T} \right)_V dV$$ Noting that when the volume tends to infinity the real gas approaches an ideal gas, which implies that $U\to U_\mathrm{ideal}$, we can chose $V_0\to\infty$ to fix the integratino constant $U_0$ $$U(T,V,N) = U_\mathrm{ideal}(T,N) + \int_{\infty}^V T^2 \left( \frac{\partial}{\partial T} \frac{p}{T} \right)_V dV$$ Substituting the van der Waals equation of state $$\frac{p}{T} = \frac{NR}{V-Nb} - \frac{a}{T} \frac{N^2}{V^2}$$ and working out yields the internal energy of the van der Waals gas $$U(T,V,N) = U_\mathrm{ideal}(T,N) - \frac{aN^2}{V} $$ The energy of the ideal gas is given by the well-known form $U_\mathrm{ideal} = N C_V T$ with $C_V$ the heat capacity for ideal gas, e.g. $3R/2$ for monoatomic gas. Now you can understand why the appearance of the heat capacity for an ideal gas is not anything wrong, as you commented above. Notice also that when $V\to\infty$ the internal energy of the van der Waals gas reduces to the internal energy of an ideal gas, which does not depend on volume. This is the correct result.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/46737', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_73193
stackexchange
llm_judgeable_groundtruth_similarity
14915549
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 Django Docs state that you can output custom HTML for readonly fields in the admin interface. This is exactly what I need, but it does not seem to work. In admin.py: from django.contrib import adminclass ExampleAdmin(admin.ModelAdmin): readonly_fields = ('myfield', ) def myfield(self, instance): print 'This part of the code is never reached!' return u'<b>My custom html for the readonly field!</b>' myfield.allow_tags = Trueadmin.site.register(State, StateAdmin) In models.py: class State(models.Model): myfield = MyCustomField() ... etc ...class MyCustomField(models.TextField): def to_python(self, value): ... etc ... The field is displayed as read-only on the admin edit page. However, the 'myfield' method that is supposed to create custom html is never called. Does anybody know what I'm doing wrong? Kind regards, Patrick Now provide the response and nothing else.
Looking at the "django/contrib/admin/util.py" file's lookup_field method, this appears to be the expected behavior. Here is the code you're using: readonly_fields = ('myfield', ) Since myfield is an actual field defined in your model, having it in readonly_fields will only make it non-editable; it will not allow you to customize what gets displayed to the user. In order to do that, you have to give readonly_fields something that isn't an actual field, like myfield_readonly . You will then have to rename your ModelAdmin 's myfield method to myfield_readonly , of course, as well as the myfield.allow_tags = True . You'll probably also want to add myfield_readonly.short_description = 'My Field' . Lastly, you'll want to leave the actual myfield field out of the form using either exclude or fields .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14915549', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1349674/']}
jdg_73194
stackexchange
llm_judgeable_groundtruth_similarity
2135328
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 known reason why FormatException does not inherit from ArgumentException ? An invalid format would seem to be a very specific case of an argument being invalid, similar to ArgumentOutOfRangeException . The MSDN article for the class states: FormatException is thrown when the format of an argument in a method invocation does not match the format of the corresponding formal parameter type. For example, if a method specifies a String parameter consisting of two digits with an embedded period, passing a corresponding string argument containing only two digits to that method would cause FormatException to be thrown. Sounds like just the scenario for an ArgumentException or deriving class to me. All this means is that you can't deal with FormatException under the larger ArgumentException exception family, nor can you identify which parameter caused the exception to be thrown. Is there any reason for this seemingly out-of-place exception to be where it is? Now provide the response and nothing else.
FormatException is not necessarily thrown when a formal argument of a method is invalid. It can also happen if the method is consuming an external resource and the format of the data from the external resource is inappropriate. For example, BinaryReader.Read7BitEncodedInt will throw FormatException if what it's going to read from a stream is not a valid 7-bit encoded integer. It doesn't take any arguments at all. ArgumentException , on the other hand, should only get thrown when an argument passed as a formal parameter to a method is invalid. The description you referenced from the MSDN article is more restrictive than FormatException really is and should be clarified.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2135328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138578/']}
jdg_73195
stackexchange
llm_judgeable_groundtruth_similarity
783189
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: Here, $AM_1$ is the angle bisector of $\angle A$ extended to the circumcircle and so on. $R$ is the circumradius and $r$ is the inradius, respectively. I have to prove that: $$8r+2R\le AM_1+BM_2+CM_3\le 6R$$ The second part is easy, since each of $AM_1$ is a chord, $AM_1\le 2R$ , so $\sum AM_1 \le 6R$ . But the first part is giving me nightmares. Applying Euler's inequality gives $8r+2R\le 6R$ , which is not much helpful and I'm out of ideas. Please help. Besides, playing GeoGebra tells that its true. Now provide the response and nothing else.
I have a (way) shorter proof, that relies on the following lemma: Lemma 1 : If $AL_A,BL_B,CL_C$ are the angle bisectors of $ABC$, then:$$\sum_{cyc}AL_A \geq 9r.$$Due to the Van Obel's theorem and the angle bisector theorem we know that if $I$ is the incenter of $ABC$, then:$$\frac{AI}{IL_A}=\frac{b+c}{a}.$$Since $IL_A\geq r$, we have:$$\sum_{cyc}AL_A \geq r\cdot\sum_{cyc}\frac{a+b+c}{a}=r\cdot\left(\sum_{cyc}a\right)\cdot\left(\sum_{cyc}\frac{1}{a}\right)$$hence the claim follows from the Cauchy-Schwarz inequality. Let $A'B'C'$ be the triangle for which $A'B'$ is the perpendicular to $OC$ through $C$ and so on. We have that the circumcircle of $ABC$ is the incircle of $A'B'C'$; moreover, $M_A$ is the incenter of $A'BC$ and so on. Let $r_A$ be the inradius of $A'BC$. Due to the Japanese-Carnot theorem we know that:$$r_A+r_B+r_C = 2R-r.$$Now we have:$$\sum_{cyc}AM_A = \sum_{cyc}AL_A + \sum_{cyc}L_A M_A \geq \sum_{cyc}AL_A + \sum_{cyc} r_A \geq (9r) + (2R-r) = 8r+2R,$$QED.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/783189', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/93616/']}
jdg_73196
stackexchange
llm_judgeable_groundtruth_similarity
6850825
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 consume some WCF services from SSIS. I had it working fine from a development machine. However, when another developer tries to do this, they have issues. If the other developer copies my .DTSX file, then it works. However, if they create it themself, then it fails to connect (monitoring it from the WCF side). We have noticed a BIG difference in how SSIS acts on the two machines and I suspect that is the cause of the problem. Both SSIS machines download the same WSDL data from the service. However, the Web Service Task on my machine (the functional one) has a different set of inputs than on the other dev's machine (the non-functional one). For example, if my method I was trying to call was DoStuff(int data1, decimal data2, string msg) , I would have 5 inputs: data1 (int) , data1Specified (bool) , data2 (decimal) , data2Specified (bool) ,and msg (string) whereas the other machine lacked the data1Specified and data2Specified inputs. When working with other inputs, it appears that this xxxSpecified variable is always created by my machine for all data types except for strings (not exhaustively tested but have thrown ~8 data types in there) but the other dev's machine NEVER creates these xxxSpecified variables. One more thing of note: If the other dev imports the .DTSX from my machine and directly runs it, it works. If he clicks on the "Download WSDL" button, even though it downloads the exact same WSDL, he gets a different set of inputs after specifying the service/method to call. So apparently his SSIS development environment is making different decisions than mine is, and we can't figure out why or how to make his act more like mine. Nor do we even realize why these xxxSpecified variables are apparently necessary ("Specified" exists NOWHERE in the WSDL). WHY does SSIS generate these xxxSpecified inputs, and why in one environment but not another? Clarification: "GoodDevBox" creates the project manually, from scratch, and it works (i.e. has the xxxSpecified inputs). "BadDevBox" creates the project manually, from scratch, and it doesn't work (i.e. is missing the xxxSpecified inputs). The problem has nothing to do with sharing projects/solutions. In fact, sharing them is the only way to get this to work, if the "BadDevBox" doesn't reprocess the WSDL. Now provide the response and nothing else.
I suspect that the reason c = a*b is so much slower than performing the operations an element at a time is that the template<class T> valarray<T> operator* (const valarray<T>&, const valarray<T>&); operator must allocate memory to put the result into, then returns that by value. Even if a "swaptimization" is used to perform the copy, that function still has the overhead of allocating the new block for the resulting valarray initializing the new valarray (it's possible that this might be optimized away) putting the results into the new valarray paging in the memory for the new valarray as it is initialized or set with result values deallocating the old valarray that gets replaced by the result
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6850825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/294863/']}
jdg_73197
stackexchange
llm_judgeable_groundtruth_similarity
42058295
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 running tests in Django applications that make use of Celery tasks I can't fully test tasks that need to get data from the database since they don't connect to the test database that Django creates. Setting task_always_eager in Celery to True partially solves this problem but as the documentation for testing says, this doesn't fully reflect how the code will run on a real Celery worker and isn't suitable for testing. How can I make Celery tasks use the Django test database when running Django tests without setting task_always_eager = True ? Now provide the response and nothing else.
Short = You must run celery worker as in production Easy: Use dedicated test db (as in production) Configure celery to use it Start celery worker manually before you run tests Advanced: Use auto created test db (it may be sqlite) Run celery worker in your test setUp() Configure celery to use auto created test db (copy django.conf.settings.DATABASE from test process to celery) And always you must provide message broker for celery. I have a test that requires dedicated celery worker to check my code that passes messages between celery task and calling code: https://gist.github.com/Sovetnikov/a7ad982fc77e8dfbc528bfc20fcf3b1e This python module is two in one - a TestUnit and celery worker runner with self contained configuration. My code does not utilize any db, but you can easily adapt it to your need. Just pass django.conf.settings.DATABASE (as json or pickle or whatever you like method) to celery starter code and configure Django DATABASE to point to test db. Additional info : There is complete solution for this case https://github.com/RentMethod/celerytest (i triedsome old version of it and have no luck because it uses threads, with python GIL ... and i think it is over-complicated) Sample code, how to configure DATABASE settings and init django itself in single module https://gist.github.com/Sovetnikov/369a8d05ba2b6482fa20769bc498f122
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42058295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1523238/']}
jdg_73198
stackexchange
llm_judgeable_groundtruth_similarity
1952573
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: Apologies for asking a stupid question. Working on the exercise 7.8 from Introduction to Lie Algebras . It says: Let $L$ be the Heisenberg algebra with basis $f$, $g$, $z$ such that $[f, g] = z$and $z$ is central. Show that $L$ does not have a faithful finite-dimensional irreducible representation. First of all, what is wrong with the traditional upper-diagonal representation? Namely, $$ f = \begin{pmatrix} 0 & 1 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0\end{pmatrix}\quad,\quadg = \begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 1 \\ 0 & 0 & 0\end{pmatrix}\quad,\quadz = \begin{pmatrix} 0 & 0 & 1 \\ 0 & 0 & 0 \\ 0 & 0 & 0\end{pmatrix}\quad. $$ I would also be great to know why these three requirements for the representation (faithful, finite-dimensional, irreducible) are incompatible for the Heisenberg algebra. Thanks. Now provide the response and nothing else.
You've already described below why the matrix representation is not irreducible (sorry, I mistakenly talked about the regular representation in the first place). To prove that there is no finite-dimensional faithful irreducible representation, consider the action of $z$: On the one hand, it must be of trace $0$ (why?) on the other hand, it must be a scalar (why?). Can you fill in the details? Remarks from the comments: The crucial point here is that ${\mathfrak g}$ has the property ${\mathfrak z}({\mathfrak g})\cap [{\mathfrak g},{\mathfrak g}]\neq \{0\}$, but this property does not distinguish Lie algebras possessing a finite-dimensional faithful irreducible representation: No reductive Lie algebra ${\mathfrak g}$ like ${\mathfrak g}{\mathfrak l}(n)$ has this property (even though it may have nontrivial center), since ${\mathfrak g} = {\mathfrak z}({\mathfrak g})\oplus [{\mathfrak g},{\mathfrak g}]$ for reductive ${\mathfrak g}$. Nonetheless, it may or may not possess a faithful finite-dimensional irreducible representation: Namely, if ${\mathfrak z}({\mathfrak g})$ is $1$-dimensional, the adjoint representation $[{\mathfrak g},{\mathfrak g}]\to{\mathfrak g}{\mathfrak l}([{\mathfrak g},{\mathfrak g}])$ extends to a faithful finite-dimensional irreducible representation of ${\mathfrak g}$ by letting ${\mathfrak z}({\mathfrak g})$ acts nontrivially by some scalar, while on the other hand, no irreducible finite-dimensional representation can be faithful on ${\mathfrak z}({\mathfrak g})$ by Schur's Lemma if $\dim{\mathfrak z}({\mathfrak g})>1$. A solvable Lie algebra may or may not have this property, but (over an algebraically closed field of characteristic $0$) it never has a finite-dimensional faithful irreducible representation by Lie's Theorem . Btw, it's not a stupid question.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1952573', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/340940/']}
jdg_73199
stackexchange
llm_judgeable_groundtruth_similarity
32904598
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it correct to write my classes like this? In question is the method getPrice() in the Item class. Every Item needs to have a getPrice() . But I can't actually return something. So I fire the this.getPrice() with gets me the Price of the ProductItem . Is there a more solid / better designed solution? class Item { String description; public Item(String description) { this.description = description; } double getPrice(){return this.getPrice();} //TODO Correct like this?}class ProductItem extends Item { int amount; double pricePerUnit; public ProductItem(String description, int amount, double pricePerUnit) { super(description); this.amount = amount; this.pricePerUnit = pricePerUnit; } @Override double getPrice(){ return amount * pricePerUnit; }} Now provide the response and nothing else.
It sounds like Item should be an abstract class then, with getPrice() being an abstract method: public abstract class Item { private final String description; public Item(String description) { this.description = description; } public abstract double getPrice(); public String getDescription() { return description; }} That means you won't be able to write Item item = new Item("foo"); // Invalid, because Item is abstract But you can write: Item item = new ProductItem("foo", 10, 2.0);double p = item.getPrice(); // 20.0 Every concrete (non-abstract) subclass you declare will have to override getPrice() and provide an implementation. See the abstract classes and methods section of the Java tutorial for more details.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32904598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4494934/']}
jdg_73200
stackexchange
llm_judgeable_groundtruth_similarity
14320666
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 wondering about the Timer component and what, if any, negative effects occur because of its use or multiple instances of its use. In practice, should there be a limit as to how many timers one should use in a project at one time? Now provide the response and nothing else.
Well, everything is relative but a System.Windows.Forms.Timer is a pretty expensive object. It works by creating a hidden window, required to make the underlying winapi SetTimer() function work. This window is not shared, every timer object gets its own window. A window is in general one of the more expensive operating system objects. So a very hard upper limit is that you can never have more than 10,000 enabled timers. Windows refuses to allow an app to create that many windows. You should stay considerably south of that limitation, given that all of the windows of all of the processes that run in one desktop session need to share a common heap. Or in other words, creating a lot of windows but staying below the 10,000 quota can negatively impact other processes, it can make them fail when the heap is exhausted. I'd say a reasonable upper limit hovers around 100. That's a large number of moving parts to keep track of in general, assuming that all of these timers have different Tick event handlers. If they don't then you should tackle this a different way, you only ever need one Timer to measure an arbitrary number of intervals. Roughly the same way you keep appointments with single watch on your wrist. You do so by storing the due times in a SortedList and start the timer only for the first one that's due. When it ticks, work off the entries in the list that have the expired due time and repeat. When you add or remove a due time, stop the timer and restart it when there's a new first due time.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14320666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1651986/']}
jdg_73201
stackexchange
llm_judgeable_groundtruth_similarity
40081888
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 change the figure size of xgboost's plot importance function? Trying to pass a figsize=(10,20) fails with the exception of unknown attribute. Now provide the response and nothing else.
You can pass an axis in the ax argument in plot_importance() . For instance, use this wrapper: def my_plot_importance(booster, figsize, **kwargs): from matplotlib import pyplot as plt from xgboost import plot_importance fig, ax = plt.subplots(1,1,figsize=figsize) return plot_importance(booster=booster, ax=ax, **kwargs) Then use my_plot_importance() instead of plot_importance()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40081888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2587904/']}
jdg_73202
stackexchange
llm_judgeable_groundtruth_similarity
12129955
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to insert, delete, update etc without using data grid server control in asp.net Now provide the response and nothing else.
I guess scipy just does not implement it, but the CSR format would support this quite well, please read the wikipedia article on "Sparse matrix" about what indptr , etc. are: # A.indptr is an array, one for each row (+1 for the nnz):def csr_row_set_nz_to_val(csr, row, value=0): """Set all nonzero elements (elements currently in the sparsity pattern) to the given value. Useful to set to 0 mostly. """ if not isinstance(csr, scipy.sparse.csr_matrix): raise ValueError('Matrix given must be of CSR format.') csr.data[csr.indptr[row]:csr.indptr[row+1]] = value# Now you can just do:for row in indices: csr_row_set_nz_to_val(A, row, 0)# And to remove zeros from the sparsity pattern:A.eliminate_zeros() Of course this removes 0s that were set from another place with eliminate_zeros from the sparsity pattern. If you want to do that (at this point) depends on what you are doing really, ie. elimination might make sense to delay until all other calculations that might add new zero's are done as well, or in some cases you may have 0 values, that you want to change again later, so it would be very bad to eliminate them! You could in principle of course short-circuit the eliminate_zeros and prune , but that should be a lot of hassle, and might be even slower (because you won't do it in C). Details about eliminiate_zeros (and prune) The sparse matrix, does generally not save zero elements, but just stores where the nonzero elements are (roughly and with various methods). eliminate_zeros removes all zeros in your matrix from the sparsity pattern (ie. there is no value stored for that position, when before there was a vlaue stored, but it was 0). Eliminate is bad if you want to change a 0 to a different value lateron, otherwise, it saves space. Prune would just shrink the data arrays stored when they are longer then necessary. Note that while I first had A.prune() in there, A.eliminiate_zeros() already includes prune.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12129955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1614446/']}
jdg_73203
stackexchange
llm_judgeable_groundtruth_similarity
21108171
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 question that sounds simple but it's driving me mad for some days. I have a historical time series closed in two lists: the first list is containing prices, let's say P = [1, 1.5, 1.3 ...] while the second list is containing the related dates, let's say D = [01/01/2010, 02/01/2010...]. What I would like to do is to plot SOME of these dates (when I say "some" is because the "best" result I got so far is to show all of them as tickers, so creating a black cloud of unreadable data in the x-axis) that, when you zoom in, are shown more in details. This picture is now having the progressive automated range made by Matplotlib: Instead of 0, 200, 400 etc. I would like to have the dates values that are related to the data-point plotted. Moreover, when I zoom-in I get the following: As well as I get the detail between 0 and 200 (20, 40 etc.) I would like to get the dates attached to the list. I'm sure this is a simple problem to solve but I'm new to Matplotlib as well as to Python and any hint would be appreciated. Thanks in advance Now provide the response and nothing else.
Matplotlib has sophisticated support for plotting dates. I'd recommend the use of AutoDateFormatter and AutoDateLocator. They are even locale-specific, so they choose month-names according to your locale. import matplotlib.pyplot as pltfrom matplotlib.dates import AutoDateFormatter, AutoDateLocatorxtick_locator = AutoDateLocator()xtick_formatter = AutoDateFormatter(xtick_locator)ax = plt.axes()ax.xaxis.set_major_locator(xtick_locator)ax.xaxis.set_major_formatter(xtick_formatter) EDIT For use with multiple subplots, use multiple locator/formatter pairs: import datetimeimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.dates import AutoDateFormatter, AutoDateLocator, date2numx = [datetime.datetime.now() + datetime.timedelta(days=30*i) for i in range(20)]y = np.random.random((20))xtick_locator = AutoDateLocator()xtick_formatter = AutoDateFormatter(xtick_locator)for i in range(4): ax = plt.subplot(2,2,i+1) ax.xaxis.set_major_locator(xtick_locator) ax.xaxis.set_major_formatter(xtick_formatter) ax.plot(date2num(x),y)plt.show()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21108171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3111149/']}
jdg_73204
stackexchange
llm_judgeable_groundtruth_similarity
1849375
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 SQLAlchemy, how do I populate or update a table from a SELECT statement? Now provide the response and nothing else.
SQLalchemy doesn't build this construct for you. You can use the query from text. session.execute('INSERT INTO t1 (SELECT * FROM t2)') EDIT: More than one year later, but now on sqlalchemy 0.6+ you can create it : from sqlalchemy.ext import compilerfrom sqlalchemy.sql.expression import Executable, ClauseElementclass InsertFromSelect(Executable, ClauseElement): def __init__(self, table, select): self.table = table self.select = [email protected](InsertFromSelect)def visit_insert_from_select(element, compiler, **kw): return "INSERT INTO %s (%s)" % ( compiler.process(element.table, asfrom=True), compiler.process(element.select) )insert = InsertFromSelect(t1, select([t1]).where(t1.c.x>5))print insert Produces: "INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z FROM mytable WHERE mytable.x > :x_1)" Another EDIT: Now, 4 years later, the syntax is incorporated in SQLAlchemy 0.9, and backported to 0.8.3; You can create any select() and then use the new from_select() method of Insert objects: >>> from sqlalchemy.sql import table, column>>> t1 = table('t1', column('a'), column('b'))>>> t2 = table('t2', column('x'), column('y'))>>> print(t1.insert().from_select(['a', 'b'], t2.select().where(t2.c.y == 5)))INSERT INTO t1 (a, b) SELECT t2.x, t2.yFROM t2WHERE t2.y = :y_1 More information in the docs .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1849375', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36330/']}
jdg_73205
stackexchange
llm_judgeable_groundtruth_similarity
154629
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 arbitrary positive integers $m$ and $n$, if we dissect a unit square into an $m\times n$ rectangular grid of $1/m\times 1/n$ rectangles, we can reassemble these $mn$ rectangles into an $n/m\times m/n$ rectangle, which is of square-rational proportion $m^2/n^2$. Is there any essentially different way to rectangularly dissect a unit square to a rectangle----that is, to a $1/r\times r$ rectangle, of proportion $r^2$, where $r$ is irrational? Notes: The usual rules for dissection problems apply (finitely many pieces, with no gaps or overlaps of positive planar measure, and no discarded or additional pieces). This question was posted, unanswered, on MathStackExchange for a month. For what it's worth, my failed attempts to find such a dissection lead me to think it impossible. Now provide the response and nothing else.
No. It is a famous problem. Suppose it were possible to cut the unit square into finitely many rectangles of sizes $a_i \times b_i$. This means that we have a decomposition $1 \otimes 1 = \sum_i a_i \otimes b_i$. If these rectangle could be reassembled into an $r \times 1/r$ rectangle, we would likewise have $r \otimes 1/r = \sum_i a_i \otimes b_i$. But $r \otimes_{\mathbb{Z}} 1/r = 1 \otimes_{\mathbb{Z}} 1$ if and only if $r \in \mathbb{Q}$. More concretely, let $f : \mathbb{R} \to \mathbb{R}$ be an additive group homomorphism such that $f(q) = 0$ iff $q \in \mathbb{Q}$; it exists by the Axiom of Choice. By additivity (refining the dissection into an elementary one, given by a complete intersection of lines parallel to the axes), we have $f(1)^2 = \sum_i f(a_i)f(b_i)$, and likewise, $f(r)f(1/r) = \sum_i f(a_i)f(b_i)$. But by construction, $f(1) = 0$ while $f(r)f(1/r) \neq 0$ unless $r \in \mathbb{Q}$.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/154629', 'https://mathoverflow.net', 'https://mathoverflow.net/users/7458/']}
jdg_73206
stackexchange
llm_judgeable_groundtruth_similarity
369115
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In a typical case we include an identifier like so: /myService/products/1234 And if I wanted to get the products for a given customer we'd do this: /myService/customer/999/products BUT, what if I wanted to get the products for a given customer and I don't model customers in my system? My system just store customer ID's on products. Would the above still be valid? You would get a 404 from /myService/customer/ or /myService/customer/999 Would this be acceptable? /myService/products/customer/999 Now provide the response and nothing else.
In addition to the VoiceOfUnreason's answer (which I agreed with). what if I wanted to get the products for a given customer and I don'tmodel customers in my system? If we consider the mentioned RFC 3986 - Path and the fact that customers are not part of the model (hence, neither part of the API), probably the following URIsare more appropiate /myservice/products/?q=customer:12345/myservice/products/?customer=12345 According to the question, customers seem to be only an attribute ( product.customer ). With no hierarchy. So, why to express hierarchy where there's not? Any URI is going to fine anyways. URIs have nothing to do with REST. They are expected to be meaningless since the only readers are other applications (mostly, HTTP clients). Just remember what URI means (Uniform resource identifier ). 1 Considerations If you foresee the possibility to implement customers in a near future, could be good not to use /customer any place (yet) since the representation of the resources referenced by these paths might change. Causing possible breaking changes to the clients. This is guesswork of course, but worth nothing to be aware of the possibilities for your API to change. Web APIs can be really resilient when we adhere to all the principles of REST, but my experience tells me that this's not the case in most of the APIs out there. When we don't fully embrace REST (specially HATEOAS), API consumers use to be fairly coupled to the URIs and data models. In such cases, web APIs and changes don't get along. 1: The two alternatives suggested just try to fulfil the necessity of "expressiveness" (what OP is looking for) and convey with the common practices of web API designs. None of both required by REST.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/369115', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/130496/']}
jdg_73207
stackexchange
llm_judgeable_groundtruth_similarity
5
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: Many operating systems references say that with cooperative (as opposed to preemptive) multitasking, a process keeps the CPU until it explicitly voluntarily suspends itself. If a running process performs an I/O request that cannot be immediately satisfied (e.g., requests a key stroke that is not yet available), does the scheduler suspend it, or does it really keep the CPU until the request can be serviced? [Edited to replace "blocks on i/o" with "performs an I/O request that cannot be immediately satisfied."] Now provide the response and nothing else.
In a truly "cooperative" setting, and if there was no hardware protection, a process could certainly block on I/O and not relinquish control until the I/O was done (or never relinquish control at all). For example, Windows 3.1 was this way: if a single user process wanted to take over the entire computer, and prevent anything else from running, it could. But on a system with multitasking you expect the system API I/O commands to relinquish control of the processor when they are called. So when a running process blocks on I/O, assuming that the process uses the normal system APIs, other processes will be allowed to run until the I/O is complete, and eventually the original process will resume once the I/O is done. In other words, calling a blocking I/O function is one way that a process on a cooperative system can voluntarily suspend itself.
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/5', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/40/']}
jdg_73208
stackexchange
llm_judgeable_groundtruth_similarity
342301
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: Most books write a family of sets $A_i$ with index set $I$ as $\{ A_i \}_{i \in I}$. However, I've read other books that have criticized this notation; they insist that one should write $(A_i )_{i \in I}$ for the family of sets $A_i$ indexed by $I$. Is there a difference between $\{ A_i \}_{i \in I}$ and $(A_i )_{i \in I}$? If so, could you please give a precise definition of each? Now provide the response and nothing else.
I don’t like either notation: I would write $\{A_i:i\in I\}$ or $\langle A_i:i\in I\rangle$. Technically there is no difference: each implies the existence of a function $i\mapsto A_i$ whose domain is $I$. The difference is one of emphasis: when I write $\{A_i:i\in I\}$, I’m thinking of this simply as a collection of sets, whereas when I write $\langle A_i:i\in I\rangle$, I’m emphasizing the existence of the function whose domain is $I$ and whose range is that collection of sets. I might let $\mathscr{A}=\{A_i:i\in I\}$ and simply talk about the collection $\mathscr{A}$ of sets, without any reference to the specific indexing, but when I write $\langle A_i:i\in I\rangle$, the specific indexing is very much on my mind: $\langle A_i:i\in I\rangle$ is an abbreviation for a function $I\to\mathscr{A}:i\mapsto A_i$. For a more familiar example of the distinction, compare $\{x_n:n\in\Bbb N\}$ and $\langle x_n:n\in\Bbb N\rangle$, where each $x_n\in\Bbb R$. In each case $x_n$ is just a handier notation for $\varphi(n)$, for some function $\varphi:\Bbb N\to\Bbb R$. However, when I write $\{x_n:n\in\Bbb N\}$ I’m not thinking of that function; I’m thinking of its range, the set of values that it assumes. When I write $\langle x_n:n\in\Bbb N\rangle$, however, I’m thinking of the function: this is a real-valued sequence , i.e., a function from $\Bbb N$ to $\Bbb R$, not just a countable set of real numbers. (Note: Many people use parentheses for my angle brackets; I prefer the angle brackets for this specific notational purpose, since parentheses already have more than enough meanings.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/342301', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/61568/']}
jdg_73209
stackexchange
llm_judgeable_groundtruth_similarity
19760585
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to get something very basic running. I am used to CI and now learning Laravel 4, and their docs are not making it easy! Anyways, I am trying to create a login form and just make sure that data is posted successfully by printing it in the next form. I am getting this exception: Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException and my MemberController.php: public function index() { if (Session::has('userToken')) { /*Retrieve data of user from DB using token & Load view*/ return View::make('members/profile'); }else{ return View::make('members/login'); } } public function validateCredentials() { if(Input::post()) { $email = Input::post('email'); $password = Input::post('password'); return "Email: " . $email . " and Password: " . $password; }else{ return View::make('members/login'); } } and routes has: Route::get('/', function(){ return View::make('hello');});Route::get('/members', 'MemberController@index');Route::get('/validate', 'MemberController@validateCredentials'); and finally my view login.php has this form direction: <?php echo Form::open(array('action' => 'MemberController@validateCredentials')); ?> Any help will be greatly appreciated. Now provide the response and nothing else.
You are getting that error because you are posting to a GET route. I would split your routing for validate into a separate GET and POST routes. New Routes: Route::post('validate', 'MemberController@validateCredentials');Route::get('validate', function () { return View::make('members/login');}); Then your controller method could just be public function validateCredentials(){ $email = Input::post('email'); $password = Input::post('password'); return "Email: " . $email . " and Password: " . $password;}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19760585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2160618/']}
jdg_73210
stackexchange
llm_judgeable_groundtruth_similarity
20288770
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 to store some message in ElasticSearch integrate with my python program. Now what I try to store the message is: d={"message":"this is message"} for index_nr in range(1,5): ElasticSearchAPI.addToIndex(index_nr, d) print d That means if I have 10 messages then I have to repeat my code 10 times. So what I want to do is try to make a script file or batch file.I've checked the ElasticSearch Guide , BULK API is possible to use. The format should be something like below: { "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }{ "field1" : "value1" }{ "delete" : { "_index" : "test", "_type" : "type1", "_id" : "2" } }{ "create" : { "_index" : "test", "_type" : "type1", "_id" : "3" } }{ "field1" : "value3" }{ "update" : {"_id" : "1", "_type" : "type1", "_index" : "index1"} }{ "doc" : {"field2" : "value2"} } what I did is: {"index":{"_index":"test1","_type":"message","_id":"1"}}{"message":"it is red"}{"index":{"_index":"test2","_type":"message","_id":"2"}}{"message":"it is green"} I also use curl tool to store the doc. $ curl -s -XPOST localhost:9200/_bulk --data-binary @message.json Now I want to use my Python code to store the file to the Elastic Search. Now provide the response and nothing else.
from datetime import datetimefrom elasticsearch import Elasticsearchfrom elasticsearch import helperses = Elasticsearch()actions = [ { "_index": "tickets-index", "_type": "tickets", "_id": j, "_source": { "any":"data" + str(j), "timestamp": datetime.now()} } for j in range(0, 10)]helpers.bulk(es, actions)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20288770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2791607/']}
jdg_73211
stackexchange
llm_judgeable_groundtruth_similarity
275891
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 recently been reading a book entitled Functional Programming in C# and it occurs to me that the immutable and stateless nature of functional programming accomplishes similar outcomes to dependency injection patterns and is possibly even a better approach, especially in regards to unit testing. I would be appreciative if anyone who has experience with both approaches could share their thoughts and experiences in order to answer the primary question: is Functional Programming a viable alternative to dependency injection patterns? Now provide the response and nothing else.
Dependency management is a big problem in OOP for the following two reasons: The tight coupling of data and code. Ubiquitous use of side effects. Most OO programmers consider the tight coupling of data and code to be wholly beneficial, but it comes with a cost. Managing the flow of data through the layers is an unavoidable part of programming in any paradigm. Coupling your data and code adds the additional problem that if you want to use a function at a certain point, you have to find a way get its object to that point. Use of side effects creates similar difficulties. If you use a side effect for some functionality, but want to be able to swap out its implementation, you pretty much have no other choice but to inject that dependency. Consider as an example a spammer program that scrapes web pages for email addresses then emails them. If you have a DI mindset, right now you're thinking of the services you will encapsulate behind interfaces, and which services will get injected where. I'll leave that design as an exercise for the reader. If you have an FP mindset, right now you're thinking of the inputs and outputs for the lowest layer of functions, like: Input a web page address, output the text of that page. Input a page's text, output a list of links from that page. Input a page's text, output a list of email addresses on that page. Input a list of email addresses, output a list of email addresses with duplicates removed. Input an email address, output a spam email for that address. Input a spam email, output the SMTP commands to send that email. When you think in terms of inputs and outputs, there are no function dependencies, only data dependencies. That's what makes them so easy to unit test. Your next layer up arranges for the output of one function to be fed into the input of the next, and can easily swap out the various implementations as needed. In a very real sense, functional programming naturally prods you to always invert your function dependencies, and therefore you usually don't have to take any special measures to do so after the fact. When you do, tools like higher-order functions, closures, and partial application make it easier to accomplish with less boilerplate. Note that it's not dependencies themselves that are problematic. It's dependencies that point the wrong way. The next layer up may have a function like: processText = spamToSMTP . emailAddressToSpam . removeEmailDups . textToEmailAddresses It's perfectly okay for this layer to have dependencies hard-coded like this, because its sole purpose is to glue the lower-layer functions together. Swapping an implementation is as simple as creating a different composition: processTextFancy = spamToSMTP . emailAddressToFancySpam . removeEmailDups . textToEmailAddresses This easy recomposition is made possible by a lack of side effects. The lower-layer functions are completely independent of each other. The next layer up may choose which processText is actually used based on some user config: actuallyUsedProcessText = if (config == "Fancy") then processTextFancy else processText Again, not an issue because all the dependencies point one way. We don't need to invert some dependencies in order to get them all pointing the same way, because pure functions already forced us to do so. Note that you could make this a lot more coupled by passing config down through to the lowest layer instead of checking it at the top. FP doesn't prevent you from doing this, but it does tend to make it a lot more annoying if you try.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/275891', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/44497/']}
jdg_73212
stackexchange
llm_judgeable_groundtruth_similarity
9602449
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: // opt_options is optionalfunction foo(a, b, opt_options) { // opt_c, opt_d, and opt_e are read from 'opt_options', only c and d have defaults var opt_c = 'default_for_c'; var opt_d = 'default_for_d'; var opt_e; // e has no default if (opt_options) { opt_c = opt_options.c || opt_c; opt_d = opt_options.d || opt_d; opt_e = opt_options.e; }} The above seems awfully verbose. What's a better way to handle argument options with default parameters? Now provide the response and nothing else.
This uses jQuery.extend but could be interchanged with an object merger from your library of choice or Object.assign in ES6. function Module(options){ var defaults = { color: 'red' }; var actual = $.extend({}, defaults, options || {}); console.info( actual.color );}var a = new Module();// Redvar b = new Module( { color: 'blue' } );// Blue Edit : Now also in underscore or lodash ! function Module(options){ var actual = _.defaults(options || {}, { color: 'red' }); console.info( actual.color );}var a = new Module();// Redvar b = new Module( { color: 'blue' } );// Blue In Javascript ES6 you can use Object.assign : function Module(options = {}){ let defaults = { color: 'red' }; let actual = Object.assign({}, defaults, options); console.info( actual.color );}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9602449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11236/']}
jdg_73213
stackexchange
llm_judgeable_groundtruth_similarity
18994434
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's how the scroll views work: One scroll view is paging enabled in the horizontal direction. Each 'page' of this scroll view contains a vertically scrolling UITableView. Without modification, this works OK, but not perfectly. The behaviour that's not right: When the user scrolls up and down on the table view, but then wants to flick over to the next page quickly, the horizontal flick/swipe will not work initially - it will not work until the table view is stationary (even if the swipe is very clearly horizontal). How it should work: If the swipe is clearly horizontal, I'd like the page to change even if the table view is still scrolling/bouncing, as this is what the user will expect too. How can I change this behaviour - what's the easiest or best way? NOTE For various reasons, a UIPageViewController as stated in some answers will not work. How can I do this with cross directional UIScrollViews (/one is a table view, but you get the idea)? I've been banging my head against a wall for hours - if you think you can do this then I'll more than happily award a bounty. Now provide the response and nothing else.
According to my understanding of the question, it is only while the tableView is scrolling we want to change the default behaviour. All the other behaviour will be the same. SubClass UITableView . UITableView s are subClass of UIScrollView s. On the UITableView subClass implement one UIScrollView 's UIGestureRecognizer 's delegate method - (BOOL)gestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UISwipeGestureRecognizer *)otherGestureRecognizer{ //Edit 1 //return self.isDecelerating; //return self.isDecelerating | self.bounces; //If we want to simultaneous gesture on bounce and scrolling //Edit 2 return self.isDecelerating || self.contentOffset.y < 0 || self.contentOffset.y > MAX(0, self.contentSize.height - self.bounds.size.height); // @Jordan edited - we don't need to always enable simultaneous gesture for bounce enabled tableViews} As we only want to change the default gesture behaviour while the tableView is decelerating. Now change all 'UITableView's class to your newly created tableViewSubClass and run the project, swipe should work while tableView is scrolling. :] But the swipe looks a little too sensitive while tableView is scrolling. Let's make the swipe a little restrictive. SubClass UIScrollView . On the UIScrollView subclass implement another UIGestureRecognizer 's delegate method gestureRecognizerShouldBegin: - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) { CGPoint velocity = [(UIPanGestureRecognizer *)gestureRecognizer velocityInView:self]; if (abs(velocity.y) * 2 < abs(velocity.x)) { return YES; } } return NO;} We want to make the "swipe is clearly horizontal". Above code only permits gesture begin if the gesture velocity on x axis is double than on y axis. [Feel free to increase the hard coded value "2" if your like. The higher the value the swipe needs to be more horizontal.] Now change the `UiScrollView' class (which has multiple TableViews) to your ScrollViewSubClass. Run the project. :] I've made a project on gitHub https://github.com/rishi420/SwipeWhileScroll
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18994434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/555619/']}
jdg_73214
stackexchange
llm_judgeable_groundtruth_similarity
23764863
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 close an open collapsed navbar on clicking outside of the navbar element? Currently, the only way to open or close it is by clicking on the navbar-toggle button. See here for an example and code: So far, I have tried the following which doesn't seem to work: jQuery(document).click(function() {});jQuery('.navbar').click(function(event) { jQuery(".navbar-collapse").collapse('hide'); event.stopPropagation();}); Now provide the response and nothing else.
Have a look that: $(document).ready(function () { $(document).click(function (event) { var clickover = $(event.target); var _opened = $(".navbar-collapse").hasClass("navbar-collapse in"); if (_opened === true && !clickover.hasClass("navbar-toggle")) { $("button.navbar-toggle").click(); } });}); Your fiddle works with that: http://jsfiddle.net/52VtD/5718/ Its a modified version of this answer , which lacks the animation and is also a tiny bit more complicated. I know, invoking the click() isn't very elegant, but collapse('hide') did not work for me either, and i think the animation is a bit nicer than adding and removing the classes hardly.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23764863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1709033/']}
jdg_73215
stackexchange
llm_judgeable_groundtruth_similarity
320957
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I recently upgraded my disk from a 128GB SSD to 512GB SSD. The / partition is encrypted with LUKS. I'm looking for help extending the partition to use all the free space on the new disk. I've already dd'd the old drive onto the new one: [root@localhost ~]# fdisk -l /dev/sdaDisk /dev/sda: 477 GiB, 512110190592 bytes, 1000215216 sectorsUnits: sectors of 1 * 512 = 512 bytesSector size (logical/physical): 512 bytes / 4096 bytesI/O size (minimum/optimal): 4096 bytes / 4096 bytesDisklabel type: dosDisk identifier: 0x00009f33Device Boot Start End Sectors Size Id Type/dev/sda1 * 2048 1026047 1024000 500M 83 Linux/dev/sda2 1026048 250064895 249038848 118.8G 83 Linux There's about 380GB of unused space after sda2. More relevant info: [root@localhost ~]# vgs VG #PV #LV #SN Attr VSize VFree fedora_chocbar 1 3 0 wz--n- 118.75g 4.00m[root@localhost ~]# lvs LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert home fedora_chocbar -wi-a----- 85.55g root fedora_chocbar -wi-a----- 29.30g swap fedora_chocbar -wi-a----- 3.89g[root@localhost ~]# pvs PV VG Fmt Attr PSize PFree /dev/mapper/encrypted fedora_chocbar lvm2 a-- 118.75g 4.00m There seems to be a lot of info regarding how to do this, but very little explanation. I appreciate any help on this. Now provide the response and nothing else.
OK! The definitive answer finally. My steps to expand a LUKS encrypted volume... cryptsetup luksOpen /dev/sda2 crypt-volume to open the encrypted volume. parted /dev/sda to extend the partition. resizepart NUMBER END . vgchange -a n fedora_chocbar . Stop using the VG so you can do the next step. cryptsetup luksClose crypt-volume . Close the encrypted volume for the next steps. cryptsetup luksOpen /dev/sda2 crypt-volume . Open it again. cryptsetup resize crypt-volume . Will automatically resize the LUKS volume to the available space. vgchange -a y fedora_chocbar . Activate the VG. pvresize /dev/mapper/crypt-volume . Resize the PV. lvresize -l+100%FREE /dev/fedora_chocbar/home . Resize the LV for /home to 100% of the free space. e2fsck -f /dev/mapper/fedora_chocbar-home . Throw some fsck magic at the resized fs. resize2fs /dev/mapper/fedora_chocbar-home . Resize the filesystem in /home (automatically uses 100% free space) I hope someone else finds this useful. I now have 300+GB for my test VMs on my laptop!
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/320957', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/198571/']}
jdg_73216
stackexchange
llm_judgeable_groundtruth_similarity
10992921
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 remove emoji code using JavaScript? I thought I had taken care of it using the code below, but I still have characters like . function removeInvalidChars() { return this.replace(/[\uE000-\uF8FF]/g, '');} Now provide the response and nothing else.
The range you have selected is the Private Use Area, containing non-standard characters. Carriers used to encode emoji as different, inconsistent values inside this range. More recently, the emoji have been given standardised 'unified' codepoints. Many of these are outside of the Basic Multilingual Plane, in the block U+1F300–U+1F5FF, including your example U+1F534 Large Red Circle. You could detect these characters with [\U0001F300-\U0001F5FF] in a regex engine that supported non-BMP characters, but JavaScript's RegExp is not such a beast. Unfortunately the JS string model is based on UTF-16 code units, so you'd have to work with the UTF-16 surrogates in a regexp: return this.replace(/([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])/g, '') However, note that there are other characters in the Basic Multilingual Plane that are used as emoji by phones but which long predate emoji. For example U+2665 is the traditional Heart Suit character ♥, but it may be rendered as an emoji graphic on some devices. It's up to you whether you treat this as emoji and try to remove it. See this list for more examples.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10992921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188477/']}
jdg_73217
stackexchange
llm_judgeable_groundtruth_similarity
582738
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm attempting to start with a file in the following form: 00: 42 ; byte 0 is 0x42 / d01: 52 ; byte 1 is 0x52 / r02: 62 ; byte 2 is 0x62 / D03: 72 ; byte 3 is 0x72 / R07: 1f ; bytes 03..0e are implicitly 00, byte 0f is 0x1f and use it to generate an 8-byte file whose values (in hex form) would be: 42 52 62 72 00 00 00 1f The exact input format isn't carved in stone. I just picked ';' as a comment delimiter because it's a single character and unambiguous. The form of the offset: and 2-digit hex value just seemed obvious based on tradition. I suspect the ultimate solution involves using sed or awk to strip away the comment, then piping their output to xxd , but so far my first experiment has fallen flat on its face & I can't even get xxd to parse what ought to be a best-case simple text file. For my first attempt, I simplified config.src: 00: 4201: 5202: 6203: 72 (omitting the comments and implied zero-bytes for now, and sticking to values corresponding to printable ASCII) ... then tried to generate the binary file from it: xxd -r config.src config.bin What I expected to see from cat config.bin and xxd config.bin : BRbr and 00000000: 42 52 62 72 BRbr What I ended up with: a 2-byte file with unprintable content cat can't render, and the following output from xxd config.bin : 00000000: 0301 So... problem #1... What am I doing wrong with xxd , and how can I fix it (or is there a better approach)? Keep in mind that I really want to specify one byte value per line, and would really like to be able to automatically skip sequential values and have them automatically filled with zeroes. The... problem #2... once I get xxd to parse my file, how can I go add the comments and strip them away before xxd sees them? Note that I'm not hellbent on using xxd per se... but this is a shared web server to which I don't have root or admin access, so apt-get install isn't an option, and compiling my own copies from source wouldn't necessarily be easy). (Background info... not necessary essential to solving the problem, but adding context to why I'm trying to do it) I'm working on an Arduino-based IoT controller. For the past few weeks, its configuration has consisted of hardcoded values and various interpretations of a DIP switch I've repurposed every few days. It's getting tedious. I'm not in the mood yet to implement a proper UI, so I came up with the idea of having it just fetch a binary config blob from my web server into a char[] as its first act upon starting up (enabling me to tweak runtime config values without having to go all the way and reflash the board itself, which is honestly kind of a pain at this point). Now provide the response and nothing else.
Your grep is likely matching more than one filename, which gives a value in $res that contains newlines. GNU sed would complain exactly the way that you describe when using a replacement string that contains literal newlines. Don't use grep to filter the output of ls . If you want to get all names in he current directory matching the pattern *.pub , use filenames=( *.pub ) This would create an array containing all names that matches the given pattern. Then: sed 's/\(@demo_project_users = \).*/\1'"${filenames[*]%.pub}"'/g' example.conf The "${filenames[*]%.pub}" expansion will expand to a single string consisting of each of the filenames in the filenames array, delimited by spaces (or whatever the first character of $IFS happens to be; a space by default), and with the suffix string .pub removed from each one. It's the "${filenames[*]}" bit that expands to the space-delimited string, and its the %.pub bit that removes the .pub suffix from each filename.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/582738', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/37564/']}
jdg_73218
stackexchange
llm_judgeable_groundtruth_similarity
50279289
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 may have inadvertently clicked on the listbox object when in Forms Designer View and created the following methods, which I did not need. Now I don't know how to undo this. When I remove the method Visual Studio is not happy, and if I don't I get an exception error when I click an object in the listbox. I do not know why I get this error and how to fix it. It may also be due to some other error, which I need to fix private void PrizesListBox_SelectedIndexChanged(object sender, EventArgs e){ throw new NotImplementedException();}private void tournamentPlayersListbox_SelectedIndexChanged(object sender, EventArgs e){ throw new NotImplementedException();} I have tried to look up the answer. Now provide the response and nothing else.
Indeed SNI in TLS does not work like that. SNI, as everything related to TLS, happens before any kind of HTTP traffic, hence the Host header is not taken into account at that step (but will be useful later on for the webserver to know which host you are connecting too). So to enable SNI you need a specific switch in your HTTP client to tell it to send the appropriate TLS extension during the handshake with the hostname value you need. In case of curl , you need at least version 7.18.1 (based on https://curl.haxx.se/changes.html ) and then it seems to automatically use the value provided in the Host header. It alo depends on which OpenSSL (or equivalent library on your platform) version it is linked to. See point 1.10 of https://curl.haxx.se/docs/knownbugs.html that speaks about a bug but explains what happens: When given a URL with a trailing dot for the host name part: "https://example.com./", libcurl will strip off the dot and use the name without a dot internally and send it dot-less in HTTP Host: headers and in the TLS SNI field. The --connect-to option could also be useful in your case. Or --resolve as a substitute to /etc/hosts , see https://curl.haxx.se/mail/archive-2015-01/0042.html for am example, or https://makandracards.com/makandra/1613-make-an-http-request-to-a-machine-but-fake-the-hostname You can add --verbose in all cases to see in more details what is happening. See this example: https://www.claudiokuenzler.com/blog/693/curious-case-of-curl-ssl-tls-sni-http-host-header ; you will also see there how to test directly with openssl . If you have a.example in your /etc/hosts you should just run curl with https://a.example/ and it should take care of the Host header and hence SNI (or use --resolve instead) So to answer your question directly, replace curl --header 'Host: a.example' https://x.example with curl --connect-to a.example:443:x.example:443 https://a.example and it should work perfectly.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50279289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/383760/']}
jdg_73219
stackexchange
llm_judgeable_groundtruth_similarity
14190788
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Below two queries are subqueries. Both are the same and both works fine for me. But the problem is Method 1 query takes about 10 secs to execute while Method 2 query takes under 1 sec. I was able to convert method 1 query to method 2 but I don't understand what's happening in the query. I have been trying to figure it out myself. I would really like to learn what's the difference between below two queries and how does the performance gain happen ? what's the logic behind it ? I'm new to these advance techniques. I hope someone will help me out here. Given that I read the docs which does not give me a clue. Method 1 : SELECT * FROM tracker WHERE reservation_id IN ( SELECT reservation_id FROM tracker GROUP BY reservation_id HAVING ( method = 1 AND type = 0 AND Count(*) > 1 ) OR ( method = 1 AND type = 1 AND Count(*) > 1 ) OR ( method = 2 AND type = 2 AND Count(*) > 0 ) OR ( method = 3 AND type = 0 AND Count(*) > 0 ) OR ( method = 3 AND type = 1 AND Count(*) > 1 ) OR ( method = 3 AND type = 3 AND Count(*) > 0 ) ) Method 2 : SELECT * FROM `tracker` t WHERE EXISTS ( SELECT reservation_id FROM `tracker` t3 WHERE t3.reservation_id = t.reservation_id GROUP BY reservation_id HAVING ( METHOD = 1 AND TYPE = 0 AND COUNT(*) > 1 ) OR ( METHOD = 1 AND TYPE = 1 AND COUNT(*) > 1 ) OR ( METHOD = 2 AND TYPE = 2 AND COUNT(*) > 0 ) OR ( METHOD = 3 AND TYPE = 0 AND COUNT(*) > 0 ) OR ( METHOD = 3 AND TYPE = 1 AND COUNT(*) > 1 ) OR ( METHOD = 3 AND TYPE = 3 AND COUNT(*) > 0 ) ) Now provide the response and nothing else.
An Explain Plan would have shown you why exactly you should use Exists . Usually the question comes Exists vs Count(*) . Exists is faster. Why? With regard to challenges present by NULL: when subquery returns Null , for IN the entire query becomes Null . So you need to handle that as well. But using Exist , it's merely a false . Much easier to cope. Simply IN can't compare anything with Null but Exists can. e.g. Exists (Select * from yourtable where bla = 'blabla'); you get true/false the moment one hit is found/matched . In this case IN sort of takes the position of the Count(*) to select ALL matching rows based on the WHERE because it's comparing all values. But don't forget this either: EXISTS executes at high speed against IN : when the subquery results is very large. IN gets ahead of EXISTS : when the subquery results is very small. Reference to for more details: subquery using IN . IN - subquery optimization Join vs. sub-query .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14190788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1263783/']}
jdg_73220
stackexchange
llm_judgeable_groundtruth_similarity
179944
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: Edit: my language allows for multiple inheritance, unlike Java. I've started designing and developing my own programming language for educational, recreational, and potentially useful purposes. At first, I've decided to base it off Java. This implied that all the code would be written in form of classes, and that code compiles into classes, which are loaded by the VM. However, I've excluded features such as interfaces and abstract classes, because I found no need for them. They seemed to be enforcing a paradigm, and I'd like my language not to do that. I wanted to keep the classes as the compilation unit though, because it seemed convenient to implement, familiar, and I just liked the idea. Then I noticed that I'm basically left with a module system, where classes could be used either as "namespaces", providing constants and functions using the static directive, or as templates for objects that need to be instantiated ("actual" purpose of classes in other languages). Now I'm left wondering: what are the upsides and the downsides of having classes as compilation units? Also, any general commentary on my design would be much appreciated. An informative post on my language can be found here: http://www.yannbane.com/2012/12/kava.html . Now provide the response and nothing else.
what are the benefits of having classes as compilation units? It can reduce the complexity of the language. No need for different constructs, everything is treated the same. In certain designs (though not yours it seems), you benefit from not having statics and the design issues they tend to run into (initialization order issues, concurrency limitations, awkwardness with generics/type classes). It also allows some benefits of the module concept like isolated module instances for sandboxing or parallelization; and module typing where dependencies fit some interface and the entire module worth of implementation can be instantiated and dropped in. That said, the concept tends to have more issues than not. Realistically, you can't treat everything the same, since 'top level' classes need special rules like having a default constructor (or else you run into odd issues spinning them up). Modularity of compilation units tends to get really awkward too. How does a class even reference others when they're just classes? How are those dependencies dealt with, and how do you determine the correct order for spinning up the classes? How do you make sure that duplicate class references are reused by different parts of the app (or how do you deal with duplicate instances if that's the semantics you want)? Having looked into it, I ran into a lot of issues with dependencies, scoping things properly, and initialization concerns. You end up running into issues that make 'top level classes' special, and many limitations to make them work that ends up shaping them into simple namespaces.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/179944', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/54627/']}
jdg_73221
stackexchange
llm_judgeable_groundtruth_similarity
119190
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: Is there a good reason not to pick $U(3)$ as the colour group? Is there any experiment or intrinsic reason that would ruled out $U(3)$ as colour group instead? Now provide the response and nothing else.
Suppose that $\text{U}(3)$ was the gauge group. We can decompose this as $$\text{U}(3)=\text{U}(1)\times\text{SU}(3),$$ which implies that in addition to the $\text{SU}(3)$ that has eight generators corresponding to eight gluons, there would be an additional generator for $\text{U}(1)$. The latter in principle corresponds to an additional gauge boson, but a theory of the strong interactions containing such a particle is inconsistent with experiment.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/119190', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/46389/']}
jdg_73222
stackexchange
llm_judgeable_groundtruth_similarity
11724311
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 ggplot2 to improve precipitation barplots. Here's a reproducible example of what I want to achieve: library(ggplot2)library(gridExtra)secu <- seq(1, 16, by=2)melt.d <- data.frame(y=secu, x=LETTERS[1:8])m <- ggplot(melt.d, aes(x=x, y=y)) + geom_bar(fill="darkblue") + labs(x="Weather stations", y="Accumulated Rainfall [mm]") + opts(axis.text.x=theme_text(angle=-45, hjust=0, vjust=1), title=expression("Rainfall"), plot.margin = unit(c(1.5, 1, 1, 1), "cm"), plot.title = theme_text(size = 25, face = "bold", colour = "black", vjust = 5))z <- arrangeGrob(m, sub = textGrob("Location", x = 0, hjust = -3.5, vjust = -33, gp = gpar(fontsize = 18, col = "gray40"))) #Or guessing x and y with just optionz I don't know how to avoid using guessing numbers on hjust and vjust on ggplot2? Is there a better way to put a subtitle (not just using \n, but a subtitle with different text color and size)? I need to be able to use with ggsave to have a pdf file. Here are two related questions: Add a footnote citation outside of plot area in R? How can I add a subtitle and change the font size of ggplot plots in R? Thanks for any help. Now provide the response and nothing else.
The latest ggplot2 builds (i.e., 2.1.0.9000 or newer) have subtitles and below-plot captions as built-in functionality. That means you can do this: library(ggplot2) # 2.1.0.9000+ secu <- seq(1, 16, by=2)melt.d <- data.frame(y=secu, x=LETTERS[1:8])m <- ggplot(melt.d, aes(x=x, y=y))m <- m + geom_bar(fill="darkblue", stat="identity")m <- m + labs(x="Weather stations", y="Accumulated Rainfall [mm]", title="Rainfall", subtitle="Location")m <- m + theme(axis.text.x=element_text(angle=-45, hjust=0, vjust=1)) m <- m + theme(plot.title=element_text(size=25, hjust=0.5, face="bold", colour="maroon", vjust=-1))m <- m + theme(plot.subtitle=element_text(size=18, hjust=0.5, face="italic", color="black"))m
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11724311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1457620/']}
jdg_73223
stackexchange
llm_judgeable_groundtruth_similarity
5916058
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 does the easing function for jQuery work? Take for example: easeInQuad = function (x, t, b, c, d) { return c*(t/=d)*t + b;}; How does that work? What does each parameter hold? How would I implement some dumb easing for an animation? Also how would I attach an easing pattern to jQuery, is loading it into $.easing good enough? Now provide the response and nothing else.
According to the jQuery 1.6.2 source, the meaning of the easing function is as follows. The function is called at various points in time during the animation. At the instants it is called, x and t both say what the time is now, relative to the start of the animation. x is expressed as a floating point number in the range [0,1], where 0 is the start and 1 is the end. t is expressed in milliseconds since the start of the animation. d is the duration of the animation, as specified in the animate call, in milliseconds. b=0 and c=1. The easing function should return a floating point number in the range [0,1], call it `r`. jQuery then computes `x=start+r*(end-start)`, where `start` and `end` are the start and end values of the property as specified in the call to animate, and it sets the property value to `x`. As far as I can see, jQuery doesn't give you direct control over when the animation step function is called, it only lets you say "if I am called at time t, then I should be thus far through the entire animation." Therefore you cannot, for example, ask for your object to be redrawn more frequently at times when it is moving faster. Also, I don't know why other people say b is the start value and c is the change -- that's not what jQuery source code says. If you wanted to define your own easing function to do the same as easeInQuad, for example, $.extend(jQuery.easing,{myfunc:function(x,t,b,c,d) { return x*x; }})$('#marker').animate({left:'800px'},'slow','myfunc'); $.extend(jQuery.easing,{myfunc:function(x,t,b,c,d) { return x*x; }})$('#marker').animate({left:'500px'},'slow','myfunc'); #marker { position: absolute; left: 10px; top: 50px; background: red; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id='marker'>Hello World!</div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5916058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465546/']}
jdg_73224
stackexchange
llm_judgeable_groundtruth_similarity
2048723
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: What is the probability of winning this game? I tried some but the closest I get was $\frac 16 \cdot \frac 16$, but it's not right. Now provide the response and nothing else.
Write down the results of the five rolls and then read them backwards . You win if the "first" result is ever repeated, and you lose if it's not. The probability of losing is $(5/6)^4$ -- i.e., a given roll does not repeat the "first" result with probability $5/6$, and there are $4$ "subsequent" rolls -- so the probability of winning is $$1-\left(5\over6\right)^4={1296-625\over1296}={671\over1296}$$
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/2048723', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/362008/']}
jdg_73225
stackexchange
llm_judgeable_groundtruth_similarity
14882404
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this accordion thing from bootstrap. The arrow icons point down . Then I click on Competency1, I get (Competency1 icon up , Competency2 icon down ): But, if I click on Competency2 now, I get (Competency1 icon is still up , Competency2 icon up ): Is this a bug in bootstrap, or it could be easily fixed? Thanks. Now provide the response and nothing else.
It's hard to offer suggestions without seeing your code. You might be triggering the image swap only on the 'show' event (check for typos in your js). Here is what I use to create the same effect on my sites: HTML: <div class="accordion"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne"> <i class="icon-chevron-down"></i> Collapsible Group Item #1 </a> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo"> <i class="icon-chevron-down"></i> Collapsible Group Item #2 </a> </div> </div></div> JavaScript: $('.accordion').on('show hide', function (n) { $(n.target).siblings('.accordion-heading').find('.accordion-toggle i').toggleClass('icon-chevron-up icon-chevron-down');});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14882404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/610422/']}
jdg_73226
stackexchange
llm_judgeable_groundtruth_similarity
167275
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: According to the definition, light cannot escape from a black hole . How did scientists deduce that light cannot escape from a black hole? Now provide the response and nothing else.
Scientists asked the question "How does a body of arbitrary mass affect spacetime around it?" To answer this question, they took Einstein's General Relativity and applied it to the description of a spherically symmetric spacetime (meaning you can rotate any way you like and it looks the same) centered on a body of arbitrary mass, $M$. I'll spare you the dirty details of this calculation, but what they found it that spacetime can be interpreted (loosely) as "falling" towards a gravitating body. They also found that the direction of an object's motion through time for any path that led away from the gravitating body was given by the sign (positive or negative) of $$1-\frac{2GM}{c^2R}$$ where $G$ is Newton's Gravitational constant, $c$ is the speed of light, and $R$ is the radius of the body. What does this mean? If the sign is positive, that means that paths away from the body move forward in time (meaning we can follow them, since we only move forward). If the sign is negative, paths leading away from the body go backward in time, which means the only way to move away from the body is to go back in time; alternatively, it means any path you choose to take would lead towards the body. If the above expression comes out to be zero, then in GR that means that it is a path light would take. This means that only light could follow paths leading away from the body if the expression gives $0$ and not even light could move away if it is negative. This is how we came to deduce the existence of a black hole. If $1-\frac{2GM}{c^2R}<0$, nothing can escape and if it equals zero, only light can escape. So they said, that means any body of mass $M$ that has a radius $R\le\frac{2GM}{c^2}$ would have a gravitational pull so strong that not even light could enter it and escape afterwards. Because this means that no light could ever come from such a body (and therefore it would look black), and because things fall into it but don't come back out (like a hole), they dubbed it a Black Hole
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/167275', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/73842/']}
jdg_73227
stackexchange
llm_judgeable_groundtruth_similarity
57588
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I observed that dictators often appoint highly educated and qualified technocrats as advisors or spokespersons. For example, Dr. Gowher Rizvi, advisor to Sheikh Hasina, Ph.D. from Oxford University. Ibrahim Kalin, spokesperson of Erdogan, Ph.D. from George Washington University. Bouthaina Shaaban, advisor to Bashar Al Assad, Ph.D. from the University of Warwick. etc. My question is, Do dictators find such people, Or, those people find dictators? Now provide the response and nothing else.
Do dictators find such people, Or, those people find dictators? It's mutual. Dictators need someone to "make the trains run on time" and operating a modern state is a complex enterprise beyond the capacity of the ambitious soldiers and politicians who usually end up as dictators to do without expert advice for very long. So, like any other executive leading a large organization, they hire people to fill these posts and look for people who can provide them with quality advice. In many cases, their view of what quality advice looks like is quite mainstream. Many dictators are not particularly ideologically pure and they often don't have well worked out policy doctrines themselves, instead seizing upon a historical moment to take power when it arises. Hitler and Mao's manifestos were the exception and not the rule among dictators. Ideologically driven and thought out agendas are more common among small "d" democratic politicians and revolutionaries (who often fail entirely or have short lived regimes) in order to persuade large numbers of mid-level elites to join their movement. In contrast, run of the mill dictators tend to be less ideological than political genius manifesto writers. They frequently step into a power vacuum marked by chaos, corruption and incompetence on the part of the democratically elected regimes that they replace, or the incompetence of their authoritarian predecessors whom they replace. Since dictators often rise to power based upon the gross incompetence of a predecessor, being able to show some level of competence is often a significant goal for the new dictator if the dictator wishes to hold onto power for long. Skilled professionals need jobs and also believe in their ideas and long to test out those ideas. Dictatorships allow intellectuals to implement their ideas rapidly and uncompromisingly in a way that democratic political processes which tend towards incrementalism and traditional solutions to social and economic problems rarely do. A famous historical example of this is the advice provided by famed democratic free market supporter and premier economist Milton Friedman who provided economic guidance to military dictator President Augusto Pinochet in Chile the 1970s. Friedman was heavily criticized for this and later attempted to publicly justify his involvement as a voice for positive change from within the regime in the long run (from the same link). During the 2000 PBS documentary The Commanding Heights (based on thebook), Friedman continued to argue that "free markets would undermine[Pinochet's] political centralization and political control.", andthat criticism over his role in Chile missed his main contention thatfreer markets resulted in freer people, and that Chile's unfreeeconomy had caused the military government. Friedman advocated forfree markets which undermined "political centralization and politicalcontrol".
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/57588', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/32479/']}
jdg_73228
stackexchange
llm_judgeable_groundtruth_similarity
3141768
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 that Schwartz space can be considered a dense subset of the Hilbert space isomorphic to $\ell^2$ . What I wish to understand is, how really different Schwartz space is from the Hilbert space. Schwartz space has completeness, and is an inner product space, at least understood as "borrowing" inner product structure from the Hilbert space. This seems to satisfy all the definitions of the Hilbert space. Yet we know that these two spaces are not isomorphic. So what distinguish them? Maybe the problem is that inner product borrowed from the Hilbert space is not natural to the natural topology of Schwartz space? It would be nice if someone clarifies on this. And I believe quantum mechanics uses inner product on Schwartz space, so I guess Schwartz space is understood at least there as an inner product space... Now provide the response and nothing else.
Let $\mathscr{S}$ denote the Schwartz space. We equip this space with a topology by giving it the family of seminorms $$p_{\alpha, \beta}(f) := \sup_{x \in \mathbb{R}^n} |x^\beta \partial^\alpha f(x)|$$ where $\alpha,\beta$ are multi indices. With respect to the induced topology, we know that $\mathscr{S}$ is completely metrizable, as you have noted. On the other hand, one can view $\mathscr{S}$ as a subspace of $L^2(\mathbb{R}^n)$ . Hence, $\mathscr{S}$ inherits an inner-product (and a metric topology). However, this is not the same topology as above! Indeed, $\mathscr{S}$ is not even complete with respect to the metric inherited from $L^2(\mathbb{R}^n)$ . This is because $\mathscr{S}$ is not closed as a subspace of $L^2(\mathbb{R}^n)$ . To see this, simply note that $$\overline{\mathscr{S}} = L^2(\mathbb{R}^n) \neq \mathscr{S}$$ when interpreted as a subspace of $L^2(\mathbb{R}^n)$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3141768', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/651957/']}
jdg_73229
stackexchange
llm_judgeable_groundtruth_similarity
14728652
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Basically I would like to make a light build of GCC with only C/C++ support. Can this be done easily or does it require manual tinkering with source? Now provide the response and nothing else.
This is covered in Installing GCC and Configuration --enable-languages=lang1,lang2,... Specify that only a particular subset of compilers and their runtime libraries should be built. For a list of valid values for langN you can issue the following command in the gcc directory of your GCC source tree: grep language= */config-lang.in Currently, you can use any of the following: all, ada, c, c++, fortran, go, java, objc, obj-c++. Building the Ada compiler has special requirements, see below. If you do not pass this flag, or specify the option all, then all default languages available in the gcc sub-tree will be configured. Ada, Go and Objective-C++ are not default languages; the rest are. So, for your case using: ../gcc/configure --enable-languages=c,c++ should be sufficient, besides other needed options, of course. See also Building Please note, that re-defining LANGUAGES when calling `make' does not work anymore!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14728652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1755847/']}
jdg_73230
stackexchange
llm_judgeable_groundtruth_similarity
341379
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As an example: def get_booking(f=None): print "Calling get_booking Decorator" def wrapper(request, **kwargs): booking = _get_booking_from_session(request) if booking == None: # we don't have a booking in our session. return HttpRedirect('/') else: return f(request=request, booking=booking, **kwargs) return wrapper@get_bookingdef do_stuff(request, booking): # do stuff here The problem I am having is, the @get_booking decorator is being called even before I called the function that I am decorating. Output on start: Calling get_booking DecoratorCalling get_booking DecoratorCalling get_booking DecoratorCalling get_booking DecoratorCalling get_booking DecoratorCalling get_booking DecoratorCalling get_booking DecoratorCalling get_booking DecoratorCalling get_booking DecoratorCalling get_booking Decorator[26/Oct/2008 19:54:04] "GET /onlinebooking/?id=1,2 HTTP/1.1" 302 0[26/Oct/2008 19:54:05] "GET /onlinebooking/ HTTP/1.1" 200 2300[26/Oct/2008 19:54:05] "GET /site-media/css/style.css HTTP/1.1" 200 800[26/Oct/2008 19:54:05] "GET /site-media/css/jquery-ui-themeroller.css HTTP/1.1" 200 25492 I haven't even made a call to a function that is decorated at this point. I am just getting started with decorators, so maybe I am missing something. Now provide the response and nothing else.
I believe python decorators are just syntactic sugar. @foodef bar (): pass is the same thing as def bar (): passbar = foo(bar) As you can see, foo is being called even though bar has not been called. This is why you see the output from your decorator function. Your output should contain a single line for every function you applied your decorator to.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/341379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22306/']}
jdg_73231
stackexchange
llm_judgeable_groundtruth_similarity
17204
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have read about convergence in terms of MC simulation for derivative pricing, but I am not clear on what it exactly means.Let us suppose I price an option 100,000 paths twice and both result in the same option price. Does that mean 100,000 paths has resulted in convergence? Also, in determining the number of paths to use for pricing, is getting the same option price with 2 different runs a factor? (Assumption is I am not reseeding the Random Number. So the sequence of Random Numbers between the two runs is different). Now provide the response and nothing else.
To keep things simple let's assume you have a perfect random number generator (i.e. I will discuss only the statistics not the numerics of the problem). I will also focus on the practical matter and gloss over some mathematical details. From a practical perspective "convergence" means that you will never get an exact answer from Monte-Carlo but increasingly good approximations. Try out your 100'000 paths example. The two values for the price of your option will be slightly different everytime you use a fresh, i.e. independent, sample. Two mathematical theorems are relevant to describe convergence: First, the law of large numbers, which says that the average of independent samples converges to the expected value (i.e. price) and the central limit theorem , which tells you that the distribution of the error converges to a properly scaled normal distribution. This justifies what Mark Joshi is alluding to in his post. You mention a typical and very relevant question: What size samples do I need to achieve a certain prescribed accuracy? If you assume normal distribution of errors you can calculate a confidence interval and solve this expression for the sample size. You will often hear people say that Monte-Carlo "converges very slowly" or "converges with $\sqrt{n}$". This is because to achieve a tenfold increase in accuracy you need a hundredfold increase in number of paths. For a serious study of this important topic I recommend the book by Paul Glasserman
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/17204', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/13648/']}
jdg_73232
stackexchange
llm_judgeable_groundtruth_similarity
5897319
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to use standard template library std::sort() to sort an array declared as int v[2000] ; Does C++ provide some function that can get the begin and end index of an array? Now provide the response and nothing else.
In C++0x/11 we get std::begin and std::end which are overloaded for arrays: #include <algorithm>int main(){ int v[2000]; std::sort(std::begin(v), std::end(v));} If you don't have access to C++0x, it isn't hard to write them yourself: // for container with nested typedefs, non-const versiontemplate<class Cont>typename Cont::iterator begin(Cont& c){ return c.begin();}template<class Cont>typename Cont::iterator end(Cont& c){ return c.end();}// const versiontemplate<class Cont>typename Cont::const_iterator begin(Cont const& c){ return c.begin();}template<class Cont>typename Cont::const_iterator end(Cont const& c){ return c.end();}// overloads for C style arraystemplate<class T, std::size_t N>T* begin(T (&arr)[N]){ return &arr[0];}template<class T, std::size_t N>T* end(T (&arr)[N]){ return arr + N;}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5897319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_73233
stackexchange
llm_judgeable_groundtruth_similarity
57685725
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 load all the pictures from the media provider to my app by using MediaStore API, but this column MediaStore.MediaColumns.DATA is deprecated. So, what can I use as an alternative? I want to update the following code to get rid of the deprecated MediaStore.MediaColumns.DATA column: fun ContentResolver.loadImagesPaths(): List<String> { val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI val images = mutableListOf<String>() val projection = arrayOf(MediaStore.MediaColumns.DATA) query(uri, projection, null, null, null)?.use { cursor -> val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA) while (cursor.moveToNext()) { images += cursor.getString(dataColumn) } } return images} Edit: Updated code: fun ContentResolver.loadImagesUris(): List<Uri> { val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI val images = mutableListOf<Uri>() val projection = arrayOf(MediaStore.Images.Media._ID) query(uri, projection, null, null, null)?.use { cursor -> val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID) while (cursor.moveToNext()) { images += ContentUris.withAppendedId(uri, cursor.getLong(idColumn)) } } return images} Check out this link for further details on how to access media files from shared storage: https://developer.android.com/training/data-storage/shared/media Now provide the response and nothing else.
I was able to replace MediaStore.MediaColumns.Data with its own file ID (incredibly, files have IDs) and correctly constructing its URI, like this: fun getAllShownImagesPath(activity: Activity): MutableList<Uri> { val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI val cursor: Cursor? val columnIndexID: Int val listOfAllImages: MutableList<Uri> = mutableListOf() val projection = arrayOf(MediaStore.Images.Media._ID) var imageId: Long cursor = activity.contentResolver.query(uriExternal, projection, null, null, null) if (cursor != null) { columnIndexID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID) while (cursor.moveToNext()) { imageId = cursor.getLong(columnIndexID) val uriImage = Uri.withAppendedPath(uriExternal, "" + imageId) listOfAllImages.add(uriImage) } cursor.close() } return listOfAllImages} and then with Uri you build it in your Views!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57685725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11987204/']}
jdg_73234
stackexchange
llm_judgeable_groundtruth_similarity
19554
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: According to Wikipedia : Under Article 59 (1) of the Basic Law (German Constitution), the President represents the Federal Republic of Germany in matters of international law, concludes treaties with foreign states on its behalf and accredits diplomats. So it seems to me that (at least on paper) it's the German President who should be signing international treaties such as the Paris Climate Accords. But in reality few people outside of Germany know the President's name and many don't even realize the position exists. So what are the de facto powers of the German President and why is he involved so little in international matters? Now provide the response and nothing else.
The reason is largely historical, the office of President was first introduced in the Weimar Republic of Germany, with significant political powers according to its constitution. Article 25 of the Weimar Constitution the President had the power to unilaterally dissolve the Reichstag Article 48 of the Weimar Constitution the President had the power to unilaterally suspend civil liberties. Article 53 of the Weimar Constitution the President had the power to unilaterally appoint and dismiss the Chancellor and the cabinet. Basically this created a very unstable sort of government and the Reichstag was constantly getting dismissed and re-elected. Indeed there were 8 elections between 1919 and 1932. Also the cabinet of the Weimar government kept getting appointed and dismissed as the President would appoint them, but they didn't enjoy support in the Reichstag who would promptly dismiss them. This led to the President Hindenburg appointing a bunch of cabinets who outright didn't enjoy support in the Reichstag and were referred to as "presidential" cabinets. However it all changed in 1933 when Adolf Hitler rose to power, to some degree through abusing powers invested in the office of the President such as with the Reichstag Fire Decree . I quote a translated copy of the text below: On the basis of Article 48 (Weimar Constitution) paragraph 2 of the Constitution of the German Reich, the following is ordered in defense against Communist state-endangering acts of violence: Articles 114, 115, 117, 118, 123, 124 and 153 of the Constitution of the German Reich are suspended until further notice. It is therefore permissible to restrict the rights of personal freedom habeas corpus, freedom of (opinion) expression, including the freedom of the press, the freedom to organize and assemble, the privacy of postal, telegraphic and telephonic communications. Warrants for House searches, orders for confiscations as well as restrictions on property, are also permissible beyond the legal limits otherwise prescribed. As you can see this was clearly an abuse of the power of the president and it along with the Enabling Act led to the downfall of democracy in Germany and the rise of Hitler as chancellor. In 1934 Hitler combined the offices of President and Chancellor to become the Fuhrer So in 1949 when the West German Basic Law (or constitution) was written, the authors intentionally reduced the powers of the president and made him indirectly elected i.e elected by the Federal Convention (which basically consists of the entirety of the Bundestag and some other regional leaders) instead of the public. Now some dude who is indirectly voted in by the parliament isn't going to garner international headlines unless he is particularly controversial, since in a democracy he isn't that powerful. Also because the public don't need to go to a polling booth to tick his name they simply don't know or don't care. Nowadays the de facto powers largely lie in the fact that the President of Germany has considerable leeway in exercising his duties, which are quoted as follows : Proposing the Chancellor to the Bundestag. Appointing and dismissing the Chancellor and Federal Ministers Dissolving the Bundestag under certain circumstances Convening the Bundestag according to article 39 of the constitution Signing and promulgating laws Appointing and dismissing federal judges, federal civil servants, and commissioned and non-commissioned officers of the Armed Forces Exercising the power to pardon individual offenders on behalf of the Federation Awarding honors on behalf of the Federation Representing Germany at home and abroad For example he could independently make representations and political suggestions which would not be allowed to some other heads of state whose role is more ceremonial e.g Her Majesty the Queen . The President of Germany also possesses some reserve powers if all goes to pot as outlined by Article 81 of Basic Law Legislative emergency (1) If, in the circumstances described in Article 68, the Bundestag is not dissolved, the Federal President, at the request of the Federal Government and with the consent of the Bundesrat, may declare a state of legislative emergency with respect to a bill, if the Bundestag rejects the bill although the Federal Government has declared it to be urgent. The same shall apply if a bill has been rejected although the Federal Chancellor had combined it with a motion under Article 68. (2) If, after a state of legislative emergency has been declared, the Bundestag again rejects the bill or adopts it in a version the Federal Government declares unacceptable, the bill shall be deemed to have become law to the extent that it receives the consent of the Bundesrat. The same shall apply if the Bundestag does not pass the bill within four weeks after it is reintroduced. (3) During the term of office of a Federal Chancellor, any other bill rejected by the Bundestag may become law in accordance with paragraphs (1) and (2) of this Article within a period of six months after the first declaration of a state of legislative emergency. After the expiration of this period, no further declaration of a state of legislative emergency may be made during the term of office of the same Federal Chancellor. (4) This Basic Law may neither be amended nor abrogated nor suspended in whole or in part by a law enacted pursuant to paragraph (2) of this Article. TLDR: President is basically ceremonial, but has some leeway in exercise of duties. You haven't heard of him because the public don't elect him and his powers were cut because Hitler used them to become a dictator.
{}
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/19554', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/7434/']}
jdg_73235
stackexchange
llm_judgeable_groundtruth_similarity
16605099
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 update scheme and initial data in spring context using the following beean: <bean id="liquibase" class="liquibase.integration.spring.SpringLiquibase"> <property name="dataSource" ref="dataSource" /> <property name="changeLog" value="classpath:db/changelog/db.changelog-master.xml" /> <property name="dropFirst" value="true" /></bean> I also use Maven liquibase plugin to generate sql scripts in order to see what tables are created and etc. <plugin> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>2.0.5</version> <configuration> <!--mvn initialize liquibase:updateSQL--> <propertyFile>src/main/resources/db/config/liquibase-gensql-data-access.properties</propertyFile> <changeLogFile>src/main/resources/db/changelog/db.changelog-master.xml</changeLogFile> </configuration> </plugin> The db.changelog-master.xml file includes child liquibase changelog files. The problem, how to refer to them from the master. When I use Spring I have to use the following path via classpath: <include file="classpath:/db/changelog/db.changelog-1.0.xml"/> When Maven is used, the path is: <include file="src/main/resources/db/changelog/db.changelog-1.0.xml"/> I'd like to have the same configuration for both cases. How can I archive it? Now provide the response and nothing else.
I commented on Igor's answer, his solution does not seem to work. In order to solve this, I just pushed a patch to Liquibase: https://github.com/liquibase/liquibase/pull/187 . This should be merged in 3.0.6-SNAPSHOT and therefore shortly available in 3.0.6. With this change, you can now configure SpringLiquibase with this additional line: <property name="ignoringClasspathPrefix" value="true" /> Another example/usecase requiring this change can be found here: https://github.com/LateralThoughts/spring-liquibase-extensions .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16605099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/511804/']}
jdg_73236
stackexchange
llm_judgeable_groundtruth_similarity
16636374
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 think that my code should make the ViewBag.test property equal to "No Match" , but instead it throws an InvalidOperationException . Why is this? string str = "Hello1,Hello,Hello2";string another = "Hello5";string retVal = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) .First(p => p.Equals(another));if (str == another){ ViewBag.test = "Match";}else{ ViewBag.test = "No Match"; //this does not happen when it should} Now provide the response and nothing else.
As you can see here , the First method throws an InvalidOperationException when the sequence on which it is called is empty. Since no element of the result of the split equals Hello5 , the result is an empty list. Using First on that list will throw the exception. Consider using FirstOrDefault , instead (documented here ), which, instead of throwing an exception when the sequence is empty, returns the default value for the type of the enumerable. In that case, the result of the call will be null , and you should check for that in the rest of the code. It might be cleaner still to use the Any Linq method (documented here ), which returns a bool . string str = "Hello1,Hello,Hello2";string another = "Hello5";bool retVal = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) .Any(p => p.Equals(another));if (retVal){ ViewBag.test = "Match";}else{ ViewBag.test = "No Match"; //not work} And now the obligatory one liner using the ternary operator : string str = "Hello1,Hello,Hello2";string another = "Hello5";ViewBag.test = str.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) .Any(p => p == another) ? "Match" : "No Match"; Note that I also used == here to compare strings, which is considered more idiomatic in C#.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16636374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2398766/']}
jdg_73237
stackexchange
llm_judgeable_groundtruth_similarity
24176
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Raid-1 is mirroring two disks (if I haven't messed up completely here :p). Does that mean that I could take one disk out and put it into another machine and it would work like a normal disk? Or does it still only work in the raid? I can understand that a Raid-0 of course only works as a whole. But with mirroring I am not so sure how it works... Of course putting the mirrored disk back in the raid afterwards would be a bad idea, but just taking it out... how would that work? Does raid store any special data on a drive that is needed? or does the raid controller handle everything like that and the harddrives are just used like normal? Now provide the response and nothing else.
Well, the REAL answer is that it depends on the RAID controller. There's Hardware RAID and there's 'Fake RAID' -- which is basically a ROM implementation of software RAID. Fake Raid will always require the same controller, just as using a linux software raid will require the same operating system (and sometimes the same kernel module version). Real hardware RAID will SOMETIMES mean that you can swap them between machines, but in some cases you will need to have the same or a similar RAID card. One case where I've seen this is with a RAID5 volume on a Dell PERC/3di card. I haven't ever tried it with RAID1, but I understand it's possible. Does raid store any special data on a drive that is needed? Usually, yes, it does. or does the raid controller handle everything like that and the harddrives are just used like normal? Sometimes this is true -- either independently from the data on the drive, or in concert with data on the drive. i.e. the drive may have metadata readable only to a certain class of controller that says it was part of a RAID1 pair, and other controllers will ignore that metadata.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/24176', 'https://serverfault.com', 'https://serverfault.com/users/773/']}
jdg_73238
stackexchange
llm_judgeable_groundtruth_similarity
609673
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have, at the four corners of a square $ABCD$ of side length $a$ , listed cyclically, the charges $+2q, +q, +2q, -5q$ .When I calculate the electric field $\mathbf{E}$ at the centre of the square, I get $$\mathbf{E} = \frac{12q}{4\pi \epsilon_0 a^2}\mathbf{\hat{r}}$$ from the principle of superposition of charges. but when I calculate the potential at the centre, I get $V = 0$ , again from superposition. How can I fit this in line with the relation $-\nabla V = E$ ? Now provide the response and nothing else.
$V=0$ at the center , but how does $V$ change as you move away from that point? $\nabla V$ doesn't care about the value of $V$ , it cares about the rate of change of $V$ . More directly, the appropriate thing to do here would be to calculate $V(x,y)$ for arbitrary $x$ and $y$ . From there you can take your derivatives, and only at the end would you set $x$ and $y$ to the coordinates of the center of your square. You should expect this exercise to be somewhat tedious. It’s also unnecessary - once you understand it for one particle it extends to many because differentiation is linear - but you may certainly do it if you wish.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/609673', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/259879/']}
jdg_73239
stackexchange
llm_judgeable_groundtruth_similarity
122499
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $X$ be an irreducible smooth projective algebraic curve over $\mathbb{C}$. Then, the Abel-Jacobi map gives embedding $X \hookrightarrow Jac(C)$ of $C$ into it's Jacobian. This map induces an isomorphism on $H_1$. Question: Can it be made obvious, using purely topological reasoning, that a connected, oriented compact 2-dimensional topological manifold of genus $g$ embeds into a torus $\phi: C \rightarrow (S^1)^{2g}$, so that $\phi$ induces an isomorphism on $H_1$? I don't know how to see this without using the Abel-Jacobi theorem. Now provide the response and nothing else.
Yes. We will come up with $g$ maps from the Riemann surface to the two-dimensional torus. We can then take the product of these maps. As long as one of them is nonconstant at each point, it will be an embedding. View the Riemann surface in the standard way as a handlebody that looks like a bunch of tori glued together . (Presumably the classification of Riemann surfaces, which we use to put it in this form, counts as purely topological reasoning!) There are $g$ tori. Pick one, and contract all but that one to a point. If that is one of the tori at the ends, then all the rest of the surface gets contracted to a single point. If it's in the middle, the left half gets contracted to a point on the left side of the torus and the right side gets contracted to a point on the right side of the torus. This set of $g$ maps gives us the associated kind of map. Clearly, this gives an isomorphism on homology. To make sure this is an embedding, we have to make sure that no point on the torus gets contracted in every single map. We will do this by defining the maps a little generously, such that the stuff that is contracted for the leftmost torus ends a little bit to the right of where the stuff contracted for the second-leftmost torus begins. Hopefully this explanation makes sense! My picture-drawing skills are not up to the task of realizing this.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/122499', 'https://mathoverflow.net', 'https://mathoverflow.net/users/25854/']}
jdg_73240