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
19216333
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 going to block all US IPs using .htaccess this way : <Limit GET HEAD POST>order deny,allowdeny from 3.0.0.0/8deny from 4.0.0.0/25deny from 4.0.0.128/26deny from 4.0.0.192/28deny from 4.0.0.208/29....allow from all</Limit> Will Google be able to access and index my website after blocking all US IPs? EDIT : Sorry for the ambiguity, but I DO want Google to index my website. Now provide the response and nothing else.
Although Google has its servers spread across the whole world, it would be quite hard to say where the search engine's bots mostly originate from. What I suggest would be to block the IP ranges but add an exclusion clause that matches against the User-Agent for search bots like: SetEnvIfNoCase User-Agent (googlebot|bingbot|yahoo!\sslurp) is_search_bot<Directory /docroot> Order Deny,Allow Deny from 3.0.0.0/8 Deny from 4.0.0.0/25 Deny from 4.0.0.128/26 Deny from 4.0.0.192/28 Deny from 4.0.0.208/29 Allow from env=is_search_bot</Directory>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19216333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1719496/']}
jdg_75441
stackexchange
llm_judgeable_groundtruth_similarity
6313539
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My question is similar to this one , but with regard to Java instead of Python. How can I force some Java code to run whenever a new instance of a Google App Engine server starts? Thanks! Now provide the response and nothing else.
in google app engine, your java code is executed within the servlet environment. thus, you could define listeners to boostrap your startup code. to do this, you need to implement your startup code in the listener and define the listener in your web.xml: listner class: package test;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;public class MyContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { // startup code here } @Override public void contextDestroyed(ServletContextEvent sce) { // shutdown code here }} web.xml: <web-app> <listener> <listener-class>test.MyContextListener</listener-class> </listener><!-- your other web configuration --></web-app>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6313539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111206/']}
jdg_75442
stackexchange
llm_judgeable_groundtruth_similarity
28405556
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 install PostgreSQL for a node project that I'm developing in OSX Yosemite . I use MacPorts and so tried the method described here: https://github.com/codeforamerica/ohana-api/wiki/Installing-PostgreSQL-with-MacPorts-on-OS-X ...but I get an error during step 2: $ sudo gem install pg -- --with-pg-config=/opt/local/lib/postgresql93/bin/pg_config > ruby_errorERROR: Error installing pg: ERROR: Failed to build gem native extension. /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb --with-pg-config=/opt/local/lib/postgresql93/bin/pg_configUsing config values from /opt/local/lib/postgresql93/bin/pg_configchecking for libpq-fe.h... yeschecking for libpq/libpq-fs.h... yeschecking for pg_config_manual.h... yeschecking for PQconnectdb() in -lpq... nochecking for PQconnectdb() in -llibpq... nochecking for PQconnectdb() in -lms/libpq... noCan't find the PostgreSQL client library (libpq)*** extconf.rb failed ***Could not create Makefile due to some reason, probably lack of necessarylibraries and/or headers. Check the mkmf.log file for more details. You mayneed configuration options. ...thinking that I may not need to install the pg gem since I want to work with Node and not Ruby, I moved on to the next steps. But there I run into an error during step 3.3: $ sudo su postgres -c '/opt/local/lib/postgresql93/bin/initdb -D /opt/local/var/db/postgresql93/defaultdb'shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission deniedcould not identify current directory: Permission deniedcould not identify current directory: Permission deniedcould not identify current directory: Permission deniedThe program "postgres" is needed by initdb but was not found in thesame directory as "initdb".Check your installation. ...checking my /opt/local/lib/postgresql93/bin/ directory, I see both initdb and postgres . I see those lines saying Permission denied and am wondering what that's about. Not sure how to progress. Thinking of using Postgres.app if it really is easier but not sure whether it would be better to install using MacPorts since I install most other things using MacPorts. Tips about any of my problems are appreciated! Now provide the response and nothing else.
The permissions/ownership on the directories between / and defaultdb likely need to be fixed. I think PostgreSQL can be sensitive to ownership of these, though it seems that in your case PostgreSQL simply doesn't have access to those. This is what I have for each directory. $ ls -hlt /opt/local/var/db/total 0drwxr-xr-x 7 root admin 238B Jan 23 16:54 texmfdrwxr-xr-x 3 root admin 102B Dec 25 07:37 postgresql94 You could fix permissions by doing sudo chmod a+rx /opt/local/var/db/ as needed. For the defaultdb directory itself, you should follow the instructions that you link to, which seem to have the same as I have: sudo chown postgres:postgres /opt/local/var/db/postgresql93/defaultdb Below are instructions adapted from my blog (though I recommend using PostgreSQL 9.4, which I now do). I've been running PostgreSQL using MacPorts since 9.1 without major problems. 1. Install PostgreSQL using MacPorts. Of course, I assume you’ve got MacPorts up and running on your system. sudo port install postgresql93 +perl +python27sudo port install postgresql93-server 2. Set up PostgreSQL I first need to initialize the database cluster and then get the server running. The following comes straight from the on-screen instructions supplied with the MacPorts port postgresql93-server . sudo mkdir -p /opt/local/var/db/postgresql93/defaultdbsudo chown postgres:postgres /opt/local/var/db/postgresql93/defaultdbsudo su postgres -c '/opt/local/lib/postgresql93/bin/initdb -D /opt/local/var/db/postgresql93/defaultdb' Note that MacPorts creates a launch daemon. To load it now and to make sure it launches on system start, do: sudo defaults write /Library/LaunchDaemons/org.macports.postgresql93-server.plist Disabled -bool falsesudo launchctl load /Library/LaunchDaemons/org.macports.postgresql93-server.plist I then use psql for some set-up to get my database going. sudo su - postgres/opt/local/lib/postgresql93/bin/psql -U postgres -d template1 If you get to here, then you have PostgreSQL running on your system.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28405556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1490350/']}
jdg_75443
stackexchange
llm_judgeable_groundtruth_similarity
121023
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: From Wikipedia : If $M$ is a metric space with metric $d$, and $\sim$ is an equivalence relation on $M$, then we can endow the quotient set $M/{\sim}$ with the following (pseudo)metric. Given two equivalence classes $[x]$ and $[y]$, we define $$ d'([x],[y]) = \inf\{d(p_1,q_1)+d(p_2,q_2)+\dotsb+d(p_{n},q_{n})\} $$ where the infimum is taken over all finite sequences $(p_1, p_2, \dots, p_n)$ and $(q_1, q_2, \dots, q_n)$ with $[p_1]=[x], [q_n]=[y], [q_i]=[p_{i+1}], i=1,2,\dots, n-1$. In general this will only define a pseudometric, i.e. $d'([x],[y])=0$ does not necessarily imply that $[x]=[y]$. However for nice equivalence relations (e.g., those given by gluing together polyhedra along faces), it is a metric. I wonder why the quotient metric is defined that way? Instead, how about using the distance between two subsets of the metric space $$ d'([x],[y]) = \inf\{d(p,q)\} $$ the infimum is taken over all $(p,q)$ such that $[p]=[x], [q]=[y]$? Thanks and regards! Now provide the response and nothing else.
This is to ensure the triangle inequality. In your proposal, it can happen that $[p]$ and $[q]$ have nearby representatives and $[q]$ and $[r]$ have nearby representatives, but the two representatives of $[q]$ involved are different, so this doesn't guarantee that $[p]$ and $[r]$ have nearby representatives, so the triangle inequality may be violated. With the Wikipedia definition, on the other hand, it's straightforward to verify the triangle inequality, since any chain of points from $[p]$ to $[q]$ and any chain of points from $[q]$ to $[r]$ can be concatenated to form a chain of points from $[p]$ to $[r]$, so the triangle inequality follows from the individual triangle inequalities. In particular, in the above situation, we can "hop" from one representative of $[q]$ to the other without extra cost.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/121023', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1281/']}
jdg_75444
stackexchange
llm_judgeable_groundtruth_similarity
3993982
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 check to make sure my variable is an int, array, double, etc...? Edit: For example, how can I check that a variable is an array? Is there some function to do this? Now provide the response and nothing else.
Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type). The examples you gave ( int , array, double ) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int : int x; You can be sure it will only ever hold int values. If you declared a variable to be a List , however, it is possible that the variable will hold sub-types of List . Examples of these include ArrayList , LinkedList , etc. If you did have a List variable, and you needed to know if it was an ArrayList , you could do the following: List y;...if (y instanceof ArrayList) { ...its and ArrayList...} However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3993982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170365/']}
jdg_75445
stackexchange
llm_judgeable_groundtruth_similarity
1356045
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a TextBox and a Button in my view. Now I am checking a condition upon button click and if the condition turns out to be false, displaying the message to the user, and then I have to set the cursor to the TextBox control. if (companyref == null){ var cs = new Lipper.Nelson.AdminClient.Main.Views.ContactPanels.CompanyAssociation(); MessageBox.Show("Company does not exist.", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); cs.txtCompanyID.Focusable = true; System.Windows.Input.Keyboard.Focus(cs.txtCompanyID);} The above code is in the ViewModel. The CompanyAssociation is the view name. But the cursor is not getting set in the TextBox . The xaml is: <igEditors:XamTextEditor Name="txtCompanyID" KeyDown="xamTextEditorAllowOnlyNumeric_KeyDown" ValueChanged="txtCompanyID_ValueChanged" Text="{Binding Company.CompanyId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ActualWidth, ElementName=border}" Grid.Column="1" Grid.Row="0" VerticalAlignment="Top" HorizontalAlignment="Stretch" Margin="0,5,0,0" IsEnabled="{Binding Path=IsEditable}"/><Button Template="{StaticResource buttonTemp1}" Command="{Binding ContactCommand}" CommandParameter="searchCompany" Content="Search" Width="80" Grid.Row="0" Grid.Column="2" VerticalAlignment="Top" Margin="0" HorizontalAlignment="Left" IsEnabled="{Binding Path=IsEditable}"/> Now provide the response and nothing else.
Let me answer to your question in three parts. I'm wondering what is "cs.txtCompanyID" in your example? Is it a TextBox control? If yes, then you are on a wrong way. Generally speaking it's not a good idea to have any reference to UI in your ViewModel. You can ask "Why?" but this is another question to post on Stackoverflow :). The best way to track down issues with Focus is... debugging .Net source code. No kidding. It saved me a lot of time many times. To enable .net source code debugging refer to Shawn Bruke's blog. Finally, general approach that I use to set focus from ViewModel is Attached Properties. I wrote very simple attached property, which can be set on any UIElement. And it can be bound to ViewModel's property "IsFocused" for example. Here it is: public static class FocusExtension{ public static bool GetIsFocused(DependencyObject obj) { return (bool) obj.GetValue(IsFocusedProperty); } public static void SetIsFocused(DependencyObject obj, bool value) { obj.SetValue(IsFocusedProperty, value); } public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached( "IsFocused", typeof (bool), typeof (FocusExtension), new UIPropertyMetadata(false, OnIsFocusedPropertyChanged)); private static void OnIsFocusedPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var uie = (UIElement) d; if ((bool) e.NewValue) { uie.Focus(); // Don't care about false values. } }} Now in your View (in XAML) you can bind this property to your ViewModel: <TextBox local:FocusExtension.IsFocused="{Binding IsUserNameFocused}" /> Hope this helps :). If it doesn't refer to the answer #2. Cheers.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1356045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111663/']}
jdg_75446
stackexchange
llm_judgeable_groundtruth_similarity
142344
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Hello I have just set up a DNS server for my domain example.org with 2 name servers ns1.example.org and ns2.example.org. I have attempted to set up a glue record for ns1 and ns2 at my registrar. It seems to work for now when I do a dig example.org but when I do a whois example.org it lists ns1.example.org and ns2.example.org but not their IP address which should be set up as a glue record. So I am wondering how do I check for the existence of a glue record? Do I do it with whois? I have seen .com and .net whois records that have both the domain name as well as the IP address for the name servers, is .org different? What's the proper way to test this? Thanks. Now provide the response and nothing else.
Glue records only ever exist in the parent zone of a domain name. Hence in the case of your example.org domain name, first find the .org name servers: % dig +short org. NSa0.org.afilias-nst.info.a2.org.afilias-nst.info.b0.org.afilias-nst.org.b2.org.afilias-nst.org.c0.org.afilias-nst.info.d0.org.afilias-nst.org. Then, for as many of these as you feel like testing, explicitly ask those name servers for the NS records for your domain: % dig +norec @a0.org.afilias-nst.info. example.org. NS You should get back the correct list of NS records in the "AUTHORITY SECTION". For any name servers that have correctly configured glue you should see those glue A (and/or AAAA ) records appear in the "ADDITONAL SECTION".
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/142344', 'https://serverfault.com', 'https://serverfault.com/users/-1/']}
jdg_75447
stackexchange
llm_judgeable_groundtruth_similarity
5751091
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 simply cannot wrap my head around how to solve this problem and after a thorough search on Google with no results, I turn to you with hopes of a solution. Given the sample array below: array( 'Type' => array( 'Toppe', 'Bukser_og_Jeans' ), 'Size' => array( 'Extra_small', 'Small' ), 'Colour' => array( 'Rod' )) (Note: This is merely a sample; the actual real life situation might have less/more groups and/or elements per group) How would I go about ending up with the following result? Toppe,Extra_small,RodToppe,Small,RodBukser_og_Jeans,Extra_small,RodBukser_og_Jeans,Small,Rod This is a product search and the API only allows ONE 'refinement' value from each of the Type, Size and Colour groups per query but my assignment requires to query and aggregate the results of multiple API queries. I'm thinking that I need some kind of recursive function to do it, but I have been unable to even produce any code that comes close to my expected result. All I've been able to find on Google is about permuations of letters or even strings, but where people need e.g. "Red,Blue,Green", "Blue,Red,Green", "Green,Red,Blue", etc., which is, clearly, not what I'm looking for. I hope someone here understands what I want to do and has an idea of how to do it. EDIT: The solution as posted by @ikegami, converted to PHP: $iter = 0;while (1) { $num = $iter++; $pick = array(); foreach ($refinements as $refineGroup => $groupValues) { $r = $num % count($groupValues); $num = ($num - $r) / count($groupValues); $pick[] = $groupValues[$r]; } if ($num > 0) { break; } print join(', ', $pick)."\n";} Now provide the response and nothing else.
If we had three groups of ten items, we could use a counter that goes from 0 to 999, and split the number into digits. For example, 456 % 10 = 6 -------------------------- Item 6 (7th item) in the first group / 10 = 45 % 10 = 5 ---------------- Item 5 (6th item) in the second group / 10 = 4 % 10 = 4 ------ Item 4 (5th item) in the third group / 10 = 0 This algorithm converts a number into base 10. If we wanted to convert to octal, we would have used 8 instead of 10. 10 (or 8) is used throughout because each position has the same number of symbols, but this algorithm also works if the number of symbols varies from position to position. 2 % 2 = 0 ------------------------ Item 0 (1st item) in the first group: Toppe / 2 = 1 ^ % 2 = 1 --------------- Item 1 (2nd item) in the second group: Small | / 2 = 0 | ^ % 1 = 0 ------ Item 0 (1st item) in the third group: Rod | | / 1 = 0 | | ^ | | | | | +------------ Number of items in third group | +--------------------- Number of items in second group +------------------------------ Number of items in first group This gives us: 0 = ( 0 * 1 + 0 ) * 2 + 0 = Toppe, Extra_small, Rod1 = ( 0 * 1 + 0 ) * 2 + 1 = Bukser_og_Jeans, Extra_small, Rod2 = ( 0 * 1 + 1 ) * 2 + 0 = Toppe, Small, Rod3 = ( 0 * 1 + 1 ) * 2 + 1 = Bukser_og_Jeans, Small, Rod The following is a Perl implementation: my %refinements = ( Type => [ 'Toppe', 'Bukser_og_Jeans', ], Size => [ 'Extra_small', 'Small', ], Colour => [ 'Rod', ],);my @groups = values(%refinements);my $iter = 0;while (1) { my $num = $iter++; my @pick; for my $group (@groups) { my $r = $num % @$group; $num = ( $num - $r ) / @$group; push @pick, $group->[$r]; } last if $num > 0; say join(', ', @pick);} I know it's not PHP—I don't know PHP—but you're just asking how to solve the problem, not necessarily the code to do it, right? It's my hope that you can understand the above Perl code enough to solve your problem and re-implement it in PHP. (If I was actually writing a Perl solution, I'd use Algorith::Loops 's NestedLoops .)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5751091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/691642/']}
jdg_75448
stackexchange
llm_judgeable_groundtruth_similarity
712821
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: Consider Minkowski space, which is determined by the spacetime line element $$ ds^{2} = -c^{2}dt^{2} + dx^{2} + dy^{2} + dz^{2}. $$ Now suppose we modify this so that the $c$ constant is not a constant, but a function of time with respect to a fixed reference frame, so instead of the above we have $$ ds^{2} = -c(t)^{2}dt^{2} + dx^{2} + dy^{2} + dz^{2}. $$ Now an interesting observation here is that we can rescale the time coordinate so that the prefactor for the time element can be made constant again. In other words, we can define another notion of time in which the speed of light is constant. In more detail, let $c_{0}$ be the usual speed of light constant and let $c(t)$ be the speed of light function from above. Then let $f$ be any solution of the first-order ODE $$ f'(t)t + f(t) = \frac{c(t)}{c_{0}}. $$ Then take the change of coordinates by $$ T = f(t)t, \qquad X = x, \qquad Y = y, \qquad Z = z. $$ Then $$ \frac{dT}{dt} = f'(t)t + f(t) \implies dT = (f'(t)t + f(t))dt \implies c_{0}dT = c(t) dt. $$ In the new coordinates, we find $$ ds^{2} = -c_{0}^{2} dT^{2} + dX^{2} + dY^{2} + dZ^{2} $$ and in these new coordinates it seems as though the speed of light is constant. This brings me to the question, what exactly would it even mean for the $c$ constant to vary? It seems like even if we allow $c$ to vary, there is still a coordinate system where $c$ is constant. I find this to be very confusing, and I am wondering if anyone can help clear this confusion. Now provide the response and nothing else.
You are correct and in good modern treatments, people are careful to say that it's only meaningful to say that dimensionless quantities change with time. The "grown up version" of looking at variations of the speed of light is to look at variations in the fine structure constant $\alpha$ , which (in SI units) is given by \begin{equation}\alpha = \frac{1}{4\pi \epsilon_0} \frac{e^2}{\hbar c}\end{equation} According to wikipedia , there is a bound on the time variation of $\alpha$ to be less than one part in $10^{17}$ per year based on precision measurements of optical clocks. I do not claim this is the best available bound at the time I am writing this answer, however; just one that I could find with a quick google search. To answer your question more directly, of course those experiments placing an upper bound of the time variation of $\alpha$ could also (theoretically) detect time variation of $\alpha$ , which would imply that at least one of $e$ , $\hbar$ , $\epsilon_0$ , or $c$ must change with time (we can hopefully agree that $1$ , $4$ , and $\pi$ are safe :))
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/712821', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/123113/']}
jdg_75449
stackexchange
llm_judgeable_groundtruth_similarity
181427
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is the class of all 2-countable manifolds a set? I think so: each such space is a countable union of sets of cardinality $|\mathbb{R}^n|\!=\!|\mathbb{R}|$, i.e. a manifold has cardinality continuum, and there are less than $\mathbb{R}^\mathbb{R}$ ways of gluing it together. Why then is this set still called a class? Now provide the response and nothing else.
No, the class of all manifolds (2nd countable) that are is not quite a set, as it is a proper class. To see this, let us consider the "isomorphism class" of the connected zero dimensional manifolds. This is just a point. But their are as many singletons as their are sets. To each set $S$, we may associate a singleton, $\{S\}$, which may be regarded as a manifold. The upshot is that all of the UP TO ISOMORPHISM, their is only one such point. A similar thing may be said of 2nd countable manifolds. Their is a class worth of these things, but if you select one representitive from each equivalence class, you do get a set. One might say that the category of 2nd countable manifolds is not small, but ESSENTIALLY SMALL.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/181427', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7325/']}
jdg_75450
stackexchange
llm_judgeable_groundtruth_similarity
14093242
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I write parse() function, can I yield both a request and items for one single page? I want to extract some data in page A and then store the data in database, and extract links to be followed (this can be done by rule in CrawlSpider). I call the links pages of A pages is B pages, so I can write another parse_item() to extract data from B pages, but I want to extract some links in B pages, so I can only use rule to extract links? how to tackle with the duplicate URLs in Scrapy? Now provide the response and nothing else.
Yes, you can yield both requests and items. From what I've seen : def parse(self, response): hxs = HtmlXPathSelector(response) base_url = response.url links = hxs.select(self.toc_xpath) for index, link in enumerate(links): href, text = link.select('@href').extract(), link.select('text()').extract() yield Request(urljoin(base_url, href[0]), callback=self.parse2) for item in self.parse2(response): yield item
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14093242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1448607/']}
jdg_75451
stackexchange
llm_judgeable_groundtruth_similarity
1376688
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 company has been using XML-RPC for a while, but lately I'm wondering what the benefit is of XML-RPC compared to plain XML. Firstly, it's horrible "obese", consider: <struct> <member> <name>ROOM_ID</name> <value> <int>1</int> </value> </member> <member> <name>CODE</name> <value> <string>MR-101</string> </value> </member> <member> <name>NAME</name> <value> <string>Math Room</string> </value> </member> <member> <name>CAPACITY</name> <value> <int>30</int> </value> </member></struct> Compared to this: <room><ROOM_ID>1</ROOM_ID><CODE>MR-101</CODE><NAME>Math Room</NAME><CAPACITY>30</CAPACITY></room> Or even this: <room ROOM_ID=1 CODE=MR-101 NAME=”Math Room” CAPACITY=30 /> Secondly, XML-RPC seems fairly widespread but not quite ubiquitous and I'm not that impressed with the support for it in C++ and PHP. I've had problems with all the libraries that I tried in both languages. Thirdly, it seems to me that I could make remote procedure calls with plain XML as easily as with XML-RPC. {(9/9/2009): Every language has libraries for serialising language-level objects into XML. Both XML and XML-RPC require application-level schemas to be defined, for example, how the fields should be spelt, but neither needs any additional schema to be defined. Many people make RPC calls with plain XML.} So what is the value-add of XML-RPC? Now provide the response and nothing else.
The short answer is: Both protocols can be used to make remote procedure calls (RPC). Both protocols require an application-level schema to be defined, and generally speaking, neither protocol requires any additional schema for defining how to serialise language-level objects (see below for some details). However, XmlRpc enjoys greater support from libraries which use meta-programming (reflection) features of language to map XmlRpc calls, directly (well, never 100% directly) to language level function calls. The reason there is better support for XmlRpc than plain XML is either (a) a historical accident/result of marketing on the part of the XmlRpc proponents, or (b) the sum of the minor translation issues listed below tip the scales in favour of XmlRpc. On the other hand, XmlRpc suffers from 2 main disadvantages: (1) it requires approximately 4 times as much bandwidth, and (2) it subverts the intent of XML schema-validation tools: every packet will simply be stamped as "yes, this is valid XmlRpc", regardless of spelling mistakes and omissions in application-level fields. The long answer: Contrary to popular belief, you don't need a standard to define how to encode language level objects in plain XML - there is generally just one "sensible" way (provided the application level schema defines whether you use XML attributes or not), e.g.: class Room { int id=1; String code="MR-101"; String name="Maths room"; int capacity=30;}; encoded as: <Room> <id>1</id> <code>MR-101</code> <name>Maths room</name> <capacity>30</capacity></Room> XmlRpc was specifically designed to facilitate the creation of libraries which automatically serialise/unserialise language-level objects in RPC calls, and as such it has some minor advantages when used in this way: With plain XML, it's possible for a struct with a single member to be confused with an array with a single element. XmlRpc defines a standard time/date format. {Although treatment of timezones and pure time or pure date timestamps is defined at the application level.} XmlRpc lets you pass arguments to the function without naming them; Plain XML RPC calls require that you name each argument. XmlRpc defines a standard way to name the method being called: "methodName". With Plain XML, the tag of the root node would typically be used for this purpose, although alternatives are possible. XmlRpc defines a simple type system: integers, strings, and so on. {Note that with statically typed languages, the types have to be compiled into the destination object anyway, and therefore are known, and with dynamically typed languages, often int's and float's and strings can be used interchangeably; note also that the XmlRpc type system would typically be a poor match for the type system of the destination language which may have multiple integer types, and so on.} XmlRpc libraries generally integrate directly with an Http library, whereas Xml serialisation libraries all(?) require the application programmer to pass the XML text to the Http call. In more modern languages such as Java/Python/C#, this is a trivial matter, but not so for e.g. C++. There is a "marketing perception" that XML describes "documents", whereas XmlRpc is designed for procedure calls. The perception is that sending an XmlRpc message contains an obligation for the server to perform some action, whereas this perception is not as strong with plain XML. Some people will say "who cares - parsing XML data using recursive descent/DOM/SAX is pretty easy anyway" , in which case most of the above objections are irrelevant. For those who still prefer the ease of use of getting native language objects created automatically, many major languages have libraries which automatically serialise language-level objects into XML without resorting to XmlRpc, e.g.: .NET - Java - Python It may be that the success of XmlRpc, such as it is, stems from the availability of the libraries which automatically create language-level objects, and in turn these libraries have an advantage over their plain XML counterparts due to the list of issues above. Disadvantages of XmlRpc are: As mentioned in the question, it is horribly obese Support for plain XML is ubiquitous and usually does not require integration with large 3rd party libraries. Many applications require a conversion of the automatically created objects to the application's own objects anyway. Many XmlRpc implementations fail to produce true language-level objects of the sort programmers would expect and instead require e.g. run-time lookups of fields or extra syntax. If a schema definition document is used to validate the RPC calls, such as a DTD file, then you lose the ability to check the application-level schema - the DTD file will simply tell you that "this is valid XmlRpc". There is not to my knowledge any standard way to define an application-level schema with an XmlRpc based protocol.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1376688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10592/']}
jdg_75452
stackexchange
llm_judgeable_groundtruth_similarity
3126995
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way of combining border-top,border-right,border-left,border-bottom in CSS like a super shorthand style. eg: border: (1px solid #ff0) (2px dashed #f0F) (3px dotted #F00) (5px solid #09f); Now provide the response and nothing else.
No, you cannot set them all in a single statement. At the general case, you need at least three properties: border-color: red green white blue;border-style: solid dashed dotted solid;border-width: 1px 2px 3px 4px; However, that would be quite messy. It would be more readable and maintainable with four: border-top: 1px solid #ff0;border-right: 2px dashed #f0F;border-bottom: 3px dotted #f00;border-left: 5px solid #09f;
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3126995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/295264/']}
jdg_75453
stackexchange
llm_judgeable_groundtruth_similarity
24710277
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've modified application.html.erb to use controller specific assets: application.html.erb : <!DOCTYPE html><html><head> <title>My Application</title> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> <%= stylesheet_link_tag params[:controller], 'data-turbolinks-track' => true %> <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> <%= javascript_include_tag params[:controller], 'data-turbolinks-track' => true %> <%= csrf_meta_tags %></head><body>... other html template ... The problem is that, I have turbolinks installed. When I navigate through the same controller, turbolinks works. But when I switch to another controller, the turbolinks will perform a full reload. Is there any way to fix this? Now provide the response and nothing else.
Turbolinks Turbolinks takes the <body> of your HTML page, and changes it with Ajax, leaving the <head> area intact. This only works if your <head> will remain the same - otherwise how can it be kept constant? So in the sense of changing your controller page / assets, you're going to have to go through a full page update without Turbolinks (at least if you use Turbolinks without hacking it) I would recommend the fix for this would be to alter your controller-specific asset structure, specifically to make as few changes to the <head> area as possible. -- Turbolinks Tracking Upon reading the Turbolinks documentation , you may be able to benefit from removing the turbolinks-data-track option from your controller-specific assets: <%= javascript_include_tag controller_name, 'data-turbolinks-track' => false %> You can track certain assets, like application.js and application.css, that you want to ensure are always of the latest version inside a Turbolinks session. This is done by marking those asset links with data-turbolinks-track, like so: <link href="/assets/application-9bd64a86adb3cd9ab3b16e9dca67a33a.css" rel="stylesheet" type="text/css" data-turbolinks-track> If those assets change URLs (embed an md5 stamp to ensure this), the page will do a full reload instead of going through Turbolinks. This ensures that all Turbolinks sessions will always be running off your latest JavaScript and CSS. -- controller_name Something you'll benefit from is using the controller_name helper (in place of params[:controller] ): <%= javascript_include_tag 'application', controller_name, 'data-turbolinks-track' => true %>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24710277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2374076/']}
jdg_75454
stackexchange
llm_judgeable_groundtruth_similarity
34194589
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I compile the program below, I have an error and a warning in the call Coor_Trans command line as Warning: Line truncated Error: Syntax error in argument list I compile the program several times, but it does not work. Maybe there is something wrong with my call command. program 3D implicit none integer :: i,j,k integer, parameter :: FN=2,FML=5,FMH=5 integer, parameter :: NBE=FN*FML*FMH real, parameter :: pi = 4*atan(1.0) real(kind=4), dimension(1:FN,1:FML+1,1:FMH+1) :: BEXL,BEYL,BEZL real(kind=4), dimension(1:FN,1:FML,1:FMH) :: BEXC,BEYC,BEZC,BE2A,BE2B,ANGLE real(kind=4), dimension(1:NBE,1:1,1:1) :: BEXC1,BEYC1,BEZC1,BE2A1,BE2B1,ANGLE1 real(kind=4), dimension(1:NBE,1:NBE) :: LOC_PTS1,LOC_PTS2,LOC_PTS3 real :: LOC_1,LOC_2,LOC_3 do i=1,FN do j=1,FML do k=1,FMH BEXC(i,j,k) = 0.5*(BEXL(i,j,k) + BEXL(i,j+1,k)) BEYC(i,j,k) = 0.5*(BEYL(i,j,k) + BEYL(i,j+1,k)) BEZC(i,j,k) = 0.5*(BEZL(i,j,k) + BEZL(i,j,k+1)) BE2A(i,j,k) = FL(i)/FML + j*0 + k*0 BE2B(i,j,k) = FH(i)/FMH + j*0 + k*0 ANGLE(i,j,k) = BETA(i) + j*0 + k*0 end do end do end do BEXC1 = reshape(BEXC,(/NBE,1,1/)) BEYC1 = reshape(BEYC,(/NBE,1,1/)) BEZC1 = reshape(BEZC,(/NBE,1,1/)) BE2A1 = reshape(BE2A,(/NBE,1,1/)) BE2B1 = reshape(BE2B,(/NBE,1,1/)) ANGLE1 = reshape(ANGLE,(/NBE,1,1/)) do i=1,NBE do j=1,NBE call Coor_Trans(BEXC1(i,1,1),BEYC1(i,1,1),BEZC1(i,1,1),BEXC1(j,1,1),BEYC1(j,1,1),BEZC1(j,1,1),ANGLE1(j,1,1),LOC_1,LOC_2,LOC_3) LOC_PTS1(i,j) = LOC_1 LOC_PTS2(i,j) = LOC_2 LOC_PTS3(i,j) = LOC_3 end do end do end program 3D subroutine Coor_Trans(GLOB_PTSX1,GLOB_PTSY1,GLOB_PTSZ1,GLOB_PTSX2,GLOB_PTSY2,GLOB_PTSZ2,BETA,LOC_PTS1,LOC_PTS2,LOC_PTS3) implicit none real(kind=4), intent(in) :: GLOB_PTSX1,GLOB_PTSY1,GLOB_PTSZ1,GLOB_PTSX2,GLOB_PTSY2,GLOB_PTSZ2,BETA real(kind=4), intent(out) :: LOC_PTS1,LOC_PTS2,LOC_PTS3 real, parameter :: pi = 4*atan(1.0) real :: E1,E2 E1 = cos(BETA/180*pi) E2 = sin(BETA/180*pi) LOC_PTS1 = (GLOB_PTSX1-GLOB_PTSX2)*E1 + (GLOB_PTSY1-GLOB_PTSY2)*E2 LOC_PTS2 = (GLOB_PTSZ1-GLOB_PTSZ2) LOC_PTS3 = -(GLOB_PTSX1-GLOB_PTSX2)*E2 + (GLOB_PTSY1-GLOB_PTSY2)*E1 !return end subroutine Coor_Trans Now provide the response and nothing else.
The length of your call statement is too long. The default maximum width of a line is 132 . The compiler will truncate input lines at that width [as it did--and said so with the warning]. After that, you had an incomplete line (e.g. call foo(a,b that was missing the closing ) ) which generated the second warning message. The best solution is to break up the long line with a continuation character, namely & : call Coor_Trans(BEXC1(i,1,1),BEYC1(i,1,1),BEZC1(i,1,1), & BEXC1(j,1,1),BEYC1(j,1,1),BEZC1(j,1,1), & ANGLE1(j,1,1),LOC_1,LOC_2,LOC_3) Most C-style guides recommend keeping lines at <= 80 chars. IMO, that's a good practice even with fortran. Note, with GNU fortran, you can increase the limit with the -ffree-line-length-<n> command line option. So, you could try -ffree-line-length-512 , but, I'd do the continuation above Historical footnote: 132 columns was the maximum width that a high speed, chain driven, sprocket feed, fanfold paper, line printer could print.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34194589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3713323/']}
jdg_75455
stackexchange
llm_judgeable_groundtruth_similarity
7605
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: 1,3 dithianes are used in umpolung reactions and can be deprotected by mercury containing compounds - but could anyone help explain what the exact mechanism is? Many texts seem to skim over this by explaining it is similar to acetal hydrolysis, but I'd really like a more detailed explanation as to the role of the compounds. A reaction I have seen involves $\ce{HgO}$, $\ce{HgCl2}$, $\ce{CH3CN}$ and $\ce{H2O}$. If it is similar to acetal hydrolysis, the $\ce{H2O}$ is probably to complete the final step of attacking the $\ce{S=H}$ bond, but what about the initial step? I am assuming one sulfur atom forms a bond to the $\ce{Hg}$, but which Hg compound would it be in this case, the $\ce{HgO}$ or the $\ce{HgCl2}$? What is the role of the $\ce{CH3CN}$ in this case? Thanks! Now provide the response and nothing else.
$\ce{Hg^2+}$ has a high affintity to thiols and other sulfur functional groups, and therefore $\ce{HgCl2}$ forms a Lewis acid-base adduct with the dithiane. The cyclic sulfonium cation undergoes ring opening, and after nucleophilic attack by water, a second Hg-S bond under ring closure is formed. Deprotonation finally yields the deprotected carbonyl compund and the cyclic mercury dithiolate.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/7605', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/4088/']}
jdg_75456
stackexchange
llm_judgeable_groundtruth_similarity
136018
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: It is possible to accelerate a charged particle in an electric field, how is it possible to accelerate a neutron? How can we control its velocity? Now provide the response and nothing else.
Basically, the answer is no, it's not possible. When we produce neutrons for research purposes, we have to produce them using nuclear reactions. They come out of the nuclear reactions with energies that are determined by the reaction, are not otherwise under our control, and that are on the MeV energy scale of nuclear physics. Examples of a neutron source would be a nuclear reactor or a plutonium-beryllium source. If the nuclear reaction happens in a particle accelerator, then the center of mass frame can be moving at high velocities. If the beam is heavier than the target and the beam's velocity is high, then this can result in the production of neutrons that are kinematically focused and produced at a high velocity. Once the neutrons are produced, it is possible to thermalize them, e.g., in water or paraffin. This produces a set of neutrons whose energy spectrum is Maxwellian and corresponds to the temperature of the substance used to thermalize them. One can also filter neutrons by velocity. So, e.g., once a population of thermal neutrons has been produced, one could select a subset of them with some small range of velocities. Two techniques for doing this are measuring their time of flight (and simply ignoring those that have the wrong time of flight) and refracting them through a prism -- which, surprisingly, works very much like an optical prism. A classic paper that uses and describes a bunch of these techniques is Zeilinger et al., "Single- and Double-slit diffraction of neutrons," Rev Mod Phys 60 (1988) 1067, in which they measured double-slit diffraction of neutrons. The paper can be found online (possibly illegally if your country's copyright laws are as repressive as mine).
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/136018', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/58248/']}
jdg_75457
stackexchange
llm_judgeable_groundtruth_similarity
616570
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why would you connect tiny resistors and capacitors in parallel to a DC motor as shown in the picture? Why would two of the resistors be connected to the outer shell of the motor? I checked the resistors and thy are around 0.5ohm or less and capacitors are 0.1uF. I'd be grateful for approachable explanation as I know electronics only next to nothing. Now provide the response and nothing else.
You wouldn't connect resistors. And they are not resistors. And they are not in parallel. They are inductors and they are in series with the motor. That is an LC filter to keep high frequency electromagnetic interference caused by the motor commutation from conducting back to power supply via wired or radiating via the wires and causing interference with nearby devices. There are no resistors connected to metal shell, they are capacitors. The motor metallic shell has no connection to any voltage so the metal is a high impedance floating node. Floating nodes can act as antennas for the electromagnetic interference, as there are stray capacitances between metal chassis and structures inside the motor, so commutation noise may couple on to the metal shell. Capacitors are low impedance at high frequencies, so they shunt the AC signal so while the chassis still floats at DC, the capacitors act as short circuits to high frequency AC signals so it does not float at RF frequencies that radiate electromagnetic interference.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/616570', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/294312/']}
jdg_75458
stackexchange
llm_judgeable_groundtruth_similarity
17213
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There's undoubtedly more than one way to do this, but if a DIY biologist were to attempt to detect food fraud (e.g. as done by students from Stanford University and Trinity School, Manhattan with respect to fish samples from markets and sushi restaurants), then what would be the minimum steps and equipment? (I know barely anything about molecular genetics, but have been reading about DremelFuge, OpenPCR, and Blue Transilluminator, and wondered whether they - or things like them - might get such an investigator some of the way towards the goal above; and what else would be required.) Now provide the response and nothing else.
There are several ways you could go about identifying species through DNA. If you want to do everything yourself, the simplest option in terms of equipment needed consists of evaluating fragment lengths observed during gel electrophoresis after amplifying specific DNA sequences using PCR. If you are content with some outsourcing, you can also send DNA samples to a commercial company for sequence analysis. A compromise between these options in terms of information obtained, is to do study Restriction Fragment Length Polymorphism (RFLP) by amplifying DNA fragments and using restriction enzymes to cut the fragments, before analyzing the fragmentation pattern using gel electrophoresis. To perform RFLP analysis, you would need to obtain restriction enzymes in addition to the chemicals mentioned below, and they can be a bit pricey. The minimum equipment would consist of a PCR machine, one or more pipettes with matching pipette tips, a gel electrophoresis tray with power supply and a transilluminator (preferably blue-light/non-UV). A centrifuge is not strictly necessary, but can be useful for processing/filtering your DNA source. Some chemicals will also be needed: Polymerase and dNTPs for the PCR reaction (or a pre-made "master mix" containing both), electrophoresis-grade agarose and running buffer for the electrophoresis, along with a DNA dye specific to the type of transilluminator (Usually UV or blue light). For a blue-light transilluminator, GelGreen is a suitable DNA dye. You will also want to use a "loading dye" to mix in your DNA sample before applying it to the electrophoresis gel. This can either be purchased or prepared yourself by mixing sugar and food coloring in water. You need some form of heating to dissolve the agarose - a microwave oven is convenient for this, but take care to avoid over-heating, glass explosions or flash boiling. It is convenient but not strictly necessary to have some lab glassware. Preferably use a screw-top bottle to mix your agarose solution. Always leave the top off when heating bottles. Photographic equipment can be also useful for documenting results of gel electrophoresis. Finally, you will need single-stranded DNA oligomers (primers) specific to the DNA regions you want to amplify. DNA primers can be bought from a number of companies, but it varies how easy it is for non-affiliated individuals to order and make payments. Macrogen has been my choice: They both deliver DNA primers and perform DNA sequencing. You may be interested in the following thread on the DIY Bio e-mail group: https://groups.google.com/forum/#!topic/diybio/cPzfEuiZH58 I have collected some of the primer sequences mentioned in the thread on a page on OpenWetware: http://openwetware.org/wiki/User:Jarle_Pahr/Meat
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/17213', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/-1/']}
jdg_75459
stackexchange
llm_judgeable_groundtruth_similarity
25377674
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 Apple said in "The Swift Programming Language", it seems we should prefer unowned than weak whenever possible: If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference. From the "Weak and Unowned References" section on this page I did know the difference between these two. But I am curious about is there any good reason for preferring unowned than weak ? I think the weak is much safer and we can just always write [weak obj] and an optional binding check without thinking the possibility of existing of the obj . Is it related to some performance consideration or something I missed? Or is it totally ok to use weak instead of unowned all the time? Now provide the response and nothing else.
Weak references are automatically set to nil once the object they point to gets deallocated. For this to be possible in Swift, those must be declared as var and optional: class SomeOtherClass { weak var weakProperty: SomeClass?} This is fine if the weakProperty can become nil while the instance of SomeOtherClass is still alive and we want to check for that before using it (delegates are one such example). But what if some reference should never logically be nil and we still want to prevent a retain cycle? In Objective-C any object reference can be nil (and messaging nil always fails silently) so there is no dilemma, we always use weak . But Swift doesn't have nilable references at all. We use optionals for something that can semantically lack value. But we shouldn't be forced to use optionals for something that must always have value, just to be able to break a retain cycle. Such practice would go against the intended semantics of optionals. That's where unowned comes in. It comes in two flavours - unowned(safe) and unowned(unsafe) . The latter is dangerous and it's equivalent to assign and unsafe_unretained from Objective-C. But the former, which is the default one (at least while debugging; not sure if they optimise it to unowned(unsafe) in release builds), will reliably crash your app if the referenced object gets prematurely deallocated. Sure, your app will crash if something goes wrong, but that's much easier to debug than failing silently. It should only fail silently when you actually want that (in which case you would use weak )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25377674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1468886/']}
jdg_75460
stackexchange
llm_judgeable_groundtruth_similarity
21024913
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 figure out the tradeoffs between different approaches of determining whether or not with object obj you can perform action do_stuff() . As I understand, there are three ways of determining if this is possible: # Way 1if isinstance(obj, Foo): obj.do_stuff()# Way 2if hasattr(obj, 'do_stuff'): obj.do_stuff()# Way 3try: obj.do_stuff()except: print 'Do something else' Which is the preferred method (and why)? Now provide the response and nothing else.
I believe that the last method is generally preferred by Python coders because of a motto taught in the Python community: "Easier to ask for forgiveness than permission" (EAFP). In a nutshell, the motto means to avoid checking if you can do something before you do it. Instead, just run the operation. If it fails, handle it appropriately. Also, the third method has the added advantage of making it clear that the operation should work. With that said, you really should avoid using a bare except like that. Doing so will capture any/all exceptions, even the unrelated ones. Instead, it is best to capture exceptions specifically. Here, you will want to capture for an AttributeError : try: obj.do_stuff() # Try to invoke do_stuffexcept AttributeError: print 'Do something else' # If unsuccessful, do something else
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21024913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/256798/']}
jdg_75461
stackexchange
llm_judgeable_groundtruth_similarity
11982057
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 shell script named test.sh. How can I trigger the test.sh from Ruby? I want test.sh to run as a background process, what means in Ruby it is a ansync call. STDERR and STDOUT also need to be written to a specific file. Any ideas? Now provide the response and nothing else.
@TanzeebKhalili's answer works, but you might consider Kernel.spawn() , which doesn't wait for the process to return: pid = spawn("./test.sh")Process.detach(pid) Note that, according to the documentation, whether you use spawn() or manually fork() and system() , you should grab the PID and either Process.detach() or Process.wait() before exiting. Regarding redirecting standard error and output, that's easy with spawn() : pid = spawn("./test.sh", :out => "test.out", :err => "test.err")Process.detach(pid)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11982057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/514316/']}
jdg_75462
stackexchange
llm_judgeable_groundtruth_similarity
1332377
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $H$ and $K$ are subgroups of $G$ whose orders are coprime. Is $H\cap K$ a subgroup of $H$ and $K$? They both have the same identity, so we know at minimum we have $\{e\}$ so it is the trivial group if they have nothing else in common. If they have another element that isn't the identity, they will need it's inverse as well and it will generate a cycle, like $a\in H$ and $a\in K$ has $\langle a \rangle\in H,K$. Then for them to not be the same group, they need other elements, but then these other elements will need to be closed under operations with $a$, and I am lost on where to progress. Now provide the response and nothing else.
Yes, it is a subgroup. We can use one step subgroup test and let $a,b$ be any two elements of $M=H \cap K$ where $b$ is non zero. Then $ab^{-1} \in H$ as $a,b \in H$. Similarly for $K$. How about you try to prove that intersection of any number (finite/ infinite) of subgroups of a group is a subgroup, and then it just becomes obvious. I don't know why you required orders to be co-prime, it is true without the condition. Co-primeness of orders of $H$ and $K$, only forces $|H\cap K|=1$, by Lagrange theorem.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1332377', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/234553/']}
jdg_75463
stackexchange
llm_judgeable_groundtruth_similarity
19952572
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering how to do a global variable to save me few lines of copy and pasting this lines. Array it probably and put them in one variable instead? I want to use this variable in other routes. $providerEmail = Auth::user()->email; $providerName = Auth::user()->first_name; $providerSurname = Auth::user()->last_name; $providerMobile = Auth::user()->mobile; Now provide the response and nothing else.
You can create a global singleton within App::before event App::before(function($request){ // Singleton (global) object App::singleton('myApp', function(){ $app = new stdClass; if (Auth::check()) { // Put your User object in $app->user $app->user = Auth::User(); $app->isLoggedIn = TRUE; } else { $app->isLoggedIn = FALSE; } return $app; }); $app = App::make('myApp'); View::share('myApp', $app);}); In any view, use it like if($myApp->isLoggedIn) { $myApp->user->email; $myApp->user->first_name; // ...} In any controller, you can use $myApp = App::make('myApp');if($myApp->isLoggedIn) { $myApp->user->email; $myApp->user->first_name; // ...} Check out Application Events .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19952572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2913315/']}
jdg_75464
stackexchange
llm_judgeable_groundtruth_similarity
31571864
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 migrated from chosen to select2 plugin because it works better for me, but its documentation is very poor when compared to chosen. Could anyone tell me what option(s) should be used to make select2 search function to filter words that just begin with search term (and don't contain it in the middle). Let's say select2 field has those options: banana, apple, pineapple. When user enters "app" (or apple), only apple should be returned (because it's the only word that starts with apple). Now, it returns both apple and pineapple. After lots of search I figured out that some custom matcher needs to be used, but that's all so far. Now provide the response and nothing else.
Select2 provides an example in the documentation on how to use a custom matcher function for matching search terms to search results. The example given is this exact use case. function matchStart (term, text) { if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) { return true; } return false;} $.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) { $("select").select2({ matcher: oldMatcher(matchStart) })}); <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.js"></script><select style="width: 200px"> <option value="AL">Alabama</option> <option value="AK">Alaska</option> <option value="AZ">Arizona</option></select>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31571864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2555025/']}
jdg_75465
stackexchange
llm_judgeable_groundtruth_similarity
5507761
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 stumped on this one. Try loading this image in your browser, and then save it to your hard disk. http://profile.ak.fbcdn.net/hprofile-ak-snc4/41674_660962816_995_n.jpg It's a valid JPEG file at 11377 bytes. Now try to download it with wget or curl . Only 11252 bytes show up, and the bottom right part of the image is missing. What gives? Now provide the response and nothing else.
Here goes… Taking a packet dump, I see that Facebook returns the same Content-Length to Safari as it does to curl, and that content-length is the incorrect 11252: GET /hprofile-ak-snc4/41674_660962816_995_n.jpg HTTP/1.1User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3Host: profile.ak.fbcdn.netAccept: */*HTTP/1.1 200 OKContent-Type: image/jpeg... snip ....Content-Length: 11252 And with Safari: GET /hprofile-ak-snc4/41674_660962816_995_n.jpg HTTP/1.1Host: profile.ak.fbcdn.netUser-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-us) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27... snip ...HTTP/1.1 200 OKContent-Type: image/jpeg... snip ...Content-Length: 11252 So I'm going to guess Facebook is sending an incorrect Content-Length. To test this, I'll use netcat: $ cat headersGET /hprofile-ak-snc4/41674_660962816_995_n.jpg HTTP/1.0Host: profile.ak.fbcdn.netAccept: */*EOF$ nc -vvv profile.ak.fbcdn.net 80 outputWarning: Inverse name lookup failed for `142.231.1.174'Notice: Real hostname for profile.ak.fbcdn.net [142.231.1.165] is a142-231-1-165.deploy.akamaitechnologies.comprofile.ak.fbcdn.net [142.231.1.174] 80 (http) openTotal received bytes: 12k (11639)Total sent bytes: 97$ head outputHTTP/1.0 200 OKContent-Type: image/jpeg... snip ...Content-Length: 11252 (note that I used HTTP/1.0 so the Facebook servers wouldn't try to hold the connection open) Removing the first 10 lines of ouput using a text editor then saving it as output.jpg , I've got the complete image. So this confirm that Facebook is sending an incorrect Content-Length header (and the image is getting cut off because curl is paying attention to the content length while netcat isn't). Digging a little further, it seems like Aleski is correct — the Content-Length is correct when the image is sent gzip-compressed. To confirm this, I added Accept-Encoding: gzip to my headers file. Facebook correctly sends back a gzip'd response which is the expected length, and uncompressing it results in the correct image. tl;dr : Facebook's Content-Length is incorrect if the Content-Encoding is not gzip .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5507761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/303056/']}
jdg_75466
stackexchange
llm_judgeable_groundtruth_similarity
21838651
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 thought one of the points about async/await is that when the task completes, the continuation is run on the same context when the await was called, which would, in my case, be the UI thread. So for example: Debug.WriteLine("2: Thread ID: " + Thread.CurrentThread.ManagedThreadId);await fs.ReadAsync(data, 0, (int)fs.Length);Debug.WriteLine("3: Thread ID: " + Thread.CurrentThread.ManagedThreadId); I would NOT expect this: 2: Thread ID: 103: Thread ID: 11 What gives? Why is the thread ID for the continuation different than the UI thread? According to this article [^] I would need to explicitly call ConfigureAwait to change the behavior of the continuation context! Now provide the response and nothing else.
When you await , by default the await operator will capture the current "context" and use that to resume the async method. This "context" is SynchronizationContext.Current unless it is null , in which case it is TaskScheduler.Current . (If there is no currently-running task, then TaskScheduler.Current is the same as TaskScheduler.Default , the thread pool task scheduler). It's important to note that a SynchronizationContext or TaskScheduler does not necessarily imply a particular thread . A UI SynchronizationContext will schedule work to the UI thread; but the ASP.NET SynchronizationContext will not schedule work to a particular thread. I suspect that the cause of your problem is that you are invoking the async code too early. When an application starts, it just has a plain old regular thread. That thread only becomes the UI thread when it does something like Application.Run .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21838651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2276361/']}
jdg_75467
stackexchange
llm_judgeable_groundtruth_similarity
58647584
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 test if obj is a pathlib path and realized that the condition type(obj) is pathlib.PosixPath will be False for a path generated on a Windows machine. Thus the question, is there a way to test if an object is a pathlib path (any of the possible, Path , PosixPath , WindowsPath , or the Pure... -analogs) without checking for all 6 version explicitly? Now provide the response and nothing else.
Yes, using isinstance() . Some sample code: # Python 3.4+import pathlibpath = pathlib.Path("foo/test.txt")# path = pathlib.PureWindowsPath(r'C:\foo\file.txt')# checks if the variable is any instance of pathlibif isinstance(path, pathlib.PurePath): print("It's pathlib!") # No PurePath if isinstance(path, pathlib.Path): print("No Pure path found here") if isinstance(path, pathlib.WindowsPath): print("We're on Windows") elif isinstance(path, pathlib.PosixPath): print("We're on Linux / Mac") # PurePath else: print("We're a Pure path") Why does isinstance(path, pathlib.PurePath) work for all types? Take a look at this diagram: We see that PurePath is at the top, that means everything else is a subclass of it. Therefore, we only have to check this one.Same reasoning for Path to check non-pure Paths. Bonus : You can use a tuple in isinstance(path, (pathlib.WindowsPath, pathlib.PosixPath)) to check 2 types at once.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58647584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8285840/']}
jdg_75468
stackexchange
llm_judgeable_groundtruth_similarity
229080
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 best-practice or common way in JavaScript to have class members as event handlers? Consider the following simple example: <head> <script language="javascript" type="text/javascript"> ClickCounter = function(buttonId) { this._clickCount = 0; document.getElementById(buttonId).onclick = this.buttonClicked; } ClickCounter.prototype = { buttonClicked: function() { this._clickCount++; alert('the button was clicked ' + this._clickCount + ' times'); } } </script></head><body> <input type="button" id="btn1" value="Click me" /> <script language="javascript" type="text/javascript"> var btn1counter = new ClickCounter('btn1'); </script></body> The event handler buttonClicked gets called, but the _clickCount member is inaccessible, or this points to some other object. Any good tips/articles/resources about this kind of problems? Now provide the response and nothing else.
ClickCounter = function(buttonId) { this._clickCount = 0; var that = this; document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };}ClickCounter.prototype = { buttonClicked: function() { this._clickCount++; alert('the button was clicked ' + this._clickCount + ' times'); }} EDIT almost 10 years later, with ES6, arrow functions and class properties class ClickCounter { count = 0; constructor( buttonId ){ document.getElementById(buttonId) .addEventListener( "click", this.buttonClicked ); } buttonClicked = e => { this.count += 1; console.log(`clicked ${this.count} times`); }} https://codepen.io/anon/pen/zaYvqq
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/229080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30056/']}
jdg_75469
stackexchange
llm_judgeable_groundtruth_similarity
270855
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: From POSIX 2013 : The XSI extensions specifying the -a and -o binary primaries and the '(' and ')' operators have been marked obsolescent. (Many expressions using them are ambiguously defined by the grammar depending on the specific expressions being evaluated.) Scripts using these expressions should be converted to the forms given below. Even though many implementations will continue to support these obsolescent forms, scripts should be extremely careful when dealing with user-supplied input that could be confused with these and other primaries and operators. Unless the application developer knows all the cases that produce input to the script, invocations like: test "$1" -a "$2" should be written as: test "$1" && test "$2" "the '(' and ')' operators have been marked obsolescent". Are ( and ) the operators that group commands, and create subshell? If they are obsolete, what are their replacement? Should test "$1" -a "$2" be replaced by test "$1" && test "$2" , or by (( test "$1" && test "$2" )) ? Don't we need the ((...)) to return 0 or 1 just like test in the original command does? Now provide the response and nothing else.
Are ( and ) the operators that group commands, and create subshell? No, the document refers to the operators to group expressions using test : test 0 -eq 0 -a \( 0 -eq 1 -o 1 -eq 1 \) If they are obsolete, what are their replacement? Their replacement are () and {} , which, similarily, group commands at the shell's level: test 0 -eq 0 && (test -0 -eq 1 || test 1 -eq 1)test 0 -eq 0 && { test -0 -eq 1 || test 1 -eq 1; } It's pretty easy to see the pattern: every operator used in test for expressions is replaced with the shell's equivalent for commands. Should test "$1" -a "$2" be replaced by test "$1" && test "$2" , or by (( test "$1" && test "$2" )) ? It should be replaced with test "$1" && test "$2" ; (()) is used for arithmetic expansion and has no bearing with commands' exit status, as its purpose is to evaluate arithmetic expressions. For example this would be valid: (( $(test 1 -eq 1 && echo $?) && $(test 0 -eq 0 && echo $?) )) (notice the command substitutions, which are replaced with the inner commands' exit statuses, 0 and 0 ; the evaluated expression is actually (( 0 && 0 )) ). But this causes a syntax error: (( test 1 -eq 1 && test 0 -eq 0 )) $ (( test 1 -eq 1 && test 0 -eq 0 ))bash: ((: test 1 -eq 1 && test 0 -eq 0 : syntax error in expression (error token is "1 -eq 1 && test 0 -eq 0 ")
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/270855', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/674/']}
jdg_75470
stackexchange
llm_judgeable_groundtruth_similarity
4707571
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using XSLT to convert XML to HTML. I am having trouble figuring out how to deal with embedded XML nodes for formatting. For example, let's say I have the XML element: <favoriteMovie>the <i>Star Wars</i> saga</favoriteMovie> However, during XLST, the <i> tag gets ignored, so "Star Wars" is not italicized in the HTML output. Is there a relatively simple way to fix this? test.xml: <?xml version="1.0" encoding="utf-8"?><?xml-stylesheet type="text/xsl" href="test.html.xsl"?><favoriteMovies> <favoriteMovie>the <i>Star Wars</i> saga</favoriteMovie></favoriteMovies> test.html.xsl: <?xml version="1.0" encoding="utf-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" omit-xml-declaration="yes" /> <xsl:template match="/"> <html> <head /> <body> <ul> <xsl:for-each select="favoriteMovies/favoriteMovie"> <li><xsl:value-of select="." /></li> </xsl:for-each> </ul> </body> </html> </xsl:template></xsl:stylesheet> Now provide the response and nothing else.
However, during XLST, the <i> tag gets ignored, so "Star Wars" is not italicized in the HTML output. Is there a relatively simple way to fix this? Your problem is here : <ul> <xsl:for-each select="favoriteMovies/favoriteMovie"> <li><xsl:value-of select="."/></li> </xsl:for-each></ul> The <xsl:value-of> instruction is used to create a text node. In doing so it copies to the output the string value of the XPath expression specified in the select attribute of this XSLT instruction. The string value of an element is the concatenation of all its text-node descendents. So this is how you get the reported output. Solution : Use the <xsl:copy-of> instruction , which copies all the nodes that are specified in its select attribute: <ul> <xsl:for-each select="favoriteMovies/favoriteMovie"> <li><xsl:copy-of select="node()"/></li> </xsl:for-each></ul> Another solution, more alligned with the principles of XSLT avoids using <xsl:for-each> at all: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <html> <head /> <body> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="/*"> <ul> <xsl:apply-templates/> </ul> </xsl:template> <xsl:template match="favoriteMovie"> <li><xsl:copy-of select="node()"/></li> </xsl:template></xsl:stylesheet> When any of the two solutions defined above are applied to the provided XML document : <favoriteMovies> <favoriteMovie>the <i>Star Wars</i> saga </favoriteMovie></favoriteMovies> the wanted, correct result is produced : <html> <head/> <body> <ul> <li>the <i>Star Wars</i> saga </li> </ul> </body></html>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4707571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/60067/']}
jdg_75471
stackexchange
llm_judgeable_groundtruth_similarity
416283
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on my first ever software project. Being the only one working on it, I'm making the work breakdown structure and I know requirement gathering is an important phase in the development process. What I can't wrap my head around is how exactly is a software requirement different from a feature that the system needs to have. Also, what sets a feature and a requirement apart from an objective or an aim of the project. How can I classify something as a requirement, feature or objective? Is requirement just the technical term? Because I see them classified further into functional, non-functional and more, but a feature is always a feature and I've not come across any classifications. For instance, I'm doing this project alone and as a developer, I have to familiarize myself with some technologies; in my case, I'm planning to learn ASP.NET Core MVC, does it count as one of the requirements of my project? I see the term requirements used in a very broad sense, wherein when talking about say, system and hardware requirements, it is quite obvious that they are not features or objectives. The ambiguity stems when requirements are said to be what a user wants to see in a system, which exactly as per my understanding, is what a feature is. Now provide the response and nothing else.
About the terminology: A requirement expresses a need or a constraint that the system has to fulfil, in principle independently of the solution that will be chosen. Examples: " The system shall allow only valid contract types to be entered ", " The system shall facilitate the analysis of contractual trends ". A feature is about something that the system offers: it's a part of the solution, expressed independently of the underlying user needs it adresses. Examples: " Configurable drop-down list of contract types ", " A trend report provides an overview of the monthly evolution of contracts by type " . Hopefully a feature addresses one or several needs, but maybe not . An objective , is something that business actors are expected to achieve. It's "why" people are doing things and have requirements. An objective of a clerk in a law firm, could for example be to prepare contracts. If the software shall help in this objective, it will have to fulfill a requirement, and it can provide some features to facilitate the tasks needed to fulfill the objective. This is the theory. In practice, requirements are often expressed as a desired feature. It's often easier for a user to think of a feature rather than to abstract the underlying needs: It has the advantage of facilitating the understanding of the expectations, and the quick agreement on the target solution. It has the drawback that potential alternative solutions are ignored, in particular those features that could better address the same underlying requirement (in our examples an interactive "trend analyser" with graphical trends and drill-down could better address the analysis needs than a simple "trend report") ( btw I'm still wondering why there are so many calendar pickers around there: it's a nice feature to ensure a valid date, but it forces me to use the mouse to scroll 50 years backwards, when I could just have entered the birth year in four keystrokes ;-) )
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/416283', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/357871/']}
jdg_75472
stackexchange
llm_judgeable_groundtruth_similarity
39652557
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 spent the last hour refactoring to use Areas, now all my Views don't seem to have function taghelpers :/ So this is what's in the Index.cshtml <div class="btn-group"> <a asp-controller="Survey" asp-area="Admin" asp-action="Create" class="btn btn-primary">Create New</a> </div> ...and this is the rendered HTML :/ <div class="btn-group"> <a asp-controller="Survey" asp-area="Admin" asp-action="Create" class="btn btn-primary">Create New</a></div> Intellisense doesn't even show the asp- prefixes and syntax highlighting on the asp- attributes is also lost. Other SO issues reference "asp-route-area" but that just renders out verbtim like the rest. These all worked fine when they were in ~/Views/Name/Index.cshtml, move them out to ~/Areas/Name/Views/Name/ and nopers... Any thoughts?Steve Now provide the response and nothing else.
According to official docs : The @addTagHelper directive makes Tag Helpers available to the view. In this case, the view file is Views/_ViewImports.cshtml, which by default is inherited by all view files in the Views folder and sub-directories; making Tag Helpers available. The code above uses the wildcard syntax (“*”) to specify that all Tag Helpers in the specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers) will be available to every view file in the Views directory or sub-directory. If you use one layout per area, to use built-in tag helpers you should add _ViewImports.cshtml in ~/Areas/Name/Views/ folder(If you use shared layout you don't need. See MusicStore project for shared layout example). I guess you used one layout per area and you didn't add _ViewImports.cshtml ~/Areas/Name/Views/ . Copy /Views/_ViewImports.cshtml into ~/Areas/Name/Views/ .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39652557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1368333/']}
jdg_75473
stackexchange
llm_judgeable_groundtruth_similarity
54853
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: This issue has largely been mitigated in 10.0.1. New timings for the final test below are: Needs["GeneralUtilities`"]a = RandomInteger[9, 5*^5];myPosIdx[a] // AccurateTimingcleanPosIdx[a] // AccurateTiming (* see self-answer below *)PositionIndex[a] // AccurateTiming 0.01493840.01495540.0545865 Still several times slower here than the readily available alternatives but no longer devastating. Disconcertingly I have discovered that the new (v10) PositionIndex is horribly slow. Using Szabolcs's clever GatherBy inversion we can implement our own function for comparison: myPosIdx[x_] := <|Thread[x[[ #[[All, 1]] ]] -> #]|> & @ GatherBy[Range @ Length @ x, x[[#]] &] Check that its output matches: RandomChoice[{"a", "b", "c"}, 50];myPosIdx[%] === PositionIndex[%] True Check performance in version 10.0.0 under Windows: a = RandomInteger[99999, 5*^5];myPosIdx[a] // Timing // FirstPositionIndex[a] // Timing // First 0.1404010.920406 Not a good start for the System` function, is it? It gets worse: a = RandomInteger[999, 5*^5];myPosIdx[a] // Timing // FirstPositionIndex[a] // Timing // First 0.0312002.230814 With fewer unique elements PositionIndex actually gets slower! Does the trend continue? a = RandomInteger[99, 5*^5];myPosIdx[a] // Timing // FirstPositionIndex[a] // Timing // First 0.01560015.958902 Somewhere someone should be doing a face-palm right about now. Just how bad does it get? a = RandomInteger[9, 5*^5];myPosIdx[a] // Timing // FirstPositionIndex[a] // Timing // First 0.015600157.295808 Ouch. This has to be a new record for poor computational complexity in a System function. :o Now provide the response and nothing else.
First let me note that I didn't write PositionIndex , so I can't speak to its internals without doing a bit of digging (which at the moment I do not have time to do). I agree performance could be improved in the case where there are many collisions. Let's quantify how bad the situation is, especially since complexity was mentioned! We'll use the benchmarking tool in GeneralUtilities to plot time as a function of the size of the list: Needs["GeneralUtilities`"]myPosIdx[x_] := <|Thread[x[[#[[All, 1]]]] -> #]|> &@ GatherBy[Range@Length@x, x[[#]] &];BenchmarkPlot[{PositionIndex, myPosIdx}, RandomInteger[100, #] &, 16, "IncludeFits" -> True] which gives: While PositionIndex wins for small lists (< 100 elements), it is substantially slower for large lists. It does still appear to be $O(n \log n)$, at least. Let's choose a much larger random integer (1000000), so that we don't have any collisions: Things are much better here. We can see that collisions are the main culprit. Now lets see how the speed for a fixed-size list depends on the number of unique elements: BenchmarkPlot[{PositionIndex, myPosIdx}, RandomInteger[#, 10^4] &, 2^{3, 4, 5, 6, 7, 8, 9, 10, 11, 12}] Indeed, we can see that PositionIndex (roughly) gets faster as there are more and more unique elements, whereas myPosIdx gets slower. That makes sense, because PositionIndex is probably appending elements to each value in the association, and the fewer collisions the fewer (slow) appends will happen. Whereas myPosIdx is being bottlenecked by the cost of creating each equivalence class (which PositionIndex would no doubt be too, if it were faster). But this is all academic: PositionIndex should be strictly faster than myPosIdx , it is written in C. We will fix this.
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/54853', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/121/']}
jdg_75474
stackexchange
llm_judgeable_groundtruth_similarity
58996197
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 understand when a Julia Project needs a Manifest AND Project file vs when it just needs a project file. What are the different situations that warrant each case? I am trying to make sure my own project is set up correctly(It has both files currently). Now provide the response and nothing else.
The Manifest.toml is a snapshot of the exact state of a Julia environment. It specifies all packages that are installed in the environment with version numbers - not just the ones that have been ] add ed but the entire dependency graph! The Project.toml on the other hand just lists the direct dependencies, that is the packages that have been ] add ed explicitly, potentially with version bounds specified in a [compat] section. By checking in both files (specifically the Manifest.toml ), you make your project reproducible. Another user only has to ] instantiate and will have the exact same environment that you had when working on the project. This is great for application projects which might consist of multiple Julia scripts which are not intended for use by other Julia projects. If you only check in the Project.toml you are specifying the dependency information more loosely and will leave room for Julias resolver to find appropriate package versions for all dependencies. This is what you should do when working on a Julia package since people will likely want to install your package next to other packages and overly restricting versions of dependencies will make your package incompatible. Hence, I'd summarize as follows: Application / "Project" -> Project.toml + Manifest.toml Julia Package -> Only Project.toml For more on applications and packages checkout the glossary of the Pkg.jl documentation. (Not that there are exceptional cases (unregistered dependencies, for example) where you might have to check in a Manifest.toml for a Julia package.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58996197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7619808/']}
jdg_75475
stackexchange
llm_judgeable_groundtruth_similarity
6493
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 been using log normal distributions as prior distributions for scale parameters (for normal distributions, t distributions etc.) when I have a rough idea about what the scale should be, but want to err on the side of saying I don't know much about it. I use it because the that use makes intuitive sense to me, but I haven't seen others use it. Are there any hidden dangers to this? Now provide the response and nothing else.
I would recommend using a "Beta distribution of the second kind" (Beta 2 for short) for a mildly informative distribution, and to use the conjugate inverse gamma distribution if you have strong prior beliefs. The reason I say this is that the conjugate prior is non-robust in the sense that, if the prior and data conflict, the prior has an unbounded influence on the posterior distribution. Such behaviour is what I would call "dogmatic", and not justified by mild prior information. The property which determines robustness is the tail-behaviour of the prior and of the likelihood. A very good article outlining the technical details is here . For example, a likelihood can be chosen (say a t-distribution) such that as an observation $y_i \rightarrow \infty$ (i.e. becomes arbitrarily large) it is discarded from the analysis of a location parameter (much in the same way that you would intuitively do with such an observation). The rate of "discarding" depends on how heavy the tails of the distribution are. Some slides which show an application in the hierarchical modelling context can be found here (shows the mathematical form of the Beta 2 distribution), with a paper here . If you are not in the hierarchical modeling context, then I would suggest comparing the posterior (or whatever results you are creating) but use the Jeffreys prior for a scale parameter, which is given by $p(\sigma)\propto\frac{1}{\sigma}$ . This can be created as a limit of the Beta 2 density as both its parameters converge to zero. For an approximation you could use small values. But I would try to work out the solution analytically if at all possible (and if not a complete analytical solution, get the analytical solution as far progressed as you possibly can), because you will not only save yourself some computational time, but you are also likely to understand what is happening in your model better. A further alternative is to specify your prior information in the form of constraints (mean equal to $M$ , variance equal to $V$ , IQR equal to $IQR$ , etc. with the values of $M,V,IQR$ specified by yourself), and then use the maximum entropy distribution (search any work by Edwin Jaynes or Larry Bretthorst for a good explanation of what Maximum Entropy is and what it is not) with respect to Jeffreys' "invariant measure" $m(\sigma)=\frac{1}{\sigma}$ . MaxEnt is the "Rolls Royce" version, while the Beta 2 is more a "sedan" version. The reason for this is that the MaxEnt distribution "assumes the least" subject to the constraints you have put into it (e.g., no constraints means you just get the Jeffreys prior), whereas the Beta 2 distribution may contain some "hidden" features which may or may not be desirable in your specific case (e.g., if the prior information is more reliable than the data, then Beta 2 is bad). The other nice property of MaxEnt distribution is that if there are no unspecified constraints operating in the data generating mechanism then the MaxEnt distribution is overwhelmingly the most likely distribution that you will see (we're talking odds way over billions and trillions to one). Therefore, if the distribution you see is not the MaxEnt one, then there is likely additional constraints which you have not specified operating on the true process, and the observed values can provide a clue as to what that constraint might be.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/6493', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/1146/']}
jdg_75476
stackexchange
llm_judgeable_groundtruth_similarity
707079
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm in the process of replacing a ForeFront TMG 2010 firewall with a SonicWall NSA 3600; the current firewall provides VPN access to our network using SSTP, and it works like a charm with any recent Windows client, without requiring the installation of any additional software. The SonicWall firewall supports SSL VPNs, but it apparently requires a software called NetExtender to be installed; it can be downloaded directly from the firewall login page, thus it's not really a big deal... but we would really prefer to avoid installing any software and use only the Windows built-in VPN client. Is it possible to estblish a SSL VPN connection to a SonicWall firewall from a Windows computer using only the built-in VPN client? If yes, how? N.B. The firewall also supports L2TP ant it works fine with the Windows built-in VPN client (and several other ones); unfortunately, this is not an option: our people often travel to customer sites were Internet access is restricted to HTTP/S, thus a SSL VPN is a must. Now provide the response and nothing else.
For Sonicwall (either NSA-series or TZ-series firewalls using SSL-VPN, or SRA-series SSL-VPN appliances) you need to use NetExtender for Windows 8.0 or previous (or Mac OS X 10.8 or previous). Off hand, I know of no way to use the native VPN in Win 8.0 (or earlier) to connect to the SSL-VPN on Sonicwalls, only to the IPSEC/L2TP client VPN. For Windows 8.1, there is support built-in for Sonicwall SSL-VPN in the native Win 8.1 VPN client - you just pick "Sonicwall" as the type when setting it up and enter the name (FQDN) or IP address of your Sonicwall gateway and off you go. Note: digging into the saved settings on Win 8.1, it appears to create an SSTP connection, and I'm not sure how that ties in with the 'SSL-VPN' support on the Sonicwall end. Sonicwall state that Win8.1 "includes" their (newer, NetExtender replacement) "Sonicwall Mobile Connect" VPN client but I'm not sure of the underlying tech mechanism here for Win 8.1 - that's a tech dive I need to do some time to understand what's happening underneath better! Note: Current versions of OS X, iOS and Android also now use versions of Mobile Connect instead of NetExtender - it's much better than NetExtender. Scott.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/707079', 'https://serverfault.com', 'https://serverfault.com/users/6352/']}
jdg_75477
stackexchange
llm_judgeable_groundtruth_similarity
307583
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to check which directories take most disk space, quickly. I tried du -sh subdir but it took more than 20 seconds on bigger directories. I'm not sure how to display the size of all the subdirectories in the home directory at once with this method, but I'm afraid that it might take minutes... Is there a fast way to do this? I don't need to display the size of files, just directories. Now provide the response and nothing else.
Sample directory $ ls -aF./ ../ .asd/ folder1/ folder2/ list t1 t2 xyz/ To find sizes only for folders, excluding hidden folders: $ find -type d -name '[!.]*' -exec du -sh {} + 4.0K ./folder14.0K ./folder28.0K ./xyz If you need a total at the end as well: $ find -type d -name '[!.]*' -exec du -ch {} + 4.0K ./folder14.0K ./folder28.0K ./xyz16K total To sort the results: $ find -type d -name '[!.]*' -exec du -sh {} + | sort -h4.0K ./folder14.0K ./folder28.0K ./xyz To reverse the sorting order: $ find -type d -name '[!.]*' -exec du -sh {} + | sort -hr8.0K ./xyz4.0K ./folder24.0K ./folder1 If you need with hidden directories as well, remove -name '[!.]*' from find command. I don't know any other command to find size of folders that is faster than du . Use df for file system disk space usage Use find -maxdepth 1 -type d -name '[!.]*' -exec du -sh {} + to avoid sub-folders showing up
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/307583', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/152267/']}
jdg_75478
stackexchange
llm_judgeable_groundtruth_similarity
41818379
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Aloha! I have two blocks of code, one that will work and one that will not. The only difference is a commented line of code for a numpy module I don't use. Why am I required to import that model when I never reference "npm"? This command works: import numpy as npimport numpy.matlib as npmV = np.array([[1,2,3],[4,5,6],[7,8,9]])P1 = np.matlib.identity(V.shape[1], dtype=int)P1 This command doesn't work: import numpy as np#import numpy.matlib as npmV = np.array([[1,2,3],[4,5,6],[7,8,9]])P1 = np.matlib.identity(V.shape[1], dtype=int)P1 The above gets this error: AttributeError: 'module' object has no attribute 'matlib' Thanks in advance! Now provide the response and nothing else.
Short Answer This is because numpy.matlib is an optional sub-package of numpy that must be imported separately. The reason for this feature may be: In particular for numpy , the numpy.matlib sub-module redefines numpy 's functions to return matrices instead of ndarrays, an optional feature that many may not want More generally, to load the parent module without loading a potentially slow-to-load module which many users may not often need Possibly, namespace separation When you import just numpy without the sub-package matlib , then Python will be looking for .matlib as an attribute of the numpy package. This attribute has not been assigned to numpy without importing numpy.matlib (see discussion below) Sub-Modules and Binding If you're wondering why np.matlib.identity works without having to use the keyword npm , that's because when you import the sub-module matlib , the parent module numpy (named np in your case) will be given an attribute matlib which is bound to the sub-module. This only works if you first define numpy . From the reference : When a submodule is loaded using any mechanism (e.g. importlib APIs, the import or import-from statements, or built-in import ()) a binding is placed in the parent module’s namespace to the submodule object. Importing and __init__.py The choice of what to import is determined in the modules' respective __init__.py files in the module directory. You can use the dir() function to see what names the respective modules define. >> import numpy>> 'matlib' in dir(numpy)# False>> import numpy.matlib>> 'matlib' in dir(numpy)# True Alternatively, if you look directly at the __init__.py file for numpy you'll see there's no import for matlib . Namespace across Sub-Modules If you're wondering how the namespace is copied over smoothly ; The matlib source code runs this command to copy over the numpy namespace: import numpy as np # (1)...# need * as we're copying the numpy namespacefrom numpy import * # (2)...__all__ = np.__all__[:] # copy numpy namespace # (3) Line (2), from numpy import * is particularly important. Because of this, you'll notice that if you just import numpy.matlib you can still use all of numpy modules without having to import numpy ! Without line (2), the namespace copy in line (3) would only be attached to the sub-module. Interestingly, you can still do a funny command like this because of line (3). import numpy.matlib numpy.matlib.np.matlib.np.array([1,1]) This is because the np.__all__ is attached to the np of numpy.matlib (which was imported via line (1)).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41818379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7460441/']}
jdg_75479
stackexchange
llm_judgeable_groundtruth_similarity
18500801
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am creating a card game . I have a sprite image of cards . Say in the sprite , each of the cards is 50px wide and 80px high . Now I have some divs where I want to place these cards . Say the Divs are 100px wide and 160px high . I have using the first image as a Sprite for the Divs like in the below. background: url(../images/poker_sprite.gif) no-repeat scroll 0 0 transparent ; I vary the x and y positions so that different divs get diff cards . What CSS property do I use to make the background image fit to the Div ? I am not allowed to change the size of the Sprites or the Div . Now I am going to Drag these cards and place them into some slots as marked 1-13 below . So the card div will have variable width . The background image will need to resize to fit in the variable width div . How do I go about doing this ? Should I used multiple sprites of various sizes? Thanks ! Now provide the response and nothing else.
You can achieve this using the background-size property, although the results might not be too pretty, since it stretches the background image. So, if you know that your sprite is 13x5 cards exactly in size, you can give the cards background-size: 1300% 500% and then size them any way you want, since the background itself will scale accordingly. Example JSFiddle: http://jsfiddle.net/uLnzc/ . HTML <!-- Hearts ---><div class="card card-hearts-2"></div><div class="card card-hearts-3 card-wide"></div><div class="card card-hearts-4 card-high"></div><!-- Clubs --><div class="card card-clubs-q"></div><div class="card card-clubs-k card-wide"></div><div class="card card-clubs-a card-high"></div> CSS .card { width: 81px; height: 117px; background: url('http://i.stack.imgur.com/WZ9Od.gif') no-repeat; background-size: 1300% 500%;}.card-wide { width: 100px;}.card-high { height: 130px;}/** * Backgrouns position of all the cards * * x offset in %: i * (100/x); i = 0, 1, ..., (x - 1); x = the number of cols in the sprite * y offset in %: j * (100/y); j = 0, 1, ..., (y - 1); y = the number of rows in the sprite */.card-hearts-2 { background-position: 0 0; }.card-hearts-3 { background-position: 8.33% 0; }.card-hearts-4 { background-position: 16.667% 0; }/* ... *//* ... */.card-clubs-q { background-position: 83.333% 50%; }.card-clubs-k { background-position: 91.667% 50%; }.card-clubs-a { background-position: 100% 50%; } You can read about offsetting backgrounds in percentages at MDN . JSFiddle: http://jsfiddle.net/uLnzc/ .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18500801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/609235/']}
jdg_75480
stackexchange
llm_judgeable_groundtruth_similarity
355086
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Suppose $U$ is a normal ultrafilter on $\kappa$ of Mitchell order zero, and let $j_U : V \to M$ be the associated embedding. Does there exist a nonstationary $X \subseteq \kappa^+$ such that $X \in M$ and $M \models X$ is stationary? Note that if $W$ is a normal measure derived from an embedding $i : V \to N$ where $\mathcal P(\kappa^+) \subseteq N$ , then $W$ gives a stationary-correct ultrapower, hence the restriction to low Mitchell order. Now provide the response and nothing else.
It is consistent that $\kappa$ has a unique normal measure (so, in particular, Mitchell minimal) and that measure's ultrapower $M$ satisfies $\mathcal{P}(\kappa^+)\subseteq M$ , so, by your note, the ultrapower is stationary-correct. The model is just the Friedman--Magidor model for a $\kappa$ with a unique normal measure with large $2^\kappa$ . I don't know that this had been observed before, but it appears as Theorem 32 in my paper with Radek Honzík, Capturing sets of ordinals by normal ultrapowers .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/355086', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11145/']}
jdg_75481
stackexchange
llm_judgeable_groundtruth_similarity
154025
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Here is a group theoretic phrasing of a special case of the union closed conjecture: Question: Given a finite group $G$, is there an element of prime power order which is contained in at most half the subgroups of $G$? Motivation : Frankl's union closed sets conjecture has an equivalent phrasing in terms of lattices. It says that in every finite lattice there is a join irreducible element which is less than or equal to at most half the elements in the lattice. Finite lattices are always isomorphic to intervals of subgroups $[H,G]$ for groups $H,G$ (i.e. the lattice of subgroups $H\subseteq K \subseteq G$, with the subgroup relation). It is not known whether it suffices to take $H$ and $G$ to be finite. I wonder if anything about Frankl's conjecture is known for the case when $H$ is the trivial group. And that is precisely what is asked above. Notice that the elements of prime power order are in correspondence with the join irreducibles of the lattice of subgroups of $G$. Is the answer to the question above known? Is this known for special classes of groups? Now provide the response and nothing else.
In a somewhat different direction from Alireza: the conjecture is true for a large family of groups, including all abelian groups and many supersolvable groups. Let me start with the abelian case. Pick an element $g$ of highest possible prime-power order in an abelian group $G$. Then $\langle g \rangle$ has a complement : that is, there is a subgroup $K$ such that $K \langle g \rangle = G$ and $K \cap \langle g \rangle = 0$. In particular, $K \cong G / \langle g \rangle $ by the Isomorphism Theorems, and for any subgroup $X$ with $\langle g \rangle \subseteq X$ there is a corresponding subgroup $X \cap K$ which does not contain $\langle g \rangle$. In fact, the same argument applies to any $G$ and prime-power order element $g$ if 1) $g$ generates a normal subgroup, and 2) we can find a complement $K$ to $\langle g \rangle$ in G. In this situation, $[\langle g \rangle, G] \cong [1,K]$. (Edit: deleted discussion of supersolvable groups, which is irrelevant in light of update below.) UPDATE: The conjecture is true for all finite solvable groups. Proof : Let $G$ be a solvable group. Then $G$ has a normal subgroup $N$ of prime index, and some element of prime-power order $g \notin N$. Since $N$ is maximal in $G$, we have $\langle g,N \rangle = G$, and since $N$ is normal we have $\langle g,N \rangle = \langle g \rangle N$. Then by Dedekind's identity, we get that $\langle g \rangle (H \cap N) = H \cap G = H$ for any $H$ containing $\langle g \rangle$. The last tells us that the map from the interval $[\langle g \rangle,G] \rightarrow [1,N]$ given by $H \mapsto H \cap N$ is an injection. Since $N$ doesn't contain $g$, we get the conjectured statement. $\square$ Indeed, the above works whenever $G$ has a maximal normal subgroup of prime index. (E.g., for symmetric groups.) (Thanks to John Shareshian for several useful comments and discussion.) UPDATE 2: By combining my argument for solvable groups with Alireza's argument for (certain) finite simple groups, we can prove the conjecture for all groups having a quotient satisfying a certain condition. This very likely holds for all finite groups, but as I'll explain, a little bit of work remains on the group theory side. Theorem 1: If $G$ is a finite group with a normal subgroup $N$ such that $G/N$ is generated by (at most) two elements of prime power order, then $G$ satisfies the Frankl condition. Proof: A routine argument shows that we can pick $g,h \in G$ of prime power order such that $g$ and $h$ project in the quotient to generators of $G/N$. (If $G/N$ is cyclic, assume $g=h$.) Let $K = \langle g, h \rangle$, and notice that $KN = \langle N, g, h\rangle = G$. Then wlog there are at least as many subgroups containing $h$ as containing $g$ (else switch $h$ and $g$). This gives an injection $\varphi_1$ from the set of subgroups containing $g$ but not $h$ to the set of subgroups containing $h$ but not $g$. Moreover, if $H$ is a subgroup containing both $h$ and $g$, then $H \supseteq K$. It then follows from the Dedekind identity that $K (H \cap N) = H \cap KN = H$, hence the map $\varphi_2$ sending $H \mapsto H \cap N$ is an injection from $[K,G] \rightarrow [1,N]$. Since the intervals $[\langle h \rangle, G]$ and $[1,N]$ are disjoint, combining the two maps gives an injection from $[\langle g \rangle, G]$ to its complement, and we see the Frankl condition to hold. $\square$ Remark 1 : The solvable case (above) is the case when $G/N$ is cyclic -- here, $K = \langle g,h \rangle = K$. The case where $N=1$ solved by Alireza has $K = G$, in which case we map $G$ to $1$ and all other subgroups containing $g$ to a subgroup containing $h$. Remark 2 : The proof has a particularly pleasing explanation if we can take $g$ and $h$ to be conjugate. In this case, the intervals $[\langle g \rangle, G]$ and $[\langle h \rangle, G]$ are isomorphic lattices, with the isomorphism given by conjugation of subgroups. As we shall see below, this stronger conjugacy condition often does seem to occur. Now, if $N$ is a maximal normal subgroup, then $G/N$ is simple, so to verify the conjecture for all groups it suffices to verify that every finite simple group is generated by two elements of prime-power order. I managed to put together the following from results in the literature: Theorem 2 : All but possibly finite many of the finite simple groups are generated by two elements of prime power order. The two elements may be taken to be conjugate. Any exceptions are classical groups. The conjugacy part will come from the following lemma: Lemma : If a finite simple group $G$ is generated by $x$ and $g$, where $x$ has order 2, then $G = \langle g, g^x \rangle$. Proof (of Lemma) : Suppose not, and let $H = \langle g, g^x \rangle$. Then $H$ is easily seen to permute with $\langle x \rangle$, hence $H$ has index 2, contradicting simplicity of $G$. $\square$ We say a group is $(2,q)$-generated if it is generated by an element of order 2, together with an element of order $q$. To prove Theorem 2, it suffices to show that (modulo possible exceptions) every finite simple group is (2,$q$)-generated for some prime-power $q$. We go through the list of groups from the Classification Theorem. Many finite simple groups are known to be (2,3)-generated, and this condition has been well-studied. ((2,3)-generated groups can be represented as quotients of $PSL_2(\mathbb{Z})$, explaining the high level of interest in this condition.) A. Liebeck and Shalev in "Classical groups, probabilistic methods, and the (2,3)-generation problem" showed that, excluding the groups $PSp_4(q)$, all but finitely many of the classical groups are (2,3)-generated. B. Di Martino and Cazzola in "$(2,3)$-generation of $PSp(4,q),\ q=p^n,\ p\neq 2,3$" showed that $PSp_4(q)$ is (2,3)-generated, except in characteristic 2 or 3. C. Malle, and Lübeck and Malle in a series of papers culminating in "(2,3)-generation of exceptional groups" show that all exceptional groups of Lie type are (2,3)-generated, except for the Suzuki groups and $G(2)' \cong PSU_2(9)$. (Nick Gill also referenced this paper in his comment to Alireza's answer.) D. Woldar in "On Hurwitz generation and genus actions of sporadic groups" showed the sporadic groups to be (2,3)-generated, except for $M_{11}$, $M_{22}$, $M_{23}$, and $McL$ E. GA Miller proved in 1901 that the alternating groups $A_n$ are (2,3)-generated for $n \neq 6,7,8$. $A_6, A_7, A_8$ are easily verified to all be (2,5)-generated. Liebeck and Shalev in Proposition 6.4 of the same paper referenced above show that all but finitely many of the groups $PSp_4(2^n)$ and $PSp_4(3^n)$ are (2,5)-generated. Suzuki, in his original paper on the topic, showed that the Suzuki groups are (2,4)-generated. For the remaining sporadics, $M_{11}$ and $M_{22}$ are (2,4)-generated, while $M_{23}$ and $McL$ are (2,5)-generated. (The best place I found to read about this is in a series of papers on symmetric genus of groups. These papers are by various authors, frequently including Conder and Woldar.) Theorem 2 follows from the list above, together with the Classification of Finite Simple Groups. There is very likely a nicer approach to some of the simple group stuff than what I do above -- I'm far from an expert. (Maybe one of the real experts around here can remove the possible exceptions from the statement!!) I found the slides linked here of Maxim Vsemirnov on (2,3)-generated groups very helpful for understanding the exceptions to (2,3)-generation. In particular, he has a list of groups that are not (2,3)-generated on page 15 (which he conjectures to be complete). I've verified with GAP that all are (2,$q$)-generated for some prime $q$, except for the PSp's and $\Omega_8^+(2), P\Omega_8^+(3)$. Corollary: The conjecture holds for any $G$ with a maximal normal subgroup $N$ such that $G/N$ is not one of the exceptional (small) classical groups in Theorem 2.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/154025', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2384/']}
jdg_75482
stackexchange
llm_judgeable_groundtruth_similarity
53760452
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I added CoreData to my app MY_APP : I defined the data model by creating a xcdatamodeld file containinga single entity XXX with a few attributes. Using Xcode/Editor/Create NSManagedSubclass, Xcode created 2 files, XXX+CoreDataClass.swift and XXX+CoreDataProperties.swift . I wrote a little code to test storage and fetch back from core data, and everything works fine. The problem: At the beginning of the build phase, I get 3 warnings: warning: The Swift file "/Users/reiner/Library/Developer/Xcode/DerivedData/ MY_APP/Build/Intermediates.noindex/MY_APP.build/Debug-iphonesimulator/ MY_APP.build/DerivedSources/CoreDataGenerated/MY_APP/XXX+CoreDataClass.swift" cannot be processed by a Copy Bundle Resources build phase (in target ‚MY_APP‘) warning: The Swift file "/Users/reiner/Library/Developer/Xcode/DerivedData/ MY_APP/Build/Intermediates.noindex/MY_APP.build/Debug-iphonesimulator/ MY_APP.build/DerivedSources/CoreDataGenerated/MY_APP/XXX+CoreDataProperties.swift" cannot be processed by a Copy Bundle Resources build phase (in target 'MY_APP') warning: The Swift file "/Users/reiner/Library/Developer/Xcode/DerivedData/ MY_APP/Build/Intermediates.noindex/MY_APP.build/Debug-iphonesimulator/ MY_APP.build/DerivedSources/CoreDataGenerated/MY_APP/MY_APP+CoreDataModel.swift" cannot be processed by a Copy Bundle Resources build phase (in target 'MY_APP') These 3 files are not listed under MY_APP target/Build Phases/Copy Bundle Resources. My questions: Is anything wrong with my build setup, i.e. what is the reason for these warnings, and how can I avoid it? Remark: This question relates to a different framework (core data), but is similar to this one , which does not have an answer yet. EDIT: My project has 2 targets, for iOS and for watchOS. Until now, core data was used only on iOS. I tried now to enable it also for watchOS, but I got an error, because the .xcdatamodeld was not yet in Build Phases / Copy Bundle Resources. As soon as I added it there, core data was executed correctly on the watch. BUT: I got the same 3 warnings mentioned above, this time additionally for the watch extension target (altogether 6 warnings). Maybe this a useful hint. Now provide the response and nothing else.
EDIT: I contacted Apple, and they provided a solution: When an Xcode project „xxx“ is created with the coreData option on, a core data model file „xxx.xcdatamodeld“ is created and added to the target Build Phases Compile Sources. Say, one adds there an entity „Entity“ with an attribute „attribute“. If one selects in the Xcode project navigator this model file and opens the file inspector, there is an entry „Code Generation“ which is set to Swift by default. This creates the 2 files Entity+CoreDataClass.swift and Entity+CoreDataProperties.swift automatically, but they are not shown in the project navigator. Building the project succeeds, and one can use a property Entity.attribute as usual in the code. However: If one selects the xcdatamodeld file in the Xcode navigator, the Xcode Editor menu has an entry „Create NSManagedObject Subclass…“. If one selects this entry and there the xxx data model, the 2 files Entity+CoreDataClass.swift and Entity+CoreDataProperties.swift are created again and shown in the project navigator, and added by default to the target. This means that these files are added twice, thus the warnings. So the solution is not to use this editor command , and I don’t know what it is for… EDIT 2: My fault; I was looking at the wrong place: Open the xcdatamodeld in the project navigator. In the pane right of it, select an entity. At the top right, open the inspector pane. At the top right of it, select the data model inspector. There is an entry „Codegen“ where one can select Manual/None. If this option is selected, no code is automatically generated from xcdatamodeld, i.e., one can manually (by using the editor command) create NSManagedObject subclasses that can be added to the target Compile Sources section, as required. Previous answer: There are apparently 2 ways to use CoreData, either 1) by using only the PROJECT.xcdatamodeld file, which is then added to Compile Sources Build Phase , or 2) by creating a NSManagedObject subclass using Xcode’s Editor/Create NSManagedObject Subclass command. If 1) is used, everything works fine, but one has no property access to the entity used. If 2) is used, Xcode creates the 2 files ENTITY+CoreDataClass.swift and ENTITY+CoreDataProperties.swift . These 2 files are added to the Compile Sources Build Phase , but PROJECT.xcdatamodeld must not . If one does anyway, one gets the build error „unexpected duplicate task“. But if one does not, the project builds without errors and warnings. However, when run, the instruction let entity = NSEntityDescription.entity(forEntityName: "MyEntity", in: managedContext)! fails, because it does not find the data model. A workaround is to add PROJECT.xcdatamodeld to target / Build Phases / Copy Bundle Resources . Then the code executes fine, but one will get the warnings that I described in my question.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53760452', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1987726/']}
jdg_75483
stackexchange
llm_judgeable_groundtruth_similarity
17576381
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 interested in trying to create simple corner labels for a multipanel figure I am preparing in ggplot. This is similar to this previously asked question , but the answers only explained how to include a label at the top of the plot, not produce a corner label in the format required by many journals. I hope to replicate something similar to the plotrix function corner.label() in ggplot2 . Here is an example using plottrix of what I would like to recreate in ggplot2 . require(plotrix)foo1<-rnorm(50,25,5)foo2<-rpois(50,25)foo3<-rbinom(50,25,0.5)foo4<-rnbinom(50,25,0.5)par(mfrow=c(2,2))hist(foo1)corner.label(label='a',figcorner=T)hist(foo2)corner.label(label='b',figcorner=T)hist(foo3)corner.label(label='c',figcorner=T)hist(foo4)corner.label(label='d',figcorner=T) This produces the following: Thanks for any help in advance! Now provide the response and nothing else.
I had the same problem and came up with the following solution, which is a bit different: loading r packages library(ggplot2)library(grid)library(gridExtra) example data a <- 1:20b <- sample(a, 20)c <- sample(b, 20)d <- sample(c, 20) create a data frame mydata <- data.frame(a, b, c, d) create example plots myplot1 <- ggplot(mydata, aes(x=a, y=b)) + geom_point()myplot2 <- ggplot(mydata, aes(x=b, y=c)) + geom_point()myplot3 <- ggplot(mydata, aes(x=c, y=d)) + geom_point()myplot4 <- ggplot(mydata, aes(x=d, y=a)) + geom_point() set corner labels myplot1 <- arrangeGrob(myplot1, top = textGrob("A", x = unit(0, "npc") , y = unit(1, "npc"), just=c("left","top"), gp=gpar(col="black", fontsize=18, fontfamily="Times Roman")))myplot2 <- arrangeGrob(myplot2, top = textGrob("B", x = unit(0, "npc") , y = unit(1, "npc"), just=c("left","top"), gp=gpar(col="black", fontsize=18, fontfamily="Times Roman")))myplot3 <- arrangeGrob(myplot3, top = textGrob("C", x = unit(0, "npc") , y = unit(1, "npc"), just=c("left","top"), gp=gpar(col="black", fontsize=18, fontfamily="Times Roman")))myplot4 <- arrangeGrob(myplot4, top = textGrob("D", x = unit(0, "npc") , y = unit(1, "npc"), just=c("left","top"), gp=gpar(col="black", fontsize=18, fontfamily="Times Roman"))) plotting all plots on one page grid.arrange(myplot1, myplot2, myplot3, myplot4, ncol = 2)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17576381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1248622/']}
jdg_75484
stackexchange
llm_judgeable_groundtruth_similarity
37526411
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to create a UIViewController programmatically without the use of a nib or a storyboard. I thought it would be enough to implement the UIViewController as: class TestViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //Add some setup code here, without it it should just be blank }} instantiate it with let vc = TestViewController(nibName: nil, bundle: nil) or just TestViewController() and then just push it: navigationController?.pushViewController(vc, animated: true) But it shows the navigationController (upper bar) with a transparent View (the UIWindow behind is being shown, I have a multi-window setup) Now provide the response and nothing else.
According to the docs: If the view controller does not have an associated nib file, this method creates a plain UIView object instead. https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instp/UIViewController/view If you do not provide a nib file when instantiating the view controller, UIViewController calls it's loadView() method which creates a plain UIView object and assigns it to its view property. The reason why you are seeing a transparent view is because the UIView object has no background color. To verify this, you can set the background color of the view controller's view property right before you push it on your navigation stack. let viewController = TestViewController()viewController.view.backgroundColor = .blueColor()navigationController?.pushViewController(viewController, animated: true)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37526411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/386738/']}
jdg_75485
stackexchange
llm_judgeable_groundtruth_similarity
44966943
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: error: invalid conversion from 'int' to 'int*' int *q = 8; Works fine. *q = 6; Why can't I directly assign an int to an int pointer like this: int *q = 6 ; and I can assign it safely in the next line? Now provide the response and nothing else.
Because they're different things at all. The 1st one is definition of variable with initializer expression, i.e an initialization (of the pointer itself): int * q = 8;~~~~~ ~ ~~~type is int*; name of variable is q; initialized with 8 The 2nd one is assignment (of the object pointed by the pointer): *q = 6;~~ ~~~dereference on q via operator*; assign the resulting lvalue pointed by q to 6 And, int *p = 6; means define a variable named p with type int* and initialize it with 6 , which fails because 6 can't be used for initializing a pointer directly (i.e. the error "invalid conversion from 'int' to 'int*'").
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44966943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462608/']}
jdg_75486
stackexchange
llm_judgeable_groundtruth_similarity
19344092
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 mechanism which would allow an object to know that a zeroing weak reference turned nil? For example I have a property @property (nonatomic, weak) MyClass *theObject; when theObject deallocates and the property turns nil I want to get notified. But how? Does the zeroing weak reference system use the setter to set the property to nil when the object goes away? Now provide the response and nothing else.
The runtime just sets the weak ivar _theObect to nil, a custom setter is not called. What you could do (if you really need the notification): define a local "watcher" class and implement dealloc in that class, create a watcher object and set it as "associated object" of _theObject. When _theObject is deallocated, the associated object is released and deallocated (if there are no other strong refereces to it). Therefore its dealloc method is called. This is your "notification". (I'm writing this on the phone and can fill in the details later if necessary.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19344092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221023/']}
jdg_75487
stackexchange
llm_judgeable_groundtruth_similarity
15044971
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using codeigniter for this project. I hava a id value in which i pass from controller A to view A. This id value is echo between an anchor tag. When this anchor tag is clicked on, it redirects to another controller B with the id value and processed this id value within controller B. Is there any other way of doing this other than using the uri class? Want to keep the url clean. I thought of a way of appending hidden input elements when I shift from controller A to view A to controller B, but i realised it can be very messy. Any clean ways of doing this? Thanks in advance guys! Now provide the response and nothing else.
New to using Stackoverflow See if you could understand my layout: METHOD 1 Use the URI Class except you have good reasons not to. From CONTROLLER_A $data["id"] = ("ID NUMBER");$this->load->view("VIEW_A", $data); ANCHOR IN VIEW A <a href="<?php echo base_url() ?>/controller_b/controllerfunction/<?php echo $id ?>">link</a> IN CONTROLLER_B $id = $this->uri->segment(3); . METHOD 2 USE FORM POST if you want to keep things hidden: $data["id"] = ("ID NUMBER");$this->load->view("VIEW A", $data); ANCHOR IN VIEW A <form name="myform" id="myform" action="<?php echo base_url() ?>/controllerB/controllerfunction/" method="post"><input type="hidden" name="id" id="id" value="<?php echo $id ?>" /><input type="submit" value="See more" /></form> You could also use javascript to submit the form here via link if you which: <a href="javascript;" onclick="document.getElementById('myform').submit();"> See more</a> Tips:You could also use css to hide submit button in the form by setting opacity to 0;If link is within the form, you could use javascript:this.submit(); OR JQUERY <a href="javascript;" id="link">See more</a>$('#link').click(function() { $('#myform').submit();}); IN CONTROLLERB $id = $this->input->post("id");
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15044971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992618/']}
jdg_75488
stackexchange
llm_judgeable_groundtruth_similarity
27946244
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 macro variable, &myvar , but it won't resolve when I try to put it in a data step variable. Why won't it, and what can I do to fix this? %let myvar=Hello, world;data _null_; x='&myvar.'; put x=;run; Now provide the response and nothing else.
Macro variables in SAS won't resolve when they are in single quotes, '&myvar' . They need to be in double quotes, "&myvar" , in order to resolve properly. If you need to have single quotes and a resolved macro variable, you have a few options, but the simplest is: %str(%'&myvar.%') The %' inside of %str will place a single quote character (or apostrophe) in the text string by itself without causing it to be quoted. data _null_; x="%str(%'&myvar.%')"; put x=;run; or %let myvar2 = %str(%'&myvar.%');
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27946244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1623007/']}
jdg_75489
stackexchange
llm_judgeable_groundtruth_similarity
80857
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a custom application running on an embedded x86 setup (built using buildroot and uClibc). The application has been running fine but this morning when I returned to work I discovered my process had been killed and the following output on my terminal SAK: killed process 1008 (CX_SC3): fd#4 opened to the ttySAK: killed process 1009 (CX_SC3): fd#4 opened to the ttySAK: killed process 1011 (CX_SC3): fd#4 opened to the ttySAK: killed process 1012 (CX_SC3): fd#4 opened to the tty Now CX_SC3 is my process - it has multiple threads, one of which opens /dev/ttyS0 to send messages over a radio modem. The fd number is 4 for the serial port. What I don't understand is What the SAK means The PID listed above must refer to a process that was killed by my application as there is only ever one instance of my application running at a time. Is it possible that these PIDs are actually my thread IDs (as my application does run 4 threads always). If my application killed other processes, why was my application also killed? What does the opened to the tty part mean? From some research this suggests that this has something to do with a interrupt character sent to the tty that I used to start the program. What events could have lead to the following output? My embedded setup is very small, uses busybox and runs vsftpd and very little else other than my custom application. It is vital that my application is robust. EDIT: In response to the comment below, if this is due to a SAK being detected, is there anything that can accidentally trigger this? Is it possible that anything being read on the serial port has triggered this? Also, how can I find the SAK combination for my system - I do not have a rc.sysinit or rc.local file anywhere in my root file system. UPDATE: I have managed to pin this event down to the point at which my host machine shuts down. I have a serial cable between my host machine and my target device which I use to send serial data to the embedded target. When I leave the target running, but shutdown the host, my application is killed as described above. When I disconnect the serial cable prior to shutting down my host machine then my application does not get killed and runs as normal. This behaviour happens even after I have performed echo 0 > /proc/sys/kernel/sysrq as advised. Now provide the response and nothing else.
SAK in this case really means Secure Attention Key . The message you are seeing is a kernel message defined in drivers/tty/tty_io.c . SAK is a key combination which ensures secure login for a user on console. On Linux SAK ensures this by killing all processes attached to the terminal SAK is invoked on. It is expected that init will then restart the trusted login process like getty followed by login or X server with display manager . The listed PIDs are indeed PIDs of threads of your application CX_SC3 which were killed by SAK. fd#n opened to the tty means that the process/thread which was killed had the file descriptor n opened to the terminal on which the SAK was invoked. In Linux there are two ways of invoking SAK : Through the magic SysRq key - typically Alt + SysRq + K (virtual terminal) or Break K (serial console). This is not your case as you already tried to disable the magic SysRq by echo 0 > /proc/sys/kernel/sysrq and sending the Break K sequence by accident is improbable. Through a defined key sequence (virtual terminal) or the break signal (serial console). SAK availability on a serial console is controlled by setserial . Break signal on a serial line is continuous sending of spacing values over a time longer than the character sending time (including start, stop and parity bits). In you case it is highly probable that the condition of the Break signal appears during shutting your host machine down. Please try to turn the SAK off on your serial port on the target device by setserial : setserial /dev/ttyS0 ^sak You can check the SAK functionality status on the serial port by setserial -g /dev/ttyS0 . When turned on it will show SAK after Flags: . For automatic setting of the option after boot see the startup scripts which on BusyBox systems are usually /etc/init.d/rcS and /etc/rc.d/S* or check /etc/inittab for other possibilities.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/80857', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/20755/']}
jdg_75490
stackexchange
llm_judgeable_groundtruth_similarity
1132144
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 $k$ be an algebraically closed field of characteristic $p$, and $G$ a cyclic group of order $p$. I was asked to show that $k[G]$ is not semisimple. But I get confused since for any $k_1g_1 + k_2 g_2 \in k[G]$, $ (k_1g_1 + k_2 g_2)^p = k_1^p g_1^p + k_2 g_2 ^p = k_1 ^p + k_2 ^p $ since $k$ is of characteristic $p$. But isn't that then implies that every element of $k[G]$ is invertible so it's actually a field. Thus it's a simple module of itself since it does not have any non-trivial ideals. Then how could it be not semisimple? Can anyone help me with this? Thanks a lot. Now provide the response and nothing else.
I don't know where to find a reference for the claim I made in the comments, so here is a proof. It feels annoyingly complicated to me; I don't know if a substantially simpler proof is possible. Theorem (Maschke): Let $k$ be a field and let $G$ be a finite group. Then $k[G]$ is semisimple iff the characteristic of $k$ does not divide $|G|$. Proof. First suppose that the characteristic of $k$ divides $|G|$; call it $p$. We will use the fact that a finite-dimensional $k$-algebra is semisimple iff its Jacobson radical vanishes (see e.g. this blog post ). Our goal will be to exhibit an element of $k[G]$ in its Jacobson radical. Let $$s = \sum_{g \in G} g \in k[G].$$ Note that $gs = s$ for all $g \in G$ and that $s^2 = |G| s = 0$; in particular, $s$ is nilpotent, but moreover the left ideal generated by $s$, which consists of scalar multiples of $s$, consists of nilpotent elements. It follows that $s$ is a nonzero element of the Jacobson radical of $k[G]$, and hence that $k[G]$ is not semisimple. Now suppose that the characteristic of $k$ does not divide $|G|$; call it $p$. Recall that if $A$ is any finite-dimensional $k$-algebra, then there is a canonical linear functional on $A$ called the trace $$\text{tr}(a) = \text{tr}(L_a), L_a : A \ni x \mapsto ax \in A.$$ That is, $\text{tr}(a)$ is the trace of $a$ acting on $A$ by left multiplication. The trace induces a symmetric bilinear form on $A$ called the trace form $\langle a, b \rangle = \text{tr}(ab)$. Recall that a bilinear form on a vector space is nondegenerate if $a \neq 0$ implies that there exists some $b$ such that $\langle a, b \rangle \neq 0$. Lemma: If the trace form on $A$ is nondegenerate, then $A$ is semisimple. Proof. Let $j \in J(A)$ be an element of the Jacobson radical of $A$. On a finite-dimensional $k$-algebra, $J(A)$ can be characterized as the largest nilpotent right ideal of $A$. Hence if $b \in A$, then $jb \in J(A)$ is nilpotent. By passing to an algebraic closure of $k$ and upper-triangularizing the action of $jb$ on $A$ by left multiplication we see that the eigenvalues of $jb$ are all zero, so $\text{tr}(jb) = \langle j, b \rangle = 0$. It follows that if $j \neq 0$ then the trace form is degenerate. $\Box$ The trace on $k[G]$ takes a very simple form: $\text{tr}(1) = |G|$, and $\text{tr}(g) = 0$ for all non-identity elements $g$. By assumption, $|G| \neq 0$ in $k$, so it follows that if $a = \sum a_g g, a_g \neq 0$, then $$\text{tr}(g^{-1} a) = |G| a_g \neq 0$$ and hence the trace form is nondegenerate. The conclusion follows. $\Box$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1132144', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/112564/']}
jdg_75491
stackexchange
llm_judgeable_groundtruth_similarity
25483754
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this code to open a word file int num = 0;object fileName = FD.FileName;object readOnly = false;object isVisible = false;object missing = System.Reflection.Missing.Value;Word.Application WordApp = new Word.Application();Word.Document aDoc = null;WordApp.Visible = false;aDoc = WordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;num = aDoc.ComputeStatistics(stat, ref missing);label3.Text = "Page Count :"+aDoc.ComputeStatistics(stat, ref missing).ToString();GC.Collect(); Now, I want to print the opened word file on the click event of a button, Any idea? Now provide the response and nothing else.
Quick tip (not relevant to your topic but actually C#): there's no need to write out optional parameters as you did above, you can use ParameterName: parameter to specify a parameter to a optional parameter. Quick answer: use Document.PrintOut() method to print the current document. For more details about the parameters, you can take a look at MSDN site and this site for a hand-on tutorial. Here is a simple demo: public class YourClass : Form{ private Word.Application word = new Word.Application {Visible = false}; private Word.Document doc; // where did you get this file name? private string fileName; private void Count() { // as you mentioned, you open your word document here doc = word.Documents.Open(fileName, ReadOnly : readOnly, Visible: isVisible); } // in your button click handler, just call PrintOut() function private void ButtonClickHandler(object sender, EventArgs e) { // if doc == null, open the document if (doc == null) { // here i assume fileName has been assigned doc = word.Documents.Open(fileName, ReadOnly : readOnly, Visible: isVisible); } doc.PrintOut(); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25483754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2442439/']}
jdg_75492
stackexchange
llm_judgeable_groundtruth_similarity
1463
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: A security report we conducted through an outside company reported XSS vulnerabilities in FCKeditor which we're using in our PHP application. They pointed out that accessing URLs such as: http://www.ourdomain.com/fckeditor/editor/filemanager/browser/mcpuk/connectors /php/connector.php?Command=837<script>alert(0)</script>&Type=837 <script>alert(1)</script>&CurrentFolder=837<script>alert(2)</script> &ExtraParams=837<br><br><br><iframe src=http://www.google.com/ height=100% width=100%></iframe> Leads to code such as the following being generated (from browser -> view source): Invalid command.Array<br />(<br />[Command] => 837<script>alert(0)</script><br />[Type] => 837<script>alert(1)</script><br />[CurrentFolder] => 837<script>alert(2)</script><br />[ExtraParams] => 837<br><br><br><iframe src=http://www.google.com/ height=100% width=100%></iframe><br />)<br /> I have no idea what this internal php script of FCKeditor does and whether it could become a source of XSS content into my system? Is this a genuine issue? Now provide the response and nothing else.
Usually there's not much you can do about vulns in 3rd party components. Among your options: Start by upgrading to the latest version. If that fixes it, you're done. Contact the vendor responsibly, and get a fix from them. If it's open source, try to patch it yourself - or find someone who did. Just make sure you do it right, and fixing XSS can be complicated and/or confusing. If none of the above options are possible, consider removing this component from your system. It's always a risk, when taking some other component blindly, if you're not able to get it fixed... In fact, make it a policy to do a security review on any 3rd party code before integrating it into your system. If you absolutely MUST continue to use a vulnerable component - reconsider :). But really, if its a done deal, consider protecting it with a WAF (web application firewall). Doesn't solve the problem, but it can help prevent exploitation...
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/1463', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/566/']}
jdg_75493
stackexchange
llm_judgeable_groundtruth_similarity
4080086
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 my SQL Search statement....... I want to return values on column NAME with first priority and then column Desc_Work . Select * from postswhere Province = 'Western_Cape'and NAME LIKE '%Etienne%' or Desc_Work LIKE '%Etienne%' What changes must I make to this to make sure that the rows in column NAME will be displayed first? Now provide the response and nothing else.
ORDER BY CASEWHEN NAME LIKE '%Etienne%' THEN 1ELSE 2END I also believe that you wanted where Province = 'Western_Cape'and (NAME LIKE '%Etienne%' or Desc_Work LIKE '%Etienne%') UPDATE Select * from postswhere Province = 'Western_Cape'and (NAME LIKE '%Etienne%' or Desc_Work LIKE '%Etienne%')ORDER BY CASEWHEN NAME LIKE '%Etienne%' THEN 1ELSE 2END I assume you need (NAME LIKE '%Etienne%' or Desc_Work LIKE '%Etienne%') in brackets - your original query returns records where (Province = 'Western_Cape' and NAME LIKE '%Etienne%' ) or Desc_Work LIKE '%Etienne%') ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4080086', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33584/']}
jdg_75494
stackexchange
llm_judgeable_groundtruth_similarity
109406
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: From what I understand: Generally speaking, a driver runs in kernel space and can be called from user space. Only code in kernel space can call usb low level things / ioctl libusb is a library, so it will compile and run in user space So how does libusb achieve low level USB? Now provide the response and nothing else.
Libusb is a library to interact with USB devices in the same manner that curses is a library to interact with text terminals, ALSA (more precisely its libasound component) is a library to interact with audi devices, etc. The kernel handles the hardware interactions. It provides device files that applications can open to interact with the hardware, through read , write and ioctl system calls . ioctl is a system call: it allows applications (user-level code) to issue requests that are processes by the kernel. Libusb allows applications to register callback functions which are executed when the device has something to report. Here's a rough overview of the information flow under the hood: The electrical signal on the bus triggers an event on the USB controller. The USB controller raises an interrupt signal on the main processor. The processor executes the interrupt handler in the operating system kernel. The kernel notices that a process is currently in a blocking read , write or ioctl system call on the device file and causes that system call to return. In the user land process, when the system call returns, library code is executed. The library code executes the callback function registered by the application programmer.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/109406', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/46465/']}
jdg_75495
stackexchange
llm_judgeable_groundtruth_similarity
1324903
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: $\newcommand{\<}{\langle} \newcommand{\>}{\rangle} $Let $||\cdot||$ be a norm on a finite dimensional real vector space $V$. Does there always exist some inner product $\<,\>$ on $V$ such that $\text{ISO}(|| \cdot ||)\subseteq \text{ISO}(\<,\>)$ ? Update: As pointed by Qiaochu Yuan the answer is positive. This raises the question of uniqueness of the inner product $\<,\>$ which satisfies $\text{ISO}(|| \cdot ||)\subseteq \text{ISO}(\<,\>)$. Is it unique (up to scalar multiple)? Remarks: 1) Determining $\<,\>$ (up to scalar multiple) is equivalent to determining $\text{ISO}(\<,\>)$. Clearly if we know the inner product we know all its isometries. The other direction follows as a corollary from an argument given here which shows which inner products are preserved by a given automorphism. 2) Since there are "rigid" norms (whose only isometries are $\pm Id$ ) the uniqueness certainly doesn't hold in general. One could hope for that in the case of "rich enough norms" ( norms with many isometries, see this question ) the subset $\text{ISO}(|| \cdot ||)\subseteq \text{ISO}(\<,\>)$ will be large enough to determine $\text{ISO}(\<,\>)$. (which by remark 1) determines $(\<,\>)$). Now provide the response and nothing else.
Yes. This is because an isometry group is always compact (with respect to the topology on $\text{End}(V)$ induced by the operator norm: this is a consequence of the Heine-Borel theorem). Hence you can average an inner product over it with respect to Haar measure.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1324903', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/104576/']}
jdg_75496
stackexchange
llm_judgeable_groundtruth_similarity
26147
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to know what $ a^4+b^4+c^4 $ would be when $ a+b+c=1, a^2+b^2+c^2=2, a^3+b^3+c^3=3. $ I tried Solve[{a + b + c == 1, a^2 + b^2 + c^2 == 2, a^3 + b^3 + c^3 == 3}, {a, b, c}]a^4 + b^4 + c^4 /. {a -> ... } I copied and pasted one instance from the result of Solve[] into {a -> ...} The solution and the result of Simplify[] of it was not quite what I expected. So as a test, I tried a+b+c /. {a -> ...} Still it was strange, it didn't come up with 1 which is obvious correct answer. So am I missing anything here? Is there any better way? Now provide the response and nothing else.
Solve your equations with respect to another variable d == a^4 + b^4 + c^4 eliminating given ones Solve[{ a + b + c == 1, a^2 + b^2 + c^2 == 2, a^3 + b^3 + c^3 == 3, a^4 + b^4 + c^4 == d}, {d}, {a, b, c}] {{d -> 25/6}} This tutorial will be helpful Eliminating Variables . Edit For the sake of completeness we add another methods of dealing with the problem. Let's point out even simpler way than the first one, just add assumptions to Simplify : Simplify[ a^4 + b^4 + c^4, {a + b + c == 1, a^2 + b^2 + c^2 == 2, a^3 + b^3 + c^3 == 3}] 25/6 Of course we can use FullSimplify as well. In this case, Simplify works nicely, but the first method is stronger and should work in more general cases. SymmetricReduction is more appropriate when we would like to get symbolic results, i.e. here we would like to express a^4 + b^4 + c^4 in terms of these polynomials: { a + b + c, a^2 + b^2 + c^2, a^3 + b^3 + c^3 } First we need to get rid of unknown symmetric polynomials (we know only a + b + c ): SymmetricPolynomial[#, {a, b, c}] & /@ Range[3] {a + b + c, a b + a c + b c, a b c} form the last reduction using the previous ones: First @ SymmetricReduction[ a^# + b^# + c^#, {a, b, c}] & /@ Range[4] // Column a + b + c(a + b + c)^2 - 2 (a b + a c + b c)3 a b c + (a + b + c)^3 - 3 (a + b + c) (a b + a c + b c) 4 a b c (a + b + c) + (a + b + c)^4 - 4 (a + b + c)^2 (a b + a c + b c)+ 2 (a b + a c + b c)^2 Now we have a^4 + b^4 + c^4 expressed in terms of given polynomials: str = First[ SymmetricReduction[ a^4 + b^4 + c^4, {a, b, c}]] //. { (a b + a c + b c) -> 1/2 (a + b + c)^2 - 1/2 (a^2 + b^2 + c^2), (a b c) -> 1/3 (a^3 + b^3 + c^3) - 1/3 (a + b + c)^3 + (a + b + c) (a b + a c + b c)} (a + b + c)^4 - 4 (a + b + c)^2 (1/2 (a + b + c)^2 + 1/2 (-a^2 - b^2 - c^2)) + 2 (1/2(a + b + c)^2 + 1/2(-a^2 - b^2 - c^2))^2 + 4(a + b + c) (-(1/3)(a + b + c)^3 + 1/3 (a^3 + b^3 + c^3) + (a + b + c) (1/2 (a + b + c)^2 + 1/2 (-a^2 - b^2 - c^2))) of course Simplify @ % a^4 + b^4 + c^4 and finally: str /. {a + b + c -> 1, (-a^2 - b^2 - c^2) -> -2, (a^3 + b^3 + c^3) -> 3} 25/6
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/26147', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7710/']}
jdg_75497
stackexchange
llm_judgeable_groundtruth_similarity
35665
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: In school, I recently proved a solid geometry excercise by assuming that the following lemma is true: If two lines $g$ and $h$ in the euclidian space are not parallel, and if the lines seem parallel under a parallel projection, then the distance between projected lines is equal to the minimal distance of the $g$ and $h$. Is this true, and if yes, how can I prove it? Please try to prove it in a way, that is understandable for somebody in highschool. (An answer of the style "This is just a special case of lemma X" is not very helpful) Now provide the response and nothing else.
If the lines appear parallel under a parallel projection, they must lie in two parallel planes perpendicular to the projection plane. Imagine these two planes superimposed. Then the square of the distance between two points on the lines is by Pythagoras given by the sum of the square of the distance within the planes and the square of the distance between the planes. If the lines are not parallel, they must intersect in the superimposed planes, so there must be a point where that squared distance takes its minimal value, the square of the distance between the planes. Thus the minimal distance is the distance between the planes, which is the distance between the projected lines.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/35665', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5282/']}
jdg_75498
stackexchange
llm_judgeable_groundtruth_similarity
26838965
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using sweet-alert plugin to display an alert. With a classical config (defaults), everything goes OK. But when I want to add a HTML tag into the TEXT, it display <b>...</b> without making it bold. After searching for the answer, it looks like I don't have the right search word... How to make sweet alert display the text also with HTML code? var hh = "<b>test</b>";swal({ title: "" + txt + "", text: "Testno sporocilo za objekt " + hh + "", confirmButtonText: "V redu", allowOutsideClick: "true" }); Now provide the response and nothing else.
The SweetAlert repo seems to be unmaintained. There's a bunch of Pull Requests without any replies, the last merged pull request was on Nov 9, 2014. I created SweetAlert2 with HTML support in modal and some other options for customization modal window - width, padding, Esc button behavior, etc. Swal.fire({ title: "<i>Title</i>", html: "Testno sporocilo za objekt: <b>test</b>", confirmButtonText: "V <u>redu</u>", }); <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/26838965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4161621/']}
jdg_75499
stackexchange
llm_judgeable_groundtruth_similarity
17872854
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was trying to find a good explanation for the difference between synchronous communication vs asynchronous communication for web services, all over the internet. but it seems that even the people who is willing to provide an answer to the problem is also confused with it. and one answer is the complete vice versa for another answer. If anybody can provide a good explanation about the difference of above matter with a clear idea, it would be helpful for everybody who would face the same problem in the future. Now provide the response and nothing else.
Asynchronous service Say you have a long running web service (say it reads a large file from the file system and does some processing). If you set this up as a 'synchronous' web service (using the WCF definition of that), then the calling client will have to wait until the processing completes, and typically this will block on one of the asp.net worker threads while processing completes. For a service with high traffic, this can become problematic. If you set this up as an asynchronous web service, then what you are saying is that your code is going to delegate some of the long running processing to another thread, or use a non-blocking mechanism, and that this will return at some point in the future (if you are using c# 5.0, then you might want to look at examples of the async and await keywords). For the example, reading a large file could be done using one of the async ReadFile methods. This will not block one of the asp.net worker threads, allowing potentially greater throughput. (There is often some confusion when people refer to making multiple simultaneous calls to the same service (often via AJAX from a web page) - while the calls from the page will typically be made using an asynchronous mechanism in javascript, this is not quite the same as what is described above - I like to keep a distinction between multiple parallel calls and asynchronous calls in my head) Asynchronous calls It's also worth noting that you can make an asynchronous call to a service even if that service is not set up to be 'asynchronous'. This is how AJAX calls in javascript will work, e.g. var jqxhr = $.ajax( "AnyService.svc" ) .done(function() { alert("success"); }) .fail(function() { alert("error"); }) .always(function() { alert("complete"); });alert("Called"); For this example, you would expect to see 'Called' displayed before 'Success', as this will not wait for the service to return prior to proceeding. The service you are calling does not have to be 'asynchronous'. Edit As pointed out in the comments, you can also have a client that calls an 'asynchronous' service in a synchronous manner (i.e. the service will not block worker threads for further requests, but the client will block at that side).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17872854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1095180/']}
jdg_75500
stackexchange
llm_judgeable_groundtruth_similarity
23693173
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 Elixir, if I try to pattern match the following two tuples: {a} = {1, 2} I get a match error. But if I do the same for two maps: %{x: a} = %{x: 1, y: 2} It works fine, and a binds to 1. I can see why matching the two tuples gave an error, but why did matching the maps not give an error? Now provide the response and nothing else.
In the first example you are attempting to match a single element tuple against a two-element tuple. In the second example you are matching on the :x key in both the left and right maps. EDIT: I should clarify the rules around data structures and pattern matching in Elixir. When matching on tuples, you need to provide a pattern which matches the entire tuple structure. You can use _ , which is the "catch-all" pattern, but you'll still need to provide it for all elements of the tuple. When matching on lists, you must match on either all elements when using the [a, b, c] = [1, 2, 3] syntax, or on the head and tail, using the [h|t] = [1, 2, 3] syntax. When matching maps though, you can match on one or more keys in the map, which gives you the %{a: b} = %{a: :foo, b: :bar} syntax. The semantics are a bit different between data structures, but are fairly common sense. The tuple rule exists because two tuples cannot be the same unless they have the same number of elements, a list has the same limitation, but because of the semantics of lists, accessing the head element of the list is the most common operation when working with them, hence the [h|t] syntax. Maps however can match based on specific keys, so the number of elements are irrelevant, as long as both sides of the match contain the same key, and optional pattern for the value, then it's a successful match.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23693173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1375688/']}
jdg_75501
stackexchange
llm_judgeable_groundtruth_similarity
4562471
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a running local instance of PostgreSql on a linux machine. When I use psql command from the shell I success to log in without any problem. I need to connect to the PostgreSql via the JDBC, but I don't know what exactly should I pass as url parameter to DriverManager.getConnection() . It should start with jdbc:postgresql: but what's going next? I was told by the system group that a database with was created like user name. e.g. if my user is jutky a db named jutky was created, but when I try to open a connection to jdbc:postgresql:jutky I get an error org.postgresql.util.PSQLException: FATAL: password authentication failed for user "jutky" :( Additional info When I login via the psql I'm not prompted for the password, so when I try to login via JDBC I pass an empty string as a password - is it correct, or should I pass null or something? When I type psql --help in the shell I see among the rest this line: Connection options: -h, --host=HOSTNAME database server host or socket directory (default: "/var/run/postgresql") So I understand that I connect to PostgreSql via a socket directory , does that matters something to the URL string in the JDBC? EDIT First thanks for the answers. Second: its not first time I'm using JDBC and in particular not the first time I'm connecting to the PostgreSql from JDBC, so I know the general rules and I have read the documentations. However in the described case I'm not sure how exactly should I construct the connection string if the instance is running via the socket directory and what password should I provide. Because when I login via the psql I'm not prompted for password at all. Thanks in advance. Now provide the response and nothing else.
In addition to other answers note that by default Postgres is configured to accept connections via Unix sockets with authentication based on your operating system account, that's why psql works fine and doesn't require the password. JDBC connections are made over TCP/IP with password authentication, so you need to modify pg_hba.conf accordingly. For example, this line allows TCP/IP connections from the same machine to all databases for all users with password authentication: host all all 127.0.0.1/32 md5 After adding this line jdbc:postgresql:databasename should work. EDIT: You can't create a JDBC connection over Unix socket since PostgreSQL JDBC driver can only work over TCP/IP. The password you use when creating JDBC connection is the password assigned to your user. If you don't have it, you can assign it, for example, using ALTER USER command. See 19.3. Authentication methods . See also: 19.1. The pg_hba.conf file
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4562471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188264/']}
jdg_75502
stackexchange
llm_judgeable_groundtruth_similarity
11819
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: In today's news , scientists found a bright object on one of Curiosity's photos (it's near the bottom of the picture below). It's a bit tricky to find - I actually spent quite some time staring at the picture before I saw it. The question, then, is how one can systematically search for such anomalies. It should be harder than famous How do i find Waldo problem, as we do not necessarily know what we are looking for upfront! Unfortunately, I know next to nothing about image processing. Playing with different Mathematica functions, I managed to find a transformation which makes the anomaly more visible at the third image after color separation -- but I knew what I was looking for already, so I played with the numerical parameter for Binarize until I found a value (0.55) that separated the bright object from the noise nicely. I'm wondering how can I do such analysis in a more systematic ways. img = Import["http://www.nasa.gov/images/content/694809main_pia16225-43_946-710.jpg"];Colorize @ MorphologicalComponents @ Binarize[#, .55] & /@ ColorSeparate[img] Any pointers would be much appreciated! Now provide the response and nothing else.
Here's another, slightly more scientific method. One that works for many kinds of anomalies (darker, brighter, different hue, different saturation). First, I use a part of the image that only contains sand as my training set (I use the high-res image from the NASA site instead of the one linked in the question. The results are similar, but I get much saner probabilities without the JPEG artifacts): img = Import["http://www.nasa.gov/images/content/694811main_pia16225-43_full.jpg"];sandSample = ImageTake[img, {0, 200}, {1000, 1200}] We can visualize the distribution of the R/G channels in this sample: SmoothHistogram3D[sandPixels[[All, {1, 2}]], Automatic, "PDF", AxesLabel -> {"R", "G", "PDF"}] The histogram looks a bit skewed, but it's close enough to treat it as gaussian. So I'll assume for simplicity that the "sand" texture is a gaussian random variable where each pixel is independent. Then I can estimate it's distribution like this: sandPixels = Flatten[ImageData[sandSample], 1];dist = MultinormalDistribution[{mR, mG, mB}, {{sRR, sRG, sRB}, {sRG, sGG, SGB}, {sRB, sGB, sBB}}];edist = EstimatedDistribution[sandPixels, dist];logPdf = PowerExpand@Log@PDF[edist, {r, g, b}] Now I can just apply the PDF of this distribution to the complete image (I use the Log PDF to prevent overflows/underflows): rgb = ImageData /@ ColorSeparate[GaussianFilter[img, 3]];p = logPdf /. {r -> rgb[[1]], g -> rgb[[2]], b -> rgb[[3]]}; We can visualize the negative log PDF with an appropriate scaling factor: Image[-p/20] Here we can see: The sand areas are dark - these pixels fit the estimated distribution from the sand sample Most of the Curiosity area in the image is very bright - it's very unlikely that these pixels are from the same distribution The shadows of the Curiosity probe are gray - they're not from the same distribution as the sand sample, but still closer than the anomaly The anomaly we're looking is very bright - It can be detected easily To find the sand/non-sand areas, I use MorphologicalBinarize. For the sand pixels, the PDF is > 0 everywhere, for the anomaly pixels, it's < 0, so finding a threshold isn't very hard. bin = MorphologicalBinarize[Image[-p], {0, 10}] Here, areas where the Log[PDF] < -10 are selected. PDF < e^-10 is very unlikely, so you won't have to check too many false positives. Final step: find connected components, ignoring components above 10000 Pixels (that's the rover) and mark them in the image: components = ComponentMeasurements[bin, {"Area", "Centroid", "CaliperLength"}, 10 < #1 < 10000 &][[All, 2]]Show[Image[img], Graphics[{Red, AbsoluteThickness[5], Circle[#[[2]], 2 #[[3]]] & /@ components}]] Obviously, the assumption that "sand pixels" are independent gaussian random variables is a gross oversimplification, but the general method would work for other distributions as well. Also, r/g/b values alone are probably not the best features to find alien objects. Normally you'd use more features (e.g. a set of Gabor filters)
{}
{'log_upvote_score': 9, 'links': ['https://mathematica.stackexchange.com/questions/11819', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1351/']}
jdg_75503
stackexchange
llm_judgeable_groundtruth_similarity
51469881
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to implement a recurring (timed) IHostedService instance in ASPNET Core that can be stopped and started on demand. My understanding is that IHostedService(s) are started by the framework on application startup. However, I would like to be able to start/stop the service 'manually', perhaps using an on/off toggle via a UI. Ideally the "off" state would dispose of currently running service, and the "on" state would then create a new instance. I've read the MS docs here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.1 . My initial thought was to get an instance of the running service and then call the public StopAsync(CancellationToken token) method. However I'm a little stuck when it comes to which token I should pass in, and the same could be said for the StartAsync(CancellationToken cancellationToken) method. Any ideas on how this should be done, or if it's even advisable? Is my approach somehow going against the intended design of hosted services in ASPNET Core? EDIT 7.27.2018 So it appears after some more research (aka actually reading the documentation :D) that hosted services StartAsync/StopAsync methods are indeed meant to coincide with the lifetime of the application. Registered IHostedServices seem to not be added to the DI container for injection into other classes. Therefore I do not think my initial idea will work. For now I registered my services with configuration dependencies ( IOptions<T> ) that can be updated at runtime. As the hosted services is processing, it will check the configuration to see if it should continue, otherwise it will just wait (instead of stopping or disposing of the hosted service). I'll probably mark this as my answer soon, unless I hear of some other ideas. Now provide the response and nothing else.
For StopAsync(CancellationToken token) , you could pass new System.Threading.CancellationToken() . In the defination of public CancellationToken(bool canceled) , canceled indicates state for the token. For your scenario, there is no need to specify the canceled since you want to Stop the service. You could follow below step by step: Create IHostedService public class RecureHostedService : IHostedService, IDisposable {private readonly ILogger _log;private Timer _timer;public RecureHostedService(ILogger<RecureHostedService> log){ _log = log;}public void Dispose(){ _timer.Dispose();}public Task StartAsync(CancellationToken cancellationToken){ _log.LogInformation("RecureHostedService is Starting"); _timer = new Timer(DoWork,null,TimeSpan.Zero, TimeSpan.FromSeconds(5)); return Task.CompletedTask;}public Task StopAsync(CancellationToken cancellationToken){ _log.LogInformation("RecureHostedService is Stopping"); _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask;}private void DoWork(object state){ _log.LogInformation("Timed Background Service is working.");}} Register IHostedService services.AddSingleton<IHostedService, RecureHostedService>(); Start and Stop Service public class HomeController : Controller { private readonly RecureHostedService _recureHostedService; public HomeController(IHostedService hostedService) { _recureHostedService = hostedService as RecureHostedService; } public IActionResult About() { ViewData["Message"] = "Your application description page."; _recureHostedService.StopAsync(new System.Threading.CancellationToken()); return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; _recureHostedService.StartAsync(new System.Threading.CancellationToken()); return View(); } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51469881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2363186/']}
jdg_75504
stackexchange
llm_judgeable_groundtruth_similarity
4132409
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 method of integrating the following: $$\int_0^{\infty}\frac{1}{(1+x)(1+x^2)}$$ I tried doing it via using partial fractions and deduce that: $$\frac{\ln(x+1)}{2} - \frac{\ln(x^2+1)}{4} + \frac{\arctan(x)}{2} + C$$ However I am unsure how to use the limits given in the question. I suspect there is a way to do this using contour integration and this is probably the most straightforward method but I cannot see how to do it. Any help would be appreciated. Now provide the response and nothing else.
HINT: Note that we have $$\begin{align}\frac12\log(x+1)-\frac14\log(x^2+1)&=\frac14 \log\left(\frac{x^2+2x+1}{x^2+1}\right)\\\\&=\frac14 \log\left(1+\frac{2x}{x^2+1}\right)\end{align}$$ And we have the estimates for $x>0$ $$0\le \log\left(1+\frac{2x}{x^2+1}\right)\le \frac{2x}{x^2+1}$$ Can you finish now? ALTERNATIVE APPROACH: Let $I$ be given by the integral $I=\int_0^\infty \frac{1}{(x+1)(x^2+1)}\,dx$ . We write the integral as the sum of integrals, the first from $0$ to $1$ and the second from $1$ to $\infty$ . The we enforce the substitution $x\mapsto 1/x$ in the second integral. Proceeding we have $$\begin{align}I&=\int_0^1 \frac{1}{(x+1)(x^2+1)}\,dx+\color{blue}{\int_1^\infty \frac{1}{(x+1)(x^2+1)}\,dx}\\\\&\overbrace{=}^{\color{blue}{x\mapsto 1/x}}\int_0^1 \frac{1}{(x+1)(x^2+1)}\,dx+\color{blue}{\int_1^0 \frac1{(1+1/x)(1+1/x^2)}\,\left(-\frac1{x^2}\right)\,dx}\\\\&=\int_0^1 \frac{1}{(x+1)(x^2+1)}\,dx+\color{blue}{\int_0^1 \frac{x}{(x+1)(x^2+1)}\,dx}\\\\&=\int_0^1 \frac1{1+x^2}\,dx\\\\&=\frac\pi4\end{align}$$ And we are done!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4132409', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/417733/']}
jdg_75505
stackexchange
llm_judgeable_groundtruth_similarity
7754317
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an app that needs to do something when it’s sent to background using the Home button and something else when the device is locked using the top hardware button. The standard way of solving these requirements are the notifications and delegate methods sent out by UIApplication . On iOS 4 they look like this: // Pressing the home buttonWill resign active.Did enter background.// Tapping app icon on SpringboardWill enter foreground.Did become active.// Pressing the lock buttonWill resign active.// Unlocking the deviceDid become active. In other words, it’s quite easy to tell between locking and backgrounding. On iOS 5 the behaviour changed: // Pressing the home buttonWill resign active.Did enter background.// Tapping app icon on SpringboardWill enter foreground.Did become active.// Pressing the lock buttonWill resign active.Did enter background.// Unlocking the deviceWill enter foreground.Did become active. Notice that the didEnterBackground and willEnterForeground notifications are now sent out even when (un)locking the device, making it impossible to tell between locking and backgrounding. Is this change documented somewhere? Is it a regression? Do you know another way to distinguish the two cases? Now provide the response and nothing else.
iOS 6 In my preliminary testing via the simulator, checking the application state with [[UIApplication sharedApplication] applicationState] in either - (void)applicationWillEnterForeground:(UIApplication *)application- (void)applicationDidEnterBackground:(UIApplication *)application allows you to differentiate between a call to lock the device and just switching back to the homescreen. A lock screen will return 1 (UIApplicationStateInactive), whereas a home button press will register as a 2 (UIApplicationStateBackground). It seems consistent and should work on an iOS device just as reliably as it does in the simulator. iOS 7 The iOS 6 method no longer works in iOS 7. In order to do this now, you have to utilize CFNotificationCenter and listen for a darwin notification (labeled: com.apple.springboard.lockcomplete). You can find the github repo with the sample project here: https://github.com/binarydev/ios-home-vs-lock-button Credit for the iOS 7 fix goes out to wqq
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7754317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17279/']}
jdg_75506
stackexchange
llm_judgeable_groundtruth_similarity
2834691
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 function with this code: foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()){//SOME CODEif (propertyInfo.CanWrite) propertyInfo.SetValue(myCopy, propertyInfo.GetValue(obj, null), null);} I would avoid to check "collection" properties; to do this now I have insert this control: if (propertyInfo.PropertyType.Name.Contains("List") || propertyInfo.PropertyType.Name.Contains("Enumerable") || propertyInfo.PropertyType.Name.Contains("Collection")) continue; but, It don't like me! Which is a better way to do it? Now provide the response and nothing else.
I was thinking you might want to check the interfaces the type of the property implements. (Removed redundant interfaces, as IList inherits ICollection and ICollection inherits IEnumerable.) static void DoSomething<T>(){ List<Type> collections = new List<Type>() { typeof(IEnumerable<>), typeof(IEnumerable) }; foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { if (propertyInfo.PropertyType != typeof(string) && propertyInfo.PropertyType.GetInterfaces().Any(i => collections.Any(c => i == c))) { continue; } Console.WriteLine(propertyInfo.Name); }} I added code to not reject string, as it implements IEnumerable, as well, and I figured you might want to keep those around. In light of the redundancy of the prior list of collection interfaces, it may be simpler just to write the code like this static void DoSomething<T>(){ foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { if (propertyInfo.PropertyType != typeof(string) && propertyInfo.PropertyType.GetInterface(typeof(IEnumerable).Name) != null && propertyInfo.PropertyType.GetInterface(typeof(IEnumerable<>).Name) != null) { continue; } Console.WriteLine(propertyInfo.Name); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2834691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198119/']}
jdg_75507
stackexchange
llm_judgeable_groundtruth_similarity
25014
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 am frequently getting warnings from my ESET firewall, like that pictured below, that Skype is attempting to communicate over SSL with a remote computer that has an untrusted certificate: The remote computer is always a different host. I don't ever know or recognize the remote computer, and I am very alarmed at this. Does anyone have an explanation for this? Now provide the response and nothing else.
Yes, be alarmed. It looks like something injected into Skype is trying to communicate with an untrusted server in Ukraine. There's no reason for Skype to be doing this normally. A bit of investigation on the domain returns this information: domain: pakko.uaadmin-c: PC226-UANICtech-c: IMENA-UANICstatus: OK-UNTIL 20131123175521dom-public: NOlicense: 43288nserver: ns1.imena.com.uanserver: ns3.imena.com.uanserver: ns2.imena.com.uamnt-by: IMENA-UANIC (ua.imena)created: 0-UANIC 20041123175521changed: IMENA-UANIC 20121011174615source: UANICnic-handle: PC226-UANICorganization: Pakko Corporationaddress: Klima Savura 21address: Lutsk Ukrainefax-no: +380332 78 94 39phone: +380332 78 94 94 A quick search for "Pakko Corporation" returns a limited liability company in Ukraine : Address:21а, Savura str., c. Lutsk, Volyn reg., 43005, UkraineTelephone:+38(0332) 78-91-90, 78-94-89Web-site:http://www.pakko.ua They list their employee count as between 50 and 100. A bit more digging finds a previous employee on LinkedIn and a bit more info. So it looks like a legitimate company, but I don't fancy going on their website to work out what they do. I'd guess that their site has been compromised and is now being used as a command and control server. I'd guess you've got some sort of malware that has injected a thread into Skype, since it's a program that's usually allowed to communicate with the network. Since your machine is likely compromised, my recommendation is to nuke it from orbit and start over.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/25014', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/16786/']}
jdg_75508
stackexchange
llm_judgeable_groundtruth_similarity
79322
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: I was told that we would use a list if the graph is sparse and a matrix if the graph is dense . For me, it's just a raw definition. I don't see much beyond it. Can you clarify when would it be the natural choice to make? Thanks in advance! Now provide the response and nothing else.
First of all note that sparse means that you have very few edges, and dense means many edges, or almost complete graph.In a complete graph you have $n(n-1)/2$ edges, where $n$ is the number of nodes. Now, when we use matrix representation we allocate $n\times n$ matrix to store node-connectivity information, e.g., $M[i][j] = 1$ if there is edge between nodes $i$ and $j$, otherwise $M[i][j] = 0$. But if we use adjacency list then we have an array of nodes and each node points to its adjacency list containing ONLY its neighboring nodes . Now if a graph is sparse and we use matrix representation then most of the matrix cells remain unused which leads to the waste of memory. Thus we usually don't use matrix representation for sparse graphs. We prefer adjacency list. But if the graph is dense then the number of edges is close to (the complete) $n(n-1)/2$, or to $n^2$ if the graph is directed with self-loops. Then there is no advantage of using adjacency list over matrix. In terms of space complexity Adjacency matrix: $O(n^2)$ Adjacency list: $O(n + m)$ where $n$ is the number nodes, $m$ is the number of edges. When the graph is undirected tree then Adjacency matrix: $O(n^2)$ Adjacency list: $O(n + n)$ is $O(n)$ (better than $n^2$) When the graph is directed, complete, with self-loops then Adjacency matrix: $O(n^2)$ Adjacency list: $O(n + n^2)$ is $O(n^2)$ (no difference) And finally, when you implement using matrix, checking if there is an edge between two nodes takes $O(1)$ times, while with an adjacency list, it may take linear time in $n$.
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/79322', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/68390/']}
jdg_75509
stackexchange
llm_judgeable_groundtruth_similarity
713971
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Evaluate $$\int_0^1 \left(\arctan x \right)^2\,dx$$ The answer should be $${\pi^2\over16} + \frac{\pi\ln(2)}{4} -C$$ where $C$ is Catalan's constant . How do I proceed? I tried doing integration by parts twice and got stuck at $$\int_0^1{\frac{\log\left(\frac1{x}+x\right)}{1+x^2}}\,dx$$ Now provide the response and nothing else.
Integrating by parts twice, $$ \begin{align} \int_{0}^{1} (\arctan x)^{2} \ dx &= x (\arctan x)^{2} \Big|^{1}_{0} - 2 \int_{0}^{1} \frac{x \arctan x}{1+x^{2}} \ dx \\ &= \frac{\pi^{2}}{16} - 2 \int_{0}^{1} \frac{x \arctan x}{1+x^{2}} \ dx \\ &= \frac{\pi^{2}}{16} - \arctan(x) \ln(1+x^{2}) \Big|^{1}_{0} + \int_{0}^{1} \frac{\ln (1+x^{2})}{1+x^{2}} \ dx \\ &= \frac{\pi^{2}}{16} - \frac{\pi}{4} \ln 2 + \int_{0}^{1} \frac{\ln(1+x^{2})}{1+x^{2}} \ dx \end{align}$$ Let $x = \tan t $. Then $$\begin{align}\int_{0}^{1} (\arctan x)^{2} \ dx &=\frac{\pi^{2}}{16} - \frac{\pi}{4} \ln 2 - 2 \int_{0}^{\pi /4} \ln (\cos t) \ dt \\ &= \frac{\pi^{2}}{16} - \frac{\pi}{4} \ln 2 -2 \int_{0}^{\pi /4} \left( \sum_{n=1}^{\infty} \frac{(-1)^{n-1}}{n} \cos (2nt) - \ln 2 \right) \ dt \\ &= \frac{\pi^{2}}{16} - \frac{\pi}{4} \ln 2 - 2 \sum_{n=1}^{\infty} \frac{(-1)^{n-1}}{n}\int_{0}^{\pi /4} \cos (2nt) \ dt + \frac{\pi}{2} \ln 2 \\ &= \frac{\pi^{2}}{16} + \frac{\pi}{4} \ln 2 - \sum_{n=1}^{\infty} \frac{\sin \left(\frac{\pi n}{2} \right)}{n^{2}} \\ &= \frac{\pi^{2}}{16} + \frac{\pi}{4} \ln 2 - \sum_{n=0}^{\infty} \frac{(-1)^{n}}{(2n+1)^{2}} \\ &= \frac{\pi^{2}}{16} + \frac{\pi}{4} \ln 2 - C \end{align}$$ Fourier series of Log sine and Log cos
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/713971', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71408/']}
jdg_75510
stackexchange
llm_judgeable_groundtruth_similarity
2907270
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have a hash in Perl that contains complete and sequential integer mappings (ie, all keys from from 0 to n are mapped to something, no keys outside of this), is there a means of converting this to an Array? I know I could iterate over the key/value pairs and place them into a new array, but something tells me there should be a built-in means of doing this. Now provide the response and nothing else.
If your original data source is a hash: # first find the max key value, if you don't already know it:use List::Util 'max';my $maxkey = max keys %hash;# get all the values, in ordermy @array = @hash{0 .. $maxkey}; Or if your original data source is a hashref: my $maxkey = max keys %$hashref;my @array = @{$hashref}{0 .. $maxkey}; This is easy to test using this example: my %hash;@hash{0 .. 9} = ('a' .. 'j');# insert code from above, and then print the result...use Data::Dumper;print Dumper(\%hash);print Dumper(\@array);$VAR1 = { '6' => 'g', '3' => 'd', '7' => 'h', '9' => 'j', '2' => 'c', '8' => 'i', '1' => 'b', '4' => 'e', '0' => 'a', '5' => 'f' };$VAR1 = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ];
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2907270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357024/']}
jdg_75511
stackexchange
llm_judgeable_groundtruth_similarity
119095
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: We have a lot of programming languages. Every language is parsed and syntax checked before being translated into code so an abstract syntax tree (AST) is built. We have this abstract syntax tree, why don't we store this syntax tree instead of the source code (or next to the source code)? By using an AST instead of the source code. Every programmer in a team can serialize this tree to any language they want (with the appropriate context free grammar) and parse back to AST when they are finished. So this would eliminate the debate about the coding style questions (where to put the { and }, where to put whitespace, indentation, etc.) What are the pros and cons of this approach? Now provide the response and nothing else.
Whitespace and Comments Generally an AST does not include whitespace, line terminators, and comments. Meaningful Formatting You are correct that in most cases this is a positive (eliminates formatting holy wars), there are many cases where the formatting of the original code conveys some meaning, such as in multi-line string literals and "code paragraphs" (separating blocks of statements with an empty line). Code that can't be compiled While many parsers are very resilient to missing syntax, code with errors often results in a very weird syntax tree, which is fine and dandy up until the point where the user reloads the file. Ever make a mistake in your IDE and then all of a sudden the entire file has "squigglies"? Imagine how that would be reloaded in another language. Maybe users don't commit unparsable code, but they certainly do have a need to save locally. No two languages are perfect matches As others have pointed out, there are almost no two languages that have perfect feature parity. The closest I can think is VB and C#, or JavaScript and CoffeeScript, but even then VB has features like XML Literals that don't quite have equivalents in C#, and the JavaScript to CoffeeScript conversion might result in a lot of JavaScript literals. Personal Experience: In a software application I write, we actually need to do this, as the users are expected to enter "plain English" expressions that are converted to JS in the background. We considered only storing the JS version, but found almost no acceptable way to do so that reliably loaded and unloaded, so we ended up always storing both the user text and the JS version, as well as a flag that indicated if the "plain english" version parsed perfectly or not.
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/119095', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/7431/']}
jdg_75512
stackexchange
llm_judgeable_groundtruth_similarity
2245169
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 recall a conversation in which somebody described to me a result that sounded something this: Let $M$ be a closed Riemann manifold satisfying [some hypotheses, most significantly some kind of negative curvature hypothesis]. Then, every class in the fundamental group $\pi_1(M)$ is represented by exactly one unit speed geodesic loop. There are some technical issues with the above statement (e.g. what about basepoints?), but I just wanted to convey the essence of the statement. Now at the time of the conversation, I was very impressed by this result and since then I have had it in the back of my mind to look up this result and at least understand where something like this could come from. I finally got around to this, but ran immediately ran into the issue that I couldn't remember the exact statement of the theorem, nor could I find a result like it by searching for relevant terms. Question: Does somebody know of a result resembling what is stated above? If so, I would very much appreciate a precise statement, and a reference. Possibly there is no result like this, and I misunderstood what was being said in this conversation. Now provide the response and nothing else.
There are two different versions of affirmative answers to your question. I'll state both of them in the language of "constant speed reparameterized geodesics" having a common domain of fixed length, rather than "unit speed geodesics" which would require using domains of varying lengths. First, I'll describe a base-pointed version. Choosing a base point $p \in M$ has the desirable effect that the fundamental group $\pi_1(M,p)$ becomes a well-defined object. Just to be precise, an element of $\pi_1(M,p)$ is thus a path homotopy class of paths $\gamma : [0,1] \to M$ with endpoints at $p$, where "path homotopy" means that the endpoints are stationary under the homotopy. In this context, if $M$ is a complete Riemannian manifold of nonpositive section curvature then each element of $\pi_1(M,p)$ has a unique representative $\gamma : [0,1] \to M$ with endpoints at $p$ which is a constant-speed reparameterization of a geodesic. Second, I'll describe a non base-pointed version, although I will still use base-points to express the result. For each base point $p$, the set of conjugacy classes in $\pi_1(M,p)$ corresponds bijectively to the set of homotopy classes of continuous functions $\sigma : S^1 \to M$ (and the latter set is well-defined independent of the choice of $p$). In this context, if $M$ is a compact Riemannian manifold of negative sectional curvature then every conjugacy class in $\pi_1(M,p)$ is represented by a constant speed reparameterized geodesic map $\sigma : S^1 \to M$ which is unique up to rotational isometries of the domain $S^1$. Note the differences between these two versions: the first one allows noncompactness and allows for nonpositive sectional curvatures; the second one requires compactness and requires negative sectional curvatures. Also, because of the presence of a base point, the first version gives a unique representative on the nose; whereas the second version is a bit weaker, allowing nonuniqueness up to "change of base point" where the base point is allowed to rotate around the curve. I don't have a particular reference to recommend, but any textbook on differential geometry which covers the Riemann curvature tensor and discusses geodesics and their conjugate points should have this result.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2245169', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6608/']}
jdg_75513
stackexchange
llm_judgeable_groundtruth_similarity
30560663
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 new NavigationView in the new Design Support Library works really great. They use " menu-items " to display the options. But how can I display a counter to the right of the menu item? Like in this picture: Or like in the GMail app. Now provide the response and nothing else.
Starting from version 23 of appcompat-v7 NavigationView supports action views, so it is quite easy to implement counter yourself. Create counter layout, i.e. menu_counter.xml : <?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical" android:textAppearance="@style/TextAppearance.AppCompat.Body2" /> Reference it in your drawer menu xml, i.e. menu/drawer.xml : <item ... app:actionLayout="@layout/menu_counter" /> Note that you should use app namespace, don't try to use android . Alternatively you can manually set action view with MenuItem.setActionView() method. Find menu item and set counter: private void setMenuCounter(@IdRes int itemId, int count) { TextView view = (TextView) navigationView.getMenu().findItem(itemId).getActionView(); view.setText(count > 0 ? String.valueOf(count) : null);} Note, that you will need to use MenuItemCompat if you have to support Android 2.x versions.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30560663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/242070/']}
jdg_75514
stackexchange
llm_judgeable_groundtruth_similarity
1334196
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 reading Pham Kim Hung's 'Secrets in Inequalities - Volume 1', and I have to say from the first few examples, that it is not a very good book. Definitely not beginner friendly. Anyway, it is proven by the author, that for four variables $a, b, c$, and $d$, each being a non-negative real number, the following inequality holds:$$\frac{a}{b+c} + \frac{b}{c+d} + \frac{c}{d+a} + \frac{d}{a+b}\ge 2$$ I have no idea how the author proves this. It comes under the very first section, AM-GM. I get the original Nesbitt's inequality in 3 variables that the author proves (which is also cryptic, but I was able to decipher it). My effort: I understood how the author defines the variables $M, N$ and $S$.$$S = \frac{a}{b+c} + \frac{b}{c+d} + \frac{c}{d+a} + \frac{d}{a+b}$$$$M = \frac{b}{b+c} + \frac{c}{c+d} + \frac{d}{d+a} + \frac{a}{a+b}$$$$N = \frac{c}{b+c} + \frac{d}{c+d} + \frac{a}{d+a} + \frac{b}{a+b}$$ $M + N = 4$, pretty straightforward. The numerators and denominators cross out to give four 1s. Then the author, without any expansion/explanation, says $$M + S = \frac{a+b}{b+c} + \frac{b+c}{c+d} + \frac{c+d}{d+a} + \frac{d+a}{a+b}\ge 4$$ Which is also true, since the AM-GM inequality says $$\frac{M+S}{4}\ge \left(\frac{a+b}{b+c}\cdot\frac{b+c}{c+d}\cdot\frac{c+d}{d+a}\cdot\frac{d+a}{a+b}\right)^{1/4}$$ The RHS above evaluates to $1^{1/4}$ since all the numerators and denominators cancel out. The next part is the crux of my question. The author claims, $$N + S =\frac{a+c}{b+c}+\frac{a+c}{a+d}+\frac{b+d}{c+d} + \frac{b+d}{a+b}\ge\frac{4(a+c)}{a+b+c+d}+\frac{4(b+d)}{a+b+c+d}$$ This is completely bizarre for me! Where did the author manage to get a sum of $(a+b+c+d)$?? As a side note, I'd definitely not recommend this book for any beginner in basic algebraic inequalities (even though the title of the book promotes that it's a treatment of basic inequalities). The author takes certain 'leaps of faith', just assuming that the student reading the book would be able to follow. Now provide the response and nothing else.
Since we have $(x-y)^2\ge 0$, we have, for $x\gt 0,y\gt 0$, $$\begin{align}(x-y)^2\ge 0&\Rightarrow x^2+y^2+2xy\ge 4xy\\&\Rightarrow y(x+y)+x(x+y)\ge 4xy\\&\Rightarrow \frac{1}{x}+\frac 1y\ge\frac{4}{x+y}\end{align}$$Now set $x=b+c,y=a+d$ and $x=c+d,y=a+b$ to get$$\frac{1}{b+c}+\frac{1}{a+d}\ge\frac{4}{b+c+a+d}$$and$$\frac{1}{c+d}+\frac{1}{a+b}\ge\frac{4}{c+d+a+b}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1334196', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/210846/']}
jdg_75515
stackexchange
llm_judgeable_groundtruth_similarity
2647352
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 $\lim\limits_{t \to \infty} e^{-t}\sum_{n=0}^{\infty}a_n\frac{t^n}{n!}=0$ if the sequence $\{a_n\}$ converges to limit 0. So, If I could show that $\lim\limits_{t \to \infty} \sum_{n=0}^{\infty}a_n\frac{t^n}{n!}$ is finite then I am done as $\lim\limits_{t \to \infty} e^{-t}=0$. Now, $e^t=\sum_{n=0}^{\infty}\frac{t^n}{n!}$ converges by ratio test. How to show $\lim\limits_{t \to \infty} \sum_{n=0}^{\infty}a_n\frac{t^n}{n!}$ is convergent? Now provide the response and nothing else.
It does not make sense to quotient a group by another abstract group. What makes sense is to quotient by a subgroup . In other words, the writing $(\mathbb{Z}\oplus \mathbb{Z})/\mathbb{Z}$ makes no sense if you don't precise how you embed $\mathbb{Z}$ into $\mathbb{Z}\oplus \mathbb{Z}$. Which subgroup you are looking at. If your embedding is $n\mapsto (n,0)$ then the answer will be $\mathbb{Z}$. If your embedding is $n\mapsto (2n,0)$ then the answer will be $\mathbb{Z}/2\mathbb{Z}\oplus \mathbb{Z}$, etc.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2647352', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/512393/']}
jdg_75516
stackexchange
llm_judgeable_groundtruth_similarity
20059943
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: describe('my homepage', function() { var ptor = protractor.getInstance(); beforeEach(function(){ // ptor.ignoreSynchronization = true; ptor.get('http://localhost/myApp/home.html'); // ptor.sleep(5000); }) describe('login', function(){ var email = element.all(protractor.By.id('email')) , pass = ptor.findElement(protractor.By.id('password')) , loginBtn = ptor.findElement(protractor.By.css('#login button')) ; it('should input and login', function(){ // email.then(function(obj){ // console.log('email', obj) // }) email.sendKeys('[email protected]'); pass.sendKeys('shakalakabam'); loginBtn.click(); }) })}); the above code returns Error: Error while waiting for Protractor to sync with the page: {} and I have no idea why this is, ptor load the page correctly, it seem to be the selection of the elements that fails. TO SSHMSH: Thanks, your almost right, and gave me the right philosophy, so the key is to ptor.sleep(3000) to have each page wait til ptor is in sync with the project. Now provide the response and nothing else.
I got the same error message (Angular 1.2.13). My tests were kicked off too early and Protractor didn't seem to wait for Angular to load. It appeared that I had misconfigured the protractor config file. When the ng-app directive is not defined on the BODY-element, but on a descendant, you have to adjust the rootElement property in your protractor config file to the selector that defines your angular root element, for example: // protractor-conf.jsrootElement: '.my-app', when your HTML is: <div ng-app="myApp" class="my-app">
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20059943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2167582/']}
jdg_75517
stackexchange
llm_judgeable_groundtruth_similarity
46823
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: Every reference I find says that they are "essentially" the same, which we all know really means that they are not the same, but different only by a some small amount that someone else other than me decides is negligible. They also like to say that UT1 and UTC are the same, but if you look into it you find that they differ by as much as 0.9 seconds. This is, admittedly, insignificant to me. But the practicality of it is not my concern here. The technical reality of it is. I want specifics and exactness where applicable here. Now provide the response and nothing else.
UT1 is a specific "flavor" of Universal Time, which is a measure of Earth's rotation relative to the mean sun, a fictitious "prime mover" upon which all our clocks are based. UT1 is related to sidereal time (Earth's rotation relative to the fixed background stars) by a rather long mathematical expression usually expressed as a polynomial function of mean solar time. Earth's rotation is not uniform though; it varies. UTC (Coordinated Universal Time) is a specific "flavor" of Universal Time intended to smooth out these variations by staying within 0.9 s of UT1. The difference between the two is called $\Delta UT1$ and is adjusted as necessary, but can only be adjusted after observation. Larger adjustments come in the form of leap seconds. The current approximate value of $\Delta UT$ is called $DUT1$ and is encoded in the standard time signals broadcast by stations such as WWV (in America) and CHU (in Canada). Listen for doubling of pips at the beginning of each minute. UT0 is an observational approximation to UT1 based on meridian observations of standard stars. UT0 must be corrected for polar motion, which varies from observatory to observatory. Both UT1 and UTC are generically referred to as Universal Time and the distinction between them is important only if the that maximum discrepancy of 0.9 s is important for your application. There is another "flavor" of Universal Time called UT1R, which is intended to account for tidal variations in Earth's rotation. There is another "flavor" of Universal Time called UT2, which is intended to account for seasonal variations in Earth's rotation. UT2 isn't used any more. GMT, Greenwich Mean Time, is a sometimes deprecated historic term equivalent to UT, but is no longer used in astronomical applications. It used still used in many civil applications though (and remains the legal time standard (outside the period of daylight-saving summer time) in the UK). By far your best reference on this topic is the latest edition of The Explanatory Supplement to the Astronomical Almanac, edited by Sean Urban and Kenneth Seidelmann. The third edition was just published in November by University Science Books. My own book, Fundamental Ephemeris Computations (Willmann-Bell, 2000) also discusses this topic and includes computer code. Be aware that since FEC was published, certain astronomical terminology has changed and now the term "Earth rotation angle" is now used to mean roughly what sidereal time previously meant. The new terminology is reflected in the new Explanatory Supplement referenced above.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/46823', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/16822/']}
jdg_75518
stackexchange
llm_judgeable_groundtruth_similarity
16659326
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 wondered for a couple years now what people think of doing inheritance with a module-pattern-esque constructor pattern and WITHOUT normal prototypal inheritance. Why do programmers not use a module pattern for non-singleton js classes? For me the advantages are: Very clear public and private scope (easy to understand the code and the api) No needing to track the 'this' pointer via $.proxy(fn, this) in callbacks No more var that = this, etc. with event handlers, etc. Whenever I see a 'this', I know it is context that is being passed into a callback, it is NOT something I am tracking to know my object instance. Disadvantages: Small perf degradation Risk possible "wag of the finger" from Doug Crockford? Consider this (just run in any js console) var Animal = function () { var publicApi = { Name: 'Generic', IsAnimal: true, AnimalHello: animalHello, GetHelloCount:getHelloCount }; var helloCount = 0; function animalHello() { helloCount++; console.log(publicApi.Name + ' says hello (animalHello)'); } function getHelloCount(callback) { callback.call(helloCount); } return publicApi;};var Sheep = function (name) { var publicApi = { Name: name || 'Woolie', IsSheep: true, SheepHello: sheepHello }; function sheepHello() { publicApi.AnimalHello(); publicApi.GetHelloCount(function() { console.log('i (' + publicApi.Name + ') have said hello ' + this + ' times (sheepHello anon callback)'); }); } publicApi = $.extend(new Animal(), publicApi); return publicApi;};var sheepie = new Sheep('Sheepie');var lambie = new Sheep('Lambie');sheepie.AnimalHello();sheepie.SheepHello();lambie.SheepHello(); My question is what are the drawbacks to this approach that I am not seeing? Is this a good approach? Thanks! [update] Thanks for the great responses. Wish I could give everyone the bounty. It was what I was looking for. Basically what I thought. I would never use module pattern to construct more than a few instances of something. Usually only a couple. The reason I think it has its advantages is whatever small perf degradation you see is recaptured in the simplicity of the coding experience. We have a LOT of code to write these days. We also have to reuse other peoples' code and personally I appreciate when someone has taken the time to create a nice elegant pattern rather than dogmatically adhering to prototypal inheritance when it makes sense. Now provide the response and nothing else.
I think it boils down to the issue of performance . You mentioned that there is small performance degradation, but this really depends on scale of the application(2 sheep vs 1000 sheep). Prototypal inheritance should not be ignored and we can create an effective module pattern using a mix of functional and prototypal inheritance . As mentioned in the post JS - Why use Prototype? ,one of the beauties of prototype is that you only need to initialize the prototypal members only once,whereas members within the constructor are created for each instance . In fact, you can access prototype directly without creating a new object. Array.prototype.reverse.call([1,2,3,4]);//=> [4,3,2,1]function add() { //convert arguments into array var arr = Array.prototype.slice.call(arguments), sum = 0; for(var i = 0; i < arr.length; i++) { sum += arr[i]; } return sum;}add(1,2,3,4,5);//=> 15 In your functions, there is extra overhead to create a completely newAnimal and sheep each time a constructor is invoked. Some members such as Animal.name are created with each instance, but we knowthat Animal.name is static so it would be better to instantiate it once. Since your code implies that Animal.nameshould be the same across all animals, it is easy to update Animal.name for all instance simply by updating Animal.prototype.name if we moved it to the prototype. Consider this var animals = [];for(var i = 0; i < 1000; i++) { animals.push(new Animal());} Functional inheritance/Module Pattern function Animal() { return { name : 'Generic', updateName : function(name) { this.name = name; } }}//update all animal names which should be the samefor(var i = 0;i < animals.length; i++) { animals[i].updateName('NewName'); //1000 invocations !} vs. Prototype Animal.prototype = {name: 'Generic',updateName : function(name) { this.name = name};//update all animal names which should be the sameAnimal.prototype.updateName('NewName'); //executed only once :) As shown above with your currently module pattern we lose effeciency in updating properties that should be in common to all members. If you are concered about visibility , I would use the same modular method you are currently using to encapsulate private members but also use priviledged members for accessing these members should they need to be reached. Priviledged members are public members that provide an interface to access private variables. Finally add common members to the prototype. Of course going this route, you will need to keep track of this. It is true that in your implementation there is No needing to track the 'this' pointer via $.proxy(fn, this) in callbacks No more var that = this, etc. with event handlers, etc. Whenever I see a 'this', I know it is context that is being passed into a callback, it is NOT something I am tracking to know my object instance. , but you are are creating a very large object each time which will consume more memory in comparison to using some prototypal inheritance. Event Delegation as Analogy An analogy to gaining performance by using prototypes is improved performance by using event delegation when manipulating the DOM. Event Delegation in Javascript Lets say you have a large grocery list.Yum. <ul ="grocery-list"> <li>Broccoli</li> <li>Milk</li> <li>Cheese</li> <li>Oreos</li> <li>Carrots</li> <li>Beef</li> <li>Chicken</li> <li>Ice Cream</li> <li>Pizza</li> <li>Apple Pie</li></ul> Let's say that you want to log the item you click on.One implementation would be to attach an event handler to every item(bad) , but if our list is very long there will be a lot of events to manage. var list = document.getElementById('grocery-list'), groceries = list.getElementsByTagName('LI');//bad esp. when there are too many list elementsfor(var i = 0; i < groceries.length; i++) { groceries[i].onclick = function() { console.log(this.innerHTML); }} Another implementation would be to attach one event handler to the parent(good) and have that one parent handle all the clicks.As you can see this is similar to using a prototype for common functionality and significantly improves performance //one event handler to manage child elements list.onclick = function(e) { var target = e.target || e.srcElement; if(target.tagName = 'LI') { console.log(target.innerHTML); }} Rewrite using Combination of Functional/Prototypal Inheritance I think the combination of functional/prototypal inheritance can be written in an easy understandable manner.I have rewritten your code using the techniques described above. var Animal = function () { var helloCount = 0; var self = this; //priviledge methods this.AnimalHello = function() { helloCount++; console.log(self.Name + ' says hello (animalHello)'); }; this.GetHelloCount = function (callback) { callback.call(null, helloCount); }};Animal.prototype = { Name: 'Generic', IsAnimal: true};var Sheep = function (name) { var sheep = new Animal(); //use parasitic inheritance to extend sheep //http://www.crockford.com/javascript/inheritance.html sheep.Name = name || 'Woolie' sheep.SheepHello = function() { this.AnimalHello(); var self = this; this.GetHelloCount(function(count) { console.log('i (' + self.Name + ') have said hello ' + count + ' times (sheepHello anon callback)'); }); } return sheep;};Sheep.prototype = new Animal();Sheep.prototype.isSheep = true;var sheepie = new Sheep('Sheepie');var lambie = new Sheep('Lambie');sheepie.AnimalHello();sheepie.SheepHello();lambie.SheepHello(); Conclusion The takeaway is to use both prototypal and functional inheritance to their advantages both to tackle performance and visibility issues .Lastly, if you are working on a small JavaScript applications and these performance issues are not a concern , then your method would be viable approach.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16659326', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1002179/']}
jdg_75519
stackexchange
llm_judgeable_groundtruth_similarity
319925
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 can't figure this out, please help: Two police officers are carrying $n$ gold coins in two bins, in a secured vehicle. The physical characteristics of the the gold coins are the same, but while the coins in the first bin are all the same, the ones in the second bin are different from the ones in the first bin. At one corner, the driver suddenly brakes and the coins are all mixed up. They have a device that can be applied to two coins and tells whether they are different or not. It is known in advance that most of the coins (more then 50% ) are from the first bin. Find the algorithm that the two officers should apply in order to put the coins back into the bins. How many comparisons are necessary, in the worst case, to find at least one coin from the first bin? (Beware: it is possible that two coins are identical, but do not belong to the first bin.) I don't understand - so the first bin has same coins and coins in the second bin are different than the first bin, but different to each other too? Now provide the response and nothing else.
Your work is fine. We just need to algebraically "manipulate" the result a bit to get the answer to match the given equality (as stated in your title): Starting with your second-to-last line, we find a common denominator, $(n+1)^2$, and then factor out the common factor, which is the term you list in your last line, but is a factor (which multiplies over a sum/difference). So we have the common factor $\;\dfrac{x^{n+1}}{(n+1)^2}\times\Big[\cdots\Big]$: $$\begin{align}\int x^n\ln{x}\ dx& = \frac{\ln{x}\cdot x^{n+1}}{n+1}-\frac{1}{n+1}\left[\frac{x^{n+1}}{n+1}\right]+C \\ \\& = \frac{(n+1)\ln x\cdot x^{n+1}}{(n+1)^2} - \frac{x^{n+1}}{(n+ 1)^2} + C \\ \\& = \frac{x^{n+1}}{(n+1)^2}\Big[\left((n+1)\cdot \ln x\right) - 1\Big] + C \\ \\ & = \frac{x^{n+1}}{(n+1)^2}\Big[-1 + (n+1)\cdot \ln x\Big] + C \\ \\ \end{align}$$ ...which is now in the desired form.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/319925', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64848/']}
jdg_75520
stackexchange
llm_judgeable_groundtruth_similarity
2286964
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There are a few folders where I house my django site that I want to be rendered as it would on any other non-django site. Namely, forum (vbulletin) and cpanel. I currently run the site with fastcgi. My .htaccess looks like this: AddHandler application/x-httpd-php5 .htmAddHandler application/x-httpd-php5 .htmlAddHandler fastcgi-script .fcgiOptions +FollowSymLinksRewriteEngine OnRewriteBase /AddHandler application/x-httpd-php5 .htmRewriteCond %{REQUEST_URI} !(mysite.fcgi)RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L] What are lines I can add so www.mysite.com/forum can not be picked up by django url and be rendered as it would do normally. Thanks. Now provide the response and nothing else.
There are many different lists/collection types in F#. F# list type. As Chris said, you cannot initialize a recursive value of this type, because the type is not lazy and not mutable (Immutability means that you have to create it at once and the fact that it's not lazy means that you can't use F# recursive values using let rec ). As ssp said, you could use Reflection to hack it, but that's probably a case that we don't want to discuss. Another type is seq (which is actually IEnumerable ) or the LazyList type from PowerPack. These are lazy, so you can use let rec to create a cyclic value. However, (as far as I know) none of the functions working with them take cyclic lists into account - if you create a cyclic list, it simply means that you're creating an infinite list, so the result of (e.g.) map will be a potentially infinite list. Here is an example for LazyList type: #r "FSharp.PowerPack.dll" // Valid use of value recursion let rec ones = LazyList.consDelayed 1 (fun () -> ones) Seq.take 5 l // Gives [1; 1; 1; 1; 1] The question is what data types can you define yourself. Chris shows a mutable list and if you write operations that modify it, they will affect the entire list (if you interpret it as an infinite data structure). You can also define a lazy (potentionally cyclic) data type and implement operations that handle cycles, so when you create a cyclic list and project it into another list, it will create cyclic list as a result (and not a potentionally infinite data structure). The type declaration may look like this (I'm using object type, so that we can use reference equality when checking for cycles): type CyclicListValue<'a> = Nil | Cons of 'a * Lazy<CyclicList<'a>>and CyclicList<'a>(value:CyclicListValue<'a>) = member x.Value = value The following map function handles cycles - if you give it a cyclic list, it will return a newly created list with the same cyclic structure: let map f (cl:CyclicList<_>) = // 'start' is the first element of the list (used for cycle checking) // 'l' is the list we're processing // 'lazyRes' is a function that returns the first cell of the resulting list // (which is not available on the first call, but can be accessed // later, because the list is constructed lazily) let rec mapAux start (l:CyclicList<_>) lazyRes = match l.Value with | Nil -> new CyclicList<_>(Nil) | Cons(v, rest) when rest.Value = start -> lazyRes() | Cons(v, rest) -> let value = Cons(f v, lazy mapAux start rest.Value lazyRes) new CyclicList<_>(value) let rec res = mapAux cl cl (fun () -> res) res
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2286964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264459/']}
jdg_75521
stackexchange
llm_judgeable_groundtruth_similarity
12036221
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 play a file through media player and I want to give options like speaker on/off, play though headset, bluetooth ,etc.I tried the below code which works well for android 2.2 but I want something that can also work for 2.2 and 4.0 both.Can you help me to programmatically turn the speaker on/off and playing via headphones? AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); if(isOn){ audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setMode(AudioManager.MODE_NORMAL); }else{ //Seems that this back and forth somehow resets the audio channel audioManager.setMode(AudioManager.MODE_NORMAL); audioManager.setMode(AudioManager.MODE_IN_CALL); } audioManager.setSpeakerphoneOn(isOn); P.S: I have given this permission in manifest: android.permission.MODIFY_AUDIO_SETTINGS Now provide the response and nothing else.
Something like this might work on some devices (I've only tested in on an XPeria P): final static int FOR_MEDIA = 1;final static int FORCE_NONE = 0;final static int FORCE_SPEAKER = 1;Class audioSystemClass = Class.forName("android.media.AudioSystem");Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);// To get back to the default behaviour, use the combination FOR_MEDIA,FORCE_NONE. The combination FOR_MEDIA, FORCE_SPEAKER is typically only used internally to route the FM-radio audio to the loudspeaker (since the FM-radio requires you to have a wired headset / headphone plugged in to act as an antenna). Devices that don't have FM-radio functionality (or uses an alternative implementation) might ignore this combination of parameters, so this method would not work on such a device.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12036221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1300813/']}
jdg_75522
stackexchange
llm_judgeable_groundtruth_similarity
10161637
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on a learning project related to Android. I am trying to get current year & month by using below code but it not works for me. GregorianCalendar gc = new GregorianCalendar();gc.YEAR // returning 1 gc.MONTH // returning 2Calendar c = Calendar.getInstance();c.YEAR // returning 1 c.MONTH // returning 2 Can someone help me? Am i doing something wrong? please forgive me i am new to java development. thanks. Now provide the response and nothing else.
Just to give a bit more background: Both new GregorianCalendar() and Calendar.getInstance() will correctly give a calendar initialized at the current date and time. MONTH and YEAR are constants within the Calendar class. You should not use them "via" a reference which makes it look like they're part of the state of an object. It's an unfortunate part of the design of the Calendar class that to access the values of different fields, you need to call get with a field number, specified as one of those constants, as shown in other answers: Calendar c = Calendar.getInstance();int year = c.get(Calendar.YEAR);int month = c.get(Calendar.MONTH); Note that the month numbers are 0-based, so at the time of this writing (in April) the month number will be 3. It's an unfortunate part of the design of the Java language that you can reference static members (such as constants) via expressions of that type, rather than only through the type name. My recommendations: If your IDE allows it (as Eclipse does), make expressions such as c.YEAR give a compile-time error - you'll end up with much clearer code if you always use Calendar.YEAR . Where possible, use Joda Time - a much better date/time library for Java. Admittedly on Android you may be a bit space-constrained, but if your app does a lot of date/time manipulation, it would save you a lot of headaches.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10161637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/265167/']}
jdg_75523
stackexchange
llm_judgeable_groundtruth_similarity
9720927
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 have a Class.prototype based classes in my project, where I don't have inline functions. Considering this example, it's impossible to remove the eventListener on myVideo video object, that I have in my class. This is a theoretical example, not an actual production code I have. var myClass = function () { this.initialize();}MyClass.prototype.myVideo = null;MyClass.prototype.initialize = function () { this.myVideo = document.getElementById("myVideo"); this.myVideo.addEventListener("ended", this.onMyVideoEnded, false); this.myVideo.play();}MyClass.prototype.onMyVideoEnded = function (event) { // cannot remove event listener here // this.myVideo.removeEventListener("ended", this.onMyVideoEnded, false);} Is there a way to leave the handler as a Class.prototype function and add and remove listeners. I need to instantiate and create a lot of objects of this sort, and am afraid of memory leaks, and object persistancy (all of previously created objects receive the "ended" event) when leaving anonymous functions not removed as event handlers. Or should I just consider a different approach (inline functions, inside the initialize function, as event handlers). These really impact readability and consistency, so I want to avoid them on all costs. Now provide the response and nothing else.
You need to bind your function onMyVideoEnded with context where you attached it: For example: this.myVideoEndedHandler = this.onMyVideoEnded.bind(this);this.myVideo.addEventListener("ended", this.myVideoEndedHandler, false); To remove listener also use stored handler: this.myVideo.removeEventListener("ended", this.myVideoEndedHandler, false); This is because when event triggers your function onMyVideoEnded gets wrong this argument.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9720927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1009933/']}
jdg_75524
stackexchange
llm_judgeable_groundtruth_similarity
479218
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an sqlite database full of huge number of URLs and it's taking huge amount of diskspace, and accessing it causes many disk seeks and is slow. Average URL path length is 97 bytes (host names repeat a lot so I moved them to a foreign-keyed table). Is there any good way of compressing them? Most compression algorithms work well with big documents, not "documents" of less that 100 bytes on average, but even 20% reduction would be very useful. Any compression algorithms that would work? Doesn't have to be anything standard. Now provide the response and nothing else.
Use the compress algorithm but use a shared dictionary. I've done something like this before where I used the LZC/LZW algorithm, as used by the Unix compress command. The trick to get good compression with short strings is to use a dictionary made up of a standard sample of the URLs you are compressing. You should easily get 20%. Edit: LZC is a variant of LZW. You only require LZW as you only need a static dictionary. LZC adds support for resetting the dictionary/table when it gets full.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/479218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52751/']}
jdg_75525
stackexchange
llm_judgeable_groundtruth_similarity
24725059
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am not sure how to handle this situation as I am very new to iOS development and Swift. I am performing data fetching like so: func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!){ loadShows() completionHandler(UIBackgroundFetchResult.NewData) println("Background Fetch Complete")} My loadShows() function parses a bunch of data it gets from a website loaded into a UIWebView. The problem is that I have a timer that waits for 10 seconds or so in the loadShows function. This allows for the javascript in the page to fully load before I start parsing the data. My problem is that the completion handler completes before my loadShows() does. What I would like to do is add a bool for "isCompletedParsingShows" and make the completionHandler line wait to complete until that bool is true. What is the best way to handle this? Now provide the response and nothing else.
you have to pass your async function the handler to call later on: func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) { loadShows(completionHandler)}func loadShows(completionHandler: ((UIBackgroundFetchResult) -> Void)!) { //.... //DO IT //.... completionHandler(UIBackgroundFetchResult.NewData) println("Background Fetch Complete")} OR (cleaner way IMHO) add an intermediate completionHandler func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) { loadShows() { completionHandler(UIBackgroundFetchResult.NewData) println("Background Fetch Complete") }}func loadShows(completionHandler: (() -> Void)!) { //.... //DO IT //.... completionHandler()}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24725059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3792045/']}
jdg_75526
stackexchange
llm_judgeable_groundtruth_similarity
26752030
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Now that the performance difference between $broadcast and $emit has been eliminated, is there any reason to prefer $scope.$emit to $rootScope.$broadcast ? They are different, yes. $emit is restricted to the scope hierarchy (upwards) - this may be good, if it fits your design, but it seems to me a rather arbitrary restriction. $rootScope.$broadcast works across all that choose to listen to the event, which is a more sensible restriction in my mind. Am I missing something? EDIT: To clarify in response to an answer, the direction of the dispatch is not the issue I'm after. $scope.$emit dispatches the event upwards, and $scope.$broadcast - downwards. But why not always use $rootScope.$broadcast to reach all the intended listeners? Now provide the response and nothing else.
tl;dr (this tl;dr is from @sp00m 's answer below) $emit dispatches an event upwards ... $broadcast dispatches an event downwards Detailed explanation $rootScope.$emit only lets other $rootScope listeners catch it. This is good when you don't want every $scope to get it. Mostly a high level communication. Think of it as adults talking to each other in a room so the kids can't hear them. $rootScope.$broadcast is a method that lets pretty much everything hear it. This would be the equivalent of parents yelling that dinner is ready so everyone in the house hears it. $scope.$emit is when you want that $scope and all its parents and $rootScope to hear the event. This is a child whining to their parents at home (but not at a grocery store where other kids can hear). $scope.$broadcast is for the $scope itself and its children. This is a child whispering to its stuffed animals so their parents can't hear.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/26752030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/968155/']}
jdg_75527
stackexchange
llm_judgeable_groundtruth_similarity
458954
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a file of genomic data with tag counts, I want to know how many are represented once: $ grep "^1" file |wc -l includes all lines beginning with 1, so it includes tags represented 10 times, 11, times, 100 times, 1245 times, etc. How do I do this? Current format79 TGCAG.....1 TGCAG.....1257 TGCAG.....1 TGCAG...... I only want the lines that are: 1 TGCAG..... So it cannot include the lines beginning with 1257. NOTE: The file above is tab delimited. Now provide the response and nothing else.
The question in the body Select lines that start with a 1 and are followed by an space grep -c '^1\s' filegrep -c '^1[[:space:]]' file That will also give the count of lines (without needing the call to wc) The question in the title A 1 not followed by another number (or nothing): grep -cE '^1([^0-9]|$)' file But both solutions above have some interesting issues, keep reading. In the body of the question the user claim that the file is "tab delimited". Delimiter tab A line starting with a 1 followed by a tab (an actual tab in the command). This fails if the delimiter is an space (or any other, or none): grep '^1 ' file space A line starting with a 1 followed by a space (an actual space in the command). This fails if the delimiter is any other or none.: grep '^1 ' file tab or space grep '^1( | )' filegrep '^1[[:blank:]]' file whitespace A more flexible option is to include several space (horizontal and vertical) characters. The [:space:] character class set is composed of (space), \t (horizontal tab), \r (carriage return), \n (newline), \v (vertical tab) and \f (form feed). But grep can not match a newline (it is an internal limitation that could only be avoided with the -z option). It is possible to use it as a description on the delimiter. It is also possible, and shorter, to use the GNU available shorthand of \s : grep -c '^1[[:space:]]` filegrep -c '^1\s' file But this option will fail if the delimiter is something like a colon : or any other punctuation character (or any letter). Boundary Or, we can use the transition from a digit to a "not a digit" boundary, well, actually "a character not in [_[:alnum:]] ( _a-zA-Z0-9 )": grep -c '^1\b' file # portable but not POSIX.grep -c '^1\>' file # portable but not POSIX.grep -wc '^1' file # portable but not POSIX.grep -c '^1\W' file # portable but not POSIX (not match only a `1`) (not underscore in BSD). This will accept as valid lines that start with a 1 and are followed by some punctuation character.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/458954', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/293255/']}
jdg_75528
stackexchange
llm_judgeable_groundtruth_similarity
85597
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Hello i want to switch electric door lock (12V, 170mA) with esp32(3.3V). If is it possible I want use tranzistor. I tried to use IRF520, but it only worked with 5V. My sugestion is use 2 tranzistors one would switch 5V to IRF520 which would switch 12V. Can someone pro provide me some schematic, how to solve it? Thanks. Now provide the response and nothing else.
BC549 provides strong pull-down for IRFR5305, which is provides up to +12V at 16A with less than 0.09 Ohm channel resistance. This circuit works well with ESP8266, I use it in some of my devices. Don't forget about placing the flyback diode ( EEV Blog , Wiki ) in reverse polarity, parallel to the magnet. Place it as close as possible to the magnet!
{}
{'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/85597', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/79782/']}
jdg_75529
stackexchange
llm_judgeable_groundtruth_similarity
11270509
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 writing a shell script to put data into hadoop as soon as they are generated. I can ssh to my master node, copy the files to a folder over there and then put them into hadoop. I am looking for a shell command to get rid of copying the file to the local disk on master node. to better explain what I need, here below you can find what I have so far: 1) copy the file to the master node's local disk: scp test.txt username@masternode:/folderName/ I have already setup SSH connection using keys. So no password is needed to do this. 2) I can use ssh to remotely execute the hadoop put command: ssh username@masternode "hadoop dfs -put /folderName/test.txt hadoopFolderName/" what I am looking for is how to pipe/combine these two steps into one and skip the local copy of the file on masterNode's local disk. thanks In other words, I want to pipe several command in a way that I can Now provide the response and nothing else.
Try this (untested): cat test.txt | ssh username@masternode "hadoop dfs -put - hadoopFoldername/test.txt" I've used similar tricks to copy directories around: tar cf - . | ssh remote "(cd /destination && tar xvf -)" This sends the output of local- tar into the input of remote- tar .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11270509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/793677/']}
jdg_75530
stackexchange
llm_judgeable_groundtruth_similarity
411875
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is an exam question I encountered while studying for my exam for our topology course: Give two continuous maps from $S^1$ to $S^1$ which are not homotopic. (Of course, provide a proof as well.) The only continuous maps from $S^1$ to $S^1$ I can think of are rotations, and I thought rotations on a circle can be continuously morphed into one another. Now provide the response and nothing else.
The identity is not homotopic to a constant map; otherwise, $S^1$ would be contractible, which would imply $\pi_1(S^1)=0$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/411875', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/53283/']}
jdg_75531
stackexchange
llm_judgeable_groundtruth_similarity
291867
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I edited the question GADM-Maps cross-country comparision graphics because I found it when doing research for another question , and noticed the URLs mentioned did not work anymore. To fix it, I found the updated URLs and replaced them in the code. I did one small change to the code because I was already there anyway. The Edit Suggestion was rejected, and I assume it's because the new URL is from a completely different domain and the reviewers probably thought it was spam or trolling, but that's just how it is now at the GADM website . Or is there something wrong with updating this kind of information? The way it is now, the question isn't even reproducible (which is one of the things that led me to it). It's also worth mentioning that the accepted answer has the same outdated URL, which IMHO should be corrected. Edit I just thought a little bit more about this, and maybe the reviewers rejected the edit because I replaced one function of the code ( paste(..., sep=" ") ) with a wrapper for it ( paste0(...) )? I understand it's not a good a idea to change question's codes, even if they don't change the overall result or context. Edit 2 Thanks to the suggestions and insight provided at the answers here, I resubmitted the suggestion without the code change and with a better explanation of the URL correction, which was accepted. Now to the Answer, I suppose. Now provide the response and nothing else.
Normally code changes of that magnitude are frowned upon and I wouldn't be surprised if people automatically reached for the Reject button. Because you can only suggest edits, when fixing links make it very clear in your comment that you are fixing link rot. I would also think twice about fixing links within a code section - ask yourself: are the actual links critical, or are they effectively decoration or noise? if the links are necessary, were they the cause of the bug? If the bug was caused by the nature of the URLs or the resource they point to then changing them makes the question invalid. But if this is the case then you could also argue that a fundamental change in the target resources (like what has happened due to the website being changed) now makes the question a candidate for closure as it is off topic and no longer reproducible. If the target resource has simply changed location but not changed in any other way then your fix would have been correct (assuming that the paste0 change was also correct).
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/291867', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/724200/']}
jdg_75532
stackexchange
llm_judgeable_groundtruth_similarity
47121961
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In C++, can atomics suffer spurious stores? For example, suppose that m and n are atomics and that m = 5 initially. In thread 1, m += 2; In thread 2, n = m; Result: the final value of n should be either 5 or 7, right? But could it spuriously be 6? Could it spuriously be 4 or 8, or even something else? In other words, does the C++ memory model forbid thread 1 from behaving as though it did this? ++m; ++m; Or, more weirdly, as though it did this? tmp = m; m = 4; tmp += 2; m = tmp; Reference: H.-J. Boehm & S. V. Adve, 2008, Figure 1. (If you follow the link, then, in the paper's section 1, see the first bulleted item: "The informal specifications provided by ...") THE QUESTION IN ALTERNATE FORM One answer (appreciated) shows that the question above can be misunderstood. If helpful, then here is the question in alternate form. Suppose that the programmer tried to tell thread 1 to skip the operation: bool a = false; if (a) m += 2; Does the C++ memory model forbid thread 1 from behaving, at run time, as though it did this? m += 2; // speculatively alter m m -= 2; // oops, should not have altered! reverse the alteration I ask because Boehm and Adve, earlier linked, seem to explain that a multithreaded execution can speculatively alter a variable, but then later change the variable back to its original value when the speculative alteration turns out to have been unnecessary. COMPILABLE SAMPLE CODE Here is some code you can actually compile, if you wish. #include <iostream>#include <atomic>#include <thread>// For the orignial question, do_alter = true.// For the question in alternate form, do_alter = false.constexpr bool do_alter = true;void f1(std::atomic_int *const p, const bool do_alter_){ if (do_alter_) p->fetch_add(2, std::memory_order_relaxed);}void f2(const std::atomic_int *const p, std::atomic_int *const q){ q->store( p->load(std::memory_order_relaxed), std::memory_order_relaxed );}int main(){ std::atomic_int m(5); std::atomic_int n(0); std::thread t1(f1, &m, do_alter); std::thread t2(f2, &m, &n); t2.join(); t1.join(); std::cout << n << "\n"; return 0;} This code always prints 5 or 7 when I run it. (In fact, as far as I can tell, it always prints 7 when I run it.) However, I see nothing in the semantics that would prevent it from printing 6 , 4 or 8 . The excellent Cppreference.com states, "Atomic objects are free of data races," which is nice, but in such a context as this, what does it mean? Undoubtedly, all this means that I do not understand the semantics very well. Any illumination you can shed on the question would be appreciated. ANSWERS @Christophe, @ZalmanStern and @BenVoigt each illuminate the question with skill. Their answers cooperate rather than compete. In my opinion, readers should heed all three answers: @Christophe first; @ZalmanStern second; and @BenVoigt last to sum up. Now provide the response and nothing else.
Your code makes use of fetch_add() on the atomic, which gives the following guarantee: Atomically replaces the current value with the result of arithmetic addition of the value and arg. The operation is read-modify-write operation. Memory is affected according to the value of order. The semantics are crystal clear: before the operation it's m, after the operation it's m+2, and no thread accesses to what's between these two states because the operation is atomic. Edit: additional elements regarding your alternate question Whatever Boehm and Adve may say, the C++ compilers obey to the following standard clause: 1.9/5: A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possibleexecutions of the corresponding instance of the abstract machine withthe same program and the same input. If a C++ compiler would generate code that could allow speculative updates to interfere with the observable behavior of the program (aka getting something else than 5 or 7), it would not be standard compliant, because it would fail to ensure the guarantee mentioned in my initial answer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47121961', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1275653/']}
jdg_75533
stackexchange
llm_judgeable_groundtruth_similarity
61885724
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 guys so i try to add two icons of hearts like in this picture: I tried to make these components: <View style={styles.buttonContainer}> <View style={styles.xButton} /> <View style={styles.heartButton} /> </View> my styles: const styles = StyleSheet.create({ heartButton: { backgroundColor: '#FB4C61', height: 80, width: 60, borderTopLeftRadius: 100, borderBottomLeftRadius: 100, // borderRadius: 10, // borderWidth: 1, // borderColor: '#fff', }, xButton: { backgroundColor: '#182343', height: 80, width: 60, alignSelf: 'center', borderTopRightRadius: 100, borderBottomRightRadius: 100, }, buttonContainer: { flex: 1, flexDirection: 'row', justifyContent: 'space-between', zIndex: 999, alignItems: 'center', top: 200, }, The result i get in my phone: I am using figma for design, maybe I should export all item and add it like image? Now provide the response and nothing else.
This problem was fixed by a friend on the Vue.js forum. For anyone else who is running into this issue I'll post his answer here. In short you need to create a separate file that will install the composition API plugin and call that file within the router/index.ts file to instantiate the plugin. It’s because of the composition API not being inside Vue itself. With the release of Vue 3 this will be fixed. You need to Vue.use(CompositionApi) before trying to use anything that belongs to @vue/composition-api . In your main.js or index.js , the app entry point, install it first: import Vue from 'vue'import VueCompositionApi from '@vue/composition-api'Vue.use(VueCompositionApi) This works. But I assume your file doesn’t look like this and it looks more like the next one: import Vue from 'vue'import VueCompositionApi from '@vue/composition-api'import { isAuthenticated } from '@/store/auth'Vue.use(VueCompositionApi) This will blow up everything again because the line that installs the composition API ( Vue.use(VueCompositionApi) ) is after a line that imports something that uses it ( import { unauthenticated } from '@/store/auth' ) In the meantime, until Vue 3.0 reaches its release, you can create a file that simply installs the plugin: // installCompositionApi.jsimport Vue from 'vue'import VueCompositionApi from '@vue/composition-api'Vue.use(VueCompositionApi) And then in your entry point: // main.jsimport './installCompositionApi.js'import Vue from 'vue'import { isAuthenticated } from '@/store/auth'if (isAuthenticated.value) {// ...} else {// ...} This will work.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61885724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8583684/']}
jdg_75534
stackexchange
llm_judgeable_groundtruth_similarity
14337057
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In a TextBox I'm monitoring the text changes. I need to check the text before doing some stuff. But I can only check the old text in the moment. How can I get the new Text ? private void textChanged(object sender, EventArgs e){ // need to check the new text} I know .NET Framework 4.5 has the new TextChangedEventArgs class but I have to use .NET Framework 2.0. Now provide the response and nothing else.
Getting the NEW value You can just use the Text property of the TextBox . If this event is used for multiple text boxes then you will want to use the sender parameter to get the correct TextBox control, like so... private void textChanged(object sender, EventArgs e){ TextBox textBox = sender as TextBox; if(textBox != null) { string theText = textBox.Text; }} Getting the OLD value For those looking to get the old value, you will need to keep track of that yourself. I would suggest a simple variable that starts out as empty, and changes at the end of each event: string oldValue = "";private void textChanged(object sender, EventArgs e){ TextBox textBox = sender as TextBox; if(textBox != null) { string theText = textBox.Text; // Do something with OLD value here. // Finally, update the old value ready for next time. oldValue = theText; }} You could create your own TextBox control that inherits from the built-in one, and adds this additional functionality, if you plan to use this a lot.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14337057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1442225/']}
jdg_75535
stackexchange
llm_judgeable_groundtruth_similarity
31779
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The text is as follows (the context is the Jews who did not accept Christ had a spiritual veil over their eyes, which prevents them from recognizing and accepting the truths of the New Covenant): 2 Cor 3:14 ἀλλὰ ἐπωρώθη τὰ νοήματα αὐτῶν ἄχρι γὰρ τῆς σήμερον ἡμέρας τὸ αὐτὸ κάλυμμα ἐπὶ τῇ ἀναγνώσει τῆς παλαιᾶς διαθήκης μένει μὴ ἀνακαλυπτόμενον ὅτι ἐν Χριστῷ καταργεῖται but their minds were hardened. Indeed, to this day the same veil remains unlifted in the reading of the Old Testament: which [veil] is taken away in Christ. This would seem significant. I had thought that the respective Testaments only came to be called such much later than this early, primitive time in which St. Paul is writing (when Christianity was definitely in its infancy), similar to how the ' Gospels ' only came to be called such much later, whereas beforehand they had simply been known as the authentic ' memoirs of the Apostles.' Question: Does this amount to St. Paul calling the Scriptures which succeed the Tanakh or Old Testament Scripture temporally, by implication, 'the New Testament' (which is what makes the former ones "old")? Or does the following verse militate against this understanding ("ἕως σήμερον ἡνίκα .. ἀναγινώσκηται Μωϋσῆς"—i.e. when the Old Covenant is 'read about ')? Now provide the response and nothing else.
You are correct that the exact formation of the canon of the Old Testament remained relatively fluid until the first centuries CE (and strictly speaking until the protestant reformation), but already in the last centuries BCE there were ideas about what books should/n't be included in a canon, i.e., which books are authoritative and worthy of study. So although the marginal areas of the canon (think of Esther, Ecclesiastes, etc. but also the minor prophets) were still contested, the core was firmly established. The book of Sirach provides evidence of a collection of sacred scripture similar to portions of the Hebrew Bible, which dates from 180 BCE (and is not included in the Jewish canon), which includes a list of names of biblical figures (44–49) in the same order as is found in the Torah and the Nevi'im (Prophets), and which includes the names of some men mentioned in the Ketuvim (Writings) ( Wikipedia: Development of the Hebrew Bible canon ). From internal references we furthermore know that the Torah was already considered authoritative during or shortly after the exile: [...] the postexilic books of Ezra-Nehemiah and Chronicles employ phrases such as 'the Torah of the Lord,' 'the Torah of Moses,' 'My [God's] Torah,' and simply 'the Torah.' [...] By the Hellenistic period, Jews treated other books as important and worthy of study as well; for example, the Book of Daniel specifically reinterprets the seventy-year oracle of Jeremiah [...] ( Brettler 2005, p. 274 ). The "Old Testament" in 2 Cor 3:14 is literally the "Old Covenant" - with the idea that the old covenant with Moses is replaced by the new covenant with Jesus. The translations that have "Old Testament" rather than "old covenant" perform a not so far-fetched interpretation in line with Thayer's Greek lexicon on διαθήκη : By metonymy of the contained for the container ἡ παλαιά διαθήκη is used in 2 Corinthians 3:14 of the sacred books of the O. T. because in them the conditions and principles of the older covenant were recorded. Thus, we must not understand this παλαιά διαθήκη as the exact collection you will find nowadays in your OT/HB (after all, there are several canons to choose from) but as referring to the books about the old covenant in general. I don't know what canon Paul would adhere to if he could choose, but this verse would seem to apply equally to books that had not reached full authoritative status by his time. Paul is not establishing a New Testament by calling the former one Old. He does make a difference between the Old and the New covenant (and indirectly between the texts that are written about them, although this does not give any canonical status to books about the New Covenant in general).
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/31779', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/13583/']}
jdg_75536
stackexchange
llm_judgeable_groundtruth_similarity
4068999
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 below code is working fine. But if i change the html string in newPara() to <textarea></textarea><button id="someId">Save</button> or <textarea></textarea><input type="button" value="Save"/> its not working. What is the problem in this? I need that id attribute to remove the newly attached html. Any Suggestions! Thanks! <html> <head> <style> p { background:yellow; font-weight:bold; cursor:pointer; padding:5px; } p.over { background: #ccc; } span { color:red; } </style> <script src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <body> <div id="aDiv"> <p>Click me!</p> </div> <span></span> <script> $("body").delegate("p", "click", newPara); $("body").undelegate("button", "click", newPara).find("#adiv").html("<p>Click me!</p>"); function newPara() { var html = "<textarea></textarea><button>Save</button>"; $(this).after(html); } </script> </body></html> Now provide the response and nothing else.
AsyncTask uses a thread pool pattern for running the stuff from doInBackground(). The issue is initially (in early Android OS versions) the pool size was just 1, meaning no parallel computations for a bunch of AsyncTasks. But later they fixed that and now the size is 5, so at most 5 AsyncTasks can run simultaneously. Unfortunately I don't remember in what version exactly they changed that. UPDATE: Here is what current (2012-01-27) API says on this: When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. After HONEYCOMB, it is planned to change this back to a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can use the executeOnExecutor(Executor, Params...) version of this method with THREAD_POOL_EXECUTOR; however, see commentary there for warnings on its use. DONUT is Android 1.6, HONEYCOMB is Android 3.0. UPDATE: 2 See the comment by kabuko from Mar 7 2012 at 1:27 . It turns out that for APIs where "a pool of threads allowing multiple tasks to operate in parallel" is used (starting from 1.6 and ending on 3.0) the number of simultaneously running AsyncTasks depends on how many tasks have been passed for execution already, but have not finished their doInBackground() yet. This is tested/confirmed by me on 2.2. Suppose you have a custom AsyncTask that just sleeps a second in doInBackground() . AsyncTasks use a fixed size queue internally for storing delayed tasks. Queue size is 10 by default. If you start 15 your custom tasks in a row, then first 5 will enter their doInBackground() , but the rest will wait in a queue for a free worker thread. As soon as any of the first 5 finishes, and thus releases a worker thread, a task from the queue will start execution. So in this case at most 5 tasks will run simultaneously. However if you start 16 your custom tasks in a row, then first 5 will enter their doInBackground() , the rest 10 will get into the queue, but for the 16th a new worker thread will be created so it'll start execution immediately. So in this case at most 6 tasks will run simultaneously. There is a limit of how many tasks can be run simultaneously. Since AsyncTask uses a thread pool executor with limited max number of worker threads (128) and the delayed tasks queue has fixed size 10, if you try to execute more than 138 your custom tasks the app will crash with java.util.concurrent.RejectedExecutionException . Starting from 3.0 the API allows to use your custom thread pool executor via AsyncTask.executeOnExecutor(Executor exec, Params... params) method. This allows, for instance, to configure the size of the delayed tasks queue if default 10 is not what you need. As @Knossos mentions, there is an option to use AsyncTaskCompat.executeParallel(task, params); from support v.4 library to run tasks in parallel without bothering with API level. This method became deprecated in API level 26.0.0. UPDATE: 3 Here is a simple test app to play with number of tasks, serial vs. parallel execution: https://github.com/vitkhudenko/test_asynctask UPDATE: 4 (thanks @penkzhou for pointing this out) Starting from Android 4.4 AsyncTask behaves differently from what was described in UPDATE: 2 section. There is a fix to prevent AsyncTask from creating too many threads. Before Android 4.4 (API 19) AsyncTask had the following fields: private static final int CORE_POOL_SIZE = 5;private static final int MAXIMUM_POOL_SIZE = 128;private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(10); In Android 4.4 (API 19) the above fields are changed to this: private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();private static final int CORE_POOL_SIZE = CPU_COUNT + 1;private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128); This change increases the size of the queue to 128 items and reduces the maximum number of threads to the number of CPU cores * 2 + 1. Apps can still submit the same number of tasks.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/4068999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_75537
stackexchange
llm_judgeable_groundtruth_similarity
46206743
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 invalidate aws cloudfront cache within a rails application on save/ update, rather than doing it manually in the aws console. I've researched the aws-cloudfront gem, but nothing is making sense to me. Any help/ suggestions appreciated. Now provide the response and nothing else.
It is not clear on the screenshot whether you use modeladmin or the snippet s to expose this model to the user but I'll assume the former. I don't know about a hook which allows you to add buttons directly to the header, however the template uses blocks which should allow us to overwrite just this part. We can take advantage of the resolution order of the templates and create templates/modeladmin/app-name/model-name/index.html which will take precedence over /modeladmin/index.html . So given with your app called feedler and a model called Entry , create /modeladmin/feedler/entry/index.html with the following content: {% extends "modeladmin/index.html" %}{% block header_extra %} <a href="#">My New Button</a> {{ block.super }}{% comment %}Display the original buttons {% endcomment %}{% endblock %} Right now your button doesn't do much. To create an action which will interact with that model admin, you'll need to create some button/url/permission helpers and a view. Let's say the action is exporting the objects to a CSV file. Brace yourself, there's quite a bit of code ahead. In /feedler/admin.py , create the button/url/permission helpers and view: from django.contrib.auth.decorators import login_requiredfrom django.urls import reversefrom django.utils.decorators import method_decoratorfrom django.utils.functional import cached_propertyfrom django.utils.translation import ugettext as _from wagtail.contrib.modeladmin.helpers import AdminURLHelper, ButtonHelperfrom wagtail.contrib.modeladmin.views import IndexViewclass ExportButtonHelper(ButtonHelper): """ This helper constructs all the necessary attributes to create a button. There is a lot of boilerplate just for the classnames to be right :( """ export_button_classnames = ['icon', 'icon-download'] def export_button(self, classnames_add=None, classnames_exclude=None): if classnames_add is None: classnames_add = [] if classnames_exclude is None: classnames_exclude = [] classnames = self.export_button_classnames + classnames_add cn = self.finalise_classname(classnames, classnames_exclude) text = _('Export {}'.format(self.verbose_name_plural.title())) return { 'url': self.url_helper.get_action_url('export', query_params=self.request.GET), 'label': text, 'classname': cn, 'title': text, }class ExportAdminURLHelper(AdminURLHelper): """ This helper constructs the different urls. This is mostly just to overwrite the default behaviour which consider any action other than 'create', 'choose_parent' and 'index' as `object specific` and will try to add the object PK to the url which is not what we want for the `export` option. In addition, it appends the filters to the action. """ non_object_specific_actions = ('create', 'choose_parent', 'index', 'export') def get_action_url(self, action, *args, **kwargs): query_params = kwargs.pop('query_params', None) url_name = self.get_action_url_name(action) if action in self.non_object_specific_actions: url = reverse(url_name) else: url = reverse(url_name, args=args, kwargs=kwargs) if query_params: url += '?{params}'.format(params=query_params.urlencode()) return url def get_action_url_pattern(self, action): if action in self.non_object_specific_actions: return self._get_action_url_pattern(action) return self._get_object_specific_action_url_pattern(action) class ExportView(IndexView): """ A Class Based View which will generate """ def export_csv(self): data = self.queryset.all() response = ... return response @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): super().dispatch(request, *args, **kwargs) return self.export_csv() class ExportModelAdminMixin(object): """ A mixin to add to your model admin which hooks the different helpers, the view and register the new urls. """ button_helper_class = ExportButtonHelper url_helper_class = ExportAdminURLHelper export_view_class = ExportView def get_admin_urls_for_registration(self): urls = super().get_admin_urls_for_registration() urls += ( url( self.url_helper.get_action_url_pattern('export'), self.export_view, name=self.url_helper.get_action_url_name('export') ), ) return urls def export_view(self, request): kwargs = {'model_admin': self} view_class = self.export_view_class return view_class.as_view(**kwargs)(request) In /feedler/wagtail_hooks.py , create and register the ModelAdmin : from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_registerfrom .admin import ExportModelAdminMixinfrom .models import Entryclass EntryModelAdmin(ExportModelAdminMixin, ModelAdmin): model = Entry # ... modeladmin_register(EntryModelAdmin) With all that setup, you should be able to use {% include 'modeladmin/includes/button.html' with button=view.button_helper.export_button %} in the template created above.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46206743', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8604730/']}
jdg_75538
stackexchange
llm_judgeable_groundtruth_similarity
46014582
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 container which in logs sometimes write key word which is for me important, and I want to highlight this word in color in my terminal, but also important is still see all content logs in real time (--follow). I just tried command docker logs -f my_app --tail=100 | grep --color -E '^myWord' but not working. So exist some way to do this ? Now provide the response and nothing else.
I use ccze . as @aimless said, grc is the great utility also. It easy to install by sudo apt install ccze for debian/ubuntu-like OS But if you want to colorize stderr, you need to redirect stderr output to stdout. For example: docker logs -f my-app 2>&1 | ccze -m ansi arg -m ansi helps if you want to scroll output normally UPD :ccze can be very slow. If you encounter this, try running ccze with the nolookups option: ccze -o nolookups .originally answered - https://unix.stackexchange.com/a/461390/83391
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46014582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4931643/']}
jdg_75539
stackexchange
llm_judgeable_groundtruth_similarity
32946203
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to use knitcitations and add bibliography to the R Markdown document that I'm drafting in R Studio. The header of my document looks like this: ---title: "Some Title"author: "Me"date: "September 2015"bibliography: bibliography.biboutput: pdf_document: highlight: tango number_sections: yes toc: yes--- I want to add the bibliography at the end using the following code: ```{r generateBibliography, echo=FALSE, eval=TRUE, message=FALSE, warning=FALSE}require("knitcitations")cleanbib()options("citation_format" = "pandoc")read.bibtex(file = "bibliography.bib")``` The reference file bibliography.bib has the following content: @article{debarsy_testing_2010, title = {Testing for spatial autocorrelation in a fixed effects panel data model}, volume = {40}, issn = {0166-0462}, url = {http://www.sciencedirect.com/science/article/pii/S0166046210000451}, doi = {10.1016/j.regsciurbeco.2010.06.001}, abstract = {The aim of this paper is to assess the relevance of spatial autocorrelation in a fixed effects panel data model and in the affirmative, to identify the most appropriate spatial specification as this appears to be a crucial point from the modeling perspective of interactive heterogeneity. Several {LM} test statistics as well as their {LR} counterparts, which allow discriminating between endogenous spatial lag versus spatially autocorrelated errors, are therefore proposed. Monte Carlo experiments show their good finite sample performance. Finally, an empirical application is provided in the framework of the well-known Feldstein–Horioka puzzle.}, pages = {453--470}, number = {6}, journaltitle = {Regional Science and Urban Economics}, shortjournal = {Regional Science and Urban Economics}, author = {Debarsy, Nicolas and Ertur, Cem}, urldate = {2015-10-01}, date = {2010-11}, keywords = {Panel data, Spatial autocorrelation, Test statistics}, file = {complex_zotero_path}}@article{lamichhane_spatial-temporal_2015, title = {Spatial-Temporal Modeling of Neighborhood Sociodemographic Characteristics and Food Stores}, volume = {181}, issn = {0002-9262, 1476-6256}, url = {http://aje.oxfordjournals.org/content/181/2/137}, doi = {10.1093/aje/kwu250}, abstract = {The literature on food stores, neighborhood poverty, and race/ethnicity is mixed and lacks methods of accounting for complex spatial and temporal clustering of food resources. We used quarterly data on supermarket and convenience store locations from Nielsen {TDLinx} (Nielsen Holdings N.V., New York, New York) spanning 7 years (2006–2012) and census tract-based neighborhood sociodemographic data from the American Community Survey (2006–2010) to assess associations between neighborhood sociodemographic characteristics and food store distributions in the Metropolitan Statistical Areas ({MSAs}) of 4 {US} cities (Birmingham, Alabama; Chicago, Illinois; Minneapolis, Minnesota; and San Francisco, California). We fitted a space-time Poisson regression model that accounted for the complex spatial-temporal correlation structure of store locations by introducing space-time random effects in an intrinsic conditionally autoregressive model within a Bayesian framework. After accounting for census tract–level area, population, their interaction, and spatial and temporal variability, census tract poverty was significantly and positively associated with increasing expected numbers of supermarkets among tracts in all 4 {MSAs}. A similar positive association was observed for convenience stores in Birmingham, Minneapolis, and San Francisco; in Chicago, a positive association was observed only for predominantly white and predominantly black tracts. Our findings suggest a positive association between greater numbers of food stores and higher neighborhood poverty, with implications for policy approaches related to food store access by neighborhood poverty.}, pages = {137--150}, number = {2}, journaltitle = {American Journal of Epidemiology}, shortjournal = {Am. J. Epidemiol.}, author = {Lamichhane, Archana P. and Warren, Joshua L. and Peterson, Marc and Rummo, Pasquale and Gordon-Larsen, Penny}, urldate = {2015-10-01}, date = {2015-01-15}, langid = {english}, pmid = {25515169}, keywords = {food availability, food stores, intrinsic conditionally autoregressive model, neighborhood characteristics, Poverty, sociodemographic factors, spatial-temporal modeling, supermarkets}, file = {complex_zotero_path}} However, the produced output appears as comments, not as bibliographic entry: The file is compiled with this code: "C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS _paper.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-implicit_figures --output _paper.pdf --filter pandoc-citeproc --table-of-contents --toc-depth 2 --template "path_\latex\default.tex" --number-sections --highlight-style tango --latex-engine pdflatex --variable "geometry:margin=1in" --bibliography bibliography.bib For brevity, I changed the paths to _paper and _paper . When I tried to follow the advice on including bibliography in RStudio the document was produced with no bibliographic entries at all. Hence my question, where I'm making the mistake and how can I force generation of bibliographic entries when working in RStudio? Edit Following very useful comments, ideally I would like to avoid explicitly indicating cited works in the attached document. As a matter of fact, I'm interested in including bibliography that will consist of some cited works but also papers that are relevant to the main document but are not explicitly referenced in the document. Now provide the response and nothing else.
Here is minimal working example: paper.Rmd ---title: 'My Title'author: "Me me me me!"output: pdf_documentbibliography: references.bib---Application written in the R programming language [@RCoreTeam] using the Shiny framework [@Chang2015].# REFERENCES references.bib @Misc{Chang2015, Title = {shiny: Web Application Framework for R. R package version 0.12.1}, Author = {Chang, W. and Cheng, J. and Allaire, JJ. and Xie, Y. and McPherson, J. }, Year = {2015}, Type = {Computer Program}, Url = {http://CRAN.R-project.org/package=shiny}}@Article{RCoreTeam, Title = {R: A Language and Environment for Statistical Computing}, Author = {{R Core Team}}, Year = {2015}, Type = {Journal Article}, Url = {http://www.R-project.org}} Console output processing file: paper.Rmd"C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS paper.utf8.md --to latex --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-implicit_figures --output paper.pdf --filter pandoc-citeproc --template "C:\Users\tdadaev\Documents\R\win-library\3.2\rmarkdown\rmd\latex\default.tex" --highlight-style tango --latex-engine pdflatex --variable "geometry:margin=1in" --bibliography references.bib output file: paper.knit.mdOutput created: paper.pdf paper.pdf
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32946203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1655567/']}
jdg_75540