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
2075720
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 any way to make a WPF app look like it's running on Windows 7 even if it's running on XP? I'm looking for some kind of theme I can just paste in. I'm aware of the themes project on Codeplex ( https://archive.codeplex.com/?p=wpfthemes ), but it lacks support for DataGrid , which is something I critically need. I was thinking maybe the Windows 7 theme would just be an easy port, or exists in some file somewhere already. Update Using @Lars Truijens idea, I was able to get the Windows 7 look for the major controls, but unfortunately it did not work for the WPF Toolkit DataGrid control, which I need. DataGrid looks like this with Aero theme DataGrid should look like this So, I'm still looking for a solution to this problem if anyone has any ideas. Maybe someone has built an extension to the Aero theme that covers the WPF toolkit controls? Again, any information you have is much appreciated. Update 2 - DataGrid Problem solved! To get the Aero theme to work with the DataGrid or any other WPF Toolkit controls, you just need to add a second Aero dictionary, so your App.xaml should now look like this. <Application.Resources> ... <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml" /> <ResourceDictionary Source="pack://application:,,,/WPFToolkit;component/Themes/Aero.NormalColor.xaml" /> ... </ResourceDictionary.MergedDictionaries> </ResourceDictionary></Application.Resources> Also, I would recommend turning the gridlines off in your DataGrid controls (because they look horrible ): <DataGrid GridLinesVisibility="None" ...> Now provide the response and nothing else.
WPF comes with the standard Windows themes on all Windows versions. For example, you can have the Aero theme (which Vista and Windows 7 use) on Windows XP with the following steps: Add PresentationFramework.Aero to your application's references list as a requires Edit your App.xaml from this <Application.Resources> <!-- Your stuff here --></Application.Resources> to this <Application.Resources> <ResourceDictionary> <!-- Put your stuff here instead --> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary></Application.Resources> Source: http://mrpmorris.blogspot.com/2008/05/using-vista-aero-theme-in-xp-wpf-apps.html Other alternatives below. Be sure to add the corresponding assembly to your application's reference list as a requires. <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml"/><ResourceDictionary Source="/PresentationFramework.Classic;component/themes/Classic.xaml"/><ResourceDictionary Source="/PresentationFramework.Royale;component/themes/Royale.NormalColor.xaml"/><ResourceDictionary Source="/PresentationFramework.Luna.Homestead;component/themes/Luna.Homestead.xaml"/><ResourceDictionary Source="/PresentationFramework.Luna.Metallic;component/themes/Luna.Metallic.xaml"/><ResourceDictionary Source="/PresentationFramework.Zune;component/themes/Zune.NormalColor.xaml"/>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2075720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/129164/']}
jdg_371241
stackexchange
llm_judgeable_groundtruth_similarity
3127104
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my app I have a text field that takes some number input from user so i set the keyboard type to "Number Pad"but now i am stuck as to how should i dismiss it when user finishes giving input . i know i have to use the delegate method "textfieldShouldReturn" but the problem is that number pad dont have a return key.so is it necessary to add a custom done key on the keyboard or there is some other way out? Now provide the response and nothing else.
Another solution - Add inputAccessoryView to yourNumberTextFiled - (void)viewDidLoad{ [super viewDidLoad]; UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)]; numberToolbar.barStyle = UIBarStyleBlackTranslucent; numberToolbar.items = [NSArray arrayWithObjects: [[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancelNumberPad)], [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [[UIBarButtonItem alloc]initWithTitle:@"Apply" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)], nil]; [numberToolbar sizeToFit]; numberTextField.inputAccessoryView = numberToolbar;}-(void)cancelNumberPad{ [numberTextField resignFirstResponder]; numberTextField.text = @"";}-(void)doneWithNumberPad{ NSString *numberFromTheKeyboard = numberTextField.text; [numberTextField resignFirstResponder];}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3127104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357445/']}
jdg_371242
stackexchange
llm_judgeable_groundtruth_similarity
24816175
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 basic bootstrap panel and I want it to be 4 columns wide. I tried adding the class col-sm-4 like I would any other div: <div class="row"> <div class="panel panel-default col-sm-4"> <div class="panel-heading">Panel heading without title</div> <div class="panel-body"> Panel content </div> </div></div> This got the width correct, but now the title bar background is messed up: How do I get it to conform to that width but still render the header correctly? Now provide the response and nothing else.
Rather than specifying the panel to be the width of four columns, what if you placed the panel in a column with length-four? I don't see anywhere in the documentation that says that you can apply the col-sm-* class to a panel component. <div class="row"> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-heading">Panel Heading</div> <div class="panel-body">Panel content</div> </div> </div></div> And remember that the columns are supposed to add up to 12. So if you wanted empty space on the right and left of your panel you would do something like this: <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-heading">Panel Heading</div> <div class="panel-body">Panel content</div> </div> </div> <div class="col-md-4"></div></div> Update 1: Sionide21 noticed that the width of the column changes depending on whether or not you have nested rows. See image below. The top row of the image is what happens when the panel is placed directly inside of the column (see first row below... this is the same as the first HTML snippet of this post). The bottom half is what happens when you insert a nested row (see second row below). <div class="row"> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-heading">Panel Heading</div> <div class="panel-body">Panel content</div> </div> </div></div><div class="row"> <div class="col-md-4 bg-primary"><p>Left Column</p></div> <div class="col-md-4"> <div class="row"> <div class="panel panel-default"> <div class="panel-heading">Panel Heading</div> <div class="panel-body">Panel content</div> </div> </div> </div> <div class="col-md-4 bg-primary"><p>Rightt Column</p></div></div> So it appears that when the panel is placed directly inside of a column, some margin is added to the panel (or padding is added to the column), whereas when you place the panel in a nested row, the margin (or padding) is eliminated. I do not know if this is by design or just a quirk of Bootstrap. Update 2: koala_dev pointed out that the "nested row" example is behaving as it is because the panel is a direct child of a .row element. So in essence we're countering the padding of the column with the negative margins of the row. I don't know enough about the matter, but he says that it should be fine to leave as is, or you can create custom CSS to remove the padding from the panel, or could even try adding the .row class to the panel itself! E.g. <div class="panel panel-default row"> .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24816175', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111644/']}
jdg_371243
stackexchange
llm_judgeable_groundtruth_similarity
8516024
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 function in javascript that will return date array of all sundays.below you can see my code : function getDefaultOffDays(year){var offdays=new Array();i=0;for(month=1;month<12;month++){ tdays=new Date(year, month, 0).getDate(); for(date=1;date<=tdays;date++) { smonth=(month<10)?"0"+month:month; sdate=(date<10)?"0"+date:date; dd=year+"-"+smonth+"-"+sdate; day=new Date(); day.setDate(date); day.setMonth(month); day.setFullYear(year); if(day.getDay() == 0 ) { offdays[i++]=dd; } }}return offdays;} the issue is that the returned array is giving random dates not the only dates for sunday :(m i missing some thing? Now provide the response and nothing else.
If you examine the result, you can see that it's actually not random. It returns the dates for january that are sundays in february, and so on. The month property of the Date object is zero based, not one based. If you change this line, the function will return the correct dates: day.setMonth(month - 1); Also, the loop only runs from 1 to 11, you need to include december too: for (month=1; month <= 12; month++) Another way to do this would be to find the first sunday, then just step forward seven days at a time: function getDefaultOffDays2(year) { var date = new Date(year, 0, 1); while (date.getDay() != 0) { date.setDate(date.getDate() + 1); } var days = []; while (date.getFullYear() == year) { var m = date.getMonth() + 1; var d = date.getDate(); days.push( year + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) ); date.setDate(date.getDate() + 7); } return days;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8516024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244546/']}
jdg_371244
stackexchange
llm_judgeable_groundtruth_similarity
59542120
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: <div> <b-dropdown id="dropdown-1" text="Dropdown Button" class="m-md-2"> <b-dropdown-item>First Action</b-dropdown-item> <b-dropdown-item>Second Action</b-dropdown-item> <b-dropdown-item>Third Action</b-dropdown-item> <b-dropdown-divider></b-dropdown-divider> <b-dropdown-item active>Active action</b-dropdown-item> <b-dropdown-item disabled>Disabled action</b-dropdown-item> </b-dropdown></div> The items should be shown when the dropdown button is hovered! Now provide the response and nothing else.
Not as straighforward as I thought but here is one example on how to convert this bootstrap-dropdown into a hoverable dropdown. <template> <div @mouseover="onOver" @mouseleave="onLeave"> <b-dropdown id="dropdown-1" text="Dropdown Button" ref="dropdown" class="m-md-2"> <b-dropdown-item>First Action</b-dropdown-item> <b-dropdown-item>Second Action</b-dropdown-item> <b-dropdown-item>Third Action</b-dropdown-item> </b-dropdown> </div></template><script> export default { methods: { onOver() { this.$refs.dropdown.visible = true; }, onLeave() { this.$refs.dropdown.visible = false; } } }</script> The idea is to use v-on directives mouseover and mouseleave on a wrapper div (somehow the vue directive does not work on the b-vue component directly, but might be only me). Then use the event trigger to alter dropdown.visible state. Also in this example I make use of Vue's $refs to get hold of the dropdown within the script. Working example https://codesandbox.io/s/2erqk Multiple Hover-Dropdowns If you are planning on having this behaviour on multiple dropdowns at once, I would go into the trouble of creating a component out of it - incorporating the b-dropdown into a new component. <template> <div @mouseover="onOver" @mouseleave="onLeave"> <b-dropdown id="dropdown-1" text="Dropdown Button" ref="dropdown" class="m-md-2"> <slot></slot> </b-dropdown> </div></template><script>export default { name: "b-dropdown-hover", methods: { onOver() { this.$refs.dropdown.visible = true; }, onLeave() { this.$refs.dropdown.visible = false; } }};</script> And then use it like this : <template> <div> <b-dropdown-hover> <b-dropdown-item>First Action</b-dropdown-item> <b-dropdown-item>Second Action</b-dropdown-item> <b-dropdown-item>Third Action</b-dropdown-item> </b-dropdown-hover> <b-dropdown-hover> <b-dropdown-item>First Action</b-dropdown-item> <b-dropdown-item>Second Action</b-dropdown-item> <b-dropdown-item>Third Action</b-dropdown-item> </b-dropdown-hover> </div></template><script> import BDropdownHover from '@/components/BDropdownHover' export default { components : { BDropdownHover } }</script> But you also have to include all events and props that you need from b-dropdown into the new component. Here is a working example of that: https://codesandbox.io/s/romantic-elgamal-lol7h
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59542120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10978576/']}
jdg_371245
stackexchange
llm_judgeable_groundtruth_similarity
10805125
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 text in a textarea and I read it out using the .value attribute. Now I would like to remove all linebreaks (the character that is produced when you press Enter ) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex? If that is not possible, is there another way? Now provide the response and nothing else.
Line breaks (better: newlines) can be one of Carriage Return (CR, \r , on older Macs), Line Feed (LF, \n , on Unices incl. Linux) or CR followed by LF ( \r\n , on WinDOS). (Contrary to another answer, this has nothing to do with character encoding.) Therefore, the most efficient RegExp literal to match all variants is /\r?\n|\r/ If you want to match all newlines in a string, use a global match, /\r?\n|\r/g respectively. Then proceed with the replace method as suggested in several other answers. (Probably you do not want to remove the newlines, but replace them with other whitespace, for example the space character, so that words remain intact.)
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/10805125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1300737/']}
jdg_371246
stackexchange
llm_judgeable_groundtruth_similarity
23922598
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 achieve this in the most generic way? I thought of overriding get() , but I'd have to override too many methods. Also tried with as_view() but I can't access the request from there. I also tried adding a <meta http-equiv="refresh" content="0;url" /> in the template, but I throught that was not the best approach. Now provide the response and nothing else.
I doubt you want to override as_view unless you are doing something exceptionally odd. It returns a function that is used as the view. The function it returns does little more than call dispatch . You can override the specific method you want. eg get , alternatively, if you want to override all methods ( get , post , etc), you should override dispatch . from django.shortcuts import redirectfrom django.views.generic import TemplateViewclass MyView(TemplateView): template_name = 'my_app/my_template.html' def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect('my-other-view') return super(MyView, self).dispatch(request, *args, **kwargs) CCBV.co.uk is a good reference for learning django's class based views. Disclaimer: I built it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23922598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2065041/']}
jdg_371247
stackexchange
llm_judgeable_groundtruth_similarity
29479479
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need your help in getting the list of months and the years in String between two dates. The user will enter two dates in the String format of: String date1 ="JAN-2015";String date2 ="APR-2015"; So the result should be: Jan-2015 FEB-2015 MAR-2015 I tried using the following code but it gave me wrong results: List<Date> dates = new ArrayList<Date>();String str_date ="JAN-2015";String end_date ="APR-2015";DateFormat formatter ; formatter = new SimpleDateFormat("MMM-yyyy");Date startDate = formatter.parse(str_date); Date endDate = formatter.parse(end_date);long endTime =endDate.getTime() ; long curTime = startDate.getTime();while (curTime <= endTime) { dates.add(new Date(curTime)); curTime ++;}for(int i=0;i<dates.size();i++){ Date lDate =(Date)dates.get(i); String ds = formatter.format(lDate); System.out.println(ds);} Now provide the response and nothing else.
Using the less code possible and basic java libraries and getting the result you asked for. So you can modify the date1 and date2 variables. import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;public class Main { public static void main(String[] args) { String date1 = "JAN-2015"; String date2 = "APR-2015"; DateFormat formater = new SimpleDateFormat("MMM-yyyy"); Calendar beginCalendar = Calendar.getInstance(); Calendar finishCalendar = Calendar.getInstance(); try { beginCalendar.setTime(formater.parse(date1)); finishCalendar.setTime(formater.parse(date2)); } catch (ParseException e) { e.printStackTrace(); } while (beginCalendar.before(finishCalendar)) { // add one month to date per loop String date = formater.format(beginCalendar.getTime()).toUpperCase(); System.out.println(date); beginCalendar.add(Calendar.MONTH, 1); } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29479479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4756141/']}
jdg_371248
stackexchange
llm_judgeable_groundtruth_similarity
552640
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 it true that for $x\in[0,2\pi]$ we have$$\sum_{n=1}^{\infty}\frac{\cos(nx)}{n^2}=\frac{x^2}{4}-\frac{\pi x}{2}+\frac{\pi^2}{6}$$How can I prove it?For other intervals what is the value of above series if is convergent? Now provide the response and nothing else.
See the results posted here , where I show that $$\sum_{n=-\infty}^{\infty} \frac{\sin^2{a n}}{n^2} = \pi a$$ when $a \in (0,\pi)$. Now, use the fact that $$\sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}$$ and let $S$ be the sum in question. Then $$\frac{\pi^2}{6} - S = \sum_{n=1}^{\infty} \frac{1-\cos{n x}}{n^2} = 2 \sum_{n=1}^{\infty} \frac{\sin^2{n x/2}}{n^2}$$ Rewrite the last sum as $$2 \sum_{n=1}^{\infty} \frac{\sin^2{n x/2}}{n^2} = \sum_{n=-\infty}^{\infty} \frac{\sin^2{n x/2}}{n^2} - \left ( \frac{x}{2} \right )^2 = \pi \frac{x}{2} - \frac{x^2}{4}$$ Then $$\frac{\pi^2}{6} - S = \pi \frac{x}{2} - \frac{x^2}{4} \implies S = \frac{x^2}{4} - \pi \frac{x}{2} + \frac{\pi^2}{6}$$ as was to be shown.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/552640', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_371249
stackexchange
llm_judgeable_groundtruth_similarity
7243401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I have my enum public enum Sample { ValueA{ @Override public String getValue(){ return "A"; } }, ValueB{ @Override public String getValue(){ return "B"; } public void doSomething(){ } };abstract public String getValue();}; and I have some other code trying to use the enum. Sample.ValueB.doSomething(); Which seems like it should be valid, but produces the error "The method doSomething() is undefined for the type Sample". As opposed to Sample value = Sample.ValueB;value.doSomething(); which produces the same error and seems reasonable. I assume there is a reasonable answer as to why the first one doesn't work and it relates to the two examples being equivalent under the hood. I was hoping someone could point me towards the documentation on why it is that way. Now provide the response and nothing else.
The type of the "field" ValueA is Sample . That means that you can only invoke methods on ValueA that Sample provides. From JLS §8.9.1. Enum Constants : Instance methods declared in these class bodies may be invoked outside the enclosing enum type only if they override accessible methods in the enclosing enum type. More importantly: From a design perspective enum values should be uniform: if some operation is possible with one specific value, then it should be possible with all values (although it might result in different code being executed).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7243401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/919674/']}
jdg_371250
stackexchange
llm_judgeable_groundtruth_similarity
6111905
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider this code: struct foo{ int a;};foo q() { foo f; f.a =4; return f;}int main(){ foo i; i.a = 5; q() = i;} No compiler complains about it, even Clang. Why q() = ... line is correct? Now provide the response and nothing else.
No, the return value of a function is an l-value if and only if it is a reference (C++03). (5.2.2 [expr.call] / 10) If the type returned were a basic type then this would be a compile error. (5.17 [expr.ass] / 1) The reason that this works is that you are allowed to call member functions (even non- const member functions) on r-values of class type and the assignment of foo is an implementation defined member function: foo& foo::operator=(const foo&) . The restrictions for operators in clause 5 only apply to built-in operators , (5 [expr] / 3), if overload resolution selects an overloaded function call for an operator then the restrictions for that function call apply instead. This is why it is sometimes recommended to return objects of class type as const objects (e.g. const foo q(); ), however this can have a negative impact in C++0x where it can inhibit move semantics from working as they should.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6111905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/742194/']}
jdg_371251
stackexchange
llm_judgeable_groundtruth_similarity
14995884
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 text input. When the input receives focus I want to select the text inside of the input. With jQuery I'd do it this way: <input type="text" value="test" /> $("input[type=text]").click(function() { $(this).select(); // would select "test" in this example}); I've searched around to try and find the Angular way but most examples I'm finding are dealing with a directive that is watching a modal property for a change. I'm assuming I need a directive that is watching for an input that receives focus. How would I do that? Now provide the response and nothing else.
The way to do this in Angular is to create a custom directive which does the autoselect for you. module.directive('selectOnClick', ['$window', function ($window) { return { restrict: 'A', link: function (scope, element, attrs) { element.on('click', function () { if (!$window.getSelection().toString()) { // Required for mobile Safari this.setSelectionRange(0, this.value.length) } }); } };}]); Apply the directive like this: <input type="text" value="test" select-on-click /> View demo Update1 : Removed jQuery dependency. Update2 : Restrict as attribute. Update3 : Works in mobile Safari. Allows selecting part of the text (requires IE>8).
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14995884', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59017/']}
jdg_371252
stackexchange
llm_judgeable_groundtruth_similarity
29490
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: It is well-known that the number of surjections from a set of size n to a set of size m is quite a bit harder to calculate than the number of functions or the number of injections. (Of course, for surjections I assume that n is at least m and for injections that it is at most m.) It is also well-known that one can get a formula for the number of surjections using inclusion-exclusion, applied to the sets $X_1,...,X_m$, where for each $i$ the set $X_i$ is defined to be the set of functions that never take the value $i$. This gives rise to the following expression: $m^n-\binom m1(m-1)^n+\binom m2(m-2)^n-\binom m3(m-3)^n+\dots$. Let us call this number $S(n,m)$. I'm wondering if anyone can tell me about the asymptotics of $S(n,m)$. A particular question I have is this: for (approximately) what value of $m$ is $S(n,m)$ maximized? It is a little exercise to check that there are more surjections to a set of size $n-1$ than there are to a set of size $n$. (To do it, one calculates $S(n,n-1)$ by exploiting the fact that every surjection must hit exactly one number twice and all the others once.) So the maximum is not attained at $m=1$ or $m=n$. I'm assuming this is known, but a search on the web just seems to lead me to the exact formula. A reference would be great. A proof, or proof sketch, would be even better. Update. I should have said that my real reason for being interested in the value of m for which S(n,m) is maximized (to use the notation of this post) or m!S(n,m) is maximized (to use the more conventional notation where S(n,m) stands for a Stirling number of the second kind) is that what I care about is the rough size of the sum. The sum is big enough that I think I'm probably not too concerned about a factor of n, so I was prepared to estimate the sum as lying between the maximum and n times the maximum. Now provide the response and nothing else.
It seems to be the case that the polynomial $P_n(x) =\sum_{m=1}^nm!S(n,m)x^m$ has only real zeros. (I know it is true that $\sum_{m=1}^nS(n,m)x^m$ has only real zeros.) If this is true, then the value of $m$ maximizing $m!S(n,m)$ is within 1 of $P'_n(1)/P_n(1)$ by a theorem of J. N. Darroch, Ann. Math. Stat. 35 (1964), 1317-1321. See also J. Pitman, J. Combinatorial Theory, Ser. A 77 (1997), 279-303. By standard combinatorics $$ \sum_{n\geq 0} P_n(x) \frac{t^n}{n!} = \frac{1}{1-x(e^t-1)}. $$Hence $$ \sum_{n\geq 0} P_n(1)\frac{t^n}{n!} = \frac{1}{2-e^t} $$ $$ \sum_{n\geq 0} P'_n(1)\frac{t^n}{n!} = \frac{e^t-1}{(2-e^t)^2}. $$Since these functions are meromorphic with smallest singularity at $t=\log 2$, it is routine to work out the asymptotics, though I have not bothered to do this. Update. It is indeed true that $P_n(x)$ has real zeros. This is because$(x-1)^nP_n(1/(x-1))=A_n(x)/x$, where $A_n(x)$ is an Eulerian polynomial. It is known that $A_n(x)$ has only real zeros, and the operation $P_n(x) \to (x-1)^nP_n(1/(x-1))$ leaves invariant the property of having realzeros.
{}
{'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/29490', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1459/']}
jdg_371253
stackexchange
llm_judgeable_groundtruth_similarity
39113464
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 some kind of variables in Golang: global variable: var a int local variable: func hello() { var a int } return variable: func hello() (a int) {} Golang sometimes will auto-init some variables, but I don't know when and why? It confused me. Example: type User struct { Name string `json:"name"` Age int `json:"age"`}func foo(bts []byte) { var a User err := json.Unmarshal(bts, &a) // It's ok}func bar(bts []byte) (a *User) { err := json.Unmarshal(bts, a) // It will crash} which one should I have to initialize before use? Now provide the response and nothing else.
Golang will init all variables (not sometimes , not some ): In your code: func bar(bts []byte) (a *User) { err := json.Unmarshal(bts, a) // It will crash} You passed a nil pointer but you need a value pointed to by a , not a nil pointer: So you may create a Value then store the address of this Value inside a : When you use var a *User or func bar(bts []byte) (a *User) : The a is a pointer to the User type, and it is initialized to it's zero value, which is nil , see ( The Go Playground ): package mainimport "fmt"func main() { var a *User fmt.Printf("%#v\n\n", a) }type User struct { Name string `json:"Name"` Age int `json:"Age"`} output: (*main.User)(nil) And You may use a = &User{} to initialize it, like this working code ( The Go Playground ): package mainimport ( "encoding/json" "fmt")func foo(bts []byte) (*User, error) { var a User err := json.Unmarshal(bts, &a) // It's ok return &a, err}func bar(bts []byte) (a *User, err error) { a = &User{} err = json.Unmarshal(bts, a) // It's ok return}func main() { str := `{ "Name": "Alex", "Age": 3 }` u, err := foo([]byte(str)) if err != nil { panic(err) } fmt.Printf("%#v\n\n", u) // &main.User{Name:"Alex", Age:3} u, err = bar([]byte(str)) if err != nil { panic(err) } fmt.Printf("%#v\n\n", u) // &main.User{Name:"Alex", Age:3}}type User struct { Name string `json:"Name"` Age int `json:"Age"`} output: &main.User{Name:"Alex", Age:3}&main.User{Name:"Alex", Age:3} Variable declarations : A variable declaration creates one or more variables, bindscorresponding identifiers to them, and gives each a type and aninitial value. The initial value (zero value) : When storage is allocated for a variable, either through a declarationor a call of new , or when a new value is created, either through acomposite literal or a call of make , and no explicit initialization isprovided, the variable or value is given a default value. Each elementof such a variable or value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers , functions, interfaces, slices, channels, andmaps. This initialization is done recursively, so for instance eachelement of an array of structs will have its fields zeroed if no valueis specified. And see func Unmarshal(data []byte, v interface{}) error Docs: Unmarshal parses the JSON-encoded data and stores the result in thevalue pointed to by v.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39113464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1557245/']}
jdg_371254
stackexchange
llm_judgeable_groundtruth_similarity
8886401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hello i do want a sort an array, that contains this: String[] info = new String[5]{"6,j", "7,d", "12,s", "4,h", "14,s" }; But if i use this: Array.Sort(info); The output becomes: "7,d""6,j""4,h""14,s""12,s" But i wont the output to be: "14,s""12,s""7,d""6,j""4,h" What is the easiest way to do it in/with C#?? And i cant get Alphanumeric sort to work when i do like this: Array.Sort(info, new AlphanumComparatorFast()); the type or namespace "AlphanumComparatorFast" could not be found areyou missing a using directive or an assembly reference is the error that i get... Now provide the response and nothing else.
try with: var sortedArray = info.OrderBy(s=>int.Parse(s.Split(',')[0])).ToArray(); This sorts just by the numeric part, but you can elaborate on that sample. This code strongly assumes that there is always the comma separator, this may be is an issue in production, do some more accurate error handling.Should the array contains some elements that does not conform the exception, providing that is acceptable to ignore the failing elements, we can write: var sortedArray = info.Where(k=>!string.IsNullOrEmpty(k)&&k.IndexOf(",")!=-1).OrderBy(s=>int.Parse(s.Split(',')[0])).ToArray();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8886401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1143330/']}
jdg_371255
stackexchange
llm_judgeable_groundtruth_similarity
49506730
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 any way to set a JVM args like -Djava.net.preferIPv4Stack=true at cell level in order to apply/pass all JVM at cell in Websphere Application Server? Now provide the response and nothing else.
It's because HashMap order internally will depend on hashcode implementation. Your Book class does not implement hashCode so it will use the default one As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.) That means it will use memory address. In your case, it happens that for a single thread, allocated memory addresses are the same on re-run, which is not the case in threaded version. But this is only 'by accident' and you cannot rely on it even in single threaded (someone else will run it and get a different result,or even when you run it later you can get a different result as objects will have different memory addresses) Please ALWAYS overwrite hashCode (& equals ) when using objects in hashmap .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49506730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2594676/']}
jdg_371256
stackexchange
llm_judgeable_groundtruth_similarity
15196329
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 android SurfaceView to show camera preview in my activity. On moving to any other application which is playing any video, and on returning back, the preview is blank. I am using android 2.3.3. When I open the logcat it shows the following E/SEC_Overlay( 107): Error - overlays already in useW/CameraService( 76): Overlay create failed - retryingE/SEC_Overlay( 107): Error - overlays already in useW/CameraService( 76): Overlay create failed - retryingE/SEC_Overlay( 107): Error - overlays already in useW/CameraService( 76): Overlay create failed - retryingE/SEC_Overlay( 107): Error - overlays already in useW/CameraService( 76): Overlay create failed - retryingE/SEC_Overlay( 107): Error - overlays already in use...E/SEC_Overlay( 107): Error - overlays already in useW/CameraService( 76): Overlay create failed - retryingE/SEC_Overlay( 107): Error - overlays already in useW/CameraService( 76): Overlay create failed - retryingE/CameraService( 76): Overlay Creation Failed!D/AndroidRuntime( 1618): Shutting down VMW/dalvikvm( 1618): threadid=1: thread exiting with uncaught exception (group=0x40015560)E/AndroidRuntime( 1618): FATAL EXCEPTION: mainE/AndroidRuntime( 1618): java.lang.RuntimeException: startPreview failedE/AndroidRuntime( 1618): at android.hardware.Camera.startPreview(Native Method)E/AndroidRuntime( 1618): at com.android.myapp.MyActivity.startCapturing(MyActivity.java:216)E/AndroidRuntime( 1618): at com.android.myapp.MyActivity.surfaceChanged(MyActivity.java:328)E/AndroidRuntime( 1618): at android.view.SurfaceView.updateWindow(SurfaceView.java:549)E/AndroidRuntime( 1618): at android.view.SurfaceView.dispatchDraw(SurfaceView.java:348)E/AndroidRuntime( 1618): at android.view.ViewGroup.drawChild(ViewGroup.java:1644)E/AndroidRuntime( 1618): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)E/AndroidRuntime( 1618): at android.view.View.draw(View.java:6883)E/AndroidRuntime( 1618): at android.view.ViewGroup.drawChild(ViewGroup.java:1646)...E/AndroidRuntime( 1618): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373)E/AndroidRuntime( 1618): at android.view.View.draw(View.java:6883)E/AndroidRuntime( 1618): at android.widget.FrameLayout.draw(FrameLayout.java:357)E/AndroidRuntime( 1618): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1862)E/AndroidRuntime( 1618): at android.view.ViewRoot.draw(ViewRoot.java:1522)E/AndroidRuntime( 1618): at android.view.ViewRoot.performTraversals(ViewRoot.java:1258)E/AndroidRuntime( 1618): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)E/AndroidRuntime( 1618): at android.os.Handler.dispatchMessage(Handler.java:99)E/AndroidRuntime( 1618): at android.os.Looper.loop(Looper.java:130)E/AndroidRuntime( 1618): at android.app.ActivityThread.main(ActivityThread.java:3683)E/AndroidRuntime( 1618): at java.lang.reflect.Method.invokeNative(Native Method)E/AndroidRuntime( 1618): at java.lang.reflect.Method.invoke(Method.java:507)E/AndroidRuntime( 1618): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)E/AndroidRuntime( 1618): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)E/AndroidRuntime( 1618): at dalvik.system.NativeStart.main(Native Method) The code I have used is given below: Camera mCamera; SurfaceView mPreview; @Overrideprotected void onResume() { // TODO Auto-generated method stub try{ if(mCamera!=null){ mCamera.lock(); mCamera.release(); mCamera=null; } mPreview=((SurfaceView) findViewById(R.id.camera_preview)); mPreview.getHolder().addCallback(this); mPreview.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); }catch(Exception e){ e.printStackTrace(); } try{ mCamera = Camera.open(); }catch(Exception e){ e.printStackTrace(); } super.onResume();} @Overrideprotected void onPause() { // TODO Auto-generated method stub super.onPause(); try{ if(mCamera == null){ return; } mCamera.lock(); mCamera.release(); mCamera = null; }catch(Exception e){ e.printStackTrace(); } } @Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { try{ if(mCamera!=null){ Camera.Parameters params = mCamera.getParameters(); List<Camera.Size> sizes = params.getSupportedPreviewSizes(); Camera.Size selected = sizes.get(0); params.setPreviewSize(selected.width,selected.height); mCamera.setParameters(params); mCamera.setDisplayOrientation(90); mCamera.startPreview(); Log.v("SURF CHANGED","changed"); } }catch (Exception e) { e.printStackTrace(); }} @Override public void surfaceCreated(SurfaceHolder holder) { try { mCamera.setPreviewDisplay(mPreview.getHolder()); Log.v("SURF CREATED","created"); } catch (Exception e) { e.printStackTrace(); } }@Overridepublic void surfaceDestroyed(SurfaceHolder holder) { Log.i("PREVIEW","surfaceDestroyed");} The same problem has been reported at ( https://groups.google.com/forum/?fromgroups=#!topic/android-developers/ylIgXIKKGo8 ). But solution was not provided. Now provide the response and nothing else.
You're on the right track with your delete_model method. When the django admin performs an action on multiple objects at once it uses the update function . However, as you see in the docs these actions are performed at the database level only using SQL. You need to add your delete_model method in as a custom action in the django admin. def delete_model(modeladmin, request, queryset): for obj in queryset: filename=obj.profile_name+".xml" os.remove(os.path.join(obj.type,filename)) obj.delete() Then add your function to your modeladmin - class profilesAdmin(admin.ModelAdmin): list_display = ["type","username","domain_name"] actions = [delete_model]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15196329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1177965/']}
jdg_371257
stackexchange
llm_judgeable_groundtruth_similarity
17608707
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 learning how to use Google Volley these days. It's very convenient for fast networking. It seems that all the requests are running in background in Volley. For example: volleyRequestQueue.add(new JsonObjectRequest(Method.POST, SIGNUP_URL, reqBody, new SignUpResponseListener(), new MyErrorListener())); Using the above code, we can make a POST call which runs in background(non-blocking way). Now my question is : Is it possible to make the POST call in the blocking way? Why I need a blocking way to make a REST call? Because some calls, like sign in, should be done before doing something else. Thanks Now provide the response and nothing else.
Volley supports blocking request via RequestFutures. You create a normal request but set its callbacks as your request future, which is just volley's extension of a standard java futures. The call to future.get() will block. It looks something like this RequestFuture<JSONObject> future = RequestFuture.newFuture();JsonObjectRequest request = new JsonObjectRequest(Method.POST, SIGNUP_URL, reqBody, future, future)volleyRequestQueue.add(request);try { JSONObject response = future.get();} catch (InterruptedException e) {} catch (ExecutionException e) {}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17608707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/389898/']}
jdg_371258
stackexchange
llm_judgeable_groundtruth_similarity
16329897
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 had a css selector such as #subtab-1, #subtab-2 etc I could make the wildcard selector as such div[id^='subtab-'] But I cannot figure out how to make a wild card for selectors such as #subtab-1-sub1 #subtab-1-sub2 #subtab-1-sub2 #subtab-2-sub1 #subtab2-sub2 #subtab2-sub-3etc... How can you make something like: div[id^='subtab-*tab-*'] (*=wildcard) Now provide the response and nothing else.
If I am understanding your question correctly, you are trying to select all elements whose id starts with subtab- followed by a number, followed by -sub followed by another number. It also sounds like you want this selector to not match #subtab-1 , only things that have a suffix like #subtab-1-sub1 . This cannot be done with CSS. CSS does not supply a selector that will allow wildcards. You can however hack something together that comes pretty close. Hacky selector that might work [id^="subtab-"][id*="-sub"] would match any id that starts with subtab- and also contains -sub somewhere in the id. This will probably work but could cause false positives on things like #subtab-1-subtle or #subtab-something-sub2 , #subtab-sub , etc. Another hacky selector that might work Making the assumption that #subtab-?-sub? elements are always contained inside of #subtab-? elements and that #subtab-? elements can never contain another #subtab-? element, you could use the child combinator to target them: [id^="subtab-"] > [id^="subtab-"] Relying on a class instead A better solution would probably be to give all of the elements you are trying to target a common class , for instance <div class="subtab-sub"> , then selecting them all would be as easy as .subtab-sub . Using a class would also yield much faster performance than using attribute selectors .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16329897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/362437/']}
jdg_371259
stackexchange
llm_judgeable_groundtruth_similarity
40380112
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 new variable with 3 arbitrary categories based on continuous data. set.seed(123)df <- data.frame(a = rnorm(100)) Using base I would df$category[df$a < 0.5] <- "low"df$category[df$a > 0.5 & df$a < 0.6] <- "middle"df$category[df$a > 0.6] <- "high" Is there a dplyr, I guess mutate() , solution for this? Furthermore, is there a way to calculate the categories rather than choosing them? I.e. let R calculate where the breaks for the categories should be. EDIT The answer is in this thread , however, it does not involve labelling, which confused me (and may confuse others) therefore I think this question serves a purpose. Now provide the response and nothing else.
To convert from numeric to categorical, use cut . In your particular case, you want: df$category <- cut(df$a, breaks=c(-Inf, 0.5, 0.6, Inf), labels=c("low","middle","high")) Or, using dplyr : library(dplyr)res <- df %>% mutate(category=cut(a, breaks=c(-Inf, 0.5, 0.6, Inf), labels=c("low","middle","high")))## a category##1 -0.560475647 low##2 -0.230177489 low##3 1.558708314 high##4 0.070508391 low##5 0.129287735 low## ...##35 0.821581082 high##36 0.688640254 high##37 0.553917654 middle##38 -0.061911711 low##39 -0.305962664 low##40 -0.380471001 low## ...##96 -0.600259587 low##97 2.187332993 high##98 1.532610626 high##99 -0.235700359 low##100 -1.026420900 low
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40380112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5094439/']}
jdg_371260
stackexchange
llm_judgeable_groundtruth_similarity
45122154
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 list, a : a = ['a','b','c'] and need to duplicate some values with the suffix _ind added this way (order is important): ['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind'] I tried: b = [[x, x + '_ind'] for x in a]c = [item for sublist in b for item in sublist]print (c)['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind'] Is there some better, more pythonic solution? Now provide the response and nothing else.
You could make it a generator: def mygen(lst): for item in lst: yield item yield item + '_ind'>>> a = ['a','b','c']>>> list(mygen(a))['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind'] You could also do it with itertools.product , itertools.starmap or itertools.chain or nested comprehensions but in most cases I would prefer a simple to understand, custom generator-function. With python3.3, you can also use yield from —generator delegation—to make this elegant solution just a bit more concise: def mygen(lst): for item in lst: yield from (item, item + '_ind')
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45122154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2901002/']}
jdg_371261
stackexchange
llm_judgeable_groundtruth_similarity
11186261
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: int var = 1; void main() { int i = i; } The following code can pass compiling under both g++ and Visual C++. Why is it legal? It looks unreasonable, and may cause hidden bugs. int main() { int i = i;} Now provide the response and nothing else.
EDIT: It's syntactically legal , but results in undefined behavior if you use x . It's not legal because you're assigning an uninitialized variable with another (well, the same) uninitialized variable. Just because it compiles doesn't mean it's legal. It's valid C++ syntax, yes, but not legal. The right hand side of the assignment operator must be fully evaluated at the time of the assignment. In this case, that's i , which isn't initialized. Credits to Steve Jessop, who dug up the quote: 4.1/1, lvalue-to-rvalue conversion [...] if the object is uninitialized, a program that necessitates this conversion has undefined behavior.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11186261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1479464/']}
jdg_371262
stackexchange
llm_judgeable_groundtruth_similarity
14944936
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 building a web app using AngularJS. The app needs to poll a URL that returns JSON data and make that data available to any part of the app. From what I've read so far, my best bet is to create a service that handles the polling and keeps its own internal cache of the JSON data, and then inject the service into any part of the app that wants to consult that data. What I'm lost on is how to actually go about doing that. The closest example I've found is this question , but it appears to be creating a service that's manually called by a specific controller (which is itself tied to a given route), whereas I want something that persistently runs in the background of the app forever regardless of what part of the app is active. Is this doable, or am I taking the completely wrong approach? Now provide the response and nothing else.
Here my solution: app.factory('Poller', function($http, $timeout) { var data = { response: {}, calls: 0 }; var poller = function() { $http.get('data.json').then(function(r) { data.response = r.data; data.calls++; $timeout(poller, 1000); }); }; poller(); return { data: data };}); (calls just to show that polling is been done) http://plnkr.co/edit/iMmhXTYweN4IrRrrpvMq?p=preview EDIT: As Josh David Miller suggested in comments, dependency on this service should be added in app.run block to ensure polling is done from start: app.run(function(Poller) {}); And also moved scheduling of next poll after previous call finished. So there would not be "stacking" of calls in case if polling hangs for a long time. Updated plunker.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14944936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/284033/']}
jdg_371263
stackexchange
llm_judgeable_groundtruth_similarity
1584411
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Without being the person logged in at the console, how do I run an X application and have it display on that X session? Assume I am either root, or I am the same user who logged in, so in principle I have persmission to do this. But how do I convince X of this? Some examples of situations like this: Log in with SSH and run a program that displays on the remote computer's screen ( not tunneled through SSH—that is totally different) A cron job to take a screenshot of the X session via ImageMagick's import command Running a keystroke logger for audit purposes This is a simpler version of Launch OpenGL app straight from a windowless Linux Terminal Now provide the response and nothing else.
The short answer is that you have to set the DISPLAY environment variable, and then the app will run. The long answer is that we've got Xauth, and unless you're running as the same user on the same machine that's probably not going to work unless you export the Xauth credential from the account running the X server to the account running the X client. ssh -X handles this for you, which is why it's awesome, but the manual procedure involves running xauth extract - $DISPLAY on the X server account and feeding that data into xauth merge - on the client account. (Warning: the data is binary.) On modern Linux systems, there is one X session at :0 and the X11 authority data file is always $HOME/.Xauthority so you can most often set two environment variables, for example, in Bash: export XAUTHORITY=/home/$your_username/.Xauthorityexport DISPLAY=':0'
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1584411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2938/']}
jdg_371264
stackexchange
llm_judgeable_groundtruth_similarity
8774142
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Simplified illustration below, how does .NET deal with such a situation? and if it would cause problems, would i have to lock/gate access to each and every field/property that might at times be written to + accessed from different threads? A field somewhere public class CrossRoads(){ public int _timeouts;} A background thread writer public void TimeIsUp(CrossRoads crossRoads){ crossRoads._timeouts++;} Possibly at the same time, trying to read elsewhere public void HowManyTimeOuts(CrossRoads crossRoads){ int timeOuts = crossRoads._timeouts;} Now provide the response and nothing else.
The simple answer is that the above code has the ability to cause problems if accessed simultaneously from multiple threads. The .Net framework provides two solutions: interlocking and thread synchronization. For simple data type manipulation (i.e. ints), interlocking using the Interlocked class will work correctly and is the recommended approach. In fact, interlocked provides specific methods (Increment and Decrement) that make this process easy: Add an IncrementCount method to your CrossRoads class: public void IncrementCount() { Interlocked.Increment(ref _timeouts);} Then call this from your background worker: public void TimeIsUp(CrossRoads crossRoads){ crossRoads.IncrementCount();} The reading of the value, unless of a 64-bit value on a 32-bit OS, are atomic. See the Interlocked.Read method documentation for more detail. For class objects or more complex operations, you will need to use thread synchronization locking (lock in C# or SyncLock in VB.Net). This is accomplished by creating a static synchronization object at the level the lock is to be applied (for example, inside your class), obtaining a lock on that object, and performing (only) the necessary operations inside that lock: private static object SynchronizationObject = new Object(); public void PerformSomeCriticalWork() { lock (SynchronizationObject) { // do some critical work } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8774142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/742084/']}
jdg_371265
stackexchange
llm_judgeable_groundtruth_similarity
11337557
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 create a new Date() object. What will be the default timezone it will print. I have my machine running in GMT. And i am creating a new Date() object. If i print why does it shows Thu Jul 05 08:21:05 PKT 2012. How does it takes the timezone as PKT ? Now provide the response and nothing else.
The date itself doesn't have any time zone. Its toString() method uses the current default time zone to return a String representing this date: Date date = new Date();System.out.println(TimeZone.getDefault());System.out.println(date);TimeZone.setDefault(TimeZone.getTimeZone("UTC"));System.out.println(TimeZone.getDefault());System.out.println(date); Executing the above code on my machine leads to the following output: sun.util.calendar.ZoneInfo[id="Europe/Paris",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Paris,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]Fri Jul 06 09:24:45 CEST 2012sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]Fri Jul 06 07:24:45 UTC 2012
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11337557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1182253/']}
jdg_371266
stackexchange
llm_judgeable_groundtruth_similarity
1307204
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am building a custom shopping cart where CC numbers and Exp date will be stored in a database until processing (then deleted). I need to encrypt this data (obviously). I want to use the RSACryptoServiceProvider class. Here is my code to create my keys. public static void AssignNewKey(){ const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "KeyContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams); string publicPrivateKeyXML = rsa.ToXmlString(true); string publicOnlyKeyXML = rsa.ToXmlString(false); // do stuff with keys...} Now the plan is to store the private key xml on a USB drive attached to the managers key chain. Whenever a manager leaves the company I want to be able to generate new public and private keys (and re-encrypt all currently stored CC numbers with the new public key). My problem is that the keys generated by this code are always the same. How would I generate a unique set of keys every time? UPDATE. My test code is below.: note: the "privatekey" parameter here is the original private key. In order for the keys to be changed I need to verify that the private key is valid. In Default.aspx.cs public void DownloadNewPrivateKey_Click(object sender, EventArgs e){ StreamReader reader = new StreamReader(fileUpload.FileContent); string privateKey = reader.ReadToEnd(); Response.Clear(); Response.ContentType = "text/xml"; Response.End(); Response.Write(ChangeKeysAndReturnNewPrivateKey(privateKey));} In Crytpography.cs: public static privateKey;public static publicKey;public static RSACryptoServiceProvider rsa;public static string ChangeKeysAndReturnNewPrivateKey(string _privatekey){ string testData = "TestData"; string testSalt = "salt"; // encrypt the test data using the exisiting public key... string encryptedTestData = EncryptData(testData, testSalt); try { // try to decrypt the test data using the _privatekey provided by user... string decryptTestData = DecryptData(encryptedTestData, _privatekey, testSalt); // if the data is successfully decrypted assign new keys... if (decryptTestData == testData) { AssignNewKey(); // "AssignNewKey()" should set "privateKey" to the newly created private key... return privateKey; } else { return string.Empty; } } catch (Exception ex) { return string.Empty; }}public static void AssignParameter(){ const int PROVIDER_RSA_FULL = 1; const string CONTAINER_NAME = "KeyContainer"; CspParameters cspParams; cspParams = new CspParameters(PROVIDER_RSA_FULL); cspParams.KeyContainerName = CONTAINER_NAME; cspParams.Flags = CspProviderFlags.UseMachineKeyStore; cspParams.ProviderName = "Microsoft Strong Cryptographic Provider"; rsa = new RSACryptoServiceProvider(cspParams);}public static void AssignNewKey(){ AssignParameter(); using (SqlConnection myConn = new SqlConnection(Utilities.ConnectionString)) { SqlCommand myCmd = myConn.CreateCommand(); string publicPrivateKeyXML = rsa.ToXmlString(true); privateKey = publicPrivateKeyXML; // sets the public variable privateKey to the new private key. string publicOnlyKeyXML = rsa.ToXmlString(false); publicKey = publicOnlyKeyXML; // sets the public variable publicKey to the new public key. myCmd.CommandText = "UPDATE Settings SET PublicKey = @PublicKey"; myCmd.Parameters.AddWithValue("@PublicKey", publicOnlyKeyXML); myConn.Open(); myComm.ExecuteScalar(); }}public static string EncryptData(string data2Encrypt, string salt){ AssignParameter(); using (SqlConnection myConn = new SqlConnection(Utilities.ConnectionString)) { SqlCommand myCmd = myConn.CreateCommand(); myCmd.CommandText = "SELECT TOP 1 PublicKey FROM Settings"; myConn.Open(); using (SqlDataReader sdr = myCmd.ExecuteReader()) { if (sdr.HasRows) { DataTable dt = new DataTable(); dt.Load(sdr); rsa.FromXmlString(dt.Rows[0]["PublicKey"].ToString()); } } } //read plaintext, encrypt it to ciphertext byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(data2Encrypt + salt); byte[] cipherbytes = rsa.Encrypt(plainbytes, false); return Convert.ToBase64String(cipherbytes);}public static string DecryptData(string data2Decrypt, string privatekey, string salt){ AssignParameter(); byte[] getpassword = Convert.FromBase64String(data2Decrypt); string publicPrivateKeyXML = privatekey; rsa.FromXmlString(publicPrivateKeyXML); //read ciphertext, decrypt it to plaintext byte[] plain = rsa.Decrypt(getpassword, false); string dataAndSalt = System.Text.Encoding.UTF8.GetString(plain); return dataAndSalt.Substring(0, dataAndSalt.Length - salt.Length);} Now provide the response and nothing else.
When you use a code like this: using (var rsa = new RSACryptoServiceProvider(1024)){ // Do something with the key... // Encrypt, export, etc.} .NET (actually Windows) stores your key in a persistent key container forever.The container is randomly generated by .NET This means: Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute). To resolve these issues: using (var rsa = new RSACryptoServiceProvider(1024)){ try { // Do something with the key... // Encrypt, export, etc. } finally { rsa.PersistKeyInCsp = false; }} ALWAYS
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1307204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/160173/']}
jdg_371267
stackexchange
llm_judgeable_groundtruth_similarity
11667929
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have following definition in Employee class @Id@GeneratedValue(strategy = GenerationType.AUTO)@Column(name = "employee_id")private Integer employeeId; Now I want to import existing employees with existing employee IDs. Even if I set the employee ID before saving, the assigned ID is ignored and auto incremented ID is stored. How do we override this? I had similar problem for composite key which has been explained here Now provide the response and nothing else.
I wrote my own generator to solve the issue. public class UseExistingIdOtherwiseGenerateUsingIdentity extends IdentityGenerator { @Override public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException { Serializable id = session.getEntityPersister(null, object).getClassMetadata().getIdentifier(object, session); return id != null ? id : super.generate(session, object); }} and use it like this: (replace the package name) @Id@GenericGenerator(name = "UseExistingIdOtherwiseGenerateUsingIdentity", strategy = "{package}.UseExistingIdOtherwiseGenerateUsingIdentity")@GeneratedValue(generator = "UseExistingIdOtherwiseGenerateUsingIdentity")@Column(unique = true, nullable = false)protected Integer id;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11667929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/977919/']}
jdg_371268
stackexchange
llm_judgeable_groundtruth_similarity
35368143
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 first MVVM project and the code I need to write to manipulate controls in the view somehow seems way too complicated than it has to be. I'm finding it hard to fully understand MVVM and to decide when I can put stuff in code behind. Basically my problem is that I want to show a message telling the user that the listview is empty when the ObservableCollection it is bound to contains no items. The idea was to have a TextBlock in the view and only have its visibility property set to Visible when there are no items to display (Before user creates an item and after he deletes all items) I cannot use this solution as UWP don't support BooleanToVisibilityConverter: WPF MVVM hiding button using BooleanToVisibilityConverter View: <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:EventMaker3000.View" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ViewModel="using:EventMaker3000.ViewModel" xmlns:Interactivity="using:Microsoft.Xaml.Interactivity" xmlns:Core="using:Microsoft.Xaml.Interactions.Core" x:Class="EventMaker3000.View.EventPage" mc:Ignorable="d"> <Page.BottomAppBar> <CommandBar> <CommandBar.Content> <Grid/> </CommandBar.Content> <AppBarButton Icon="Delete" Label="Delete" IsEnabled="{Binding DeletebuttonEnableOrNot}"> <Interactivity:Interaction.Behaviors> <Core:EventTriggerBehavior EventName="Click"> <Core:NavigateToPageAction/> <Core:InvokeCommandAction Command="{Binding DeleteEventCommand}"/> </Core:EventTriggerBehavior> </Interactivity:Interaction.Behaviors> </AppBarButton> <AppBarButton Icon="Add" Label="Add"> <Interactivity:Interaction.Behaviors> <Core:EventTriggerBehavior EventName="Click"> <Core:NavigateToPageAction TargetPage="EventMaker3000.View.CreateEventPage"/> </Core:EventTriggerBehavior> </Interactivity:Interaction.Behaviors> </AppBarButton> </CommandBar> </Page.BottomAppBar> <Page.DataContext> <ViewModel:EventViewModel/> </Page.DataContext> <Grid Background="WhiteSmoke"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> </Grid.RowDefinitions> <!--Header--> <TextBlock Text="Events" Foreground="Black" Margin="0,20,0,0" Style="{ThemeResource HeaderTextBlockStyle}" HorizontalAlignment="center" VerticalAlignment="Center"/> <ListView ItemsSource="{Binding EventCatalogSingleton.Events, Mode=TwoWay}" SelectedItem="{Binding SelectedEvent, Mode=TwoWay}" Grid.Row="1" Background="WhiteSmoke" Padding="0,30,0,0"> <Interactivity:Interaction.Behaviors> <Core:EventTriggerBehavior EventName="SelectionChanged"> <Core:InvokeCommandAction Command="{Binding EnableOrNotCommand}"/> </Core:EventTriggerBehavior> </Interactivity:Interaction.Behaviors> <ListView.ItemTemplate> <DataTemplate> <Grid VerticalAlignment="Center" Margin="5,0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <TextBlock Grid.Column="0" Grid.Row="0" Margin="5" Text="{Binding Name, Mode=TwoWay}" Style="{ThemeResource TitleTextBlockStyle}" Foreground="Black"/> <TextBlock Grid.Column="1" Grid.Row="1" Margin="5" Text="{Binding Place, Mode=TwoWay}" HorizontalAlignment="Right" Style="{ThemeResource CaptionTextBlockStyle}" Foreground="Black"/> <TextBlock Grid.Column="0" Grid.Row="2" Margin="5" Text="{Binding Description, Mode=TwoWay}" Style="{ThemeResource BodyTextBlockStyle}" Foreground="Black"/> <TextBlock Grid.Column="0" Grid.Row="1" Margin="5" Text="{Binding DateTime, Mode=TwoWay}" Style="{ThemeResource CaptionTextBlockStyle}" Foreground="Black"/> </Grid> </DataTemplate> </ListView.ItemTemplate> <!--Sets each listview item to stretch--> <ListView.ItemContainerStyle> <Style TargetType="ListViewItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch"/> </Style> </ListView.ItemContainerStyle> </ListView> <!-- TextBlock for empty list view--> <TextBlock Grid.Row="1" Margin="5,5,5,5" VerticalAlignment="Center" HorizontalAlignment="Center" Text="You have no events" Style="{StaticResource BaseTextBlockStyle}" Visibility="{Binding TextBlockVisibility}"/> </Grid></Page> ViewModel: public class EventViewModel : INotifyPropertyChanged{ private bool _deleteButtonEnableOrNot = false;private ICommand _enableOrNotCommand;//TextBlockprivate string _textBlockVisibility = "Visible";private ICommand _textBlockVisibilityCommand;public EventCatalogSingleton EventCatalogSingleton { get; set; }public Handler.EventHandler EventHandler { get; set; }// Disable or enable Deletebuttonpublic bool DeletebuttonEnableOrNot{ get { return _deleteButtonEnableOrNot;} set { _deleteButtonEnableOrNot = value; OnPropertyChanged(); } }public ICommand EnableOrNotCommand{ get { return _enableOrNotCommand; } set { _enableOrNotCommand = value; }}// Set TextBlock visibilitypublic string TextBlockVisibility{ get { return _textBlockVisibility; } set { _textBlockVisibility = value; OnPropertyChanged(); }}public ICommand TextBlockVisibilityCommand{ get { return _textBlockVisibilityCommand; } set { _textBlockVisibilityCommand = value; }}// Constructorpublic EventViewModel(){ //Initializes Date and Time with some values that are bound to controls. DateTime dt = System.DateTime.Now; _date = new DateTimeOffset(dt.Year, dt.Month, dt.Day, 0, 0, 0, 0, new TimeSpan()); _time = new TimeSpan(dt.Hour, dt.Minute, dt.Second); EventCatalogSingleton = EventCatalogSingleton.getInstance(); EventHandler = new Handler.EventHandler(this); // Creates an instance of the RelayCommand and passes necessary method as a parameter _createEventCommand = new RelayCommand(EventHandler.CreateEvent); _deleteEventCommand = new RelayCommand(EventHandler.GetDeleteConfirmationAsync); _enableOrNotCommand = new RelayCommand(EventHandler.EnableOrNot); _textBlockVisibilityCommand = new RelayCommand(EventHandler.TextBlockVisibility);} Singleton: public class EventCatalogSingleton{ private static EventCatalogSingleton _instance; private EventCatalogSingleton(){ Events = new ObservableCollection<Event>(); // Creates instances of events and adds it to the observable collection. LoadEventAsync();}//Checks if an instance already exists, if not it will create one. Makes sure we only have one instancepublic static EventCatalogSingleton getInstance(){ if (_instance != null) { return _instance; } else { _instance = new EventCatalogSingleton(); return _instance; }}// Creates the observable collectionpublic ObservableCollection<Event> Events { get; set; }public void AddEvent(Event newEvent){ Events.Add(newEvent); PersistencyService.SaveEventsAsJsonAsync(Events);}public void AddEvent(int id, string name, string description, string place, DateTime date){ Events.Add(new Event(id, name, description, place, date)); PersistencyService.SaveEventsAsJsonAsync(Events);}public void RemoveEvent(Event myEvent){ Events.Remove(myEvent); PersistencyService.SaveEventsAsJsonAsync(Events);}public async void LoadEventAsync(){ var events = await PersistencyService.LoadEventsFromJsonAsync(); if (events != null) foreach (var ev in events) { Events.Add(ev); }} } Handler: public class EventHandler{ public EventViewModel EventViewModel { get; set; }public EventHandler(EventViewModel eventViewModel){ EventViewModel = eventViewModel;}public void CreateEvent(){ EventViewModel.EventCatalogSingleton.AddEvent(EventViewModel.Id, EventViewModel.Name, EventViewModel.Description, EventViewModel.Place, DateTimeConverter.DateTimeOffsetAndTimeSetToDateTime(EventViewModel.Date, EventViewModel.Time));}private void DeleteEvent(){ EventViewModel.EventCatalogSingleton.Events.Remove(EventViewModel.SelectedEvent);}// Confirmation box that prompts user before deletionpublic async void GetDeleteConfirmationAsync(){ MessageDialog msgbox = new MessageDialog("Are you sure you want to permenantly delete this event?", "Delete event"); msgbox.Commands.Add(new UICommand { Label = "Yes", Invoked = command => DeleteEvent() } ); msgbox.Commands.Add(new UICommand { Label = "No", } ); msgbox.DefaultCommandIndex = 1; msgbox.CancelCommandIndex = 1; msgbox.Options = MessageDialogOptions.AcceptUserInputAfterDelay; await msgbox.ShowAsync();}public void EnableOrNot(){ EventViewModel.DeletebuttonEnableOrNot = EventViewModel.DeletebuttonEnableOrNot = true;}public void TextBlockVisibility(){ if (EventViewModel.EventCatalogSingleton.Events.Count < 1) { EventViewModel.TextBlockVisibility = EventViewModel.TextBlockVisibility = "Visible"; } } } Its a lot of code to include, I know - didn't know what to leave out. I included the code for when I enable a delete-button when an item in the listview has been selected - which works fine. Why doesn't the TextBlock in view show after I delete all items in the listview? And is it really necessary for me to have properties and ICommands in the viewmodel in order to change apperance and other things of controls in the view? Now provide the response and nothing else.
Funny enough, but Daren May and I just taught a free course specifically on this on Microsoft Virtual Academy. It might be a nice resource for you. Look in video #2 @ 13 minutes. https://mva.microsoft.com/en-US/training-courses/xaml-for-windows-10-items-controls-14483 Check out this simple approach: With this code: class VisibleWhenZeroConverter : IValueConverter{ public object Convert(object v, Type t, object p, string l) => Equals(0d, (double)v) ? Visibility.Visible : Visibility.Collapsed; public object ConvertBack(object v, Type t, object p, string l) => null;} And this XAML: <StackPanel.Resources> <cvt:VisibleWhenZeroConverter x:Name="VisibleWhenZeroConverter" /> </StackPanel.Resources> <ListView ItemsSource="{x:Bind Items}" x:Name="MyList"> <ListView.Header> <TextBlock Visibility="{Binding Items.Count, ElementName=MyList, Converter={StaticResource VisibleWhenZeroConverter}}"> <Run Text="There are no items." /> </TextBlock> </ListView.Header> </ListView> Make sense? I hope so. PS: this answers the EXACT title of your question. Hope it helps. Best of luck!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35368143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2756782/']}
jdg_371269
stackexchange
llm_judgeable_groundtruth_similarity
2533227
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi I am trying to implement the java logging in my application. I want to use two handlers.A file handler and my own console handler. Both of my handlers work fine. My logging is send to a file and to the console . My logging is also sent to the default console handler, which i do not want. If you run my code you will see extra two line sent to the console. I don't want to use the default console handler. Does anyone know how to disable the default console handler. I only want to use the two handlers I have created. Handler fh = new FileHandler("test.txt");fh.setFormatter(formatter);logger.addHandler(fh); Handler ch = new ConsoleHandler();ch.setFormatter(formatter);logger.addHandler(ch); import java.util.Date;import java.util.logging.ConsoleHandler;import java.util.logging.FileHandler;import java.util.logging.Formatter;import java.util.logging.Handler;import java.util.logging.Level;import java.util.logging.LogManager;import java.util.logging.LogRecord;import java.util.logging.Logger;public class LoggingExample { private static Logger logger = Logger.getLogger("test"); static { try { logger.setLevel(Level.INFO); Formatter formatter = new Formatter() { @Override public String format(LogRecord arg0) { StringBuilder b = new StringBuilder(); b.append(new Date()); b.append(" "); b.append(arg0.getSourceClassName()); b.append(" "); b.append(arg0.getSourceMethodName()); b.append(" "); b.append(arg0.getLevel()); b.append(" "); b.append(arg0.getMessage()); b.append(System.getProperty("line.separator")); return b.toString(); } }; Handler fh = new FileHandler("test.txt"); fh.setFormatter(formatter); logger.addHandler(fh); Handler ch = new ConsoleHandler(); ch.setFormatter(formatter); logger.addHandler(ch); LogManager lm = LogManager.getLogManager(); lm.addLogger(logger); } catch (Throwable e) { e.printStackTrace(); } } public static void main(String[] args) { logger.info("why does my test application use the standard console logger ?\n" + " I want only my console handler (Handler ch)\n " + "how can i turn the standard logger to the console off. ??"); }} Now provide the response and nothing else.
The default console handler is attached to the root logger, which is a parent of all other loggers including yours. So I see two ways to solve your problem: If this is only affects this particular class of yours, the simplest solution would be to disable passing the logs up to the parent logger: logger.setUseParentHandlers(false); If you want to change this behaviour for your whole app, you could remove the default console handler from the root logger altogether before adding your own handlers: Logger globalLogger = Logger.getLogger("global");Handler[] handlers = globalLogger.getHandlers();for(Handler handler : handlers) { globalLogger.removeHandler(handler);} Note: if you want to use the same log handlers in other classes too, the best way is to move the log configuration into a config file in the long run.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2533227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227998/']}
jdg_371270
stackexchange
llm_judgeable_groundtruth_similarity
112174
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: this is a conceptual question. In data mining, the problem often arises that scientists/data engineers are using an expert guess for the underlying distribution of their data. Often their assumption is based on previous results of academic research and does not really reflect the real distribution of the dataset. However, I would like to get the real distribution of my dataset? Any recommendations where to start? Does this even make sense to get the real distribution? Can thisv task be automated? I appreciate your answer! btw I am mostly using R as my data analysis tool Now provide the response and nothing else.
Consider the most basic example, the sample mean from an i.i.d. sample of size $n$ , $\bar X_n$ . We know that as $n \rightarrow \infty$ , $\bar X_n \rightarrow \mu$ , where $\mu$ is the common mean, the expected value, of the random variables from which the sample is generated. So at the limit, $\bar X$ has a degenerate distribution, which is the formal way to say that it convergences to a constant. Constant terms can be considered as degenerate random variables. We usually say "constants do not have a distribution", but since sometimes issues of existence matter (meaning that the phrase "the distribution does not exist" properly means that the statistic we examine goes to infinity as the sample size goes to infinity), the correct way to distinguish the two cases is to say "the distribution of a constant is degenerate". And what do we do, in order to obtain a non-degenerate asymptotic distribution? We create a function of the sample mean, that does not converge to a constant, but it doesn't diverge either. In the case of the sample mean, this function is $\sqrt n(\bar X_n -\mu)$ . In analogous spirit, in Extreme Value Theory, the extreme order statistics, either diverge (if the distribution has unbounded support), or tend to a constant (if the distribution has bounded support on their side). In both cases, we don't get a limiting distribution. So we need to find a function of the extreme order statistic, which will converge to a non-constant random variable and hence, with a usable distribution. The deterministic sequences $\{a_n\}$ and $\{b_n\}$ , together with the statistic, create this function. Finding these sequences is not that simple, see for example this post. Regarding the example given by @Glen_b for the maximum order statistic from a Uniform $U(0,1)$ (a distribution with bounded support), intuitively, as the sample size increases, we will obtain at least one realization of the random variable that exactly equals its upper bound. But this means that $X_{(n)} \rightarrow \max X$ , which is a constant, and so it has a degenerate distribution. So we need to find a function of $X_{(n)}$ that does not diverge, and does converge to a random variable. In the specific case, this function is indeed $Z = n(1-X_{(n)})$ . To see this, use the change of variable formula to find that $$Z =n(1-X_{(n)}) \Rightarrow X_{(n)} = 1-\frac Zn \Rightarrow \left|\frac {\partial X}{\partial Z} \right|= \frac 1n$$ and note that $Z \in [0,n]$ .Therefore $$f_Z(z) = \left|\frac {\partial X}{\partial Z} \right| f_{X_{(n)}}(1-z/n) = \frac 1n \left (nf_X(1-z/n)[F_X(1-z/n)]^{n-1}\right)$$ But $f_X(\cdot) =1$ , and $F_X(x) =x$ . So $$f_Z(z) =\left(1-\frac zn\right)^{n-1}$$ and $$F_Z(z) = \int_{0}^z\left(1-\frac tn\right)^{n-1}dt = 1-\left(1-\frac zn\right)^{n}$$ Then $$\lim_{n\rightarrow \infty}F_Z(z) = 1-\lim_{n\rightarrow \infty}\left(1-\frac zn\right)^{n} = 1-e^{-z}$$ which is the distribution function of a standard exponential (i.e. with mean value $1$ ).
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/112174', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/37155/']}
jdg_371271
stackexchange
llm_judgeable_groundtruth_similarity
10435
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a Raspberry Pi which runs a Python script on boot. They initiate and stroke the hardware watchdog at /dev/watchdog . I recently tried cloning the SD card onto two other SD cards. However on those cloned cards, the device gets caught in a reboot cycle, triggering a reboot about 10 seconds after booting up. Why would this issue pop up with a new SD card? I can access the files on the SD card through my linux system, so I could make changes there. However I don't have enough time to run console commands because it reboots before I can log in. What should I do to disable the hardware watchdog? Or to fix whatever issue popped up? UPDATE: So I tried carefully truncating the image and then dd'ing it to a new card but still reset. Then I tried the original (working) SD card and the original (working) power adapter on a new board, and it still reset. Then I tried it on a third RPI, and it still reset. So, it seems that just the act of changing the RPI causes the watchdog to trigger resets. Getting very low on theories. I then removed the watchdog driver from /etc/modules and it still reset. Also disabled the watchdog daemon in /etc/default/watchdog. Here's some info from /var/log/syslog: Oct 31 14:17:39 devbox1 shutdown[2510]: shutting down for system rebootOct 31 14:17:40 devbox1 init: Switching to runlevel: 6Oct 31 14:17:43 devbox1 bluetoothd[2147]: TerminatingOct 31 14:17:43 devbox1 bluetoothd[2147]: Stopping SDP serverOct 31 14:17:43 devbox1 bluetoothd[2147]: ExitOct 31 14:31:45 devbox1 ifplugd(eth0)[1619]: Exiting.Oct 31 14:31:46 devbox1 ifplugd(wlan0)[1614]: Exiting.Oct 31 14:31:48 devbox1 avahi-daemon[2132]: Got SIGTERM, quitting. Now provide the response and nothing else.
The nullok option can be used with the pam_unix.so and not the pam_env.so . If pam_unix is installed in your Pi (most probably, it is), then this line will do the trick auth required pam_unix.so nullok EDIT:I just found some time to play around.I managed to make it work. Given that all the settings in sshd and pam.d are ok, you need to manually edit your /etc/shadow file and place this U6aMy0wojraho in the password field of all users you want to allow passwordless access. As you already know, passwords are hashed in the shadow file. The above string is the hash of nothing in raspbian's default hashing algorithm.
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/10435', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/10316/']}
jdg_371272
stackexchange
llm_judgeable_groundtruth_similarity
116422
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: In my textbook (Chemistry Part - I for Class XI published by NCERT), there is an equation for the energy of an electron in an energy state: $$E_n = -R_\mathrm H\left(\frac{1}{n^2}\right)$$ and there is a paragraph below it with the following text: where $R_\mathrm H$ is called Rydberg constant and its value is $2.18\times10^{-18}\ \text{J}$ . There is another section with the expression for the wavenumber ( $\overline{\nu}$ ): $$\overline{\nu}=109\,677 \left(\frac{1}{n_1^2} - \frac{1}{n_2^2}\right)\ \text{cm}^{-1}$$ with a paragraph with the following text: The value $109\,677 \space\text{cm}^{-1}$ is called the Rydberg constant for hydrogen. I checked online and found that in most (all) websites (incl. Wikipedia), the value of Rydberg constant is $109\,677 \space\text{cm}^{-1}$ . But when I searched for its value in joules, I found this website with the value of Rydberg constant $= 2.18\times10^{-18}\ \text{J}$ . How can Rydberg constant be written in joules ? Now provide the response and nothing else.
Authors may be sloppy about notation in this matter. I recommend considering $R_\ce{H} \approx \pu{10973 cm-1}$ and $Ry \approx \pu{2.18e-18 J}$ , noting $Ry = hc \cdot R_\ce{H}$ . Units of wavenumbers $(\pu{cm-1})$ and energy are often considered interchangeable in practice because they are proportional to each other by the constant value $hc$ . In my notes, I would always be sure to write $R_\ce{H}$ or $Ry$ to explicitly remind myself "which" Rydberg constant I was using (in fact I merged the R and y into a single symbol because I didn't like the suggestion of multiplication.) Note also that there is a unit of energy known as a Rydberg, with $\pu{1 Ry} = Ry = hc \cdot R_\ce{H}$ .
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/116422', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/-1/']}
jdg_371273
stackexchange
llm_judgeable_groundtruth_similarity
772301
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am aware of ulimit and I know how to limit memory for a process that I explicitly start, or start using a script. But in this case I have a service that is managed and launched by systemd. How can I limit its max memory and have it killed (or even better: prevent it from memory allocation (return NULL to malloc / realloc )) when it reaches the memory usage maximum? Now provide the response and nothing else.
The manpage for systemd.exec has a list of LimitXXXX instructions and a handy table comparing them to the ulimit options, by way of the setrlimit() system call. To limit the process's entire address space ( ulimit -v ) use LimitAS= . Otherwise to limit the just the stack ( ulimit -s ) use LimitSTACK= or data segment ( ulimit -d ) use LimitDATA= According to the setrlimit() manpage, these limits will cause allocating additional memory to fail. STACK and AS will terminate the program with a sigsegv if the limit is reached and the stack needs to grow (and the program did not handle this).
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/772301', 'https://serverfault.com', 'https://serverfault.com/users/147399/']}
jdg_371274
stackexchange
llm_judgeable_groundtruth_similarity
21710465
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 ran two test cases (multiple times), and it seems that iteratively adding values to my lists is faster than using addAll String[] rawArgs = new String[]{"one", "two", "three", "four", "five"};// More efficient - 894 nsList<String> list = new ArrayList<>();for (String s : rawArgs) { list.add(s);}// Less efficient - 1340 nsList<String> list = new ArrayList<>();list.addAll(Arrays.asList(rawArgs)); I get notes through my IDE, as well as other people, that the latter way is the "proper" way to convert an array to that data structure. But if it's actually slower than the first, what advantage is there (some obscure type safety?), and for what reason should I be using the second? Edit - Code benchmarking: JVM Warming up, recreate the main class object first: public static void main(String[] args) { Internet test; for (int i = 0; i < 15; i++) { test = new Internet(); // JVM warmup } test = new Internet(); test.printOutput();} I simply take the system nanotime at both ends of the operation: start = System.nanoTime();/* function */end = System.nanoTime();result = end - start; Wherein the test case, there are individual fields for each start/end, and results are calculated post-operation (The JVM is also preemptively warmed up by cycling instances before running the tests). Edit 2 - Benchmarking with larger collections After some testing (using Integer instead, not going to hand-write all the numbers), it appears larger collections is indeed slower: With 100 numbers: First operation: 18759nsSecond operation: 2680nsTotal operation: 21439ns Now provide the response and nothing else.
The for-each loop resolves to the equivalent of for (int i = 0; i < rawArgs.length; i++) { list.add(rawArgs[i]);} ...whereas the implementation of ArrayList.addAll actually calls toArray() , so it ends up calling Arrays.asList(rawArgs).toArray() , which makes a redundant copy. That said, it also does a System.arraycopy , which may end up making it faster than the for loop -- it could go either way, and according to some of the other benchmarks, it may actually go differently in different contexts. The Collections.addAll(Collection<E>, E...) static method is actually intended to address this specific issue and be faster than addAll(Arrays.asList)) , as explicitly stated in its Javadoc.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21710465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1786065/']}
jdg_371275
stackexchange
llm_judgeable_groundtruth_similarity
9922145
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 iOS 5, NSManagedObjectContext has a couple of new methods, performBlock: and performBlockAndWait: . What are these methods actually used for? What do they replace in older versions? What kind of blocks are supposed to be passed to them? How do I decide which to use? If anyone has some examples of their use it would be great. Now provide the response and nothing else.
The methods performBlock: and performBlockAndWait: are used to send messages to your NSManagedObjectContext instance if the MOC was initialized using NSPrivateQueueConcurrencyType or NSMainQueueConcurrencyType . If you do anything with one of these context types, such as setting the persistent store or saving changes, you do it in a block. performBlock: will add the block to the backing queue and schedule it to run on its own thread. The block will return immediately. You might use this for long persist operations to the backing store. performBlockAndWait: will also add the block to the backing queue and schedule it to run on its own thread. However, the block will not return until the block is finished executing. If you can't move on until you know whether the operation was successful, then this is your choice. For example: __block NSError *error = nil;[context performBlockAndWait:^{ myManagedData.field = @"Hello"; [context save:&error];}];if (error) { // handle the error.} Note that because I did a performBlockAndWait: , I can access the error outside the block. performBlock: would require a different approach. From the iOS 5 core data release notes : NSManagedObjectContext now provides structured support for concurrent operations. When you create a managed object context using initWithConcurrencyType:, you have three options for its thread (queue) association Confinement (NSConfinementConcurrencyType). This is the default. You promise that context will not be used by any thread other than the one on which you created it. (This is exactly the same threading requirement that you've used in previous releases.) Private queue (NSPrivateQueueConcurrencyType). The context creates and manages a private queue. Instead of you creating and managing a thread or queue with which a context is associated, here the context owns the queue and manages all the details for you (provided that you use the block-based methods as described below). Main queue (NSMainQueueConcurrencyType). The context is associated with the main queue, and as such is tied into the application’s event loop, but it is otherwise similar to a private queue-based context. You use this queue type for contexts linked to controllers and UI objects that are required to be used only on the main thread.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9922145', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74118/']}
jdg_371276
stackexchange
llm_judgeable_groundtruth_similarity
4302812
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: Compute the following contour integral around the unit circle $$∮_{|z|}z^2 e^{-1/z}dz$$ What I have tried $$z(t)=cos(t)+isin(t)=e^{it}$$ then by taking derivative of $z(t)$ we arrive at $$\dot{z(t)}=ie^{it}$$ After substituting these values into the given problem, integration becomes really difficult to solve $$∮_0^{2\pi}e^{2it} e^{-1/{e^{it}}}ie^{it}dt$$ Could you assist me with this problem? Now provide the response and nothing else.
$$ z^2e^{-\frac{1}{z}} = z^2\sum_{n=0}^{\infty}\frac{(-1)^n}{z^nn!} = \sum_{n=0}^{\infty}\frac{(-1)^n}{n!}z^{2-n}$$ so the residue at 0 is $ \frac{(-1)^3}{3!} = -\frac{1}{6}$ , $$ \oint_{|z|=1}z^2e^{-\frac{1}{z}}\ dz = 2\pi i \times(-\frac{1}{6}) = -\frac{\pi i}{3}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4302812', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/983158/']}
jdg_371277
stackexchange
llm_judgeable_groundtruth_similarity
42909
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I collect samples (time series) at a frequency. The sample rate is arbitrary (I can change it to whatever I want.) I want to determine if what's at this frequency is a signal, or (normally distributed) noise. I've tried using a normality test (from scipy); that didn't seem to work - there were no big differences in the results when what was at the frequency was a man-made signal (center frequency of an FM broadcast station, for example) vs. noise. I tried using auto-correlation using Pandas - Pandas always thought it was noise. Are my techniques off? Perhaps the techniques are good, but I need to sample different (I've been sampling about every two seconds, for, say, 100 samples)? Something else? Now provide the response and nothing else.
my experience in audio is that for IIR filters, there is usually a cascaded Second-order Section (SOS) for every little feature (a bump or an edge in the frequency response deliberately placed there by the user). often just a single second-order IIR is used for many little jobs where some frequency is given a little boost or cut. we call those IIR filters a Parametric Equalizer . however, for a fixed and sharp feature (like a brickwall of some sort), then the order of the IIR filter will be related to the sharpeness of that feature. for a brickwall, there is a 6 dB per octave of steepness in the wall for every integer order of the filter. for FIR, Fat's answer is good. the order of the filter is 1 less than the number of taps of the FIR. the minimum order again is related to the sharpness of some particular feature in the frequency response. there are a couple of heuristic formula for initial guessing at what order you will need. i will try to express them in a way to compare apples-to-apples. using a Kaiser-windowed FIR design the filter order (one less than the number of taps) is about: $$ N \ge \frac{(A-7.95)F_\text{s}}{14.357 \cdot \Delta f} $$ where $A$ is the amount of attenuation in dB of the brickwall, $\Delta f$ is the frequency width of the transition between the nominally un-attenuated and attenuated portions of the frequency response, and $F_\text{s}$ is the sample rate. using Parks-McClellan will reduce $N$ a bit: $$ N \ge \frac{(\tfrac12 A + \frac{4.343}{r_\text{p}} - 29.7)F_\text{s}}{14.602 \cdot \Delta f} $$ where the new symbol $r_\text{p}$ is the passband ripple in dB. this appears to be twice as good as i was expecting. so i am not sure i did this right, but i was being very careful with the equations from O&S about the P-McC alg.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/42909', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/10591/']}
jdg_371278
stackexchange
llm_judgeable_groundtruth_similarity
49689315
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 submit a comment on a guestbook application based on the Yii 2 Framework. On localhost on my PC works everything fine, but on the shared hosting when I want to submit a comment in View, I get this error. Here is the error: An error occurred while handling another error: exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /home/mahdikas/public_html/guestbook/controllers/PostController.php on line 117.' in /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php:366 Stack trace: #0 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders() #1 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/ErrorHandler.php(135): yii\web\Response->send() #2 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/base/ErrorHandler.php(111): yii\web\ErrorHandler->renderException(Object(yii\web\HeadersAlreadySentException)) #3 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\HeadersAlreadySentException)) #4 {main} Previous exception: exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /home/mahdikas/public_html/guestbook/controllers/PostController.php on line 117.' in /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php:366 Stack trace: #0 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders() #1 /home/mahdikas/public_html/guestbook/vendor/yiisoft/yii2/base/Application.php(392): yii\web\Response->send() #2 /home/mahdikas/public_html/guestbook/web/index.php(12): yii\base\Application->run() #3 {main} In the postController I have this code: public function actionAdd_comment(){ //print_r($_POST); $model = new \app\models\Comments; if ($model->load(Yii::$app->request->post()) && $model->validate()) { $model->comment_date = date('Y-m-d H:i:s'); if ($model->save()) { echo 'Thanks for your comment.'; } else { echo 'Failed!'; } }} which line 117 in the error is: echo 'Thanks for your comment.'; How can I solve this problem? Now provide the response and nothing else.
Since Yii 2.0.14 you cannot echo in a controller. A response must be returned: public function actionAdd_comment() { $model = new \app\models\Comments(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { $model->comment_date = date('Y-m-d H:i:s'); if ($model->save()) { return 'Thanks for your comment.'; } else { return 'Failed!'; } }} You may also call exit at the end of your method to prevent further processing or wrap your code with ob_start() and ob_get_clean() , if you're not able to avoid echo. public function actionAdd_comment() { $model = new \app\models\Comments(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { $this->someMagicWithEcho(); exit; }} or public function actionAdd_comment() { $model = new \app\models\Comments(); if ($model->load(Yii::$app->request->post()) && $model->validate()) { ob_start(); $this->someMagicWithEcho(); return ob_get_clean(); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49689315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9564857/']}
jdg_371279
stackexchange
llm_judgeable_groundtruth_similarity
18496282
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following simplified code: #include <stdio.h>int main () { printf("Hello "); goto Cleanup;Cleanup: char *str = "World\n"; printf("%s\n", str);} I get an error because a new variable is declared after the label. If I put the content (mainly initialization) after the label in a {} block, compilation succeeds. I think I understand the reason for the block in case of a switch, but why should it be applicable in case of a label ? This error is from a gcc compiler Now provide the response and nothing else.
The language standard simply doesn't allow for it. Labels can only be followed by statements, and declarations do not count as statements in C. The easiest way to get around this is by inserting an empty statement after your label, which relieves you from keeping track of the scope the way you would need to inside a block. #include <stdio.h>int main () { printf("Hello "); goto Cleanup;Cleanup: ; //This is an empty statement. char *str = "World\n"; printf("%s\n", str);}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18496282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1952500/']}
jdg_371280
stackexchange
llm_judgeable_groundtruth_similarity
12731897
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following models: class Company(CachedModel): name = models.CharField(max_length=255)class UserExtendedProfile(CachedModel): company = models.ForeignKey(Company) user = models.ForeignKey(User) I basically need to get a list of users ordered by company like this: Company A User 1 User 2Company B User 3 user 4 I tried a few things, and the closest I could get to is: users = UserExtendedProfile.objects.values('company', 'user').order_by('company') However this would just give me results something like this: [{'company': 1L, 'user': 17L}, {'company': 1L, 'user': 6L}, {'company': 2L, 'user': 15L}] Any inputs? Thanks Now provide the response and nothing else.
You can add multiple arguments on your order_by() method. Therefore you can do ordering inside orderings. users = UserExtendedProfile.objects.values('company', 'user').order_by('company', 'user') For a structure like: [{ company: [user1, user2, ] }, ] Try using a defaultdict from collections import defaultdict users = defaultdict(list)for result in UserExtendedProfile.objects.values('company', 'user').order_by('company', 'user'): users[result['company']].append(result['user']) With this you should get on users the structure you want.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12731897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1628832/']}
jdg_371281
stackexchange
llm_judgeable_groundtruth_similarity
2467289
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 just realized a function may be defined inside another function in C: void main(){ int foo(){ return 2; }; printf("%d\n", foo());} Besides being a neat trick, the useful thing about this is that the inner function is private to the outer function. But... is that a good enough reason to do this in a "real-world" application? What are the best practices for using this syntax? Now provide the response and nothing else.
Nested functions are a non-standard extension, implemented by GCC (and maybe others that I don't know about). Seeing as it does not follow a standard, best practices probably include not using it in code you intend to be portable. If your ultimate goal is to have "private" functions in C, then you are better off using separate files and making the "private" functions static so that they won't be linked to other object files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2467289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/101258/']}
jdg_371282
stackexchange
llm_judgeable_groundtruth_similarity
24259952
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following code does print 'I want this to print' in 'ipython qtconsole', however it does not print in plain IPython. import loggingimport logging.handlerslog = logging.getLogger()f = logging.Formatter("%(asctime)s - %(module)s. %(funcName)s - %(levelname)s - %(message)s")fh = logging.handlers.TimedRotatingFileHandler('log.txt', 'W6')fh.setFormatter(f)log.addHandler(fh)log.setLevel(logging.INFO)log.info('I want this to print') In 'IPython qtconsole' however i get different problems, that i tried to explain here (which did not go so well, no need to read!). Can you please tell me why? EDIT: I use Python 2.7 EDIT2: Maybe i really just need to add logging.StreamHandler. Now provide the response and nothing else.
It seems like qtconsole adds an handler to the root logger: In [1]: import logging ...: root = logging.getLogger() ...: root.handlers ...: Out[1]: [<logging.StreamHandler at 0x7fd8e00e1f98>] While using the normal python interpreter or just ipython : In [1]: import loggingIn [2]: root = logging.getLogger()In [3]: root.handlersOut[3]: [] If you want both to behave the same you should either add a StreamHandler to the root logger for normal ipython , or remove the StreamHandler from the qtconsole interpreter. If you want the former just add: root = logging.getLogger()root.addHandler(logging.StreamHandler()) If you want the latter, before adding your own handler, do: for handler in root.handlers[:]: root.removeHandler(handler) Note that IPython already provides some machinery for logging to a file. See the documentation . If you want to use the code only inside ipython using its magics might be simpler.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24259952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1193279/']}
jdg_371283
stackexchange
llm_judgeable_groundtruth_similarity
4633282
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 received a messages with the above notice "Notice of Suspected Hacking on my website. I'm not sure what happen here, however, I noticed there were some pages listed and they are not apart of my website?? Has anyone received the same message before? If so, what did you do to solve the issue?and what i do for the next? Now provide the response and nothing else.
DATE is a built-in type in Oracle, which is represented in a fixed way and you have no control over it. So: I want it to insert [...] as 08/01/2011 12:00:00 AM The above is nonsensical. You don't insert a string, you insert a date. Format is useful only when you want: to convert a string to an internal representation of date with TO_DATE (format mask: how to parse the string); to convert an internal representation of date to a string with TO_CHAR (format mask: how to render the date). So basically, in your example you take a DATE, you convert it to a STRING with some format, and convert it back to DATE with the same format. This is a no-op. Now, what your client displays: this is because your Oracle Client won't display DATE fields directly and the NLS layer will convert any DATE field that is selected. So it depends on your locale by default. What you want is SELECT TO_CHAR(SYSDATE,'DD/MM/YYYY') FROM dual; which will explicitly perform the conversion and return a string. And when you want to insert a date in a database, you can use TO_DATE or date literals.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4633282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565024/']}
jdg_371284
stackexchange
llm_judgeable_groundtruth_similarity
1396617
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A common scenario when I develop is that the codebase will have several config files which require machine specific settings. These files will be checked into Git and other developers will always accidentally check them back in and break someone else's configuration. A simple solution to this would be to just not check them in to Git, or even to additionally add a .gitignore entry for them. However, I find that it is much more elegant to have some sensible defaults in the file which the developer can modify to suit his needs. Is there an elegant way to make Git play nicely with such files? I would like to be able to modify a machine-specific configuration file and then be able to run "git commit -a" without checking that file in. Now provide the response and nothing else.
Have your program read a pair of configuration files for its settings. First, it should read a config.defaults file that would be included in the repository. Then, it should read a config.local file that should be listed in .gitignore With this arrangement, new settings appear in the defaults file and take effect as soon as it's updated. They will only vary on particular systems if they're overridden. As a variation on this, you could have just a general config file that you ship in version control, and have it do something like include config.local to bring in the machine-specific values. This introduces a more general mechanism (versus policy) in you code, and consequently enables more complicated configurations (if that's desirable for your application). The popular extension from this, seen in many large-scale open-source software, is to include conf.d , which reads configuration from all the files in a directory. Also see my answer to a similar question.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1396617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80617/']}
jdg_371285
stackexchange
llm_judgeable_groundtruth_similarity
55613438
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I got really confused with file I/O in JS/TS. most examples I see works with DOM and has browser-based solutions. Also, I did not understand how to make fs work, it seems to need a webpack config, where I use CRA and do not want to eject. in a React component I want to fetch some data from a server then save them as a JSON file in the project folder (the same path, root, public folder, no matter) or directly download (no button needed). //data type just in caseinteface IAllData{ name:string; allData:IData[];} so after fetching some data want to save them to name.json public componentDidMount(){ this.fetchData().then(()=>this.saveData())}public async fetchData(){/* sets data in state*/}public saveData(){ const {myData}=this.state; const fileName=myData.name; const json=JSON.stringify(myData); const blob=new Blob([json],{type:'application/json'}) /* How to write/download this blob as a file? */} here trying window.navigator.msSaveOrOpenBlob(blob, 'export.json'); did not work note: I know it has security risks, it is not for production. save the file in the project folder is preferred but a download is totally ok. Now provide the response and nothing else.
I had a blob containing data and I had found a solution on stackoverflow and manipulated a bit, and succeded to download as a xlsx file. I am adding my code below, it might help you, too. const blob = await res.blob(); // blob just as yoursconst href = await URL.createObjectURL(blob);const link = document.createElement('a');link.href = href;link.download = "file.xlsx";document.body.appendChild(link);link.click();document.body.removeChild(link); EDIT: You can use the function below, but be sure to switch out fileName and myData from this.state to something that will work in your application. const downloadFile = () => { const { myData } = this.state; // I am assuming that "this.state.myData" // is an object and I wrote it to file as // json // create file in browser const fileName = "my-file"; const json = JSON.stringify(myData, null, 2); const blob = new Blob([json], { type: "application/json" }); const href = URL.createObjectURL(blob); // create "a" HTLM element with href to file const link = document.createElement("a"); link.href = href; link.download = fileName + ".json"; document.body.appendChild(link); link.click(); // clean up "a" element & remove ObjectURL document.body.removeChild(link); URL.revokeObjectURL(href);} More documentation for URL.createObjectURL is available on MDN. It's critical to release the object with URL.revokeObjectURL to prevent a memory leak. In the function above, since we've already downloaded the file, we can immediately revoke the object. Each time you call createObjectURL(), a new object URL is created, even if you've already created one for the same object. Each of these must be released by calling URL.revokeObjectURL() when you no longer need them. Browsers will release object URLs automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55613438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1624844/']}
jdg_371286
stackexchange
llm_judgeable_groundtruth_similarity
68376130
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 write a function that recursively determines the amount of steps needed to resolve the collatz conjecture. I want the function input to be just the starting input number for the series, with an additional counter variable to be added in the first iteration. The JS equivalent would look like: const collatz = (v, count) => { if (!count) return collatz(v,0) if (v === 1) return count if (v % 2 === 0) return collatz(v/2, count + 1) return collatz(v*3+1, count + 1)} My Haskell code: module CollatzConjecture (collatz) wherecollatz :: Integer -> Maybe Integer -> Maybe Integercollatz v () = collatz v 0collatz 1 count = Just countcollatz v count | even v = collatz (div v 2) next | otherwise = collatz (v * 3 + 1) next where next = count + 1 But the compiler complains • Couldn't match type ‘Maybe Integer’ with ‘Integer’ Expected type: Maybe Integer Actual type: Maybe (Maybe Integer) • In the expression: Just count In an equation for ‘collatz’: collatz 1 count = Just count |4 | collatz 1 count = Just count | ^^^^^^^^^^ What is the error in my thinking? Now provide the response and nothing else.
Don't pollute your function's public API with an extra parameter used only for an implementation detail. Instead, have your public 1-argument function delegate to a private 2-argument function. Often an internal function like this is named go , if you can't think of a better name. collatz :: Integer -> Integercollatz = go 0 where go count 1 = count go count v | even v = next $ div v 2 | otherwise = next $ v * 3 + 1 where next = go $ count + 1 I've also made some other improvements: There's no reason to return a Maybe Integer when you never return Nothing . I swapped the parameter order ( count first) to make partial application of go and next more convenient. Instead of defining your helper variable next as an integer, I've defined it as a partial application of go , so that your two cases only have to repeat next , rather than go (...) next . The function as a whole would also be much simpler if you didn't do the counting yourself at all. I don't suggest this immediately, since it's fairly unrecognizable compared to your initial attempt, but an experienced Haskeller would write this more like: collatz :: Integer -> Intcollatz = length . takeWhile (/= 1) . iterate step where step n | even n = n `div` 2 | otherwise = 3 * n + 1
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/68376130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7371776/']}
jdg_371287
stackexchange
llm_judgeable_groundtruth_similarity
10506637
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 feel that the drawing performance of JavaFX 2 is worse than those of Swing. I think one of the reasons is how you draw things, e.g. when drawing a Line, one has to create a Line object for each line and add it to some container while in Swing one just gets the Graphics2D once and then does drawLine without creating a new object each time. So, is there any more performant way to draw using JavaFX 2, e.g. if you have to draw about 3000 Arcs? What's the best "drawing surface"? Currently I am using a Group . Thanks for any hint! Now provide the response and nothing else.
Your current approach of using a Group, is likely fine, and you will probably find that the performance of drawing 3000 arcs within your Group is perfectly acceptable for your application users. A current alternative to using a Group would be to use layout Panes which would add some convenient functionality, but add an extra layer of overhead, which is unnecessary when you have thousands of easily manually laid out objects. See the JavaFX mailing list archive for a discussion of an upcoming direct draw interface (called the Canvas Node) for JavaFX 2.2 and it's implications. Although it may seem less performant to stick objects in a container, the container implementation can, if it wishes, make use of accelerated retained mode rendering hardware built into modern gpus. Also note that the JavaFX architecture internally keeps track of dirty areas and caches the results of expensive rendering operations to increase performance. Therefore, the use of a container does not, in and of itself, imply slower performance than a direct draw interface which might rely on an immediate mode implementation. Choosing a drawing surface will depend on the application. The best surface for most JavaFX apps will be a collection of scenegraph nodes rather than a canvas node. Using many nodes in a scenegraph rather than a single Canvas node will (usually) be easier to develop for and the performance will be perfectly acceptable. Eventually, it is likely that numerous blog articles will be written to compare performance of Canvas vs many scenegraph objects and perhaps against other frameworks such as html canvas, java2d, swing, etc. So in time, it will be easier to answer such a question. Related Osvaldo's JavaFX performance analysis , though old, also includes a in depth discussion of some of the issues raised in your question. There is a nice section on Performance Tips and Tricks in the openjfx wiki . There are some related StackOverflow JavaFX performance questions: JavaFX 2 path drawing performance What is the best way to display millions of images in Java?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10506637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298288/']}
jdg_371288
stackexchange
llm_judgeable_groundtruth_similarity
12774
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Radioactive rocks can release a gas called radon when they decay, which can build up in the basements of buildings with serious effects on people's health. Does anybody have information on how radon is produce naturally in nature? How do these rock’s become radioactively charged? Are these rocks common? Pictures or examples? Now provide the response and nothing else.
Radon ( more specifically Radon-222 ) is produced in the decay chain of Uranium-238. Radon-223 is also produced by the decay chain of Uranium-235 and Radon-220 is produced by the decay chain of Thorium-232 but both Radon-223 and Radon-220 have half-lives of less than a minute, so they almost never reach the atmosphere where they can be breathed in because they mostly form underground and they decay too quickly to reach the atmosphere. Radon is unusual in that it's the only noble gas along the 4 primary decay chains and only the Uranium to Lead chain produces Radon-222 which has half life long enough to reach the atmosphere and get breathed in. More on decay chains here and here . Uranium-238 has half life of about 4.5 billion years, so about half the Uranium-238 that was present when the Earth formed is still here. It decays very slowly, which is why it's not dangerous to be around Uranium in it's natural form. (though if somebody hands you a block of it, you might still want to wash your hands after touching it - then call national security) . . . but I digress. Radon-222 has a very short half life of 3.8 days, so while the Uranium that produces it decays very slowly, the Radon is highly radioactive and it decays (into other radioactive elements) quite rapidly. If you had a sample of Radon-222 for example, in less than a month, 99% of your sample would be gone. Because it forms slowly and decays quickly it never collects beyond a very trace concentration and it continuously needs to be regenerated. Houses with a Radon problem need to be continuously ventilated because of that regeneration. At least/about two or three times a day I would think (see comment directly below, once a day may be sufficient) , but it's worth pointing out that the Radon in houses is so faint that it takes months, if not years, for any kind of health problems to arise. It's kind of a weird thing. It's not dangerous at all to walk through a house with unsafe Radon levels, similar to how it's not dangerous to visit Chernobyl . It's just not a good idea to live there. Radon is also likely to only be a problem in poorly ventilated houses, (basement's especially, because the heavy gas tends to settle) but a good ventilation system should make any house safe. And it's more common in specific areas . There's the problem of keeping the house warm in winter and maintaining ventilation, because ventilation does need to be maintained. Houses can be also built above ground to reduce exposure. As a general rule, it's the ingestion, either breathing or swallowing of radioactive material that's most dangerous. That's why it's a good idea to put on a gas mask to prevent breathing in any radioactive dust or fallout (though a gas mask won't keep gas like Radon out). And it's a good idea to leave your clothes in a separate changing room and shower thoroughly if exposed or walking through radioactive fallout - that has nothing to do with your question, just putting it out there. Also the opposite applies if there's radiation outside from a nuclear accident or bomb- close all windows and try to keep ventilation as close to zero as possible, at least for a day or so until you get instruction on the levels, but . . . I digress. Point is, because Radon is easily breathed in, it's quite toxic even in very small amounts. At the same time, the Radon concentration inside houses with a radon problem is so small, that it still takes months if not years of exposure to lead to problems. That's why Geiger-counters aren't used to test for Radon. There's too little radiation. You need specific Radon detectors. Are these rocks common? Yes, and no. Because the gas comes from Uranium, (and mostly from underground), Uranium isn't exactly common but it's not super-rare either. How do these rock’s become radioactively charged? This was covered above, but Uranium, in small amounts, is in lots of different places. The Rocks were always (mildly) radioactive. Pictures or examples? To my knowledge, pictures or examples don't do any good because trace amounts of Uranium in rocks doesn't look any different. Besides, most of the Uranium is underground. You have to rely on Radon testing and look at locations where Radon is more of a problem. If you live and work above the first floor, and not near a mine or massive dig-site, you probably have little to worry about. If you live in a basement, you should have it checked out. On the process The Uranium or U-238 goes through several steps in it's decay and this chain is only the most common outcome. Part of the problem with Radon, is if you breath it in, and don't breath it out, it becomes Polonium and goes through a few other steps. In high enough concentration, Radon is extremely toxic. From rocks, the concentration that's likely to form in a house is usually low enough that harmful exposure takes months or years.
{}
{'log_upvote_score': 4, 'links': ['https://earthscience.stackexchange.com/questions/12774', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/11565/']}
jdg_371289
stackexchange
llm_judgeable_groundtruth_similarity
32322393
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 currently sending sms in python using this code, but sometimes it is unstable. It went straight to "send successfully" but the other party did not receive any message. Is there any other ways to send sms through the dongle? Much appreciated. This is the code. class TextMessage: def __init__(self, recipient="XXXXXXXX", message="TextMessage.content not set."): self.recipient = recipient self.content = message def setRecipient(self, number): self.recipient = number def setContent(self, message): self.content = message def connectPhone(self): self.ser = serial.Serial('/dev/ttyUSBSMS', 460800, timeout=5) time.sleep(1) def sendMessage(self): self.ser.write('ATZ\r') time.sleep(1) self.ser.write('AT+CMGF=1\r') time.sleep(1) self.ser.write('''AT+CMGS="''' + self.recipient + '''"\r''') time.sleep(1) self.ser.write(self.content + "\r") time.sleep(1) self.ser.write(chr(26)) time.sleep(1) def disconnectPhone(self): self.ser.close()sms = TextMessage("XXXXXXXX","This is the message to send.")sms.connectPhone()sms.sendMessage()sms.disconnectPhone()print "sent successfully" Now provide the response and nothing else.
Your code won't work because URLSessionDownloadTask runs asynchronously. Thus the BlockOperation completes before the download is done and therefore while the operations fire off sequentially, the download tasks will continue asynchronously and in parallel. While there are work-arounds one can contemplate (e.g., recursive patterns initiating one request after the prior one finishes, non-zero semaphore pattern on background thread, etc.), the elegant solution is one of the proven asynchronous frameworks. In iOS 15 and later, we would use async - await method download(from:delegate:) , e.g. func downloadFiles() async throws { let folder = try! FileManager.default .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) for url in urls { let (source, _) = try await URLSession.shared.download(from: url) let destination = folder.appendingPathComponent(url.lastPathComponent) try FileManager.default.moveItem(at: source, to: destination) }} Where override func viewDidLoad() { super.viewDidLoad() Task { do { try await downloadFiles() } catch { print(error) } }} That only works in iOS 15 and later. But Xcode 13.2 and later actually lets you use async-await in iOS 13, but you just have to write your own async rendition of download : extension URLSession { @available(iOS, deprecated: 15, message: "Use `download(from:delegate:)` instead") func download(with url: URL) async throws -> (URL, URLResponse) { try await download(with: URLRequest(url: url)) } @available(iOS, deprecated: 15, message: "Use `download(for:delegate:)` instead") func download(with request: URLRequest) async throws -> (URL, URLResponse) { let sessionTask = URLSessionTaskActor() return try await withTaskCancellationHandler { Task { await sessionTask.cancel() } } operation: { try await withCheckedThrowingContinuation { continuation in Task { await sessionTask.start(downloadTask(with: request) { location, response, error in guard let location = location, let response = response else { continuation.resume(throwing: error ?? URLError(.badServerResponse)) return } // since continuation can happen later, let's figure out where to store it ... let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent(UUID().uuidString) .appendingPathExtension(request.url!.pathExtension) // ... and move it to there do { try FileManager.default.moveItem(at: location, to: tempURL) } catch { continuation.resume(throwing: error) return } continuation.resume(returning: (tempURL, response)) }) } } } }}private extension URLSession { actor URLSessionTaskActor { weak var task: URLSessionTask? func start(_ task: URLSessionTask) { self.task = task task.resume() } func cancel() { task?.cancel() } }} And you would then call this rendition for iOS 13 and later: func downloadFiles() async throws { let folder = try! FileManager.default .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) for url in urls { let (source, _) = try await URLSession.shared.download(with: url) let destination = folder.appendingPathComponent(url.lastPathComponent) try FileManager.default.moveItem(at: source, to: destination) }} In iOS versions prior to 13, if you wanted to control the degree of concurrency of a series of asynchronous tasks, we would reach for an asynchronous Operation subclass. Or, in iOS 13 and later, you might also consider Combine . (There are other third-party asynchronous programming frameworks, but I will restrict myself to Apple-provided approaches.) Both of these are described below in my original answer. Operation To address this, you can wrap the requests in asynchronous Operation subclass. See Configuring Operations for Concurrent Execution in the Concurrency Programming Guide for more information. But before I illustrate how to do this in your situation (the delegate-based URLSession ), let me first show you the simpler solution when using the completion handler rendition. We'll later build upon this for your more complicated question. So, in Swift 3 and later: class DownloadOperation : AsynchronousOperation { var task: URLSessionTask! init(session: URLSession, url: URL) { super.init() task = session.downloadTask(with: url) { temporaryURL, response, error in defer { self.finish() } guard let httpResponse = response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else { // handle invalid return codes however you'd like return } guard let temporaryURL = temporaryURL, error == nil else { print(error ?? "Unknown error") return } do { let manager = FileManager.default let destinationURL = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent(url.lastPathComponent) try? manager.removeItem(at: destinationURL) // remove the old one, if any try manager.moveItem(at: temporaryURL, to: destinationURL) // move new one there } catch let moveError { print("\(moveError)") } } } override func cancel() { task.cancel() super.cancel() } override func main() { task.resume() } } Where /// Asynchronous operation base class////// This is abstract to class emits all of the necessary KVO notifications of `isFinished`/// and `isExecuting` for a concurrent `Operation` subclass. You can subclass this and/// implement asynchronous operations. All you must do is:////// - override `main()` with the tasks that initiate the asynchronous task;////// - call `completeOperation()` function when the asynchronous task is done;////// - optionally, periodically check `self.cancelled` status, performing any clean-up/// necessary and then ensuring that `finish()` is called; or/// override `cancel` method, calling `super.cancel()` and then cleaning-up/// and ensuring `finish()` is called.class AsynchronousOperation: Operation { /// State for this operation. @objc private enum OperationState: Int { case ready case executing case finished } /// Concurrent queue for synchronizing access to `state`. private let stateQueue = DispatchQueue(label: Bundle.main.bundleIdentifier! + ".rw.state", attributes: .concurrent) /// Private backing stored property for `state`. private var rawState: OperationState = .ready /// The state of the operation @objc private dynamic var state: OperationState { get { return stateQueue.sync { rawState } } set { stateQueue.sync(flags: .barrier) { rawState = newValue } } } // MARK: - Various `Operation` properties open override var isReady: Bool { return state == .ready && super.isReady } public final override var isExecuting: Bool { return state == .executing } public final override var isFinished: Bool { return state == .finished } // KVO for dependent properties open override class func keyPathsForValuesAffectingValue(forKey key: String) -> Set<String> { if ["isReady", "isFinished", "isExecuting"].contains(key) { return [#keyPath(state)] } return super.keyPathsForValuesAffectingValue(forKey: key) } // Start public final override func start() { if isCancelled { finish() return } state = .executing main() } /// Subclasses must implement this to perform their work and they must not call `super`. The default implementation of this function throws an exception. open override func main() { fatalError("Subclasses must implement `main`.") } /// Call this function to finish an operation that is currently executing public final func finish() { if !isFinished { state = .finished } }} Then you can do: for url in urls { queue.addOperation(DownloadOperation(session: session, url: url))} So that's one very easy way to wrap asynchronous URLSession / NSURLSession requests in asynchronous Operation / NSOperation subclass. More generally, this is a useful pattern, using AsynchronousOperation to wrap up some asynchronous task in an Operation / NSOperation object. Unfortunately, in your question, you wanted to use delegate-based URLSession / NSURLSession so you could monitor the progress of the downloads. This is more complicated. This is because the "task complete" NSURLSession delegate methods are called at the session object's delegate. This is an infuriating design feature of NSURLSession (but Apple did it to simplify background sessions, which isn't relevant here, but we're stuck with that design limitation). But we have to asynchronously complete the operations as the tasks finish. So we need some way for the session to figure out which operation to complete when didCompleteWithError is called. Now you could have each operation have its own NSURLSession object, but it turns out that this is pretty inefficient. So, to handle that, I maintain a dictionary, keyed by the task's taskIdentifier , which identifies the appropriate operation. That way, when the download finishes, you can "complete" the correct asynchronous operation. Thus: /// Manager of asynchronous download `Operation` objectsclass DownloadManager: NSObject { /// Dictionary of operations, keyed by the `taskIdentifier` of the `URLSessionTask` fileprivate var operations = [Int: DownloadOperation]() /// Serial OperationQueue for downloads private let queue: OperationQueue = { let _queue = OperationQueue() _queue.name = "download" _queue.maxConcurrentOperationCount = 1 // I'd usually use values like 3 or 4 for performance reasons, but OP asked about downloading one at a time return _queue }() /// Delegate-based `URLSession` for DownloadManager lazy var session: URLSession = { let configuration = URLSessionConfiguration.default return URLSession(configuration: configuration, delegate: self, delegateQueue: nil) }() /// Add download /// /// - parameter URL: The URL of the file to be downloaded /// /// - returns: The DownloadOperation of the operation that was queued @discardableResult func queueDownload(_ url: URL) -> DownloadOperation { let operation = DownloadOperation(session: session, url: url) operations[operation.task.taskIdentifier] = operation queue.addOperation(operation) return operation } /// Cancel all queued operations func cancelAll() { queue.cancelAllOperations() } }// MARK: URLSessionDownloadDelegate methodsextension DownloadManager: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { operations[downloadTask.taskIdentifier]?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { operations[downloadTask.taskIdentifier]?.urlSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) }}// MARK: URLSessionTaskDelegate methodsextension DownloadManager: URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { let key = task.taskIdentifier operations[key]?.urlSession(session, task: task, didCompleteWithError: error) operations.removeValue(forKey: key) } }/// Asynchronous Operation subclass for downloadingclass DownloadOperation : AsynchronousOperation { let task: URLSessionTask init(session: URLSession, url: URL) { task = session.downloadTask(with: url) super.init() } override func cancel() { task.cancel() super.cancel() } override func main() { task.resume() }}// MARK: NSURLSessionDownloadDelegate methodsextension DownloadOperation: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let httpResponse = downloadTask.response as? HTTPURLResponse, 200..<300 ~= httpResponse.statusCode else { // handle invalid return codes however you'd like return } do { let manager = FileManager.default let destinationURL = try manager .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(downloadTask.originalRequest!.url!.lastPathComponent) try? manager.removeItem(at: destinationURL) try manager.moveItem(at: location, to: destinationURL) } catch { print(error) } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) print("\(downloadTask.originalRequest!.url!.absoluteString) \(progress)") }}// MARK: URLSessionTaskDelegate methodsextension DownloadOperation: URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { defer { finish() } if let error = error { print(error) return } // do whatever you want upon success } } And then use it like so: let downloadManager = DownloadManager()override func viewDidLoad() { super.viewDidLoad() let urlStrings = [ "http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/s72-55482.jpg", "http://spaceflight.nasa.gov/gallery/images/apollo/apollo10/hires/as10-34-5162.jpg", "http://spaceflight.nasa.gov/gallery/images/apollo-soyuz/apollo-soyuz/hires/s75-33375.jpg", "http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-134-20380.jpg", "http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-140-21497.jpg", "http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-148-22727.jpg" ] let urls = urlStrings.compactMap { URL(string: $0) } let completion = BlockOperation { print("all done") } for url in urls { let operation = downloadManager.queueDownload(url) completion.addDependency(operation) } OperationQueue.main.addOperation(completion)} See revision history for Swift 2 implementation. Combine For Combine , the idea would be to create a Publisher for URLSessionDownloadTask . Then you can do something like: var downloadRequests: AnyCancellable?/// Download a series of assetsfunc downloadAssets() { downloadRequests = downloadsPublisher(for: urls, maxConcurrent: 1).sink { completion in switch completion { case .finished: print("done") case .failure(let error): print("failed", error) } } receiveValue: { destinationUrl in print(destinationUrl) }}/// Publisher for single download////// Copy downloaded resource to caches folder.////// - Parameter url: `URL` being downloaded./// - Returns: Publisher for the URL with final destination of the downloaded asset.func downloadPublisher(for url: URL) -> AnyPublisher<URL, Error> { URLSession.shared.downloadTaskPublisher(for: url) .tryCompactMap { let destination = try FileManager.default .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(url.lastPathComponent) try FileManager.default.moveItem(at: $0.location, to: destination) return destination } .receive(on: RunLoop.main) .eraseToAnyPublisher()}/// Publisher for a series of downloads////// This downloads not more than `maxConcurrent` assets at a given time.////// - Parameters:/// - urls: Array of `URL`s of assets to be downloaded./// - maxConcurrent: The maximum number of downloads to run at any given time (default 4)./// - Returns: Publisher for the URLs with final destination of the downloaded assets.func downloadsPublisher(for urls: [URL], maxConcurrent: Int = 4) -> AnyPublisher<URL, Error> { Publishers.Sequence(sequence: urls.map { downloadPublisher(for: $0) }) .flatMap(maxPublishers: .max(maxConcurrent)) { $0 } .eraseToAnyPublisher()} Now, unfortunately, Apple supplies a DataTaskPublisher (which loads the full asset into memory which is not acceptable solution for large assets), but one can refer to their source code and adapt it to create a DownloadTaskPublisher : // DownloadTaskPublisher.swift//// Created by Robert Ryan on 9/28/20.//// Adapted from Apple's `DataTaskPublisher` at:// https://github.com/apple/swift/blob/88b093e9d77d6201935a2c2fb13f27d961836777/stdlib/public/Darwin/Foundation/Publishers%2BURLSession.swiftimport Foundationimport Combine// MARK: Download Tasks@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)extension URLSession { /// Returns a publisher that wraps a URL session download task for a given URL. /// /// The publisher publishes temporary when the task completes, or terminates if the task fails with an error. /// /// - Parameter url: The URL for which to create a download task. /// - Returns: A publisher that wraps a download task for the URL. public func downloadTaskPublisher(for url: URL) -> DownloadTaskPublisher { let request = URLRequest(url: url) return DownloadTaskPublisher(request: request, session: self) } /// Returns a publisher that wraps a URL session download task for a given URL request. /// /// The publisher publishes download when the task completes, or terminates if the task fails with an error. /// /// - Parameter request: The URL request for which to create a download task. /// - Returns: A publisher that wraps a download task for the URL request. public func downloadTaskPublisher(for request: URLRequest) -> DownloadTaskPublisher { return DownloadTaskPublisher(request: request, session: self) } public struct DownloadTaskPublisher: Publisher { public typealias Output = (location: URL, response: URLResponse) public typealias Failure = URLError public let request: URLRequest public let session: URLSession public init(request: URLRequest, session: URLSession) { self.request = request self.session = session } public func receive<S: Subscriber>(subscriber: S) where Failure == S.Failure, Output == S.Input { subscriber.receive(subscription: Inner(self, subscriber)) } private typealias Parent = DownloadTaskPublisher private final class Inner<Downstream: Subscriber>: Subscription, CustomStringConvertible, CustomReflectable, CustomPlaygroundDisplayConvertible where Downstream.Input == Parent.Output, Downstream.Failure == Parent.Failure { typealias Input = Downstream.Input typealias Failure = Downstream.Failure private let lock: NSLocking private var parent: Parent? // GuardedBy(lock) private var downstream: Downstream? // GuardedBy(lock) private var demand: Subscribers.Demand // GuardedBy(lock) private var task: URLSessionDownloadTask! // GuardedBy(lock) var description: String { return "DownloadTaskPublisher" } var customMirror: Mirror { lock.lock() defer { lock.unlock() } return Mirror(self, children: [ "task": task as Any, "downstream": downstream as Any, "parent": parent as Any, "demand": demand, ]) } var playgroundDescription: Any { return description } init(_ parent: Parent, _ downstream: Downstream) { self.lock = NSLock() self.parent = parent self.downstream = downstream self.demand = .max(0) } // MARK: - Upward Signals func request(_ d: Subscribers.Demand) { precondition(d > 0, "Invalid request of zero demand") lock.lock() guard let p = parent else { // We've already been cancelled so bail lock.unlock() return } // Avoid issues around `self` before init by setting up only once here if self.task == nil { let task = p.session.downloadTask( with: p.request, completionHandler: handleResponse(location:response:error:) ) self.task = task } self.demand += d let task = self.task! lock.unlock() task.resume() } private func handleResponse(location: URL?, response: URLResponse?, error: Error?) { lock.lock() guard demand > 0, parent != nil, let ds = downstream else { lock.unlock() return } parent = nil downstream = nil // We clear demand since this is a single shot shape demand = .max(0) task = nil lock.unlock() if let location = location, let response = response, error == nil { _ = ds.receive((location, response)) ds.receive(completion: .finished) } else { let urlError = error as? URLError ?? URLError(.unknown) ds.receive(completion: .failure(urlError)) } } func cancel() { lock.lock() guard parent != nil else { lock.unlock() return } parent = nil downstream = nil demand = .max(0) let task = self.task self.task = nil lock.unlock() task?.cancel() } } }} Now, unfortunately, that isn’t using URLSession delegate pattern, but rather the completion handler rendition. But one could conceivably adapt it for delegate pattern. Also, this will stop downloads when one fails. If you don't want it to stop just because one fails, you could conceivably define it to Never fail, and instead replaceError with nil : /// Publisher for single download////// Copy downloaded resource to caches folder.////// - Parameter url: `URL` being downloaded./// - Returns: Publisher for the URL with final destination of the downloaded asset. Returns `nil` if request failed.func downloadPublisher(for url: URL) -> AnyPublisher<URL?, Never> { URLSession.shared.downloadTaskPublisher(for: url) .tryCompactMap { let destination = try FileManager.default .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(url.lastPathComponent) try FileManager.default.moveItem(at: $0.location, to: destination) return destination } .replaceError(with: nil) .receive(on: RunLoop.main) .eraseToAnyPublisher()}/// Publisher for a series of downloads////// This downloads not more than `maxConcurrent` assets at a given time.////// - Parameters:/// - urls: Array of `URL`s of assets to be downloaded./// - maxConcurrent: The maximum number of downloads to run at any given time (default 4)./// - Returns: Publisher for the URLs with final destination of the downloaded assets.func downloadsPublisher(for urls: [URL], maxConcurrent: Int = 4) -> AnyPublisher<URL?, Never> { Publishers.Sequence(sequence: urls.map { downloadPublisher(for: $0) }) .flatMap(maxPublishers: .max(maxConcurrent)) { $0 } .eraseToAnyPublisher()} Perhaps needless to say, I would generally discourage the downloading of assets/files sequentially. You should allow them to run concurrently, but control the degree of concurrency so your app is not overloaded. All of the patterns outlined above constrain the degree of concurrency to something reasonable.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32322393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5082810/']}
jdg_371290
stackexchange
llm_judgeable_groundtruth_similarity
65860
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: Can someone please explain why neighbouring group participation happens? Does it stabilise the carbocation? If so then is NGP dominant over an intermolecular S N 2 reaction (especially in aprotic medium)? Now provide the response and nothing else.
There may be some confusion over what neighbouring group participation (NGP, also sometimes referred to as anchimeric assistance) is. Carey puts it quite succinctly: When a molecule that can react by nucleophilic substitution also contains a substituent group that can act as a nucleophile, it is often observed that the rate and stereochemistry of the nucleophilic substitution are strongly affected. The involvement of nearby nucleophilic substituents in a substitution process is called neighboring- group participation. Source : Advanced Organic Chemistry (Part A). Francis Carey. Rather than a discrete carbocation forming, which is then stabilised, NGP usually (though not exclusively) occurs via two consecutive S N 2 processes, with overall retention of stereochemistry. The reason why the NGP happens, rather than an external nucleophile just doing the substitution is generally due to the fact that intramolecular reactions happen at a faster rate than intermolecular ones, since this removes the necessity of encounter between nucleophile and electrophile (the two are essentially tethered together). The initial internal attack forms a ring (usually 3 or 5 membered for reasons that should be familiar to you) which may then be opened by the external nucleophile. A classical example is of a sulfide displacing a halide, with subsequent opening of the reactive 3-membered intermediate: Source : Organic Chemistry. Clayden/Warren.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/65860', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/31523/']}
jdg_371291
stackexchange
llm_judgeable_groundtruth_similarity
14614573
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: simplified version of my query SELECT *FROM logs WHERE pw='correct' AND CASE WHEN id<800 THEN success=1 ELSE END AND YEAR(timestamp)=2011 this doesn't work. What i'm trying to do is to add in success=1 only for rows with id<800 , else ignore this check. how do i write this? thanks! edit: to clarify, this what the table looks like |id | pw | success |--------------------------|700 | correct | 1 ||710 | correct | 1 ||900 | correct | NULL ||999 | correct | 0 | I'm trying to return all the rows, the column pw cannot be ignored. Now provide the response and nothing else.
You don't have to use CASE...WHEN, you could use an OR condition, like this: WHERE pw='correct' AND (id>=800 OR success=1) AND YEAR(timestamp)=2011 this means that if id<800, success has to be 1 for the condition to be evaluated as true. Otherwise, it will be true anyway. It is less common, however you could still use CASE WHEN, like this: WHERE pw='correct' AND CASE WHEN id<800 THEN success=1 ELSE TRUE END AND YEAR(timestamp)=2011 this means: return success=1 (which can be TRUE or FALSE) in case id<800, or always return TRUE otherwise.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14614573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1484186/']}
jdg_371292
stackexchange
llm_judgeable_groundtruth_similarity
1381937
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following code summarizes the problem I have at the moment. My current execution flow is as follows and a I'm running in GCC 4.3. jmp_buf a_buf;jmp_buf b_buf;void b_helper(){ printf("entering b_helper"); if(setjmp(b_buf) == 0) { printf("longjmping to a_buf"); longjmp(a_buf, 1); } printf("returning from b_helper"); return; //segfaults right here}void b(){ b_helper();}void a(){ printf("setjmping a_buf"); if(setjmp(a_buf) == 0) { printf("calling b"); b(); } printf("longjmping to b_buf"); longjmp(b_buf, 1);}int main(){ a();} The above execution flow creates a segfault right after the return in b_helper. It's almost as if only the b_helper stack frame is valid, and the stacks below it are erased. Can anyone explain why this is happening? I'm guessing it's a GCC optimization that's erasing unused stack frames or something. Thanks. Now provide the response and nothing else.
You can only longjmp() back up the call stack. The call to longjmp(b_buf, 1) is where things start to go wrong, because the stack frame referenced by b_buf no longer exists after the longjmp(a_buf) . From the documentation for longjmp : The longjmp() routines may not be called after the routine which called the setjmp() routines returns. This includes "returning" through a longjmp() out of the function.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1381937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156242/']}
jdg_371293
stackexchange
llm_judgeable_groundtruth_similarity
7033170
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's my code: import java.util.Scanner;public class Arrays { public static void main(String[] args) { Arrays psvm = new Arrays(); psvm.start(); } public void start() { Scanner ben = new Scanner(System.in); int[] arr = new int[4]; int[] arrs = new int[4]; for (int i = 0; i < arr.length; i++) { arr[i] = ben.nextInt(); } check(arr, arrs); } public void check(int arr[], int arrs[]) { for (int i = 0; i < arr.length; i++) { arrs[i] = arr[i]; } for (int i : arrs) { System.out.println(arrs[i]); } }} The enhanced for loop gives ArrayIndexOutOfBoundsException : for (int i : arrs) { System.out.println(arrs[i]);} While this for loop statement works. Why? What's wrong with the code? for (int i = 0; i < arrs.length; i++) { System.out.println(arrs[i]);} Now provide the response and nothing else.
In this case, i will be assigned to each element in the array - it is not an index into the array. What you want to do is: for(int i : arrs){ System.out.println(i);} In your code, you're trying to select the integer at the array index referenced by the iteration object. In other words, your code is equivalent to: for(int idx = 0; idx < arrs.length; idx++){ int i = arrs[idx]; System.out.println(arrs[i]);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7033170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/798818/']}
jdg_371294
stackexchange
llm_judgeable_groundtruth_similarity
54475
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 would like to know what is known (both explanations and references) about the spaces of smooth solutions to linear systems of PDEs of the following form: Let $g_{1},...,g_{n}$ be smooth functions on $\mathbb{R}^{n}$ with the integrability condition $\partial{g_{i}}/\partial{x^{j}}=\partial{g_{j}}/\partial{x^{i}}$ and consider the space of smooth functions $f$ on $\mathbb{R}^{n}$ satisfying $\partial{f}/\partial{x^{i}}=fg_{i}$ for all $i$. Similarly for the $g_{i}$ and $f$ being holomorphic on $\mathbb{C}^{n}$, and replacing $\mathbb{R}^{n}, \mathbb{C}^{n}$ with open contractible subsets. My hope is that the answer is there is a unique solution, up to scaling. Now provide the response and nothing else.
There are other ways of doing this integral, but let me try to fix your attempt, which is certainly a fine idea as far as it goes. The main problem I spot with your development is that you forgot to change the $dx$ when you did the change of variable. (And you should be able to evaluate $\sec(\arctan a)$ as well; we'll get to that shortly). So: you start with$$\int_0^8 \sqrt{x^4+4x^2}\,dx = \int_0^8 \sqrt{x^2(x^2+4)}\,dx.$$ Then you do the change of variable $x=2\tan(\theta)$. If you do this, then$$dx = 2\sec^2\theta\,d\theta;$$when $x=0$, you want $\theta=0$, and when $x=8$ you want $\theta=\arctan(4)$ (you are correct there). So the integral actually becomes, after changing integrand, limits, and the $dx$:$$\begin{align*}\int_0^8\sqrt{x^2(x^2+4)}\,dx &= \int_0^{\arctan(4)}\sqrt{4\tan^2\theta(4\tan^2\theta+4)}2\sec^2\theta\,d\theta\\&= \int_0^{\arctan(4)} \sqrt{16\tan^2\theta(\tan^2\theta+1)}2\sec^2\theta\,d\theta\\&= \int_0^{\arctan(4)}8\sec^2\theta\sqrt{\tan^2\theta\sec^2\theta}\,d\theta\\&= 8\int_0^{\arctan(4)}\sec^2\theta|\tan\theta\sec\theta|\,d\theta.\end{align*}$$Now, on $[0,\arctan(4)]$, both tangent and secant are positive, so we can drop the absolute value signs (something else you were not careful with), and the integral becomes$$8\int_0^{\arctan(4)}\sec^3\theta\tan\theta\,d\theta.$$Set $u=\sec\theta$. Then $du=\sec\theta\tan\theta$, so we have$$\begin{align*}8\int_0^{\arctan(4)}\sec^3\theta\tan\theta\,d\theta &= 8\int_{\sec(0)}^{\sec(\arctan(4))}u^2\,du\\&= \frac{8}{3}u^3\Biggm|_{\sec(0)}^{\sec(\arctan(4))}\\&=\frac{8}{3}\left(\sec^3(\arctan(4)) - \sec^3(0)\right).\end{align*}$$ Now, $\sec(0) = 1$. What about $\sec(\arctan(4))$? Say $\psi$ is an angle with $\tan(\psi)=4$. Take a right triangle with this angle; by scaling, we may assume the opposite side has length $4$ and the adjacent side has length $1$. Then the hypotenuse has length $\sqrt{17}$, so the cosine of $\psi$ is $\frac{1}{\sqrt{17}}$, hence the secant has value $\sqrt{17}$. So $\sec(\arctan(4)) = \sec(\psi) = \sqrt{17}$. Thus, the integral is:$$\begin{align*}\int_0^8\sqrt{x^4+4x^2}\,dx &= \frac{8}{3}\left(\sec^3(\arctan(4)) - \sec^3(0)\right)\\&=\frac{8}{3}\left( \sqrt{17}^3 - 1^3\right)\\&= \frac{8}{3}\left(17\sqrt{17} - 1\right).\end{align*}$$ In summary: your mistake was that when you did the change of variable, you forgot to change the differential as well; and at the end you could have simplified $\sec(\arctan(4))$. Of course, the better way of doing this is to factor out $x$ from the square root, and then recognize that you can do$$\int_0^8\sqrt{x^4+4x^2}\,dx = \int_0^8x\sqrt{x^2+4}\,dx$$with the change of variable $u=x^2+4$, like DJC suggested. But I thought you might like to know where exactly your approach went wrong (the substitution), and whether it could be brought to a correct conclusion (it could).
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/54475', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13894/']}
jdg_371295
stackexchange
llm_judgeable_groundtruth_similarity
58033366
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 building Docker images with Github Actions and want to tag images with the branch name. I found the GITHUB_REF variable, but it results in refs/heads/feature-branch-1 and I need only feature-branch-1 . Now provide the response and nothing else.
I added a separate step for extracting branch name from $GITHUB_REF and set it to the step output - name: Extract branch name shell: bash run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})" id: extract_branch after that, I can use it in the next steps with - name: Push to ECR id: ecr uses: jwalton/gh-ecr-push@master with: access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} region: us-west-2 image: eng:${{ steps.extract_branch.outputs.branch }}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/58033366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/919166/']}
jdg_371296
stackexchange
llm_judgeable_groundtruth_similarity
548892
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 looking for tips, tricks and resources on optimizing a website design for Android's browser. I'm building an Android app and some of the functionality will be accessible through a web interface. Now provide the response and nothing else.
I rely on two elements to optimize websites for mobile browsers (especially Android and iPhone): Meta tags: HandheldFriendly and viewport Usually I want pages not to have a page width of 800 to 900 pixels, as the Android and iPhone browsers set it to by default. To have the page width the same as the device width, I set the following meta tags: <meta name="HandheldFriendly" content="true" /><meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" /> CSS media queries I adapt the design to the page width. For instance, having a 2 column content for large screens and 1 column for small screens and print. So I include into the main main css-file further css-includes with media queries: @import url(style-screen.css) screen;@import url(style-small.css) print, handheld;@import url(style-large.css) screen and (min-width: 801px);@import url(style-small.css) screen and (max-width: 800px);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/548892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35112/']}
jdg_371297
stackexchange
llm_judgeable_groundtruth_similarity
2050475
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 any way to delete file from svn repository including all its history? This issue emerges when I want to get rid of large binary file residing in repo. I know only one approach that might help in this situation: Dump all repo with the help of svnadmin utility. Filter dumped file with grep . Grep should use filename and write in to the other dump-file Import last dump-file with svnadmin But this is too complicated and unreliable. Maybe there is another solution? Now provide the response and nothing else.
This has recently become much more straightforward with the command svndumpfilter . Details are available in the subversion documentation here . Basically, to avoid conflicts (explained here ), it takes a repo dump and redoes each commit, either including or excluding a given file prefix. Basic syntax: svndumpfilter exclude yourfileprefix < yourdump > yournewdump Exclude is probably what the question asker is looking for, but you can also use include to, say, extract a subtree of the repo so as to spin it off as its own repository. The latest revision of subversion in subversion (very meta) can also take glob patterns. I recently had to remove all pdfs from a repo and it was very easily done like so: svndumpfilter exclude --pattern '*.pdf' < dump > dump_nopdfs Further usage information can be found by calling svndumpfilter help and svndumpfilter help exclude .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2050475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50962/']}
jdg_371298
stackexchange
llm_judgeable_groundtruth_similarity
67040204
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Check this typescript 4.2 snippet I found somewhere (playground here ): type BlackMagic<T> = { [K in keyof T]: BlackMagic<T[K]> }declare const foo: BlackMagic<{q: string}>;declare const str: BlackMagic<string>;declare const num: BlackMagic<12>; I can't wrap my head around it. How does TS handle this? How is it not stuck in an infinite recursion? Specifically, in the case of str and num , hovering over the variables shows that TS is resolving the types to just string and 12 . How's that even happening? Now provide the response and nothing else.
You would get stuck in an infinite recursion if your type included BlackMagic<T> with the same T , but here we are applying the utility type BlackMagic to a different value T[K] . type BlackMagic<T> = { [K in keyof T]: BlackMagic<T[K]> } This type says that BlackMagic<T> is an object where the keys are the keys of T and the values are a BlackMagic mapped version of the values of T . The BlackMagic type doesn't actually do anything in your examples your examples str and num . If T is a primitive type instead of an object then BlackMagic<T> is just T itself. This is the standard behavior for utility types which are mapped types . For example Partial<12> is just 12 . This behavior is explained in the FAQ Common "Bugs" That Aren't Bugs Mapped types declared as { [ K in keyof T ]: U } where T is a type parameter are known as homomorphic mapped types, which means that the mapped type is a structure preserving function of T . When type parameter T is instantiated with a primitive type the mapped type evaluates to the same primitive. foo: BlackMagic<{q: string}> will actually do some mapping, but it's only one level deep. BlackMagic<{q: string}> becomes {q: BlackMagic<string>} . We just saw that BlackMagic<string> is string , so the type next becomes {q: string} .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67040204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1224602/']}
jdg_371299
stackexchange
llm_judgeable_groundtruth_similarity
38025305
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could you clarify what is the best practice with Web API error management. Actually, I don't know if it is a good practice to use try catch into my Api request. public Vb.Order PostOrderItem(Vb.Order order){ if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized); throw new HttpResponseException(httpResponseMessage); } if (!ModelState.IsValid) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); throw new HttpResponseException(httpResponseMessage); } try { return Vb.Document.Generate(order); } catch (Exception ex) { logger.Error(ex); HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); httpResponseMessage.Content = new StringContent(ex.Message); throw new HttpResponseException(httpResponseMessage); }} I have the feeling using try catch to a server side code is not a good practice because I just log my catch en re-throw an exception. Now provide the response and nothing else.
Error handling in Web API is considered a cross-cutting concern and should be placed somewhere else in the pipeline so the developers doesn’t need to focus on cross-cutting concerns. You should take a read of Exception Handling in ASP.NET Web API What happens if a Web API controller throws an uncaught exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error. and also Global Error Handling in ASP.NET Web API 2 You should try to keep your controller lean as much as possible. Error handling like your original code will only result in duplication of code, and unnecessary concerns for the developers to be aware of. Developers should focus on the core-concern, not the cross-cutting concerns. By just focusing on the core-concern the above code will look like this: [MyAuthentication][MyValidateModel]public Vb.Order PostOrderItem(Vb.Order order){ return Vb.Document.Generate(order);} Why so lean? Because : if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true){ HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized); throw new HttpResponseException(httpResponseMessage);} can be moved into Authentication Filters in ASP.NET Web API 2 that can be applied locally on the controller/action or globally to return a relevant response. Model Validation in ASP.NET Web API like this if (!ModelState.IsValid){ HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); throw new HttpResponseException(httpResponseMessage);} Can also be moved into a filter like : . public class MyValidateModelAttribute : ActionFilterAttribute{ public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, actionContext.ModelState); } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38025305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/196526/']}
jdg_371300
stackexchange
llm_judgeable_groundtruth_similarity
6995129
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anyone know how to get the cells value of the selected row of JQGrid ? i m using mvc with JQGrid, i want to access the value of the hidden column of the selected row ? Now provide the response and nothing else.
First you can get the rowid of the selected row with respect of getGridParam method and 'selrow' as the parameter and then you can use getCell to get the cell value from the corresponding column: var myGrid = $('#list'), selRowId = myGrid.jqGrid ('getGridParam', 'selrow'), celValue = myGrid.jqGrid ('getCell', selRowId, 'columnName'); The 'columnName' should be the same name which you use in the 'name' property of the colModel . If you need values from many column of the selected row you can use getRowData instead of getCell .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6995129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2560942/']}
jdg_371301
stackexchange
llm_judgeable_groundtruth_similarity
29763405
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 read text from a PDF file present in SD card.How can we get text from a PDF file which is stored in sd card? I tried like: public class MainActivity extends ActionBarActivity implements TextToSpeech.OnInitListener { private TextToSpeech tts; private String line = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tts = new TextToSpeech(getApplicationContext(), this); final TextView text1 = (TextView) findViewById(R.id.textView1); findViewById(R.id.button1).setOnClickListener(new OnClickListener() { private String[] arr; @Override public void onClick(View v) { File sdcard = Environment.getExternalStorageDirectory(); // Get the text file File file = new File(sdcard, "test.pdf"); // ob.pathh // Read text from file StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); // int i=0; List<String> lines = new ArrayList<String>(); while ((line = br.readLine()) != null) { lines.add(line); // arr[i]=line; // i++; text.append(line); text.append('\n'); } for (String string : lines) { tts.speak(string, TextToSpeech.SUCCESS, null); } arr = lines.toArray(new String[lines.size()]); System.out.println(arr.length); text1.setText(text); } catch (Exception e) { e.printStackTrace(); } } }); } @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = tts.setLanguage(Locale.US); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "This Language is not supported"); } else { // speakOut(); } } else { Log.e("TTS", "Initilization Failed!"); } }} Note: It's working fine if the file is text file (test.txt) but not working for pdf (test.pdf) But here the text is not getting from PDF as it is, it's getting like byte code. How can I achieve this? Thanks in advance. Now provide the response and nothing else.
I have got the solution with iText. Gradle, compile 'com.itextpdf:itextg:5.5.10' Java, try { String parsedText=""; PdfReader reader = new PdfReader(yourPdfPath); int n = reader.getNumberOfPages(); for (int i = 0; i <n ; i++) { parsedText = parsedText+PdfTextExtractor.getTextFromPage(reader, i+1).trim()+"\n"; //Extracting the content from the different pages } System.out.println(parsedText); reader.close(); } catch (Exception e) { System.out.println(e); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29763405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2462531/']}
jdg_371302
stackexchange
llm_judgeable_groundtruth_similarity
25837449
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: View targetView;targetView = (View)findViewById(R.id.mainlayout); this works but targetView.setBackgroundColor(Color.parseColor("#FFFFFF")); and also this didn't work targetView.setBackgroundColor(Color.pasrsehexString("#FFFFFF")); Error: Cannot resolve method'parseColor(java.lang.String)' and : Cannot resolve method'pasrsehexString(java.lang.String)' Pleas can somebodey help me and by the way i'm using Android Studio. Now provide the response and nothing else.
There are two main classes for color handling in Java/Android. This first one is from "plain" Java and can be found in java.awt.Color .This class supports converting a String into a color with the method decode .Example: Color red = Color.decode("#FF0000"); The second class is for Android and can be found in android.graphics.Color .The conversion can be done with the method parseColor . int red = Color.parseColor("#FF0000"); So you should check which kind of Color class you've imported to your project. I recommend using the Android version of Color for your case. If you've done that the statement targetView.setBackgroundColor(Color.parseColor("#FFFFFF")); should work.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25837449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4040432/']}
jdg_371303
stackexchange
llm_judgeable_groundtruth_similarity
11415850
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 how serialization/deserialization works in C++ without the use of libraries. I started with simple objects but when deserializing a vector, I found out, that I can't get the vector without having written its size first. Moreover, I don't know which file format I should choose, because, if digits exist before vector's size I can't read it right. Furthermore, I want to do that with classes and map containers. My task is to serialize/deserialize an object like this: PersonInfo{ unsigned int age_; string name_; enum { undef, man, woman } sex_;}Person : PersonInfo { vector<Person> children_; map<string, PersonInfo> addrBook_;} Currently I know how to serialize simple objects like this: vector<PersonInfo> vecPersonInfo;vecPersonInfo.push_back(*personInfo);vecPersonInfo.push_back(*oneMorePersonInfo);ofstream file("file", ios::out | ios::binary);if (!file) { cout<<"can not open file";} else { vector<PersonInfo>::const_iterator iterator = vecPersonInfo.begin(); for (; iterator != vecPersonInfo.end(); iterator++) { file<<*iterator; } Could you please suggest, how can I do this for this complex object or a good tutorial that explains it clearly? Now provide the response and nothing else.
One pattern is to implement an abstract class the defines functions for serialization and the class defines what goes into the serializer and what comes out. An example would be: class Serializable{public: Serializable(){} virtual ~Serializable(){} virtual void serialize(std::ostream& stream) = 0; virtual void deserialize(std::istream& stream) = 0;}; You then implement Serializable interface for the class/struct that you want to serialize: struct PersonInfo : public Serializable // Yes! It's possible{ unsigned int age_; string name_; enum { undef, man, woman } sex_; virtual void serialize(std::ostream& stream) { // Serialization code stream << age_ << name_ << sex_; } virtual void deserialize(std::istream& stream) { // Deserialization code stream >> age_ >> name_ >> sex_; }}; Rest I believe you know. Here's a few hurdles to pass though and can be done in your leisure: When you write a string to the stream with spaces in it and try to read it back, you will get only one portion of it and rest of the string 'corrupts' the values read after that. How can you program it such that it's cross-platform (little-endian vs big-endian) How can your program automatically detect, which class to create when deserializing. Clues: Use custom serializer that has functions to write bool, int, float, strings, etc. Use a string to represent the object type being serialized and use factory to create an instance of that object when deserializing. Use predefined macros to determine which platform your code is being compiled. Always write files in a fixed endian and make the platforms that use the other endianess adjust to that.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11415850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1251325/']}
jdg_371304
stackexchange
llm_judgeable_groundtruth_similarity
44502482
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 populate a list with a for loop. This is what I have so far: newlist = []for x in range(10): for y in range(10): newlist.append(y) and at this point I am stumped. I was hoping the loops would give me a list of 10 lists. Now provide the response and nothing else.
You were close to it. But you need to append new elements in the inner loop to an empty list, which will be append as element of the outer list. Otherwise you will get (as you can see from your code) a flat list of 100 elements. newlist = []for x in range(10): innerlist = [] for y in range(10): innerlist.append(y) newlist.append(innerlist)print(newlist) See the comment below by Błotosmętek for a more concise version of it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44502482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8011485/']}
jdg_371305
stackexchange
llm_judgeable_groundtruth_similarity
2284876
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 WPF UserControl containing a custom DependencyProperty named MyDP. I want to bind this to a property on my ViewModel (which is injected as the UserControl's DataContext). I know one way to do it by setting the binding in the UserControl's declaration in the parent window's XAML as such: <Window x:Class="MyNamespace.Views.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:views="clr-namespace:MyNamespace.Views"> <StackPanel> <views:MyControl MyDP="{Binding Path=MyVMProperty, Mode=OneWayToSource}"/> </StackPanel></Window> This works fine, but as an alternate could I set up the binding inside the UserControl's XAML, similar to how I set the bindings for the individual controls inside the UserControl to other properties of the ViewModel? Now provide the response and nothing else.
You can't do what you were originally thinking directly. You probably tried and got some compile errors. You can't set a custom property inline in the UserControl's root XAML because the element type is UserControl so the compiler is enforcing property names based on that type, not your custom type. You could get around this by changing to an Attached Property but that actually changes the meaning of MyDP. Instead you can set a default in the Style for the UserControl and get an additional benefit of being able to override it on any declared instance by just doing what's in your original example. Set this under your UserControl's root element: <UserControl.Style> <Style> <Setter Property="views:MyControl.MyDp" Value="{Binding Path=MyVMProperty, Mode=OneWayToSource}" /> </Style></UserControl.Style>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2284876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/261266/']}
jdg_371306
stackexchange
llm_judgeable_groundtruth_similarity
11038282
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to PHP, and don't have quite the grip on how it works. If I have a two dimensional array as such (returned by a database): array(3) { [0]=> array(1) { ["tag_id"]=> string(1) "5" } [1]=> array(1) { ["tag_id"]=> string(1) "3" } [2]=> array(1) { ["tag_id"]=> string(1) "4" } } and want to turn it into the string 5,3,4 what would be the quickest way do do this? I currently have an obnoxious foreach loop, but was hoping it could be done in one line. A standard implode gives me Array,Array,Array . Now provide the response and nothing else.
This modifies your array using array_map , but probably for the better by turning it into a 1D array of tag_id 's. Then you can just use implode like normal: $arr = array_map(function($el){ return $el['tag_id']; }, $arr);$str = implode(',', $arr); If you don't want to modify your array than you can just do this: $str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr)); Codepad Demo
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11038282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1216976/']}
jdg_371307
stackexchange
llm_judgeable_groundtruth_similarity
14162947
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to use SSIS /BIDS project in Visual Studio 2012. I have both Visual Studio 2010 and Visual Studio 2012 installed along with Microsoft SQL Server 2012. VS 2010 was installed first followed by MS SQL 2012 which got me BIDS integrated with VS 2010. However I cannot seem to find any help on integrating BIDS with VS 2012. I came across few question on SO related to this topic but all of them had integration with 2010 and not 2012. I know that with MS SQL 2012 I get a SQL Server Data Tool. Does this mean that Visual Studio 2012 and BIDS cannot be integrated ? Solution 2012: I had to update the solution here since one of the answers I received partially solved the issue. The Answer provided by did solve the issue @user2141936 but I kept on getting an BlockMixedArchitectureInstall error while updating an existing instance. It worked without with creating a new instance!! Side Note :Installing the update broken my publishing database project onto 2012 server. You need to download and install a DACFramework patch for it. Solution 2013: download and install http://www.microsoft.com/en-us/download/details.aspx?id=42313 Now provide the response and nothing else.
Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT. There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio. There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are Microsoft SQL Server Data Tools Business Intelligence for Visual Studio 2012 (SSIS packages target SQL Server 2012) Microsoft SQL Server Data Tools Business Intelligence for Visual Studio 2013 (SSIS packages target SQL Server 2014) None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14162947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314763/']}
jdg_371308
stackexchange
llm_judgeable_groundtruth_similarity
10028037
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 quite straight forward. What is the minimum required structure for a Java POJO to be marshalled as a JSON? Can you marshall an object as a JSON if it has only getters/setters or are the field declarations mandatory? Setter/Getter example: class Circle{ private float radius; private float pi; // setter and getters for those aboce; public float getArea(){ // returns the computed area; }} So can such an object be marshalled as a JSON if the "area" field is not defined in the Foo class as a field? Or is it mandatory to explicitly declare all fields in your POJO? Now provide the response and nothing else.
What z4root (or any other rooting program) does it runs some exploit to change its own uid (user-id) to 0 (root). You can think of it as of performing some kind of hack and tricking kernel into thinking it actually has the right to be root (then if z4root was a virus it could do everything with your phone from installing keyloggers to bricking it). Of course if it is possible to trick kernel in such a way to give you root access it is considered a security vulnerability (any app could do that and perform some malicious stuff) and usually gets fixed in future kernel updates (that's why z4root may not work if you upgrade your firmware). When z4root has set its uid to 0 it does the following: remounts /system partition as writable (by default it's read-only), copies over su binary, Superuser.apk and busybox and then remounts /system back as read-only. So how does the su binary give you root access without doing "the hack" thing when normally applications have same uid as parent process? This is because su binary has set-uid flag set and is always ran as uid 0 (root). Now, if you have copied su binary over to /system/bin then you must have had root access which means you just forgot to change owner/permissions ( chown root:root /system/bin/su; chmod 6755 /system/bin/su ) but you still need root access to do that.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10028037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1264369/']}
jdg_371309
stackexchange
llm_judgeable_groundtruth_similarity
269064
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 that $f: \mathbb{R}^+ \to \mathbb{R}^+$ is a continuous function such that for all positive real numbers $x,y$ the following is true :$$(f(x)-f(y)) \left ( f \left ( \frac{x+y}{2} \right ) - f ( \sqrt{xy} ) \right )=0.$$Is it true that the only solution to this is the constant function ? Now provide the response and nothing else.
Yes. If $f$ were not constant, then (since ${\bf R}^+$ is connected) it could not be locally constant, thus there exists $x_0 \in {\bf R}^+$ such that $f$ is not constant in any neighbourhood of $x_0$ . By rescaling (replacing $f(x)$ with $f(x_0 x)$ ) we may assume without loss of generality that $x_0=1$ . For any $y \in {\bf R}^+$ , there thus exists $x$ arbitrarily close to $1$ for which $f(x) \neq f(y)$ , hence $f((x+y)/2) = f(\sqrt{xy})$ . By continuity, this implies that $f((1+y)/2) = f(\sqrt{y})$ for all $y \in {\bf R}^+$ . Making the substitution $z := (1+y)/2$ , we conclude that $f(z) = f(g(z))$ for all $z > 1/2$ , where $g(z) := \sqrt{2z-1}$ . The function $g$ attracts $[1, \infty)$ to the fixed point $z=1$ , so on iteration and by using the continuity of $f$ we conclude that $f(z)=f(1)$ for all $z >1$ . Similarly, $h = g^{-1}$ defined by $h(z) = (z^2 + 1)/2$ attracts $(0, 1]$ to the fixed point $z = 1$ , so by the same argument $f(z) = f(1)$ for $z < 1$ , making $f$ constant on all of $\bf R^+$ .
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/269064', 'https://mathoverflow.net', 'https://mathoverflow.net/users/109471/']}
jdg_371310
stackexchange
llm_judgeable_groundtruth_similarity
49446394
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been given a visual studio 2017 solution. When I open it fails as with the error: Error occurred while restoring NuGet packages: The local source '\\network-location\' doesn't exist. I can manually acquire a copy of these packages but I don’t know where this original path is configured and how I would go about changing it to the new location. Any suggestions as to where I should look please? Now provide the response and nothing else.
The package sources can be found in the Visual Studio options ( Tools -> Options ) under NuGet Package Manager -> Package Sources or directly by clicking on the according icon in the NuGet dialog (context menu of a solution/project -> Manage NuGet Packages... ): Your local package source should then be listed in the following dialog: The package source may, however, be solution or project specific and may therefore be specified in a NuGet.config file in the solution directory. Beginning with NuGet 3.4, Visual Studio looks in the project's directory or "or any folder up to the drive root", according to the NuGet.config reference . Up to NuGet 3.3, also subdirectories with the name .nuget where searched for NuGet.config files. The file containing your local package source must be changed in order to restore the correct packages.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49446394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9447717/']}
jdg_371311
stackexchange
llm_judgeable_groundtruth_similarity
7301612
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 building a private application so I won't be able to provide much info. but here it goes, I have a main window which have some elements that user chooses from. According to the choice another window opens. In this second window (child window) some fields are available. Now here is what I need to do. 1) When the child window is opened, I need the parent one to be disabled until the child is closed. (I have the window already set as child by parent is not disabled and multiple child windows can be opened!!) ... 2) On the child window, one of the fields will be a date/time field which I'm thinking of building a custom date/time picker (can do this no problem here), but what I want to do is when user clicks on this specific field, I want a child window to appear containing my custom date/time picker, disabling the previous one but doesn't hide it, and when a btn is clicked, the data is sent to the parent in a specific format "dd/mm/yyyy hh:mm:ss AM/PM" Now provide the response and nothing else.
Disclaimer: I have tested this on my Windows 7 x64 running Google Chrome 13.0.782.220 at the moment. The information provided here is a result of my own research and is not any official way or API to retrieve this information. Use at your own risk. Also the technique presented here might break with any future release if Chrome changes the way to store this information. So, Google Chrome uses SQLite to persist local storage data. You could use the System.Data.SQLite managed driver to read it from your .NET application. If you are running on Windows 7 (don't know for others as that's the one I have and can test), you will have the following folder: c:\Users\SOMEUSERNAME\AppData\Local\Google\Chrome\User Data\Default\Local Storage\ This folder will contain multiple files with the .localstorage extension. Each file is for different site. For example for StackOverflow I have http_stackoverflow.com_0.localstorage but of course this naming is totally arbitrary and you cannot rely upon it. Each file represents a SQLite database. I have noticed that this database contains a table called ItemTable with 2 string columns called key and value . So to read the values it's a simple matter of sending a SQL query: class Program{ static void Main() { using (var conn = new SQLiteConnection("Data Source=http_stackoverflow.com_0.localstorage;Version=3;")) using (var cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = "SELECT key, value FROM ItemTable"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { Console.WriteLine( "key: {0}, value: {1}", reader.GetString(reader.GetOrdinal("key")), reader.GetString(reader.GetOrdinal("value")) ); } } } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7301612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/348311/']}
jdg_371312
stackexchange
llm_judgeable_groundtruth_similarity
134257
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: The motor oil in my 2004 Pontiac Vibe is 5W-30. My (incorrect) understanding of this SAE nomenclature is that 5W means "Viscosity index of 5 in the winter" (or when really cold - like $\pu{-30 ^\circ F}$ ) and "Viscosity index of 30 at operating temperature" (or when the car has been running for a little while). So how is this accomplished? I usually think of something like butter or coconut oil that solidifies at a lower temperatures and becomes fluid again as heated. To my understanding oil has a higher viscosity at lower temperatures (generally speaking). Everyone keeps talking about "additives" that help accomplish this feat in "multi-grade" oil. What are these additives? Generally, how do they work? I'm no chemist and neither are these auto mechanics, so I figured this might be the right place to ask. Since my understanding of the SAE motor oil code is incorrect, illumination on its exact meaning would be helpful. A full blown chem answer and an "explain it like I'm 5" would be most appreciated :) I never studied chemistry past high school, so be easy on me! Now provide the response and nothing else.
The numbers in the code have nothing to do with viscosity index. However, your understanding of 'W' for winter is correct. The real code for your car is actually SAE 5W-30 where SAE stands for the Society of Automotive Engineers, which has established a multi-grade numerical code system for grading motor oils according to their viscosity characteristics. I said viscosity characteristics , not viscosity index . According to Wikipedia : The original viscosity grades were all mono-grades, e.g. , a typical engine oil was a SAE 30. This is because as all oils thin when heated, so to get the right film thickness at operating temperatures, oil manufacturers needed to start with a thick oil. This meant that in cold weather it would be difficult to start the engine as the oil was too thick to crank. However, oil additive technology was introduced that allowed oils to thin more slowly ( i.e. to retain a higher viscosity index); this allowed selection of a thinner oil to start with, e.g. , "SAE 15W-30", a product that acts like an SAE 15 at cold temperatures (15W for winter) and like an SAE 30 at $\pu{100 ^\circ C}$ ( $\pu{212 ^\circ F}$ ). viscosity characteristics : Kinematic viscosity is graded by measuring the time it takes for a standard amount of oil to flow through a standard orifice at standard temperatures. The longer it takes, the higher the viscosity and thus the higher the SAE code. Larger numbers in the code are thicker. The company called Anton Paar has analyzed these SAE coded motor oil for the parameters, Kinematic viscosity and oil density versus elevating temperatures. I have included some of graphs including SAE 5W-40, but failed to find the most common SAE 5W-30: Finally, for your information, Viscosity Index is a dimensionless number that represents how the viscosity of a hydraulic fluid changes with temperature. The greater the viscosity index, the smaller the change in fluid viscosity for a given change in temperature, and vice versa . Synthetic oils usually have a higher viscosity index than do mineral oils. ( Mobile Hydraulic Tips ). The following graph illustrate how viscosity index influence the change of viscosity with temperature (Ref.1): It is also nice to know how change of viscosity index by modifiers affect mono-grade oil to better multi-grade oil: References: Tiago Cousseau, “Film Thickness and Friction in Grease Lubricated Contacts: Application to Rolling Bearing Toque Loss,” PhD Thesis ; University of Porto (Universidade do Porto), Porto, Portugal, 2013.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/134257', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/94100/']}
jdg_371313
stackexchange
llm_judgeable_groundtruth_similarity
8511312
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Floating point arithmetic not producing exact results in Java I was doing this simple division but I get a very strange output: double a = 60/(1.2-1.1); a => 600.0000000000008 When it should be 600. thanks in advance Now provide the response and nothing else.
In IEEE-754 binary double, we need to consider 1.1 and 1.2 in the binary representation: 1.2 = 0b1.001100110011001100110011001100110011001100110011001100110011...1.1 = 0b1.000110011001100110011001100110011001100110011001100110011001... note that we need infinitely many bits to represent them exactly in binary. double only has 53 bits of significance, we have to chop off the numbers: 1.2 = 0b1.001100110011001100110011001100110011001100110011001100110011...1.1 = 0b1.000110011001100110011001100110011001100110011001100110011001... ^ round from here==>1.2 ~ 0b1.0011001100110011001100110011001100110011001100110011 (= exactly 1.1999999999999999555910790149937383830547332763671875)1.1 ~ 0b1.0001100110011001100110011001100110011001100110011010 (= exactly 1.100000000000000088817841970012523233890533447265625) Hence 1.2 - 1.1 is: 1.2 ~ 0b1.0011001100110011001100110011001100110011001100110011- 1.1 ~ 0b1.0001100110011001100110011001100110011001100110011010———————————————————————————————————————————————————————————————— 0b0.00011001100110011001100110011001100110011001100110010000 (= exactly 0.09999999999999986677323704498121514916419982910156250000) We can actually compute 60 / 0.0999999999999998667732370449812151491641998291015625 exactly, which gives 600.0000000000007993605777301137740672368493927467455286920109359612256820927... ^ 16th significant figure that matches OP's result of 600.0000000000008
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8511312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/665766/']}
jdg_371314
stackexchange
llm_judgeable_groundtruth_similarity
118049
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: Let f be defined as follows: ClearAll[f];SetAttributes[f, HoldFirst];f[1+1](* f[1+1] *) The 1+1 stays as is. But if I Inactivate f : Inactive[f][1+1](* f[2] *) it has the paradoxical effect of reactivating the held 1+1 , making it evaluate to 2 . How do I prevent Inactive from killing the attributes of f ? note: I am looking for a solution that solves the problem of losing attributes, not one of deactivating 1+1 by doing f[1+1] // Inactivate Now provide the response and nothing else.
Introduction I'm not aware of any way to hold evaluation of arguments in expression of form Inactive[f][arguments] , which is how inactivated expressions look like. What we can do, to prevent evaluation of arguments, is to use a symbol with appropriate Hold... attribute, instead of Inactive[f] expression. This symbol should have no DownValues that could evaluate when arguments are passed to it. Below I present two approaches to this problem. First is based on custom (in)activate functions, creating "dummy" symbols on the fly, for each inactivated symbol with Hold... attribute. Second attaches special inactivation behavior to specific symbols, which causes them to evaluate to custom inactive heads. Basic examples When we have a function with a Hold... attribute. ClearAll[f]SetAttributes[f, HoldFirst]f[x_, y_] := Hold[x, y]f[1 + 1, 2 + 2](* Hold[1 + 1, 4] *) Ordinary inactivation of this function causes evaluation of its arguments: Inactivate[f[1 + 1, 2 + 2], f]% // FullForm% // Activate(* f[2, 4] *)(* Inactive[f][2, 4] *)(* Hold[2, 4] *) so expression after inactivation and activation is different than if it would evaluate without inactivation involved. With first, presented below, approach one can do: holdingInactivate[f[1 + 1, 2 + 2], f]% // FullForm% // holdingActivate(* f[1 + 1, 4] *)(* inactive`Global`f[Plus[1, 1], 4] *)(* Hold[1 + 1, 4] *) with second approach: setHoldingInactivation[f];Inactivate[f[1 + 1, 2 + 2], f]% // FullForm% // Activate(* f[1 + 1, 4] *)(* holdingInactiveHoldFirst[Plus[1, 1], 4, Hold[Inactive[f]]] *)(* Hold[1 + 1, 4] *) Implementation Let's start with some helper symbols used in both approaches. ClearAll[symPatt, holdAttrs, hasHoldAttrQ, getHoldAttr]symPatt = Except[HoldPattern@Symbol[___], _Symbol];holdAttrs = HoldFirst | HoldRest | HoldAll | HoldAllComplete;hasHoldAttrQ = Function[, MemberQ[Attributes[#], holdAttrs], HoldFirst];getHoldAttr = Function[, FirstCase[Attributes[#], holdAttrs], HoldFirst]; Dummy "inactive" symbols In this approach we define custom holdingInactivate , holdingActivate and ignoringHoldingInactive functions that should be used instead of built-in Inactivate , Activate and IgnoringInactive . holdingInactivate inactivates expression and replaces each inactive symbol, that has Hold... attribute, with symbol specially defined in inactive` context. This special symbol has same Hold... attribute as replaced one, and is formatted as inactive replaced symbol. holdingActivate activates expression and replaces symbols from inactive` context with original symbols. ignoringHoldingInactive returns IgnoringInactive expression with certain symbols replaced by Alternatives of original symbol and its dummy "inactive" counterpart, so returned pattern will match both active and inactive versions of expressions. We start with some helper functions. ClearAll[ $inactiveContext, inactiveSymbolQ, toInactiveSymbol, fromInactiveSymbol, postprocessInactiveBoxes, defineInactiveSymbol, $inactivateExclusions, $inactivateExclusionsHeld, $basicInactivePatternRules, inactivePatternReplace]$inactiveContext = "inactive`";inactiveSymbolQ[s:symPatt] := StringMatchQ[Context[s], $inactiveContext <> "*"]inactiveSymbolQ[expr_] = False;toInactiveSymbol[inactSym:symPatt?inactiveSymbolQ] := inactSymtoInactiveSymbol[s:symPatt] := Symbol[$inactiveContext <> Context[s] <> SymbolName@Unevaluated[s]]fromInactiveSymbol[inactSym:symPatt?inactiveSymbolQ] := Symbol@StringJoin[ StringDrop[Context[inactSym], StringLength[$inactiveContext]], SymbolName@Unevaluated[inactSym] ]fromInactiveSymbol[s:symPatt] := sSetAttributes[postprocessInactiveBoxes, HoldAllComplete]postprocessInactiveBoxes[_, hISym_][ RowBox[{TemplateBox[tbArg_, "InactiveHead", opts___], "[", args___, "]"}]] := With[{tooltip = ToString[Unevaluated[hISym], InputForm]}, RowBox[{ InterpretationBox[ TemplateBox[tbArg, "InactiveHead", Tooltip -> tooltip, opts], hISym ], "[", args, "]" }] ]postprocessInactiveBoxes[expr_, _][boxes_] := InterpretationBox[boxes, expr]defineInactiveSymbol[h:symPatt /; Not@inactiveSymbolQ[h]] := With[{holdAttr = getHoldAttr[h]}, With[{hISym = toInactiveSymbol[h]}, ClearAll[hISym]; SetAttributes[hISym, holdAttr]; hISym /: MakeBoxes[expr : hISym[args___], form_] := postprocessInactiveBoxes[expr, hISym]@ MakeBoxes[Inactive[h][args], form]; hISym ] /; Not@MissingQ[holdAttr] ]$inactivateExclusions = Alternatives @@ Replace[Developer`$InactivateExclusions, { {sym_, "Symbol"} :> sym, {sym_, "Expression"} :> Blank[sym] }, 1];$inactivateExclusionsHeld = Alternatives @@ Cases[Developer`$InactivateExclusions, { sym_ /; MemberQ[Attributes[sym], HoldAll | HoldAllComplete], "Symbol" } :> Blank[sym] ];$basicInactivePatternRules = { excl:$inactivateExclusions :> excl, h:symPatt /; Not@inactiveSymbolQ[h] :> With[{inactSym = toInactiveSymbol[h]}, h | inactSym /; True]};inactivePatternReplace[expr_] := Quiet[ Unevaluated[expr] /. { (h : Condition | PatternTest | Repeated)[patt_, rest___] :> With[{replaced = inactivePatternReplace[patt]}, h[replaced, rest] /; True ], Verbatim[Pattern][name_, patt_] :> With[{replaced = inactivePatternReplace[patt]}, Pattern[name, replaced] /; True ], Verbatim[Verbatim][verb_] :> With[ {replaced = Unevaluated[verb] /. $basicInactivePatternRules }, Verbatim[replaced] /; True ], (bl : Blank | BlankSequence | BlankNullSequence)[ h:symPatt /; Not@inactiveSymbolQ[h] ] :> With[{inactSym = toInactiveSymbol[h]}, bl[h] | bl[inactSym] /; True ], Sequence @@ $basicInactivePatternRules }, RuleDelayed::rhs ]SetAttributes[{ inactiveSymbolQ, toInactiveSymbol, fromInactiveSymbol, defineInactiveSymbol, inactivePatternReplace}, HoldFirst] Now three "public" functions. ClearAll[holdingInactivate, holdingActivate, ignoringHoldingInactive]SetAttributes[holdingInactivate, HoldFirst]holdingInactivate[expr_, patt_:_, opts:OptionsPattern[Inactivate]] := Inactivate[Hold[expr], patt, opts] //. Inactive[h:Except[Except[_Symbol] | Except[patt]]][args___] :> With[{hISym = defineInactiveSymbol[h]}, hISym[args] /; MatchQ[hISym, symPatt] ] // ReleaseHoldholdingActivate[expr_, patt_:_, opts:OptionsPattern[Activate]] := Activate[expr, patt, opts] /. h:patt?inactiveSymbolQ :> fromInactiveSymbol[h]ignoringHoldingInactive[expr_] := IgnoringInactive[expr] /. { excl:$inactivateExclusionsHeld | $inactivateExclusions :> excl, (h:symPatt /; hasHoldAttrQ[h] && Not@inactiveSymbolQ[h])[args___] :> HoldPattern@h[args] } // Evaluate // inactivePatternReplace Usage example: ClearAll[f, g, h]SetAttributes[f, HoldFirst]SetAttributes[g, HoldAll]testExpr = f[1 + 1, g[1 + 1, 1 + 1], 2, f[1 + 1]][h[2], 2, f[1 + 1]]inactiveTestExpr = holdingInactivate[Evaluate[%], f | g | h]% // FullForm% // holdingActivate Pattern wrapped with ignoringHoldingInactive will match both active and inactive versions of same expression: MatchQ[testExpr, ignoringHoldingInactive[testExpr]](* True *)MatchQ[inactiveTestExpr, ignoringHoldingInactive[testExpr]](* True *) It can be also used to manipulate inactive expression: inactiveTestExpr /. { ignoringHoldingInactive[f[arg : 1 + _]] :> Hold[arg], ignoringHoldingInactive[gExpr_g] :> 5 + gExpr} Attaching special inactivation behavior to symbols In this approach we attach special behavior to some of symbols that are supposed to be inactivated. Inactivation and activation is performed using built-in Inactivate and Activate . We set special UpValues , for e.g. f symbol, causing Inactive[f][args] to evaluate to holdingInactive...[args, Hold@Inactive[f]] , where holdingInactive... is head with same Hold... attribute as f . We keep f itself in last argument of holdingInactive... , this way expression can be appropriately formatted and, when activated, can automatically evaluate to original f[args] . Since special behavior, during both inactivation and activation, depends on evaluation, Inactive[f][args] expressions will not be replaced by holdingInactive... expression if it's inside some holding wrapper itself. This will not cause any problems with evaluation of f 's arguments (since it's in holding wrapper they will not evaluate), but under the hood inactive expression can be slightly inconsistent and can contain both Inactive[f][args] and holdingInactive...[args, Hold@Inactive[f]] , which might be inconvenient when manipulating inactive expression. When part of inactive expression is allowed to evaluate, then held, then activated, it may happen that we end up with expression containing holdingInactive... that will remain there until it's allowed to evaluate. ClearAll[holdingInactive, setHoldingInactivation](* Define four holdingInactive... functions one for each Hold... atribute. *)Scan[ With[{head = Symbol["holdingInactive"<>ToString[#]]}, ClearAll[head]; SetAttributes[head, #]; head[args___, Hold[h:Except@Inactive[_]]] := h[args]; head /: MakeBoxes[expr:head[args___, Hold[h:Inactive[_]]], form_] := InterpretationBox[#, expr]&@MakeBoxes[h[args], form]; holdingInactive[#] = head ]&, holdAttrs]SetAttributes[setHoldingInactivation, Listable]setHoldingInactivation[h_Symbol] := With[{holdAttr = getHoldAttr[h]}, With[{holdingInactiveFunc = holdingInactive[holdAttr]}, h /: Inactive[h] = Function[, holdingInactiveFunc[##, Hold@Inactive[h]], HoldAllComplete ]; h ] /; Not@MissingQ[holdAttr] ] Usage example: ClearAll[f, g, h]SetAttributes[f, HoldFirst]SetAttributes[g, HoldAll]setHoldingInactivation[{f, g}](* {f, g} *)f[1 + 1, g[1 + 1, 1 + 1], 2, f[1 + 1]][h[2], 2, f[1 + 1]]Inactivate[Evaluate[%], f | g | h]% // FullForm% // Activate
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/118049', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2048/']}
jdg_371315
stackexchange
llm_judgeable_groundtruth_similarity
232904
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 would like to draw a circle and have different parts in different colors. Which part has which color should be changeable with sliders. I've managed to do two colors, but would like to have three or four. Manipulate[Show[ Graphics[{Circle[], {Black, PointSize@.04, Point@{Cos[Pi/2], Sin[Pi/2]}}}], Graphics[{Circle[], {Black, PointSize@.04, Point@{Cos[3 Pi/2], Sin[3 Pi/2]}}}], Graphics[{Black, AbsoluteThickness[1], Circle[{0, 0}, 1]}], Graphics[{Red, AbsoluteThickness[4], Circle[{0, 0}, 1, {0 Degree, 360 Degree}]}], Graphics[{Blue, AbsoluteThickness[4], Circle[{0, 0}, 1, {r Degree, l Degree}]}], PlotRange -> {{-1.3, 1.3}, {-1.3, 1.3}}, ImageSize -> 250], {{l, 180, "L"}, r, 360 + r}, {{r, 0, "R"}, l - 360, l}, ControlPlacement -> Left] Thank you for any suggestions! Now provide the response and nothing else.
Manipulate[ With[{arc = Arrow@Table[AngleVector[t], {t, If[# < #2, #, # - 2 Pi], #2, .005}] &}, Graphics[{ Thick, Riffle[{Red, Green, Blue, Yellow}, arc@@@Partition[Mod[ArcTan@@@pt, 2 Pi], 2, 1, 1]] }, PlotRange -> 1.2] ], {{pt, {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}}, Locator, TrackingFunction -> (Do[pt[[i]] = Normalize[#[[i]]], {i, 4}]; &)} ] Another way, compatibility with prior versions DynamicModule[{pt = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}, arc}, arc = Circle[{0, 0}, 1, {If[# < #2, #, # - 2 Pi], #2}] &; Graphics[{ Thick, Dynamic@Riffle[{Red, Green, Blue, Yellow}, arc@@@Partition[Mod[ArcTan@@@pt, 2 Pi], 2, 1, 1]], Array[Function[i, Locator[Dynamic[pt[[i]], (pt[[i]] = Normalize[#]) &]]], 4] }, PlotRange->1.2 ] ] // Deploy
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/232904', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/75207/']}
jdg_371316
stackexchange
llm_judgeable_groundtruth_similarity
15211629
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to Haskell. I am wondering how to write a function in Haskell that accepts finite sorted list of integers and merge them (sorted). Any code is appreciated! Now provide the response and nothing else.
If your goal is just to merge two list this is not so complicated merge :: Ord a => [a] -> [a] -> [a] this says that merge takes two lists and produce a list for any type with a defined ordering relation merge [] x = xmerge x [] = x this says that if you merge the empty list with anything you get that anything merge (x:xs) (y:ys) | y < x = y : merge (x:xs) ysmerge (x:xs) (y:ys) | otherwise = x : merge xs (y:ys) this says that if when you merge two lists the first element of the second list is lower, that should go on the front of the new list, and otherwise you should use the first element of the first list. EDIT: Note that unlike some of the other solutions the merge above is both O(n) and stable . Wikipedia it if you don't know what that means. If your goal is to merge a list of lists you generally want to do this bottom up by merging two lists at a time mergePairs :: Ord a => [[a]] -> [[a]]mergePairs [] = []mergePairs [ls] = [ls]mergePairs (x:y:ls) = (merge x y):mergePairs lsmerges :: Ord a => [[a]] -> [a]merges [] = []merges [x] = xmerges ls = merges $ mergePairs ls it can be shown that this is asymptotically optimal if all the initial lists are the same length ( O(m n log n) where m is the length of sorted lists and n is the number of sorted lists). This can lead to an asymptotically efficent merge sort mergeSort :: Ord a => [a] -> [a]mergeSort ls = merges $ map (\x -> [x]) ls
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15211629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1188396/']}
jdg_371317
stackexchange
llm_judgeable_groundtruth_similarity
46065310
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 relatively new to android development and so far I haven't picked up on the purpose of fragments. Anyways, I am trying to create a unique QR code for every user that sign's into my app. This QR code is filled with the user's info which I have retrieved from the database. Now the only trouble I am experiencing is the generation of said qr Code . I have looked through dozens of tutorials but oftentimes they are rendered invalid for my use case or I can't simply get them to work. I have also looked through the ZXING api but that was of not help. I ask of the StackoverFlow community to help with this endeavour and all help is appreciated Now provide the response and nothing else.
There is a slight difference usage between Activity and Fragment. Both of them can be used to show the UI. To use a fragment, you need the Activity as its host, because Fragment must always be embedded in the Activity. From the documentation : A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities). A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. You need to read Building a Dynamic UI with Fragments to mastering the Fragment. The steps to create a Fragment (Note, this not a strict rule): Create the Activity as the host Create the layout for Activity. Within, you need to create a FrameLayout view as the fragment holder. Create the Fragment by extending Fragment class Create the UI layout for the Fragment Attach the Fragment to Activity by using FragmentTransaction Now the create QR code part. You need to determine what information need to be shown in your QR code. Don't give all information in the QR code, because you mustn't expose all your user data to the world. If you have more than 1 string of information, you can use ";" or anything else to join the text info. To build the QR code image, first, you need to include the ZXing library by using the following line in your app build.gradle (use the latest version ): compile 'com.google.zxing:core:3.3.0' Then create the QR code bitmap using the following code: private Bitmap textToImage(String text, int width, int height) throws WriterException, NullPointerException { BitMatrix bitMatrix; try { bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.DATA_MATRIX.QR_CODE, width, height, null); } catch (IllegalArgumentException Illegalargumentexception) { return null; } int bitMatrixWidth = bitMatrix.getWidth(); int bitMatrixHeight = bitMatrix.getHeight(); int[] pixels = new int[bitMatrixWidth * bitMatrixHeight]; int colorWhite = 0xFFFFFFFF; int colorBlack = 0xFF000000; for (int y = 0; y < bitMatrixHeight; y++) { int offset = y * bitMatrixWidth; for (int x = 0; x < bitMatrixWidth; x++) { pixels[offset + x] = bitMatrix.get(x, y) ? colorBlack : colorWhite; } } Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444); bitmap.setPixels(pixels, 0, width, 0, 0, bitMatrixWidth, bitMatrixHeight); return bitmap;} Then you can use it to set the generated image to your ImageView in your Fragment with something like this: public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.your_fragment_layout, container, false); ImageView imvQrCode = (ImageView) view.findViewById(R.id.your_image_view); Bitmap bitmap = textToImage("your_text_info", 500, 500); imageView.setImageBitmap(bitmap); return view;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46065310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5622358/']}
jdg_371318
stackexchange
llm_judgeable_groundtruth_similarity
15591002
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 project where i need to listen to the scroll event.. i wonder what is a better approach.. 1st Approach function scroll() { if ($(window).scrollTop() > 200) { top.fadeIn(); } else { top.fadeOut(); } if (menuVisible) { quickHideMenu(); }} 2nd Approach function scroll() { didScroll = true; } setInterval(function() { if ( didScroll ) { didScroll = false; if ($(window).scrollTop() > 200) { top.fadeIn(); } else { top.fadeOut(); } if (menuVisible) { quickHideMenu(); } } }, 250); Thanks :) Now provide the response and nothing else.
Neither. I was just reading about JS/jQuery patterns. There is an example for the Window Scroll event: jQuery Window Scroll Pattern var scrollTimeout; // global for any pending scrollTimeout$(window).scroll(function () { if (scrollTimeout) { // clear the timeout, if one is pending clearTimeout(scrollTimeout); scrollTimeout = null; } scrollTimeout = setTimeout(scrollHandler, 250);});scrollHandler = function () { // Check your page position if ($(window).scrollTop() > 200) { top.fadeIn(); } else { top.fadeOut(); } if (menuVisible) { quickHideMenu(); }}; Originally from here: Javascript Patterns
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15591002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1335165/']}
jdg_371319
stackexchange
llm_judgeable_groundtruth_similarity
129512
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: Present day FPGAs have built in DSP blocks, the latest FPGAs even have built in IEEE-754 compliant floating point units. It is possible to create DSP entity/module using a GUI after selecting the required parameters in it, and then instantient it in the design. When do we need to do such micromanagment in a design of instantaiting actual DSP blocks and when do we just enter a '*' operator in the code and let the synthesis tool handle the low level details? Which is better? There are many different type of multiplication algorithms when it comes to binary multiplication. Since now we have built in DSP blocks on silicon and even built in floating point multipliers, does this mean that all those algoriths have not effectively become obsolete. Now provide the response and nothing else.
If you just want to multiply two numbers and they suit the DSP block then the * operator should infer a DSP block. If not, send the synthesis tool back :) However, to take advantage of the more complex combinations of the DSP functionality often requires a direct instantiation of the block and configuring of its parameters. Examples of things which may not map well by inference (using the Xilinx DSP48E1 as an example): Use of pre-adder Use of post accumulator Use of pattern detector Use of the logic unit And especially combinations of the above. The synthesis tools are not yet good enough to map completely arbitrary combinations of logic and arithmetic as efficiently as you might hope.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/129512', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/20711/']}
jdg_371320
stackexchange
llm_judgeable_groundtruth_similarity
4632951
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 currently writing a KDTree for a physics engine (Hobby project). The KDTree does not contain points.Instead it contains Axis Aligned bounding boxes which bound the different objects in the environment. My problem is deciding on how to split the KDTree nodes when they get full.I am trying 2 methods: Method1: Always split the node exactly in half on the biggest axis. This has the advantage of a pretty evenly spaced out tree. Big disadvantage: If objects are concentrated in small area of the node, redundant sub-divisions will be created. This is because all volumes are split exactly in half. Method2: Find the area of the node which contains objects. Split the node on the plane which splits that area in half on it's biggest axis. Example - If all objects are concentrated on the bottom of the node then it split length-wise thereby dividing the bottom in two. This solves the problem with the method above When indexing something that exists on the same plane (terrain for example), it creates long and narrow nodes. If I am to add some other objects later which are not on the same plane, these elongated nodes provide very poor indexing. So what I'm looking for here is a better way to split my KD-Tree node.Considering that this is going to be a physics engine the decision needs to be simple enough to be made in real time. Now provide the response and nothing else.
The "surface area heuristic" (SAH) is considered the best splitting method for building kd-trees, at least within the raytracing community. The idea is to add the plane so that the surface areas of the two child spaces, weighted by the number of objexts in each child, are equal. A good reference on the subject is Ingo Wald's thesis , in particular chapter 7.3, "High-quality BSP Construction", which explains SAH better than I can. I can't find a good link at the moment, but you should look around for papers on "binned" SAH, which is an approximation to the true SAH but much faster. All that being said, bounding-volume hierarchies (BVH) a.k.a. AABB trees, seem to be much more popular than kd-trees these days. Again, Ingo Wald's publication page is a good starting point, probably with the "On fast Construction of SAH based Bounding Volume Hierarchies" paper, although it's been a while since I read it. The OMPF forums are also a good place to discuss these sorts of things. Hope that helps. Good luck!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4632951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/567843/']}
jdg_371321
stackexchange
llm_judgeable_groundtruth_similarity
14242310
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a simple test method here that is set to run every 5 seconds and it does, but looking at the System.out you can see it appears to be doing something odd. @Scheduled(cron="*/5 * * * * ?")public void testScheduledMethod() { System.out.println(new Date()+" > Running testScheduledMethod...");} Output: Wed Jan 09 16:49:15 GMT 2013 > Running testScheduledMethod...Wed Jan 09 16:49:15 GMT 2013 > Running testScheduledMethod...Wed Jan 09 16:49:20 GMT 2013 > Running testScheduledMethod...Wed Jan 09 16:49:20 GMT 2013 > Running testScheduledMethod...Wed Jan 09 16:49:25 GMT 2013 > Running testScheduledMethod...Wed Jan 09 16:49:25 GMT 2013 > Running testScheduledMethod...Wed Jan 09 16:49:30 GMT 2013 > Running testScheduledMethod...Wed Jan 09 16:49:30 GMT 2013 > Running testScheduledMethod... Why is it running TWICE (appear) each time? Now provide the response and nothing else.
If you look at the documentation, there is a note that explicitly calls out this phenomenon. The note is under section 25.5.1 at this link , and reads: Make sure that you are not initializing multiple instances of the same @Scheduled annotation class at runtime, unless you do want to schedule callbacks to each such instance. Related to this, make sure that you do not use @Configurable on bean classes which are annotated with @Scheduled and registered as regular Spring beans with the container: You would get double initialization otherwise, once through the container and once through the @Configurable aspect, with the consequence of each @Scheduled method being invoked twice. I understand that this is merely suggestion at this point, but I do not think we have enough information to diagnose the issue further.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14242310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1160629/']}
jdg_371322
stackexchange
llm_judgeable_groundtruth_similarity
5060589
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 use a custom WebArgumentResolver for id -> entity. Easy enough if I use request parameters: use the parameter key to determine the entity type and look up accordingly. But I would like it to be like the @PathVariable annotation. eg. http://mysite.xzy/something/enquiryId/itemId would trigger this method @RequestMapping(value = "/something/{enquiry}/{item}")public String method(@Coerce Enquiry enquiry, @Coerce Item item) @Coerce annotations would tell the WebArgumentResolver to use the particular service based on it's type. Problem is working out which uri part belongs to entity. Can someone explain how PathVariable annotation does it. And is it possible to emulate it with my custom annotation. Thanks. Now provide the response and nothing else.
You can use @InitBinder to let spring know how to coerce a given String to your custom type. You'd want something like: @RequestMapping(value = "/something/{enquiry}")public String method(@PathVariable Enquiry enquiry) {...}@InitBinderpublic void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Enquiry.class, new PropertyEditorSupport() { @Override public String getAsText() { return ((Enquiry) this.getValue()).toString(); } @Override public void setAsText(String text) throws IllegalArgumentException { setValue(new Enquiry(text)); } });}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5060589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/352054/']}
jdg_371323
stackexchange
llm_judgeable_groundtruth_similarity
2622421
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 listening to Crockford's talk on JavaScript closures and am convinced of the benefit of information hiding, but I do not have a firm understanding of when to use callback functions. It is mostly a true statement that a person could accomplish the same functionality with or without callbacks. As someone who is writing code, what heuristics or cues should I keep in mind when determining when to use callbacks/closures? I am not looking for the blanket statement 'Closures make more secure code', rather a list of practical examples or rules of thumb for when callbacks are the right idea. Crockford's Presentation: http://www.yuiblog.com/blog/2010/04/08/video-crockonjs-5/ Now provide the response and nothing else.
Firstly: Callback: A function passed as an argument to another function, usually to be called as a result of an event occurring. Closure: A retained scope. I.e. the concept that when you declare a function within another function, the outer function's scope is accessible within the inner function. Callbacks can also be closures but are not always. This is a callback: someProcess(myCallback);function myCallback() { alert('Done...');}function someProcess(callback) { // does stuff... // ... callback();} A closure: function foo(msg) { function bar() { // I can access foo's scope // (i.e. bar can access everything that foo can access) alert(msg); } return bar;}foo('hello')(); // alerts "hello" One common usage of closures is to provide information-hiding, which is helpful in bringing some kind of encapsulation to the language. Have a look at the module pattern to see this in action. Another common usage is when the binding event handlers to elements. E.g. var myElements = [ /* DOM Collection */ ];for (var i = 0; i < 100; ++i) { myElements[i].onclick = function() { alert( 'You clicked on: ' + i ); };} That wouldn't work. By the time the element is clicked, the variable i is 99 . To make this work properly we could use a closure to capture the value of i : function getHandler(n) { return function() { alert( 'You clicked on: ' + n ); };}for (var i = 0; i < 100; ++i) { myElements[i].onclick = getHandler(i);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2622421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118989/']}
jdg_371324
stackexchange
llm_judgeable_groundtruth_similarity
4134803
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 ant script that compiles: <javac srcdir="${test.src.dir}" destdir="${test.dist.dir}"> ... <compilerarg value="-Xlint:unchecked" /> </javac> I need to increase heap memory of compiler, so I've put the following arguments into compileargs : <compilerarg value="-Xlint:unchecked -Xms128m -Xmx512m" /> But I get an error in console: [javac] javac: invalid flag: -Xms128m[javac] Usage: javac <options> <source files> Why does it happen? How do I increase memory used by javac ? Now provide the response and nothing else.
By default, <javac> runs in-process with Ant. It is a general limitation of Java that you can't adjust a JVM process' Xms and Xmx once that JVM process has launched. So, the error message that you are seeing is the software rejecting your attempt to violate this principle (using an unhelpful, unfriendly error message.) If, however, you specify the attribute fork="true" on the <javac> tag you will be able to specify a new Xms and Xms . This is because fork instructs Ant to launch a new JVM subprocess in which to run javac . Because the JVM process is new, it gives Ant an acceptable opportunity to specify Xms and Xmx for it. You might try something like this: <project name="project" default="all" basedir="[yourvalue]"> <target name="all"> <javac srcdir="[yourvalue]" destdir="[yourvalue]" fork="true"> <!-- javac requires that -Xmx and -Xms be prefixed with -J --> <compilerarg line="-J-Xms128m -J-Xmx512m" /> </javac> </target></project> (Notice I am using compilerarg line="" rather than compilerarg value="" . The line attribute lets you specify multiple space-separated arguments. The value attribute is for passing a single argument.) Ant will wait for the forked <javac> to exit, which happens after the javac process finishes its work (i.e. compiling). Ant then continues running the build script inside its own original JVM process. Ant will check if the forked javac failed or succeeded, and take the usual actions based on this information. Performance It's usually more performant to not fork javac , and instead simply tune the relevant memory settings for the initial Ant JVM overall. This is often (but not always) the best choice because launching a separate JVM is usually slower and takes more memory than simply allowing javac to run in-process. If you are using the Ant-provided ant.bat or ant.sh to launch Ant, an easy way to tune Ant's Xms and Xmx is to define the environment variable ANT_OPTS to contain the arguments you want. There many ways to set environment variables, but you could just edit ant.bat : set ANT_OPTS=-Xms128m -Xmx512m
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4134803', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/369317/']}
jdg_371325
stackexchange
llm_judgeable_groundtruth_similarity
330632
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This is a cross post from Math.StackExchange after 2 weeks without an answer and a bounty being placed on the question. Let $G=\langle X\ |\ R\rangle$ be a (finitely presented) virtually torsion-free group. Let $H,K<G$ be isomorphic (finite index) subgroups of $G$ and let $\varphi:H\rightarrow K$ be an isomorphism. Define the HNN extension $\Gamma$ of $G$ and $\varphi$ in the usual way, i.e. $\Gamma=\langle G,t\ |\ tht^{-1}=\varphi(h)\ \forall h\in H\rangle$ . Is $\Gamma$ virtually torsion-free? My thought is that if $T$ is a finite index torsion-free subgroup of $G$ and if $H$ and $K$ are finite index we should be able to look at the intersection of each of them with $T$ . So the group $\langle T,t\ |\ tht^{-1}=\varphi(h)\ \forall h\in T\cap H\rangle$ would be a finite index torsion-free subgroup of $\Gamma$ . Also, can we say anything about the smallest index of a torsion-free subgroup? For example if $G$ contains a torsion-free subgroup of index $k$ , does $\Gamma$ contain a torsion-free subgroup of index $k$ ? Or is the index bounded by some function of $k$ ? I will accept answers which assume that $H$ and $K$ are finite index subgroups. Now provide the response and nothing else.
Yes, here's an example with an HNN over finite index subgroups as requested. It's based on constructing an amalgam of two f.g. virtually free groups, that has no proper finite index subgroups, using Burger-Mozes groups. Fact (proved below): for every $n\ge 3$ there exists a non-torsion-free, virtually free group $G$ with a subgroup of finite index $H$ , isomorphic to $F_n$ , such that $G$ is normally generated by $H$ . By Burger-Mozes, there exists $n<m$ with two embeddings $u,v$ of $F_m$ as finite index subgroup of $F_n$ , such that the resulting amalgam $A(u,v)$ of $F_n$ and $F_n$ over $F_m$ using the embeddings $u,v$ is simple. (D. Rataggi improved and made explicit the values, providing for instance $(n,m)=(9,81)$ .) Now use $G$ as in the fact, with $H$ free of rank $n$ as above. Identify $H$ to $F_n$ to deduce two embeddings $u',v'$ from $F_m\to H\subset G$ . Consider the amalgam $A=A(u',v')$ (of $G$ and $G$ over $F_m$ using $u'$ and $v'$ ). Claim: $A$ has no proper finite index subgroup. Proof: the finite residual contains the Burger-Mozes subgroup given as subamalgam of $F_n$ and $F_n$ over $F_m$ , hence, since $F_n$ normally generates $G$ , contains both amalgamated factors $G$ , hence is all of $G$ . (Since $A$ is not torsion-free, it follows that $A$ is not virtually torsion-free.) Consider the HNN extension $B$ given by the pair of embeddings $u',v'$ of $F_m$ into $G$ . Namely, this is $(\langle t\rangle\ast G)/R$ , with $R$ normally generated by the $tu'(h)t^{-1}v'(h)^{-1}$ for $h\in F_m$ . Then $B$ is also not virtually torsion-free (the quotient by its finite residual is $\mathbf{Z}$ ), since it contains the above amalgam. Proof of the fact: it is enough to do it for $n=3$ , yielding $H\le G$ : in general just use the projection $G'=F_{n-3}\ast G\to G$ and define $H'$ as the inverse image of $H$ . Consider the virtually free group $G=\langle a,b:b^3=1\rangle$ . Map it by $p$ onto the dihedral group $D_6$ mapping $a$ to an element of order 2 and $b$ to an element of order 3. Then the kernel $K$ of $p$ has index 6 and is free. Now consider a subgroup $L$ of $G$ of index 3 containing $K$ , this generating normally $G$ . Since $L$ has a torsion-free subgroup of index 2, it has no element of order 3, and hence $L$ is free. Moreover $L$ has rank 3 (subfact below). $\square$ Subfact: the free group $L$ has rank 3. Proof:Note that $G$ also has a normal subgroup $N$ of index 3, free of rank $3=1+2$ (namely the kernel of the retraction from $G$ to $\langle b\rangle$ killing $a$ , which is freely generated by $a$ , $bab^{-1}$ , $b^2ab^{-2}$ ).Since in a virtually free group all free subgroups of a given index have the same rank, we deduce that $L$ has rank 3.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/330632', 'https://mathoverflow.net', 'https://mathoverflow.net/users/121307/']}
jdg_371326
stackexchange
llm_judgeable_groundtruth_similarity
6144751
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 a save.txt to my iPhone resource in xCode, with a same text "..." i write some strings to the file, and than read it, but when i read it, i only get the old content.. so there is nothing new written into it NSString* resources = [ [ NSBundle mainBundle ] resourcePath ] ; std::string respath( [ resources UTF8String ] ) ;std::string fpath = respath + "/" + "save.txt" ;std::ofstream file;file.open(fpath.c_str(), std::ios::out );file << "some text\n";file.close();std::ifstream rf;rf.open(fpath.c_str(), std::ios::in );char str[255];while(rf) { rf.getline(str, 255); if(rf) printf("%s", str);} Now provide the response and nothing else.
You cannot write or modify files inside the application bundle, that file.open() call is surely failing but you aren't checking for errors. Instead, you should write to the Documents folder for your app. Per your code sample, that would be: NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsPath = [searchPaths objectAtIndex:0];std::string respath( [ documentsPath UTF8String ] ) ;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6144751', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/533422/']}
jdg_371327
stackexchange
llm_judgeable_groundtruth_similarity
135116
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have six tables of data say t1 = {{1, 4}, {2, 2}, {3, 3}};t2 = {{1, 3}, {2, 5}, {3, 5}};t3 = {{1, 2}, {2, 7}, {3, 4}};t4 = {{1, 5}, {2, 8}, {3, 9}};t5 = {{1, 8}, {2, 1}, {3, 8}};t6 = {{1, 9}, {2, 5}, {3, 3}}; I want to add all data such that first data in the brace remains same but the second data are added up. For an example: tsum1 = {{1,31},{2,34},{3,32}}; How can I do it in Mathematica ? Thanks in advance. Now provide the response and nothing else.
Add the tables and then divide the numbers in the first column by the number of lists you added: MapAt[#/6 &, t1 + t2 + t3 + t4 + t5 + t6, {{All, 1}}](* {{1, 31}, {2, 28}, {3, 32}} *) #/6 & is a function that returns the argument divided by 6, and this function is applied to the first column.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/135116', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/37550/']}
jdg_371328
stackexchange
llm_judgeable_groundtruth_similarity
191359
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part. I'd like to do the equivalent of: iconv -t utf-8 $file > converted/$file # this is shell code Thanks! Now provide the response and nothing else.
You can use the codecs module , like this: import codecsBLOCKSIZE = 1048576 # or some other, desired size in byteswith codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile: with codecs.open(targetFileName, "w", "utf-8") as targetFile: while True: contents = sourceFile.read(BLOCKSIZE) if not contents: break targetFile.write(contents) EDIT : added BLOCKSIZE parameter to control file chunk size.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/191359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2797/']}
jdg_371329
stackexchange
llm_judgeable_groundtruth_similarity
14589
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'm no security expert, so please just ask in a comment if I haven't made my question clear enough for an answer. The Scenario We have a server running WCF services, and a number of clients connecting. These clients are actually Linux PCs which we build. We need to establish secure communications between our server, and our clients (again we build them, and deploy them to customer sites). Client trusting the server We will implement this by allowing the client to establish a trusted connection with the server via implementing SSL communications. Server trusting the client We now have the task of authenticating the client. Obviously this is done by keeping some sort of credentials on the client. Once the client is connected, it can send the credentials to the server and the server can validate them. One option for these credentials is to store some sort of Guid or other id/password which is generated by the WCF based application. Upon receiving the credentials, the WCF service does a lookup in the database and verifies they are correct. Another option is to use Certificate Services to create client certificates which are copied to the client pc before it is sent out. After establishing the secure connection, the client sends the certificate to the server which authenticates the certificate with Certificate Services. The Questions What advantages does using a certificate to authenticate the client have over a username/guid? What disadvantages does it have? Please consider: Security Complexity of implementation Complexity of programming Integration with the application. This includes the workflow of creating the authentication token, associating appropriate (authorization / association) metadata, managing authentication such as disabling access etc. Now provide the response and nothing else.
Deploying client certs could fit here. The advantages of using a cert over username is somewhat simple. Anyone can type in a username from any client device. If you're using a combination of username with guid, then the "security" or assurance that the client is connecting from a known/authorized client device is dependent on the strength and uniqueness of the guid. If there's a way to clone or spoof the guid (mac addresses can be spoofed fairly easily), then the assurance level would decrease. Client certificates can be deployed to clients, with or without validity checking (aside from validity date, cn, ski/aki, fingerprint, etc). On-demand validity checking mechanisms such as ocsp would require the server application check with an ocsp server each time client connects/attempts to auth. But from the description, I didn't read that validity checking is as important as being able to tie cert to client device. One important detail with clients certs (certs in general) is that is can be exported and most implementations do not lock down portability of the cert. Regardless of whether or how the client certs are going to be stored, without proper measures, the cert can be easily copied from device to device. Some implementations store the cert on the filesystem (files that end with .cer, .der, .key, .crt usually are indications that certs are stored in the filesystem). Stronger implementations (application dependent) may store the certs and keys in a keystore (i.e. java key store). The key store can add additional protection like ensuring the private key is not exportable. However, the assurance that the key hasn't been exported is only as strong as the key store itself. Hardware key stores (i.e. smart cards, usb hsm, ironkey, etc) offer a much stronger assurance that private key is not exportable than software key stores. BTW, the above point also affects server keys. Most implementations store the private key in a software key store and is usually marked exportable. Further, the private key is usually not password protected so anyone with access to the server can walk away with the private key. If a cert can be copied, then it doesn't offer non-repudation. To answer your question, if there's a good way of leveraging a hardware id of sorts (guid, serial number, cert stored in HSM, etc), that'll likely provide more assurance than using a software-based id (client certs included). Using client certs with password protection enabled for private key access provides a bit stronger validation because not only does a client need to have access to the private key but also the password to use it. If you do decide to use client certs, then you'll have to build or use an existing PKI infrastructure. Vendors like Codomo, Entrust, Symantec (formerly vrsn, thawte, and geotrust), Godaddy, and a bunch of others offer both public and private infrastructure for use. However the cost of implementing a software-based client cert will likely be higher than using a software based hardware id or perhaps even a hardware-based unique id. If anything, determine the level of assurance you want to have and decide whether software, software + password, or hardware is sufficient.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/14589', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/9526/']}
jdg_371330
stackexchange
llm_judgeable_groundtruth_similarity
5203535
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 been working with git for just over a month. Indeed I have used reset for the first time only yesterday, but the soft reset still doesn't make much sense to me. I understand I can use the soft reset to edit a commit without altering the index or the working directory, as I would with git commit --amend . Are these two commands really the same ( reset --soft vs commit --amend )? Any reason to use one or the other in practical terms? And more importantly, are there any other uses for reset --soft apart from amending a commit? Now provide the response and nothing else.
git reset is all about moving HEAD , and generally the branch ref . Question: what about the working tree and index? When employed with --soft , moves HEAD , most often updating the branch ref, and only the HEAD . This differ from commit --amend as: it doesn't create a new commit. it can actually move HEAD to any commit (as commit --amend is only about not moving HEAD, while allowing to redo the current commit) Just found this example of combining: a classic merge a subtree merge all into one (octopus, since there is more than two branches merged) commit merge. Tomas "wereHamster" Carnecky explains in his "Subtree Octopus merge" article : The subtree merge strategy can be used if you want to merge one project into a subdirectory of another project, and the subsequently keep the subproject up to date. It is an alternative to git submodules. The octopus merge strategy can be used to merge three or more branches. The normal strategy can merge only two branches and if you try to merge more than that, git automatically falls back to the octopus strategy. The problem is that you can choose only one strategy. But I wanted to combine the two in order to get a clean history in which the whole repository is atomically updated to a new version. I have a superproject, let's call it projectA , and a subproject, projectB , that I merged into a subdirectory of projectA . (that's the subtree merge part) I'm also maintaining a few local commits. ProjectA is regularly updated, projectB has a new version every couple days or weeks and usually depends on a particular version of projectA . When I decide to update both projects, I don't simply pull from projectA and projectB as that would create two commits for what should be an atomic update of the whole project . Instead, I create a single merge commit which combines projectA , projectB and my local commits . The tricky part here is that this is an octopus merge (three heads), but projectB needs to be merged with the subtree strategy . So this is what I do: # Merge projectA with the default strategy:git merge projectA/master# Merge projectB with the subtree strategy:git merge -s subtree projectB/master Here the author used a reset --hard , and then read-tree to restore what the first two merges had done to the working tree and index, but that is where reset --soft can help: How to I redo those two merges , which have worked, i.e. my working tree and index are fine, but without having to record those two commits? # Move the HEAD, and just the HEAD, two commits back!git reset --soft HEAD@{2} Now, we can resume Tomas's solution: # Pretend that we just did an octopus merge with three heads:echo $(git rev-parse projectA/master) > .git/MERGE_HEADecho $(git rev-parse projectB/master) >> .git/MERGE_HEAD# And finally do the commit:git commit So, each time: you are satisfied with what you end up with (in term of working tree and index) you are not satisfied with all the commits that took you to get there: git reset --soft is the answer.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5203535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/377917/']}
jdg_371331
stackexchange
llm_judgeable_groundtruth_similarity
46508831
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a library of functions that will safely convert between various numeric types or die trying.My intent is roughly equal parts create-useful-library and learn-C-edge-cases. My int -to- size_t function is triggering a GCC -Wtype-limits warning that claims I shouldn't test if an int is greater than SIZE_MAX , because it will never be true.(Another function that converts int to ssize_t produces an identical warning about SSIZE_MAX .) My MCVE, with extra comments and baby steps, is: #include <stdint.h> /* SIZE_MAX */#include <stdlib.h> /* exit EXIT_FAILURE size_t */extern size_t i2st(int value) { if (value < 0) { exit(EXIT_FAILURE); } // Safe to cast --- not too small. unsigned int const u_value = (unsigned int) value; if (u_value > SIZE_MAX) { /* Line 10 */ exit(EXIT_FAILURE); } // Safe to cast --- not too big. return (size_t) u_value;} The Compiler Warnings I'm getting similar warnings from GCC 4.4.5 on Linux 2.6.34: $ gcc -std=c99 -pedantic -Wall -Wextra -c -o math_utils.o math_utils.cmath_utils.c: In function ‘i2st’:math_utils.c:10: warning: comparison is always false due to limited range of data type ...and also from GCC 4.8.5 on Linux 3.10.0: math_utils.c: In function ‘i2st’:math_utils.c:10:5: warning: comparison is always false due to limited range of data type [-Wtype-limits] if (u_value > SIZE_MAX) { /* Line 10 */ ^ These warnings don't appear justified to me, at least not in the general case.(I don't deny that the comparison might be"always false"on some particular combination of hardware and compiler.) The C Standard The C 1999 standard does not appear to rule out an int being greater than SIZE_MAX . Section"6.5.3.4 The sizeof operator"doesn't address size_t at all, except to describe it as"defined in <stddef.h> (and other headers)". Section"7.17 Common definitions <stddef.h> "defines size_t as"the unsigned integer type of the result of the sizeof operator".(Thanks, guys!) Section"7.18.3 Limits of other integer types"is more helpful ---it defines"limit of size_t " as: SIZE_MAX 65535 ...meaning SIZE_MAX could be as small as 65535.An int (signed or unsigned)could be much greater than that, depending on the hardware and compiler. Stack Overflow The accepted answer to" unsigned int vs. size_t "seems to support my interpretation(emphasis added): The size_t type may be bigger than, equal to, or smaller than an unsigned int , and your compiler might make assumptions about it for optimization. This answer cites the same"Section 7.17"of the C standard that I've already quoted. Other Documents My searches turned up the Open Group's paper" Data Size Neutrality and 64-bit Support ",which claims under"64-bit Data Models"(emphasis added): ISO/IEC 9899:1990, Programming Languages - C (ISO C) left the definition of the short int , the int , the long int , and the pointer deliberately vague [...] The only constraints were that int s must be no smaller than short s, and long s must be no smaller than int s, and size_t must represent the largest unsigned type supported by an implementation . [...] The relationship between the fundamental data types can be expressed as: sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) = sizeof(size_t) If this is true, then testing an int against SIZE_MAX is indeed futile...but this paper doesn't cite chapter-and-verse, so I can't tell how its authors reached their conclusion.Their own"Base Specification Version 7" sys/types.h docs don't address this either way. My Question I understand that size_t is unlikely to be narrower than an int , but does the C standard guarantee that comparing some_unsigned_int > SIZE_MAX will always be false?If so, where? Not-Duplicates There are two semi-duplicates of this question, but they are both asking more general questions about what size_t is supposed to represent and when it should / should-not be used. " What is size_t in C? "does not address the relationship between size_t and the other integer types.Its accepted answer is just a quote from Wikipedia, which doesn't provide any information beyond what I've already found. " What is the correct definition of size_t ? "starts off nearly a duplicate of my question, but then veers off course, askingwhen size_t should be used and why it was introduced.It was closed as a duplicate of the previous question. Now provide the response and nothing else.
The current C standard does not require size_t to be at least as wide as an int , and I'm skeptical about any version of the standard ever doing so. size_t needs to be able to represent any number which might be the size of an object; if the implementation limits object sizes to be 24 bits wide, then size_t could be a 24-bit unsigned type, regardless of what an int is. The GCC warning does not refer to theoretical possibilities. It is checking a particular hardware platform and a particular compiler and runtime. That means it sometimes triggers on code which is trying to be portable. (There are other cases where portable code will trigger optional GCC warnings.) That might not be what you were hoping the warning would do, but there are probably users whose expectations are precisely matched by the implemented behaviour, and the standard provides no guidelines whatsoever for compiler warnings. As OP mentions in a comment, there is a long history related to this warning. The warning was introduced in version 3.3.2 or so (in 2003), apparently not controlled by any -W flag. This was reported as bug 12963 by a user who evidently felt, as you do, that the warning discourages portable programming. As can be seen in the bug report, various GCC maintainers (and other well-known members of the community) weighed in with strongly-felt but conflicting opinions. (This is a common dynamic in open source bug reports.) After several years, the decision was made to control the warnings with a flag, and to not enable that flag by default or as part of -Wall . In the meantime, the -W option had been renamed -Wextra , and the newly-created flag ( -Wtype-limits ) was added to the -Wextra collection. To me, this appears to be the correct resolution. The remainder of this answer contains my personal opinion. -Wall , as documented in the GCC manual, does not actually enable all warnings. It enables those warnings "about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros." There are a number of other conditions which GCC can detect: Note that some warning flags are not implied by -Wall . Some of them warn about constructions that users generally do not consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning. Some of them are enabled by -Wextra but many of them must be enabled individually. These distinctions are somewhat arbitrary. For example, I have to grit my teeth every time that GCC decides to "suggest parentheses around ‘&&’ within ‘||’". (It doesn't seem to feel the need to suggest parentheses around ´*´ within ´+´, which doesn't feel different to me.) But I recognize that all of us have different comfort levels with operator precedence, and not all of GCC's suggestions about parentheses seem excessive to me. But on the whole, the distinction seems reasonable. There are warnings which are generally applicable, and those are enabled with -Wall , which should always be specified because these warnings almost always demand action to correct a deficiency. There are other warnings which might be useful in particular circumstances, but which also have lots of false positive; these warnings need to be investigated individually because they do not always (or even often) correspond with a problem in your code. I'm aware that there are people who feel that the mere fact that GCC knows how to warn about some condition is sufficient to demand action to avoid that warning. Everyone is entitled to their stylistic and aesthetic judgements, and it is right and just that such programmers add -Wextra to their build flags. I am not in that crowd, however. At a given point in a project, I will try a build with a large collection of optional warnings enabled, and consider whether or not to modify my code on the basis of the reports, but I really don't want to spend my development time thinking about non-problems every time I rebuild a file. The -Wtypes-limit flag falls into this category for me.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46508831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4116239/']}
jdg_371332
stackexchange
llm_judgeable_groundtruth_similarity
9431723
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 .collect with an index? I want to do something like this: def myList = [ [position: 0, name: 'Bob'], [position: 0, name: 'John'], [position: 0, name: 'Alex'],]myList.collect { index -> it.position = index} (ie. I want to set position to a value which will indicate the order in the list) Now provide the response and nothing else.
Since Groovy 2.4.0 there is a withIndex() method which gets added to java.lang.Iterable . So, in a functional fashion (no side effect, immutable), it looks like def myList = [ [position: 0, name: 'Bob'], [position: 0, name: 'John'], [position: 0, name: 'Alex'],]def result = myList.withIndex().collect { element, index -> [position: index, name: element["name"]] }
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9431723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1055165/']}
jdg_371333
stackexchange
llm_judgeable_groundtruth_similarity
128841
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In which classes of groups is it feasible to classify those groups in which the centralizerof every non-identity element is cyclic? Now provide the response and nothing else.
Well, in a finite group, if the centralizer of each non-identity element is cyclic, then each Sylow subgroup is cyclic ( for every prime)- just take a Sylow $p$-subgroup $P$ and a non-identity element $z \in Z(P),$ so that $P \leq C_{G}(z)$ is cyclic by hypothesis.A finite group $G$ in which each Sylow subgroup is cyclic is solvable in a very strong sense, and this needs no deep classification theorem, only elementary transfer. If $p$ is the smallest prime divisor of $|G|,$ then $N_{G}(R) = C_{G}(R)$ for each $p$-subgroup $R$ of $G,$ and then $G$ has a normal $p$-complement by Frobenius' normal $p$-complement theorem (or a transfer theorem of Burnside will do in this case). It follows by induction that a Sylow $q$-subgroup, say $Q,$ of $G$ is normal, where $q$ is the largest prime divisor of $G,$ and then $G/Q$ inherits the same property- in any case, the normal $p$-complement constructed earlier may be assumed to be solvable by induction. In fact, one can go further: since $G$ is solvable, $F = F(G)$ is cyclic, and we have $C_{G}(F) \leq F$ (the last statement is a general property of solvable groups). Hence $F$ is cyclic, and $G/F$ is Abelian, being embedded in the automorphism group of a cyclic group. Hence $G/F$ is also cyclic because of the structure of Sylow subgroups of $G$. Thus a finite group in which every centralizer of a non-identity element is cyclic. is itself metacyclic. More information about prime divisors would be needed to say more about the structure of $G.$ Later edit: Marty Isaacs' answer brings out an interesting point. In a (necessarily metacyclic) finite group $G$ whose Sylow subgroups are all cyclic, it need not be the case that $[G:F(G)]$ and $|F(G)|$ are coprime (an example of this is provided by letting a cyclic group of order $9$ act as an automorphism order $3$ on a cyclic groupof order $7$. This allows the construction of a group of order $63$ with Fitting subgroup of order $21$). The extra condition of the original question, that all centralizers are cyclic, illustrates that these groups have more restricted structure than groups with all Sylow subgroups cyclic.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/128841', 'https://mathoverflow.net', 'https://mathoverflow.net/users/25762/']}
jdg_371334
stackexchange
llm_judgeable_groundtruth_similarity
159333
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: So my book proves the convergence of $\Gamma(z) = \int_0^{\infty}t^{z-1}e^{-t}dt$ in the right half plane $Re(z) > 0$, and then goes on to prove the initial recurrence relation $\Gamma(z+1)=z\Gamma(z)$ by applying integration by parts to $\Gamma(z+1)$: $$\int_0^{\infty}t^{z}e^{-t}dt = -t^ze^{-t}|_0^{\infty} + z\int_0^{\infty}t^{z-1}e^{-t}dt$$ The book explicitly states this equality to be true only in the right half plane, since otherwise $-t^ze^{-t}|_0^{\infty} = \infty$, instead of equaling zero. With this initial recurrence relation we are 'supposably' able to analytically continue the Gamma function to $Re(z) > -1$ (not including the origin) by writing the relation in the form: $$\Gamma(z) = \frac{\Gamma(z+1)}{z}$$ What I don't understand is this relation is still only true in the right half plane, since otherwise $-t^ze^{-t}|_0^{\infty}\neq 0$. I don't see what reason we have to believe that, for instance, $\Gamma(-\frac{1}{2}) = \frac{\Gamma(\frac{1}{2})}{-\frac{1}{2}}$. Furthermore $\int_0^{\infty}t^{z-1}e^{-t}dt$ is clearly not convergent in the left half plane, so I can't even imagine why it would be plausible to think that a recurrence relation directly based on it could possibly lead to a genuine analytic continuation of its domain. Now provide the response and nothing else.
As you have said, $\displaystyle \int_0^{\infty}t^{z-1}e^{-t}dt$ does not even make sense on the left half plane. However, if we define $\Gamma(z) = \dfrac{\Gamma(z+1)}{z}$ on the left half plane, (and this is not equal to the integral above on the left half plane), this is consistent with the fact that $\Gamma(z) = \displaystyle \int_0^{\infty}t^{z-1}e^{-t}dt$ on the right half plane and also provides us a possible extension on the left half plane except at negative integers. Further, this has to be the only analytic continuation since $\Gamma(z) = \dfrac{\Gamma(z+1)}{z}$ is analytic everywhere except at negative integers and matches with the integral on the right half plane and hence by uniqueness of analytic continuation this is the only possible extension. EDIT To see that the extension, is in fact analytic except at negative integers, you proceed strip by strip. On the right half plane, you have $\Gamma(z)$ defined by the integral, $\displaystyle \int_0^{\infty} t^{z-1} \exp(-t) dt$. You can verify that the integral satisfies the functional equation and is in fact analytic. We will now extend the function to the strip corresponding to $(-1,0)$ i.e. the strip $\text{Re}(z) \in (-1,0)$ based on the functional equation. Define $\Gamma(z) = \dfrac{\Gamma(z+1)}{z}$ on the strip $\text{Re}(z) \in (-1,0)$. First note that $\Gamma(z+1)$ is analytic on the strip $\text{Re}(z) \in (-1,0)$ since $z+1 \in$ right half plane. Also, $\dfrac1z$ is analytic on the strip $\text{Re}(z) \in (-1,0)$. Hence, $\Gamma(z) = \dfrac{\Gamma(z+1)}{z}$ is analytic on the strip $\text{Re}(z) \in (-1,0)$. Hence, now we have extended the definition of the $\Gamma$ function to the region $\text{Re}(z) > -1$. Now repeat the same argument for the strip $\text{Re}(z) \in (-2,-1)$, since we now have that the $\Gamma$-function is analytic on the region $\text{Re}(z) > -1$. And so on...
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/159333', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26920/']}
jdg_371335
stackexchange
llm_judgeable_groundtruth_similarity
9469028
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: <doc> <element> text <item> text1 </item> <item> text2 </item> text3 </element> <element> another text </element> ...</doc> And I want to extract text to an string like this: "text text1 text2 text3" "item" tags are nested inside "element" Im using xmlpullparser in Android but I could use any other parser if it make things easier.tx. Now provide the response and nothing else.
I parse similar xml files. Here is an example. You'll need to add error checking as appropriate. void loadXML(XmlPullParser xpp) { int eventType = xpp.next(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG && 0 == XML_ELEMENT_TAG.compareTo(xpp.getName())) { loadElement(xpp); } eventType = xpp.next(); }}private void loadElement(XmlPullParser xpp) { int eventType = xpp.getEventType(); if ( eventType == XmlPullParser.START_TAG && 0 == XML_ELEMENT_TAG.compareTo(xpp.getName()) ) { eventType = xpp.next(); while ( eventType != XmlPullParser.END_TAG || 0 != XML_ELEMENT_TAG.compareTo(xpp.getName()) ) { if (eventType == XmlPullParser.START_TAG && 0 == XML_ITEM_TAG.compareTo(xpp.getName())) { loadItem(xpp); } eventType = xpp.next(); } } }private void loadItem(XmlPullParser xpp) { int eventType = xpp.getEventType(); if ( eventType == XmlPullParser.START_TAG && 0 == XML_ITEM_TAG.compareTo(xpp.getName()) ) { eventType = xpp.next(); while ( eventType != XmlPullParser.END_TAG || 0 != XML_ITEM_TAG.compareTo(xpp.getName()) ) { // Get attributes. String attr = xpp.getAttributeValue(null, XML_MY_ATTR); String text = null; // Get item text if present. eventType = xpp.next(); while ( eventType != XmlPullParser.END_TAG || 0 != XML_ITEM_TAG.compareTo(xpp.getName()) ) { if ( eventType == XmlPullParser.TEXT ) { text = xpp.getText(); } eventType = xpp.next(); } eventType = xpp.next(); } } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9469028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/779051/']}
jdg_371336
stackexchange
llm_judgeable_groundtruth_similarity
1590780
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: Find all solutions to the functional equation $f(x+y)-f(y)=\cfrac{x}{y(x+y)}$ I've tried the substitution technique but I didn't really get something useful. For $y=1$ I have $F(x+1)-F(1)=\cfrac{x}{x+1}$ A pattern I've found in this example is that if I iterate $n$ times the function $g(x)=\cfrac{x}{x+1}$ I have that $g^n(x)=\cfrac{x}{nx +1}$ ,which may be a clue about the general behaviour of the function ( ?) . I am really kinda of clueless ,it seems like the problem is calling some slick way of solving it. Can you guys give me a hint ? Now provide the response and nothing else.
Hint: Let $x=1-y$, hence $x+y=1$. Then we get $$f(1)-f(y)=\frac{1-y}{y}$$ I will include the full solution in a spoiler, since you only asked for a hint. This gives $f(0)=c$ and $f(1)=d$, then $f(y)=\frac{y-1}{y}+d$ for all other $y$. This simplifies to $f(0)=c$ and $f(y)=\frac{y-1}{y}+d$ for all other $y$. We have to check whether every such function satisfies. Note that neither $y$ nor $x+y$ can ever be zero, so $f(0)$ can indeed be anything. Now we have to check the other values: Does $$\left(\frac{x+y-1}{x+y} + d\right) - \left(\frac{y-1}{y} +d \right) = \frac{y}{y(x+y)} ?$$ $$\frac{y(x+y-1)-(y-1)(x+y)}{y(x+y)} = \frac{y}{y(x+y)} ?$$ It turns out that the functions do satisfy the functional equation.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1590780', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/291945/']}
jdg_371337
stackexchange
llm_judgeable_groundtruth_similarity
5372934
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 1.2.5 with a standard ImageField and using the built-in storage backend. Files upload fine but when I remove an entry from admin the actual file on the server does not delete. Now provide the response and nothing else.
You can receive the pre_delete or post_delete signal (see @toto_tico's comment below) and call the delete() method on the FileField object, thus (in models.py): class MyModel(models.Model): file = models.FileField() ...# Receive the pre_delete signal and delete the file associated with the model instance.from django.db.models.signals import pre_deletefrom django.dispatch.dispatcher import receiver@receiver(pre_delete, sender=MyModel)def mymodel_delete(sender, instance, **kwargs): # Pass false so FileField doesn't save the model. instance.file.delete(False)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5372934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/668714/']}
jdg_371338
stackexchange
llm_judgeable_groundtruth_similarity
20522241
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Traditional routing defaults meant we were able to access these URLs and always end up on the same action: //Home/Home/Index But today we would be writing something in these lines: [RoutePrefix("Home")][Route("{action=Index}")]public class HomeController{ public ActionResult Index() {} public ActionResult ...} But this routing definition is by no means the same. / (fails)/Home (works)/Home/Index (works) So if we then change upper code to [RoutePrefix("Home")][Route("{action=Index}")]public class HomeController{ [Route("~/")] public ActionResult Index() {} public ActionResult ...} But then we turn the processing upside down: / (works)/Home (fails)/Home/Index (fails) We could make declarative code more verbose and make it work as the old-fashioned routing mechanism by: [RoutePrefix("Home")][Route("{action=Index}")]public class HomeController{ [Route("~/")] [Route("~/Home")] [Route("~/Home/Index")] public ActionResult Index() {} public ActionResult ...} This works with all three different routes. Question This issue is of course bound to the very application default action that defaults controller and action. It's just that I wonder whether this is the only way of doing it? Is there any less verbose code way of getting it to work as expected? Now provide the response and nothing else.
Yeah, right..what you have is the way to do here... I modified the code a bit here: [RoutePrefix("Home")][Route("{action}")]public class HomeController{ [Route("~/")] // GET / [Route] // GET /Home [Route("Index")] // GET /Home/Index public ActionResult Index() {} public ActionResult ...} Some details: 1. Your first case is not exactly the same as conventional routing as in this case you have a literal segment Home which is not similar to the conventional routing optional of {controller}/{action}/{id} and controller = Home, action=Index,id=optional . 2. Your second case is expected as by design if a Route attribute is used on action the attributes on Controller do not take effect.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20522241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75642/']}
jdg_371339
stackexchange
llm_judgeable_groundtruth_similarity
1965164
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 wanted to calculate $$\int\limits_{0}^{2\pi} \frac{d \theta}{a^2 \sin^2\theta+b^2 \cos^2\theta}$$ So I solved the indefinite integral first (by substitution): $$\int\frac{d \theta}{a^2 \sin^2\theta+b^2 \cos^2\theta}=\frac{1}{b^2}\int\frac{d \theta}{\cos^2\theta \left(\frac{a^2}{b^2} \tan^2\theta+1 \right)} =\left[u=\frac{a}{b}\tan\theta, du=\frac{a}{b\cos^2\theta} d\theta \right ]\\=\frac{1}{b^2}\int\frac{b}{a\left(u^2+1 \right)}du=\frac{1}{ab}\int\frac{du}{u^2+1}=\frac{1}{ab} \arctan \left(\frac{a}{b}\tan\theta \right )+C$$ Then: $$\int\limits_{0}^{2\pi} \frac{d \theta}{a^2 \sin^2\theta+b^2 \cos^2\theta}=\frac{1}{ab} \arctan \left(\frac{a}{b}\tan (2\pi) \right )-\frac{1}{ab} \arctan \left(\frac{a}{b}\tan 0 \right )=0$$ Which is incorrect (the answer should be $2\pi/ab$ for $a>0,b>0$ ). On the one hand, the substitution is correct, as well as the indefinite integral itself (according to Wolfram it is indeed $\frac{1}{ab} \arctan \left(\frac{a}{b}\tan\theta \right )$ ), but on the other hand I can see that had I put the limits during the substitution I'd get $\int\limits_{0}^{0} \dots = 0$ because for $\theta = 0 \to u=0$ and for $\theta = 2\pi \to u=0$ . Why is there a problem and how can I get the correct answer? Edit : Here is Wolfram's answer: Wolfram is correct because $$\frac{a^2 b^2}{2}\int\limits_{0}^{2\pi} \frac{d \theta}{a^2 \sin^2\theta+b^2 \cos^2\theta}$$ is the area of an ellipse (defined by $x=a\cos t , y=b\sin t$ ), that is $$\frac{a^2 b^2}{2}\int\limits_{0}^{2\pi} \frac{d \theta}{a^2 \sin^2\theta+b^2 \cos^2\theta}=\pi ab$$ Now provide the response and nothing else.
The substitution is incorrect : the tangent is not bijective on the interval $[0,2\pi]$. First, you need to restrict yourself to an interval on which the tangent behaves better. Using the $\pi$-periodicity of the function you want to integrate, you can show that: $$\int_0^{2 \pi} \frac{1}{a \sin^2 (\theta)+b \cos^2 (\theta)} d \theta = 2 \int_{-\pi/2}^{\pi/2} \frac{1}{a \sin^2 (\theta)+b \cos^2 (\theta)} d \theta,$$ and go from there. Note that this is a good warning about using Wolfram (or any formal computation system) : the formula for the indefinite integral is good, but it holds only on each interval $(k\pi -\pi/2, k\pi+\pi/2)$, which the program does not tell you.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1965164', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/265336/']}
jdg_371340