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 | 52542149 |
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 web scraping and want to download all images on a webpage using puppeteer: const puppeteer = require('puppeteer');let scrape = async () => { // Actual Scraping goes Here... const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage(); await page.goto('https://memeculture69.tumblr.com/'); // Right click and save images};scrape().then((value) => { console.log(value); // Success!}); I have looked at the API docs but could not figure out how to acheive this. So appreciate your help.
Now provide the response and nothing else.
| If you want to skip the manual dom traversal you can write the images to disk directly from the page response. Example: const puppeteer = require('puppeteer');const fs = require('fs');const path = require('path');(async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); page.on('response', async response => { const url = response.url(); if (response.request().resourceType() === 'image') { response.buffer().then(file => { const fileName = url.split('/').pop(); const filePath = path.resolve(__dirname, fileName); const writeStream = fs.createWriteStream(filePath); writeStream.write(file); }); } }); await page.goto('https://memeculture69.tumblr.com/'); await browser.close();})(); See the documentation for page.on and for the HTTPResponse object that you get from page.on('response', ...) . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52542149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727695/']} | jdg_81641 |
stackexchange | llm_judgeable_groundtruth_similarity | 1227147 |
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:
During a long night without sleep I managed to come up with a proof for a statement I know is false, and for the life of me I cannot figure out what I did wrong. Where is my mistake? Theorem: Let $f:A\to B$ be any function. There is a bijection from A onto B. Proof: By contradiction. Assume there is no bijection from A onto B. Consider the statement "If f is a surjection, then f is an injection." This statement is true iff either f is not a surjection or f is an injection (this is material implication). But this statement is false, because if f is a surjection it can't be an injection because there are no bijections. So then the statement "Either f is not a surjections or it is an injection" is false, meaning f is a surjection and not an injection (demorgan). But if f is not an injection then either f is not an injection or it is a surjection. Using material implication again, this is equivalent to the statement "if f is an injection then it is a surjection," which is false because then there would be a bijection. So f is an injection and not a surjection, which is clearly a contradiction. This is obviously absurd but I'm having trouble thinking straight. Where is my error?
Now provide the response and nothing else.
| Your material implication mix the variables: "If f is a surjection, then f is an injection." This statement is true iff either f is not a surjection or f is an injection (this is material implication). should be: "If f is a surjection, then f is an injection." This statement is true iff there exist a function $g$ such that $g$ is not an injection and $g$ is a surjection or for all $g$ $g$ is not a surjection (this is material implication). which is false, so your material application you applied more than two times is actually false. Edit This was the origin of the mistake and the following statements are just consequences of the negation of this statement. Read this if you want to understand clearly where is the minstakes: Let's rewrite your proof: Proof: By contradiction. Assume there is no bijection from $A$ onto $B$. Consider the statement : $$P \, \, \text{ "If f is a surjection, then f is an injection."}$$ $P$ does not depend on $f$ , so this statement $P$ is true if and only if every surjection is an injection. (this is clearly false) This statement is true iff either f is not a surjection or f is an injection (this is material implication). First of all you did not fix any function $f$, so this would be: this statement is true if and only if every surjection is an injection. But the problem in the proof it's the fact you seem to have fixed a function in the biginig but you did not fix any function. If we want to continue to analyse the proof we must fix a function $f$ so let's restart the proof and fix a function: Proof: By contradiction. Assume there is no bijection from $A$ onto $B$. Fix a function $f$,Consider the statement : $$P_f \, \, \text{ "If f is a surjection, then f is an injection."}$$ Now I agree that this a statement will match your thoughts and satisfy your creteria: This statement $P_f$ is true iff either f is not a surjection or f is an injection (this is material implication). now your reasoning is correct and this follows easily. But this statement is false, because if f is a surjection it can't be an injection because there are no bijections. So then the statement "Either f is not a surjections or it is an injection" is false, So if $f$ is a surjection then the statement $P_f$ is false What if $f$ is not a surjection?, if we investigate a little, it turns out that $P_f$ is true. And this is not correct , you concluded that $P_f$ is false, but no $P_f$ is not false for every function $f$ , it's false only for functions $f$ which are not surjective (onto) and here in order to pass this step we must assume in the beginning that $f$ is a surjection but every thing will not work simply because what we're trying to prove is not correct! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1227147', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/179053/']} | jdg_81642 |
stackexchange | llm_judgeable_groundtruth_similarity | 388 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Some high-energy experiments ( RHIC , LHC ) use ion-ion collisions instead of proton-proton collisions. Although the total center-of-mass energy is indeed higher than p-p collisions, it might happen that the total energy per nucleon is actually lower. What are the advantages of using ion-ion collisions (e.g. gold-gold or lead-lead) instead of proton-proton collisions, considering the same accelerator?
Now provide the response and nothing else.
| As a clarification the energy per nucleon is always lower: for example, currently in the LHC the proton top energy is 3.5 TeV. Now the Pb energy is 3.5 TeV times Z so the energy per nucleon is 3.5*Z/A and A is greater than Z for every nucleus (except the proton where it is equal to one). But the goal of ion-ion collision is not to increase the total energy or the energy per nucleon: it is to obtain a different type of collision. It should be noted than in a proton-proton collision, the energy involved in the real collision process is variable: each quark and gluon carry a fraction of the energy of the proton, and hard collision involve a collision between a quark/gluon of one proton against a quark/gluon of the other. In the case of ion-ion collision you have the same process: the energy is shared by the protons/neutrons and they can have different energies. The goal of such collision is also to obtain a volume (bigger than in a p-p collision) with a very high energy density. In such a volume, a "state of matter" called quark-gluon-plasma is believed to be possibly created. The study of this QGP is one of the main goal of the ALICE experiment at the LHC. A few references: The ALICE experiment at CERN Live control screen of the LHC now running as a Pb-Pb collider at 574 TeV in the center of mass | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/388', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/103/']} | jdg_81643 |
stackexchange | llm_judgeable_groundtruth_similarity | 21697359 |
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 referring to the maven binary version that is returned when you usually run mvn --version from the command line which returns an output like the below, Apache Maven 3.0.4Maven home: /usr/share/mavenJava version: 1.6.0_45, vendor: Sun Microsystems Inc.Java home: /home/uvindra/Apps/java6/jdk1.6.0_45/jreDefault locale: en_US, platform encoding: UTF-8OS name: "linux", version: "3.11.0-15-generic", arch: "amd64", family: "unix" Note the maven version 3.0.4. What's best way of accessing this from within a custom Maven Mojo in Java? Is there a property available for this? I want to run a validation against current maven version that is executing my Mojo, Thanks
Now provide the response and nothing else.
| Method references can be used when you have a method (or constructor) that fits the shape of the target you're trying to satisfy. You can't use a method reference in this case because the shape you're targeting is a Supplier , which takes no arguments, but what you have is a TreeSet constructor, which does take an argument, and you need to specify what that argument is. So you have to take the less concise approach and use a lambda expression: TreeSet<Report> toTreeSet(Collection<Report> reports, long timestamp) { return reports.stream().filter(report -> report.timestamp() >= timestamp).collect( Collectors.toCollection( () -> new TreeSet<>(Comparator.comparingLong(Report::timestamp)) ) );} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21697359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3296350/']} | jdg_81644 |
stackexchange | llm_judgeable_groundtruth_similarity | 5087546 |
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 created a UISwitch using this code... UISwitch *switch = [[UISwitch alloc]initWithFrame:CGRectMake(110, 230, 60, 60)];[window addSubview:switchView];[switchView release]; The created button will be.... The default properties are, It contains " ON " & " OFF " states The OFF button is white & the ON button is in blue color I want to create a customized switch, so that the background color & text in the switch should be changed. Is it possible? Please explain in detail. Thanks in Advance, Rajkanth
Now provide the response and nothing else.
| You can not modify UISwitch control unless and until you write your own control, But best way so far, you can used UISegmentControl and handle event on it to switch the on.png and off.png images. UISegmentedControl* switchView=[[UISegmentedControl alloc] initWithItems:[[[NSMutableArray alloc] initWithObjects:@"On",@"Off",nil] autorelease]]; [switchView setFrame:CGRectMake(20,365,140,28)]; switchView.selectedSegmentIndex=0; switchView.segmentedControlStyle=UISegmentedControlStyleBar; [switchView setImage:[UIImage imageNamed:@"onSelected.png"] forSegmentAtIndex:0]; [switchView setImage:[UIImage imageNamed:@"off.png"] forSegmentAtIndex:1]; [switchView addTarget:self action:@selector(checkOnOffState:) forControlEvents:UIControlEventValueChanged]; self.navigationItem.titleView=switchView; and write checkOnOffState method code like this- -(IBAction)checkOnOffState:(id)sender{ UISegmentedControl* tempSeg=(UISegmentedControl *)sender; if(tempSeg.selectedSegmentIndex==0){ [tempSeg setImage:[UIImage imageNamed:@"onSelected.png"] forSegmentAtIndex:0]; [tempSeg setImage:[UIImage imageNamed:@"off.png"] forSegmentAtIndex:1]; } else{ [tempSeg setImage:[UIImage imageNamed:@"on.png"] forSegmentAtIndex:0]; [tempSeg setImage:[UIImage imageNamed:@"offSelected.png"] forSegmentAtIndex:1]; } } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5087546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_81645 |
stackexchange | llm_judgeable_groundtruth_similarity | 69332 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
HOSTNAME:~ # fsck -n /FSMOUNTPOINTfsck 1.38 (30-Jun-2005)e2fsck 1.38 (30-Jun-2005)Warning! /dev/vgname/lvname is mounted.Warning: skipping journal recovery because doing a read-only filesystem check./dev/vgname/lvname contains a file system with errors, check forced.Pass 1: Checking inodes, blocks, and sizesPass 2: Checking directory structurePass 3: Checking directory connectivityPass 4: Checking reference countsInode 12845121 ref count is 1, should be 2. Fix? noInode 12845122 ref count is 1, should be 2. Fix? noInode 12845123 ref count is 1, should be 2. Fix? noInode 12845124 ref count is 1, should be 2. Fix? noPass 5: Checking group summary informationFree blocks count wrong (38829073, counted=37828469).Fix? noFree inodes count wrong (22658484, counted=22658235).Fix? no/dev/vgname/lvname: ********** WARNING: Filesystem still has errors **********/dev/vgname/lvname: 16972/22675456 files (0.3% non-contiguous), 6521839/45350912 blocksfsck.ext3 /dev/vgname/lvname failed (status 0x4). Run manually!HOSTNAME:~ # OS: SUSE LINUX Enterprise Server 9.4 FS: EXT3 with only rw options Question : So if there is the "WARNING: Filesystem still has errors" message, I can be 100% sure that the FS has problems, and needs to be umount/fsck/mount'ed? UPDATE: $ tune2fs -l /dev/vgname/lvname | grep 'Filesystem state:'Filesystem state: clean$
Now provide the response and nothing else.
| The usual advice is to not run fsck on a mounted file system . You get unreliable results - while fsck is trying to scan the file system, the kernel is still reading and writing data to it, so it will appear, to fsck , inconsistent. Some file systems allow online use of fsck , but not all - FreeBSD, for example, can check a static snapshot of a UFS2 file system while it is in use, but you still wouldn't check the file system itself while it's mounted. The best way to check your file system is to unmount it, then run fsck on it. If it still reports problems, you can take remedial action. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/69332', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/18526/']} | jdg_81646 |
stackexchange | llm_judgeable_groundtruth_similarity | 1998544 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why is it not legal to have the following two methods in the same class? class Test{ void add(Set<Integer> ii){} void add(Set<String> ss){}} I get the compilation error Method add(Set) has the same erasure add(Set) as another method in type Test. while I can work around it, I was wondering why javac doesn't like this. I can see that in many cases, the logic of those two methods would be very similar and could be replaced by a single public void add(Set<?> set){} method, but this is not always the case. This is extra annoying if you want to have two constructors that takes those arguments because then you can't just change the name of one of the constructors .
Now provide the response and nothing else.
| This rule is intended to avoid conflicts in legacy code that still uses raw types. Here's an illustration of why this was not allowed, drawn from the JLS. Suppose, before generics were introduced to Java, I wrote some code like this: class CollectionConverter { List toList(Collection c) {...}} You extend my class, like this: class Overrider extends CollectionConverter{ List toList(Collection c) {...}} After the introduction of generics, I decided to update my library. class CollectionConverter { <T> List<T> toList(Collection<T> c) {...}} You aren't ready to make any updates, so you leave your Overrider class alone. In order to correctly override the toList() method, the language designers decided that a raw type was "override-equivalent" to any generified type. This means that although your method signature is no longer formally equal to my superclass' signature, your method still overrides. Now, time passes and you decide you are ready to update your class. But you screw up a little, and instead of editing the existing, raw toList() method, you add a new method like this: class Overrider extends CollectionConverter { @Override List toList(Collection c) {...} @Override <T> List<T> toList(Collection<T> c) {...}} Because of the override equivalence of raw types, both methods are in a valid form to override the toList(Collection<T>) method. But of course, the compiler needs to resolve a single method. To eliminate this ambiguity, classes are not allowed to have multiple methods that are override-equivalent—that is, multiple methods with the same parameter types after erasure. The key is that this is a language rule designed to maintain compatibility with old code using raw types. It is not a limitation required by the erasure of type parameters; because method resolution occurs at compile-time, adding generic types to the method identifier would have been sufficient. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1998544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1930838/']} | jdg_81647 |
stackexchange | llm_judgeable_groundtruth_similarity | 57727107 |
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 resize an Image frame to be a square that takes the same width of the iPhone's screen and consequently the same value (screen width) for height. The following code don't work cause it gives the image the same height of the view. var body: some View { Image("someImage") .resizable() .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center) .clipped() }
Now provide the response and nothing else.
| Try using Geometry Reader let placeholder = UIImage(systemName: "photo")! // SF Symbolsstruct ContentView: View { var body: some View { GeometryReader { geometry in Image(uiImage: placeholder) .resizable() .frame(width: geometry.size.width, height: geometry.size.height, alignment: .center) // .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center) .clipped() } }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57727107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6316195/']} | jdg_81648 |
stackexchange | llm_judgeable_groundtruth_similarity | 2384078 |
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 Python 2.x: >>> '' > 0True Why is that?
Now provide the response and nothing else.
| The original design motivation for allowing order-comparisons of arbitrary objects was to allow sorting of heterogeneous lists -- usefully, that would put all strings next to each other in alphabetical order, and all numbers next to each other in numerical order, although which of the two blocks came first was not guaranteed by the language. For example, this allowed getting only unique items in any list (even one with non-hashable items) in O(N log N) worst-case time Over the years, this pragmatic arrangement eroded. The first crack came when the ability to order-compare complex numbers was taken away, quite a few versions ago. Suddenly, the ability to sort any list disappeared: it did not apply any more if the list contained complex numbers, possibly together with items of other types. Then Guido started disliking heterogeneous lists more generally, and thus started thinking that it didn't really matter if such lists could be usefully sorted or not... because such lists should not exist in the first place, according to his new thinking. He didn't do anything to forbid them, but was not inclined to accept any compromises to support them either. Note that both changes move the balance a little bit away from the "practicality beats purity" item of the Zen of Python (which was written earlier, back when complex numbers still could be order-compared ;-) – a bit more purity, a bit less practicality. Nevertheless the ability to order-compare two arbitrary objects (as long as neither was a complex number ;-) remained for a long time, because around that same time Guido started really insisting on maintaining strong backwards compatibility (a shift that's both practical and pure ;-). So, it's only in Python 3, which explicitly and deliberately removed the constraint of strong backwards compatibility to allow some long-desired but backwards incompatible enhancements (especially simplifications and removal of obsolete, redundant way to perform certain tasks), that order comparison of instances of different types became an error. So this historical and philosophical treatise is basically the only way to truly respond to your "why" question...! :-) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2384078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/68119/']} | jdg_81649 |
stackexchange | llm_judgeable_groundtruth_similarity | 39092200 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have records in our datastore that have effective & expiry time. This information is stored using the string representation of Instant . There are some records that would never expire. But since the value for expiry date is mandatory, we decided to store string representation of Instant.MAX . So far so good. We have search use-case to return all the records that are active within the input time range [s,e] . We query the datastore and return all such records [Si, Ei] which satisfy the condition Si < s && e < Ei Note that string representations are being compared here. Now the problem is that + is being prepended to the string representation of Instant.MAX . This is failing the condition e < Ei since ASCII('+') < ASCII(digit) . I've written a piece of code to know after which second , the + starts getting prepended: Long e = Instant.now().getEpochSecond()*1000;for (int i = 0; i < 5; i++) { System.out.println(e + "->" + Instant.ofEpochMilli(e)); e *= 10;} which prints: 1471925168000->2016-08-23T04:06:08Z14719251680000->2436-06-07T17:01:20Z147192516800000->6634-05-07T02:13:20Z1471925168000000->+48613-06-14T22:13:20Z14719251680000000->+468404-07-08T06:13:20Z I've the option of truncating the + before persisting in datastore. I'm more interested in why this is happening and how can we explicitly avoid it?
Now provide the response and nothing else.
| The answer to your question 'why?' is hidden in the implementation of DateTimeFormatterBuilder.InstantPrinterParser.format() (I left out irrelevant code for brevity): // use INSTANT_SECONDS, thus this code is not bound by Instant.MAXLong inSec = context.getValue(INSTANT_SECONDS);if (inSec >= -SECONDS_0000_TO_1970) { // current era long zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970; long hi = Math.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1; long lo = Math.floorMod(zeroSecs, SECONDS_PER_10000_YEARS); LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC); if (hi > 0) { buf.append('+').append(hi); } buf.append(ldt);} As you can see, it checks boundaries of 10000-year periods and if the value exceeds at least one of them, it adds + and the quantity of such periods. So, to prevent such behaviour, keep your maximum date within the epoch bounds, don't use Instant.MAX . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39092200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1240384/']} | jdg_81650 |
stackexchange | llm_judgeable_groundtruth_similarity | 45295031 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got a little problem adding more then one prop to column in ngx-datatable: columns = [ { prop: 'semesterName', name: 'סמסטר', resizeable: false }, { prop: 'eventName', name: 'מפגש', resizeable: false }, { prop: 'when', name: 'מועד מפגש', resizeable: false }, { prop: 'lecturerName', name: 'מרצה', resizeable: false }, { prop: 'hugName', name: 'חוג', resizeable: false },]; I need to display two props in one column. Like 'eventName' and 'when' in one column. The model: export class Course { semester: string; semesterName: string; courseObject: string; course: string; courseName: string; eventObject: string; event: string; eventName: string; hugName: string; dayOfWeek: string; dayOfWeekNum: string; where: string; when: string; lecturerName: string; lecturerEMail: string; authMembers: number; eventStatus: string;} The Html: <ngx-datatable[columns]="columns" [rows]="courses"></ngx-datatable> Thank you!
Now provide the response and nothing else.
| Figured it out: To change column names - let-column Formatting cell content (ex: Date) - let-value Formatting with multiple properties Ex: Date - let-row The template: <ngx-datatable [rows]="courses"> <ngx-datatable-column> <ng-template let-column="column" ngx-datatable-header-template> סמסטר </ng-template> <ng-template let-row="row" ngx-datatable-cell-template> {{row.semesterName}} </ng-template> </ngx-datatable-column> <ngx-datatable-column> <ng-template let-column="column" ngx-datatable-header-template> מפגש </ng-template> <ng-template let-row="row" ngx-datatable-cell-template> {{row.event}} <br> {{row.eventName}} </ng-template> </ngx-datatable-column> <ngx-datatable-column> <ng-template let-column="column" ngx-datatable-header-template> מועד מפגש </ng-template> <ng-template let-row="row" ngx-datatable-cell-template> {{row.where}} <br> {{row.when}} </ng-template> </ngx-datatable-column> <ngx-datatable-column> <ng-template let-column="column" ngx-datatable-header-template> מרצה </ng-template> <ng-template let-row="row" ngx-datatable-cell-template> <a href="mailto:{{row.lecturerEmail}}">{{row.lecturerName}}</a> </ng-template> </ngx-datatable-column> <ngx-datatable-column> <ng-template let-column="column" ngx-datatable-header-template> חוג </ng-template> <ng-template let-row="row" ngx-datatable-cell-template> {{row.hugName}} </ng-template> </ngx-datatable-column> </ngx-datatable> No need for [columns] anymore - remove it from the template. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45295031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3703755/']} | jdg_81651 |
stackexchange | llm_judgeable_groundtruth_similarity | 7198633 |
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 tell when [UITableView setEditing:YES animated:YES] has completed? I don't want to give any context, because I want to avoid anybody giving me workarounds, which do not interest me. What I want is to call the above, then have a separate function called when the animation is completed. I am edited the post to give context and some workarounds.Originally I setEditing and immediately reload the table data. [tableView setEditing:YES animated:YES];[tableView reloadData]; The problem is that the table reloads before the animation begins, and so the animation is never seen. Here are some various workarounds: [tableView setEditing:YES animated:YES];[self performSelector:@selector(ReloadTable) withObject:nil afterDelay:1.0]; This works but if I get the delay incorrect then it will look bad. So I need to know what the delay is, which I can figure out, but we are not gauranteed that the delay will always be the same. isEditing = YES;[tableView reloadData];[tableView setEditing:YES animated:YES]; This could work, but the table behaves differently depending on if we are in editing mode. So I have to use my own isEditing variable instead of the standard UITableView.editing. I would rather not have to create a new boolean isEditing variable. [tableView setEditing:YES animated:YES];[tableView insertRowsAtIndexPaths:path withRowAnimation:UITableViewRowAnimationTop]; This almost works well but in editing mode the first row should have the UITableViewCellEditingStyleInsert, while the other rows get UITableViewCellEditingStyleDelete. And with the above code the editing style gets set BEFORE the row is added. Therefore the second row ends up with UITableViewCellEditingStyleInsert.
Now provide the response and nothing else.
| [CATransaction begin];[CATransaction setCompletionBlock: ^{ // your animation has finished}];[tableView setEditing:YES animated:YES];[CATransaction commit]; Note that setCompletionBlock must be on the top. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7198633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/564189/']} | jdg_81652 |
stackexchange | llm_judgeable_groundtruth_similarity | 12960141 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two entities I wish to serialize with the JMSSerializerBundle. The Music Entity has a mapping-file with exclusion_policy: NONE . The Music entity has a field of the entity User from FOSUserBundle . The User entity has a mapping-file with exclusion_policy: ALL with a few fields set to expose: true , so they will be serialized. The problem is, the User field gets fully serialized. It does not matter if I change the mapping-file of the User entity. This is how it looks: #My/Bundle/Resources/config/serializer/Entity.Music.ymlxxx\xxx\Entity\Music: exclusion_policy: NONE#My/Bundle/Resources/config/serializer/Entity.User.ymlxxx\xxx\Entity\User: exclusion_policy: ALL properties: id: expose: true username: expose: true username_canonical: exclude: true email: exclude: true email_canonical: exclude: true enabled: exclude: true salt: exclude: true password: exclude: true last_login: exclude: true confirmation_token: exclude: true password_requested_at: exclude: true groups: exclude: true locked: exclude: true expired: exclude: true expires_at: exclude: true roles: expose: true credentials_expired: exclude: true credentials_expired_at: exclude: true Why does it not refer to it's own mapping file? Or am I mistaken somewhere? What have I tried thusfar I have read the third party meta data documentation. It simply says to add a new directory in my serializer service. I have done that, but I have to extend the FOS\UserBundle\Entity class, and that also does not have access to the parent protected fields I'm trying to exclude.
Now provide the response and nothing else.
| I bet xxx\xxx\Entity\User: refers to your own namespace and class . If it is, it is the wrong way to do. The rules must be applied to the class where the properties live. Given the property you exposed in your configuration, I guess you're using FOSUserBundle . Therefore, you must apply your rules on FOS\UserBundle\Model\User . Then you need to add a JMSSerializer config to indicate where the serializer metadata live for the given namespace. It should look like: jms_serializer: metadata: auto_detection: true directories: FOSUserBundle: namespace_prefix: "FOS\\UserBundle" path: "@YourUserBundle/Resources/config/serializer/fos" In fos/ directory you should have Model.User.yml With something like: FOS\UserBundle\Model\User: exclusion_policy: ALL properties: id: expose: true groups: [list, details] username: expose: true groups: [details] email: expose: true groups: [me] roles: expose: true groups: [details] Details: When applying rules to the Serializer through metadata, the Serializer looks for the property which are declared inside the class which is defined in the Metadata. Example: class Foo { protected $foo;}class Bar extends Foo { protected $bar;} Your metadata will look like this: Foo: exclusion_policy: ALL properties: foo: expose: trueBar: exclusion_policy: ALL properties: bar: expose: true THE EXAMPLE BELOW IS NOT THE CORRECT WAY TO DO Bar: exclusion_policy: ALL properties: foo: expose: true bar: expose: true if you do this, only the rules on the property bar will be applied (and exposed). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12960141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1366455/']} | jdg_81653 |
stackexchange | llm_judgeable_groundtruth_similarity | 162 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have recently received an ad for a device attaching to my inlet water pipe and a power socket, and claiming to massively reduce the scale build-up. This compact, computerised limescale remover uses a coil wrapped around the outside of your main intake pipe to create an electronic force, which changes the physical properties of the scale-forming calcium. Those limescale beasties are literally shocked into shape. Scalewatcher electronically alters the shape of the limescale crystals so they can't stick onto your pipes any more. Instead they just wash straight through your system. Your water doesn't just stop depositing limescale anymore — it actually absorbs and dissolves existing limescale, so, over time, Scalewatcher actually helps to clean up your plumbing! I can't think of any mechanism through which it could possibly achieve that, although my knowledge of physics is amateur-level. Could it work? (It does seem to trigger all the "scam" alarms in me, but now I have a good place where to seek a second opinion!) P.S. Curiously, it is claimed that the water remains chemically unchanged - which is weird because any device that actually succeeds at reducing the scale buildup will necessarily increase the amount of minerals in the tap water...
Now provide the response and nothing else.
| I have met with a similar device in a form of either permanent magnet or an electro-magnet . In both cases the devices failed when subject to an experiment: Scientific and engineering studies generally refute the effectiveness of the method, finding no differences not attributable to other causes between systems with and without a magnetic water treatment device, and no theoretical basis to expect that there might be. Vendors frequently use pictures and testimonials to support their claims, but omit quantitative detail and well-controlled studies. In this case the description "how it works" is quite similar, using physical terms very vaguely, which gives impression of scientific approach to a buyer, but actually tells nothing at all. How it "increases the solubility of water"? As the operating principle is different, the magnetic treatment studies are not relevant here and to be absolutely sure it would be necessary to perform a controlled experiment, but from the external similarities I would most likely expect it to be the same, and having no effect at all. From their how it works : The electronic unit works by sending out a signal which changes the electrical and physical properties of scale forming calcium molecules. This action stops any further build-up of scale by preventing molecules from adhering to themselves or any other surface. The solubility of the water is also increased, therefore existing scale is dissolved back into the water and gradually reduced. And more "scientific" section (emphasis mine): The nuclei upon which the crystals start growing are minute in size and have charged surfaces in their natural condition within the water. When they pass through the field, these naturally charged nuclei encounter considerable forces as the field interacts with them. The field acts at the surfaces of the nuclei and modifies the nature of the electrical charges and this ionisation effect thus alters the growth rate and pattern of the crystals in general and on specific planes. | {} | {'log_upvote_score': 4, 'links': ['https://skeptics.stackexchange.com/questions/162', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/106/']} | jdg_81654 |
stackexchange | llm_judgeable_groundtruth_similarity | 39382412 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I have a numpy image of some width x and height y.I have to crop the center portion of the image to width cropx and height cropy. Let's assume that cropx and cropy are positive non zero integers and less than the respective image size. What's the best way to apply the slicing for the output image?
Now provide the response and nothing else.
| Something along these lines - def crop_center(img,cropx,cropy): y,x = img.shape startx = x//2-(cropx//2) starty = y//2-(cropy//2) return img[starty:starty+cropy,startx:startx+cropx] Sample run - In [45]: imgOut[45]: array([[88, 93, 42, 25, 36, 14, 59, 46, 77, 13, 52, 58], [43, 47, 40, 48, 23, 74, 12, 33, 58, 93, 87, 87], [54, 75, 79, 21, 15, 44, 51, 68, 28, 94, 78, 48], [57, 46, 14, 98, 43, 76, 86, 56, 86, 88, 96, 49], [52, 83, 13, 18, 40, 33, 11, 87, 38, 74, 23, 88], [81, 28, 86, 89, 16, 28, 66, 67, 80, 23, 95, 98], [46, 30, 18, 31, 73, 15, 90, 77, 71, 57, 61, 78], [33, 58, 20, 11, 80, 25, 96, 80, 27, 40, 66, 92], [13, 59, 77, 53, 91, 16, 47, 79, 33, 78, 25, 66], [22, 80, 40, 24, 17, 85, 20, 70, 81, 68, 50, 80]])In [46]: crop_center(img,4,6)Out[46]: array([[15, 44, 51, 68], [43, 76, 86, 56], [40, 33, 11, 87], [16, 28, 66, 67], [73, 15, 90, 77], [80, 25, 96, 80]]) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39382412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2200539/']} | jdg_81655 |
stackexchange | llm_judgeable_groundtruth_similarity | 336261 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a data frame in python where I need to find all categorical variables. Checking the type of the column doesn't always work because int type can also be categorical. So I seek help in finding the right hypothesis test method to identify if a column is categorical or not. I was trying below chi-square test but I am not sure if this is good enough import numpy as npdata = np.random.randint(0,5,100)import scipy.stats as ssss.chisquare(data) Please advise.
Now provide the response and nothing else.
| Short answer: you can't. There is no statistical test that will tell you whether a predictor that contains the integers between 1 and 10 is a numeric predictor (e.g., number of children) or encodes ten different categories. (If the predictor contains negative numbers, or the smallest number is larger than one, or it skips integers, this might argue against its being a categorical encoding - or it may just mean that the analyst used nonstandard encoding.) The only way to be sure is to leverage domain expertise, or the dataset's codebook (which should always exist). | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/336261', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/89996/']} | jdg_81656 |
stackexchange | llm_judgeable_groundtruth_similarity | 4553624 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are used to saying that HashMap get/put operations are O(1). However it depends on the hash implementation. The default object hash is actually the internal address in the JVM heap. Are we sure it is good enough to claim that the get/put are O(1)? Available memory is another issue. As I understand from the javadocs, the HashMap load factor should be 0.75. What if we do not have enough memory in JVM and the load factor exceeds the limit? So, it looks like O(1) is not guaranteed. Does it make sense or am I missing something?
Now provide the response and nothing else.
| It depends on many things. It's usually O(1), with a decent hash which itself is constant time... but you could have a hash which takes a long time to compute, and if there are multiple items in the hash map which return the same hash code, get will have to iterate over them calling equals on each of them to find a match. In the worst case, a HashMap has an O(n) lookup due to walking through all entries in the same hash bucket (e.g. if they all have the same hash code). Fortunately, that worst case scenario doesn't come up very often in real life, in my experience. So no, O(1) certainly isn't guaranteed - but it's usually what you should assume when considering which algorithms and data structures to use. In JDK 8, HashMap has been tweaked so that if keys can be compared for ordering, then any densely-populated bucket is implemented as a tree, so that even if there are lots of entries with the same hash code, the complexity is O(log n). That can cause issues if you have a key type where equality and ordering are different, of course. And yes, if you don't have enough memory for the hash map, you'll be in trouble... but that's going to be true whatever data structure you use. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4553624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/521070/']} | jdg_81657 |
stackexchange | llm_judgeable_groundtruth_similarity | 63696735 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got custom member_action in my Active Admin panel which is responsible for resending devise reset password instructions. admin/users.rb ActiveAdmin.register User do member_action :reset_password do user = User.find(params[:id]) user.send_reset_password_instructions redirect_to(admin_user_path(user), notice: "Password reset email sent to #{user.email}") endend How to write RSpec tests for such an action? The only thing I found is this one and I think it's not quite related to my problem. I was trying to sth like below: require 'rails_helper'describe Admin::UsersController, type: :controller do include Devise::TestHelpers let!(:admin) { create(:admin_user) } before(:each) do sign_in admin end describe 'GET user' do let(:user) { create(:user, :random_email) } before(:each) do User.should_receive(:find).at_least(:once).and_return(user) get :show end it 'sends email' do get :reset_password expect(user).should_receive(:send_reset_password_instructions) end endend But I'm getting an error: ActionController::UrlGenerationError: No route matches {:action=>"reset_password", :controller=>"admin/users"}
Now provide the response and nothing else.
| I found another solution for functional components - you can just use React.FC , which provides type checking and autocomplete for static properties like defaultProps. const Hello: React.FC<{name: string, gretting: string}> = ({ name, gretting = 'night' }) => In that case you don't have to use interface at all. But in case you want for some reason: const Hello: React.FC<IProps> = ({ name, gretting = 'night' }) => ===== UPDATE===== Additionally: "react/prop-types": "off" // Since we do not use prop-types "react/require-default-props": "off" // Since we do not use prop-types | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/63696735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10443890/']} | jdg_81658 |
stackexchange | llm_judgeable_groundtruth_similarity | 41053331 |
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 playbook, i have a task to update audit.rules and then notify a handler which should restart the auditd service. task: - name: 6.6.7 - audit rules configuration template: src=X/ansible/templates/auditd_rules.j2 dest=/etc/audit/rules.d/audit.rules backup=yes owner=root group=root mode=0640 notify: - restart auditd handlers: - name: restart auditd service: name=auditd state=restarted When the playbook runs, the audit rules are updated and a request is made to restart auditd but this fails as below. RUNNING HANDLER [restart auditd] ***********************************************fatal: [ipX-southeast-2.compute.internal]: FAILED! => {"changed": false, "failed": true, "msg": "Unable to restart service auditd: Failed to restart auditd.service: Operation refused, unit auditd.service may be requested by dependency only.\n"} When i look at the unit definition for auditd, i can see refuseManualStop=yes. Is this why i cant restart the service? how does one over come this to pickup the new audit rules? systemctl cat auditd.service# /usr/lib/systemd/system/auditd.service[Unit]Description=Security Auditing ServiceDefaultDependencies=noAfter=local-fs.target systemd-tmpfiles-setup.serviceConflicts=shutdown.targetBefore=sysinit.target shutdown.targetRefuseManualStop=yesConditionKernelCommandLine=!audit=0Documentation=man:auditd(8) https://people.redhat.com/sgrubb/audit/[Service]ExecStart=/sbin/auditd -n## To not use augenrules, copy this file to /etc/systemd/system/auditd.service## and comment/delete the next line and uncomment the auditctl line.## NOTE: augenrules expect any rules to be added to /etc/audit/rules.d/ExecStartPost=-/sbin/augenrules --load#ExecStartPost=-/sbin/auditctl -R /etc/audit/audit.rulesExecReload=/bin/kill -HUP $MAINPID# By default we don't clear the rules on exit. To enable this, uncomment# the next line after copying the file to /etc/systemd/system/auditd.service#ExecStopPost=/sbin/auditctl -R /etc/audit/audit-stop.rules[Install]WantedBy=multi-user.target
Now provide the response and nothing else.
| This has been explored, discussed, and resolved (mostly) in the Red Hat Bugzilla #1026648 and Anisble Issue # 22171 (github) reports. Resolution Use the ansible service module parameter use=service to force execution of the /sbin/service utility instead of the gathered-fact value of systemd (which invokes /sbin/systemctl ) like this: - service: name=auditd state=restarted use=service Example playbook (pastebin.com) Workaround: Use the ansible command module to explicitly run the service executable like this: - command: /sbin/service auditd restart Analysis - root cause: This is an issue created by upstream packaging of auditd.service unit. It will not start/stop/restart when acted upon by systemctl , apparently by design . It is further compounded by the Ansible service control function, which uses the preferred method identified when system facts are gathered and "ansible_service_mgr" returns "systemd". This is regardless of the actual module used to manage the service.unit. RHEL dev team may fix if considered a problem in upcoming updates (ERRATA) Ansible dev team has offered a workaround and (as of 2.2) updated the service module with the use parameter. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41053331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4093626/']} | jdg_81659 |
stackexchange | llm_judgeable_groundtruth_similarity | 2824272 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am not sure how to approach this problem. The usual methods do not work to find a minimum. I can see that, but how to show that there must not exist a minimum?
Now provide the response and nothing else.
| Suppose that it has a global minimum at $(a,b)$. Then the map $y\mapsto f(a,y)$ has a minimum at $b$. But then the standard Calculus methods show that $b=-\sqrt{1+a^4}$ and that tharefore the minimum is $-\frac{a^2}{2\sqrt{1+a^4}}$. This cannot be, because$$\lim_{a\to\pm\infty}-\frac{a^2}{2\sqrt{1+a^4}}=-\frac12,$$but the limit is never attained. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2824272', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/82654/']} | jdg_81660 |
stackexchange | llm_judgeable_groundtruth_similarity | 7389662 |
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 know how to run a command using cmd = subprocess.Popen and then subprocess.communicate.Most of the time I use a string tokenized with shlex.split as 'argv' argument for Popen.Example with "ls -l": import subprocessimport shlexprint subprocess.Popen(shlex.split(r'ls -l'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0] However, pipes seem not to work... For instance, the following example returns noting: import subprocessimport shlexprint subprocess.Popen(shlex.split(r'ls -l | sed "s/a/b/g"'), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0] Can you tell me what I am doing wrong please? Thx
Now provide the response and nothing else.
| I think you want to instantiate two separate Popen objects here, one for 'ls' and the other for 'sed'. You'll want to pass the first Popen object's stdout attribute as the stdin argument to the 2nd Popen object. Example: p1 = subprocess.Popen('ls ...', stdout=subprocess.PIPE)p2 = subprocess.Popen('sed ...', stdin=p1.stdout, stdout=subprocess.PIPE)print p2.communicate() You can keep chaining this way if you have more commands: p3 = subprocess.Popen('prog', stdin=p2.stdout, ...) See the subprocess documentation for more info on how to work with subprocesses. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7389662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_81661 |
stackexchange | llm_judgeable_groundtruth_similarity | 16592222 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to group boxplots in matplotlib? Assume we have three groups "A", "B", and "C" and for each we want to create a boxplot for both "apples" and "oranges". If a grouping is not possible directly, we can create all six combinations and place them linearly side by side. What would be to simplest way to visualize the groupings? I'm trying to avoid setting the tick labels to something like "A + apples" since my scenario involves much longer names than "A".
Now provide the response and nothing else.
| How about using colors to differentiate between "apples" and "oranges" and spacing to separate "A", "B" and "C"? Something like this: from pylab import plot, show, savefig, xlim, figure, \ hold, ylim, legend, boxplot, setp, axes# function for setting the colors of the box plots pairsdef setBoxColors(bp): setp(bp['boxes'][0], color='blue') setp(bp['caps'][0], color='blue') setp(bp['caps'][1], color='blue') setp(bp['whiskers'][0], color='blue') setp(bp['whiskers'][1], color='blue') setp(bp['fliers'][0], color='blue') setp(bp['fliers'][1], color='blue') setp(bp['medians'][0], color='blue') setp(bp['boxes'][1], color='red') setp(bp['caps'][2], color='red') setp(bp['caps'][3], color='red') setp(bp['whiskers'][2], color='red') setp(bp['whiskers'][3], color='red') setp(bp['fliers'][2], color='red') setp(bp['fliers'][3], color='red') setp(bp['medians'][1], color='red')# Some fake data to plotA= [[1, 2, 5,], [7, 2]]B = [[5, 7, 2, 2, 5], [7, 2, 5]]C = [[3,2,5,7], [6, 7, 3]]fig = figure()ax = axes()hold(True)# first boxplot pairbp = boxplot(A, positions = [1, 2], widths = 0.6)setBoxColors(bp)# second boxplot pairbp = boxplot(B, positions = [4, 5], widths = 0.6)setBoxColors(bp)# thrid boxplot pairbp = boxplot(C, positions = [7, 8], widths = 0.6)setBoxColors(bp)# set axes limits and labelsxlim(0,9)ylim(0,9)ax.set_xticklabels(['A', 'B', 'C'])ax.set_xticks([1.5, 4.5, 7.5])# draw temporary red and blue lines and use them to create a legendhB, = plot([1,1],'b-')hR, = plot([1,1],'r-')legend((hB, hR),('Apples', 'Oranges'))hB.set_visible(False)hR.set_visible(False)savefig('boxcompare.png')show() | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16592222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1804173/']} | jdg_81662 |
stackexchange | llm_judgeable_groundtruth_similarity | 29949501 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With the below code my notification are only added to the notification bar, no popup style message is displayed like if you would receive a whatsapp message when you're in another application. What makes that happen to a notification? private void sendNotification(int distance, ViewObject viewObject) { Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); notificationIntent.putExtra("path", viewObject.getPath()); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(MainActivity.class); stackBuilder.addNextIntent(notificationIntent); PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(Integer.parseInt(viewObject.getRefId()), PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle(); bigText.bigText(String.format(getString(R.string.notification), viewObject.getTitle())); bigText.setBigContentTitle(getString(R.string.hello)); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(R.drawable.ic_wald_poi) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_poi)) .setColor(getResources().getColor(R.color.primary)) .setContentTitle(getString(R.string.hello)) .setContentIntent(notificationPendingIntent) .setContentText(String.format(getString(R.string.notification), viewObject.getTitle())) .setDefaults(Notification.DEFAULT_ALL) .setStyle(bigText); builder.setAutoCancel(true); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(0, builder.build());}
Now provide the response and nothing else.
| If you want use Heads-up Notifications like this: You must change Notification priority or NotificationChannel importance. The notification priority, set by setPriority() . The priority determines how intrusive the notification should be on Android 7.1 and lower. (For Android 8.0 and higher, you must instead set the channel importance) On Android 7.1 (API level 25) and lower: Set notification priority to NotificationCompat.PRIORITY_HIGH or NotificationCompat.PRIORITY_MAX . Set ringtone and vibrations - you can use setDefaults(Notification.DEFAULT_ALL) Android 8.0 (API level 26) and higher: Set notification channel priority to NotificationManager.IMPORTANCE_HIGH Notification: NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setSmallIcon(R.drawable.ic_wald_poi) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_poi)) .setColor(getResources().getColor(R.color.primary)) .setContentTitle(getString(R.string.hello)) .setContentIntent(notificationPendingIntent) .setContentText(String.format(getString(R.string.notification), viewObject.getTitle())) .setDefaults(NotificationCompat.DEFAULT_ALL) .setStyle(bigText) .setPriority(NotificationCompat.PRIORITY_HIGH) // or NotificationCompat.PRIORITY_MAX Notification channel: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create the NotificationChannel val name = getString(R.string.notification_channel_name) val descriptionText = getString(R.string.notification_channel_description) val importance = NotificationManager.IMPORTANCE_HIGH val mChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance) mChannel.description = descriptionText // Register the channel with the system; you can't change the importance // or other notification behaviors after this val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(mChannel)} Important If you'd like to further customize your channel's default notification behaviors, you can call methods such as enableLights() , setLightColor() , and setVibrationPattern() on the NotificationChannel . But remember that once you create the channel, you cannot change these settings and the user has final control of whether these behaviors are active. Other option is to uninstall and install application again. Read more Examples of conditions that may trigger heads-up notifications include: The user's activity is in fullscreen mode (the app uses fullScreenIntent). The notification has high priority and uses ringtones or vibrations on devices running Android 7.1 (API level 25) and lower. The notification channel has high importance on devices running Android 8.0 (API level 26) and higher. Priority: Notification.PRIORITY_HIGH and Notification.PRIORITY_MAX was deprecated in API level 26. use NotificationCompat instead. Here is more info :-) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29949501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/964887/']} | jdg_81663 |
stackexchange | llm_judgeable_groundtruth_similarity | 49099637 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to tell if there was an exception once you're in the finally clause? Something like: try: funky codefinally: if ???: print('the funky code raised') I'm looking to make something like this more DRY: try: funky codeexcept HandleThis: # handle it raised = Trueexcept DontHandleThis: raised = True raiseelse: raised = Falsefinally: logger.info('funky code raised %s', raised) I don't like that it requires to catch an exception, which you don't intend to handle, just to set a flag. Since some comments are asking for less "M" in the MCVE, here is some more background on the use-case. The actual problem is about escalation of logging levels. The funky code is third party and can't be changed. The failure exception and stack trace does not contain any useful diagnostic information, so using logger.exception in an except block is not helpful here. If the funky code raised then some information which I need to see has already been logged, at level DEBUG. We do not and can not handle the error, but want to escalate the DEBUG logging because the information needed is in there. The funky code does not raise, most of the time. I don't want to escalate logging levels for the general case, because it is too verbose. Hence, the code runs under a log capture context (which sets up custom handlers to intercept log records) and some debug info gets re-logged retrospectively: try: with LogCapture() as log: funky_code() # <-- third party badnessfinally: # log events are buffered in memory. if there was an exception, # emit everything that was captured at a WARNING level for record in log.captured: if <there was an exception>: log_fn = mylogger.warning else: log_fn = getattr(mylogger, record.levelname.lower()) log_fn(record.msg, record.args)
Now provide the response and nothing else.
| raised = Truetry: funky code raised = Falseexcept HandleThis: # handle itfinally: logger.info('funky code raised %s', raised) Given the additional background information added to the question about selecting a log level, this seems very easily adapted to the intended use-case: mylog = WARNINGtry: funky code mylog = DEBUGexcept HandleThis: # handle itfinally: mylog(...) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49099637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/674039/']} | jdg_81664 |
stackexchange | llm_judgeable_groundtruth_similarity | 19496593 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Basically, I followed the instructions here: http://wiki.gnustep.org/index.php/GNUstep_under_Ubuntu_Linux With the extra step of building the gui and back. If I build and run a non-gui program, all works well. Only when I add something that uses the gui, like the following: // Created by Tobias Lensing on 2/22/13.#import <Foundation/Foundation.h>#import <AppKit/AppKit.h>#import <dispatch/dispatch.h>int main(int argc, const char * argv[]){ @autoreleasepool { int multiplier = 7; int (^myBlock)(int) = ^(int num) { return num * multiplier; }; NSLog(@"%d", myBlock(3)); dispatch_queue_t queue = dispatch_queue_create(NULL, NULL); dispatch_sync(queue, ^{ printf("Hello, world from a dispatch queue!\n"); });// dispatch_release(queue); // ARC takes care of this } @autoreleasepool { [NSApplication sharedApplication]; NSRunAlertPanel(@"Test", @"Wow it works!", @"OK", nil, nil); } return 0;} I compile this with the following: clang `gnustep-config --objc-flags` `gnustep-config --objc-libs` -fobjc-arc -fobjc-runtime=gnustep -fblocks -lobjc -ldispatch -lgnustep-gui test.m It compiles and links with no errors. When I run it, however, it spits out the following ugly-gram: Hello, world from a dispatch queue!Objective-C ABI Error: Loading modules from incompatible ABI's while loading .GSBackend.ma.out: /home/lloyd/projects/ThirdParty/BuildGnuStep/libobjc2/loader.c:53: void __objc_exec_class(struct objc_module_abi_8 *): Assertion `objc_check_abi_verion(module)' failed.Aborted (core dumped) I have assured myself that there is no other version of libobjc (this is on a virtual machine so I can go back redo my steps). Commenting out the following: // [NSApplication sharedApplication];// NSRunAlertPanel(@"Test", @"Wow it works!", @"OK", nil, nil); and everything compiles and runs, aside from the GUI obviously. How can I have two ABI's when I build everything from scratch? Do I need to configure the GUI differently? I've been puzzling over this for a couple of weeks.
Now provide the response and nothing else.
| Your main function has a for loop iterating on a variable called j , but the body of the loop is trying to use an undefined variable called i . Your main function also never even calls your added() function. Moreover, your added() function is kind of problematic too. int added(int input){ for(int i=1;i<= input; i++){ if(i>0 && input % 2) // checking if the numbers are even... m[i]= input; //array implementation return m[i]; }} I code in several different languages, so I'm not sure if this is actually an issue here or not, but your return statement is within a for loop . In many languages, this won't compile because your added() function doesn't have a return statement for every possible execution path. What happens if you send added() an argument <1 ? added(0) or any negative int will never enter the for loop, so added() gets to the end of the function without a return statement . Moreover, with your return within the for loop and outside the if statement, you're guaranteed to only return the result of the first for loop, so you may as well just do a nested if statement or something. Then there's your if statement. if(i>0 && input % 2) . The && returns true when both halves also return true (and that's the only time your if statement is executed). In this case, i>0 returns true every time i is a non-zero positive integer. No problem here. Meanwhile, input % 2 doesn't return a boolean. It will return an int , and in this case, it will return 0 or 1 . It will return 0 on even numbers and 1 on odd numbers. And as it turns out, the integer 0 is evaluated as a boolean false here and non-zero integers are evaluated as boolean true so this is probably doing the opposite of what you want. You need to change input % 2 to ((input % 2) == 0) probably. And finally, if m[] is declared globably, you don't actually need to return anything. main() and added() can both see the variable perfectly fine. You can modify your function to look like this: void added(int input){ for(int i=1;i<= input; i++){ if(/*i will always be >0 in this for loop*/(input % 2) == 0) m[i]= input; } return;} Then all you have to do is actually call added() from main and it will correctly modify the array. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19496593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1582248/']} | jdg_81665 |
stackexchange | llm_judgeable_groundtruth_similarity | 3870726 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible force the browser to fresh the cached CSS? This is not as simple as every request. We have a site that has had stable CSS for a while. Now we need to make some major updates to the CSS; however, browsers that have cached the CSS will not receive the new CSS for a couple of days causing rendering issues. Is there a way to force refresh of the CSS or are we better just opting for version specific CSS URLs?
Now provide the response and nothing else.
| TL;DR Change the file name or query string Use a change that only occurs once per release File renaming is preferable to a query string change Always set HTTP headers to maximize the benefits of caching There are several things to consider and a variety of ways to approach this. First, the spec What are we trying to accomplish? Ideally, a modified resource will be unconditionally fetched the first time it is requested, and then retrieved from a local cache until it expires with no subsequent server interaction. Observed Caching Behavior Keeping track of the different permutations can be a bit confusing, so I created the following table. These observations were generated by making requests from Chrome against IIS and observing the response/behavior in the developer console. In all cases, a new URL will result in HTTP 200. The important thing is what happens with subsequent requests. +---------------------+--------------------+-------------------------+| Type | Cache Headers | Observed Result |+---------------------+--------------------+-------------------------+| Static filename | Expiration +1 Year | Taken from cache || Static filename | Expire immediately | Never caches || Static filename | None | HTTP 304 (not modified) || | | || Static query string | Expiration +1 Year | HTTP 304 (not modified) || Static query string | Expire immediately | HTTP 304 (not modified) || Static query string | None | HTTP 304 (not modified) || | | || Random query string | Expiration +1 Year | Never caches || Random query string | Expire immediately | Never caches || Random query string | None | Never caches |+---------------------+--------------------+-------------------------+ However , remember that browsers and web servers don't always behave the way we expect. A famous example: in 2012 mobile Safari began caching POST requests . Developers weren't pleased. Query String Examples in ASP.Net MVC Razor syntax, but applicable in nearly any server processing language. ...since some applications have traditionally used GETs and HEADs withquery URLs (those containing a "?" in the rel_path part) to performoperations with significant side effects, caches MUST NOT treatresponses to such URIs as fresh unless the server provides an explicitexpiration time. This specifically means that responses from HTTP/1.0servers for such URIs SHOULD NOT be taken from a cache. Appending a random parameter to the end of the CSS URL included in your HTML will force a new request and the server should respond with HTTP 200 (not 304, even if it is hasn't beenmodified). <link href="[email protected]" /> Of course, if we randomize the query string with every request, this will defeat caching entirely. This is rarely/never desirable for a production application. If you are only maintaining a few URLs, you might manually modify them to contain a build number or a date: @{ var assembly = Assembly.GetEntryAssembly(); var name = assembly.GetName(); var version = name.Version;}<link href="[email protected]" /> This will cause a new request the first time the user agent encounters the URL, but subsequent requests will mostly return 304s. This still causes a request to be made, but at least the whole file isn't served. Path Modification A better solution is to create a new path. With a little effort, this process can be automated to rewrite the path with a version number (or some other consistent identifier). This answer shows a few simple and elegant options for non-Microsoft platforms. Microsoft developers can use a HTTP module which intercepts all requests for a given file type(s), or possibly leverage an MVC route/controller combo to serve up the correct file (I haven't seen this done, but I believe it is feasible). Of course, the simplest (not necessarily the quickest or the best) method is to just rename the files in question with each release and reference the updated paths in the link tags. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3870726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148361/']} | jdg_81666 |
stackexchange | llm_judgeable_groundtruth_similarity | 304661 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Sometimes I have strange troubles booting my computer (which runs Debian). So I issued "dmesg" command. In its output I saw a lot of errors. However, when I run extended SMART test on hard disks (using "smartctl -t long /dev/sda" command), the result is that my disks are not broken. What can be the reason of those errors? Here are the errors: (...) [ 505.918537] ata3.00: exception Emask 0x50 SAct 0x400 SErr 0x280900 action 0x6 frozen [ 505.918549] ata3.00: irq_stat 0x08000000, interface fatal error [ 505.918558] ata3: SError: { UnrecovData HostInt 10B8B BadCRC } [ 505.918566] ata3.00: failed command: READ FPDMA QUEUED [ 505.918579] ata3.00: cmd 60/40:50:20:5b:60/00:00:0b:00:00/40 tag 10 ncq 32768 in res 40/00:54:20:5b:60/00:00:0b:00:00/40 Emask 0x50 (ATA bus error) [ 505.918586] ata3.00: status: { DRDY } [ 505.918595] ata3: hard resetting link [ 506.410055] ata3: SATA link up 3.0 Gbps (SStatus 123 SControl 300) [ 506.422648] ata3.00: configured for UDMA/133 [ 506.422679] ata3: EH complete [ 1633.123880] md: bind<sdb3> [ 1633.187966] RAID1 conf printout: [ 1633.187977] --- wd:1 rd:2 [ 1633.187984] disk 0, wo:0, o:1, dev:sda3 [ 1633.187989] disk 1, wo:1, o:1, dev:sdb3 [ 1633.188866] md: recovery of RAID array md0 [ 1633.188871] md: minimum _guaranteed_ speed: 1000 KB/sec/disk. [ 1633.188875] md: using maximum available idle IO bandwidth (but not more than 200000 KB/sec) for recovery. [ 1633.188890] md: using 128k window, over a total of 1943618560k. [ 1634.167341] ata3.00: exception Emask 0x50 SAct 0x7f80 SErr 0x280900 action 0x6 frozen [ 1634.167353] ata3.00: irq_stat 0x08000000, interface fatal error [ 1634.167361] ata3: SError: { UnrecovData HostInt 10B8B BadCRC } [ 1634.167369] ata3.00: failed command: READ FPDMA QUEUED [ 1634.167382] ata3.00: cmd 60/00:38:00:00:6f/02:00:01:00:00/40 tag 7 ncq 262144 in res 40/00:6c:00:0c:6f/00:00:01:00:00/40 Emask 0x50 (ATA bus error) [ 1634.167389] ata3.00: status: { DRDY } [ 1634.167395] ata3.00: failed command: READ FPDMA QUEUED [ 1634.167407] ata3.00: cmd 60/00:40:00:02:6f/02:00:01:00:00/40 tag 8 ncq 262144 in res 40/00:6c:00:0c:6f/00:00:01:00:00/40 Emask 0x50 (ATA bus error) [ 1634.167413] ata3.00: status: { DRDY } [ 1634.167418] ata3.00: failed command: READ FPDMA QUEUED [ 1634.167429] ata3.00: cmd 60/00:48:00:04:6f/02:00:01:00:00/40 tag 9 ncq 262144 in res 40/00:6c:00:0c:6f/00:00:01:00:00/40 Emask 0x50 (ATA bus error) [ 1634.167435] ata3.00: status: { DRDY } [ 1634.167439] ata3.00: failed command: READ FPDMA QUEUED [ 1634.167451] ata3.00: cmd 60/00:50:00:06:6f/02:00:01:00:00/40 tag 10 ncq 262144 in res 40/00:6c:00:0c:6f/00:00:01:00:00/40 Emask 0x50 (ATA bus error) [ 1634.167457] ata3.00: status: { DRDY } [ 1634.167462] ata3.00: failed command: READ FPDMA QUEUED [ 1634.167473] ata3.00: cmd 60/00:58:00:08:6f/02:00:01:00:00/40 tag 11 ncq 262144 in res 40/00:6c:00:0c:6f/00:00:01:00:00/40 Emask 0x50 (ATA bus error) [ 1634.167479] ata3.00: status: { DRDY } [ 1634.167484] ata3.00: failed command: READ FPDMA QUEUED [ 1634.167495] ata3.00: cmd 60/00:60:00:0a:6f/02:00:01:00:00/40 tag 12 ncq 262144 in res 40/00:6c:00:0c:6f/00:00:01:00:00/40 Emask 0x50 (ATA bus error) [ 1634.167500] ata3.00: status: { DRDY } [ 1634.167505] ata3.00: failed command: READ FPDMA QUEUED [ 1634.167516] ata3.00: cmd 60/80:68:00:0c:6f/00:00:01:00:00/40 tag 13 ncq 65536 in res 40/00:6c:00:0c:6f/00:00:01:00:00/40 Emask 0x50 (ATA bus error) [ 1634.167522] ata3.00: status: { DRDY } [ 1634.167527] ata3.00: failed command: READ FPDMA QUEUED [ 1634.167538] ata3.00: cmd 60/00:70:80:0c:6f/02:00:01:00:00/40 tag 14 ncq 262144 in res 40/00:6c:00:0c:6f/00:00:01:00:00/40 Emask 0x50 (ATA bus error) [ 1634.167544] ata3.00: status: { DRDY } [ 1634.167553] ata3: hard resetting link [ 1634.658816] ata3: SATA link up 3.0 Gbps (SStatus 123 SControl 300) [ 1634.672645] ata3.00: configured for UDMA/133 [ 1634.672696] ata3: EH complete [ 1637.687898] ata3.00: exception Emask 0x50 SAct 0x3ff000 SErr 0x280900 action 0x6 frozen [ 1637.687910] ata3.00: irq_stat 0x08000000, interface fatal error [ 1637.687918] ata3: SError: { UnrecovData HostInt 10B8B BadCRC } [ 1637.687926] ata3.00: failed command: READ FPDMA QUEUED [ 1637.687940] ata3.00: cmd 60/00:60:80:a7:af/02:00:02:00:00/40 tag 12 ncq 262144 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.687947] ata3.00: status: { DRDY } [ 1637.687953] ata3.00: failed command: READ FPDMA QUEUED [ 1637.687965] ata3.00: cmd 60/00:68:80:a9:af/02:00:02:00:00/40 tag 13 ncq 262144 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.687971] ata3.00: status: { DRDY } [ 1637.687976] ata3.00: failed command: READ FPDMA QUEUED [ 1637.687987] ata3.00: cmd 60/80:70:80:ab:af/01:00:02:00:00/40 tag 14 ncq 196608 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.687993] ata3.00: status: { DRDY } [ 1637.687998] ata3.00: failed command: READ FPDMA QUEUED [ 1637.688009] ata3.00: cmd 60/00:78:00:ad:af/02:00:02:00:00/40 tag 15 ncq 262144 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.688015] ata3.00: status: { DRDY } [ 1637.688020] ata3.00: failed command: READ FPDMA QUEUED [ 1637.688031] ata3.00: cmd 60/80:80:00:af:af/00:00:02:00:00/40 tag 16 ncq 65536 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.688037] ata3.00: status: { DRDY } [ 1637.688042] ata3.00: failed command: READ FPDMA QUEUED [ 1637.688053] ata3.00: cmd 60/00:88:80:af:af/01:00:02:00:00/40 tag 17 ncq 131072 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.688059] ata3.00: status: { DRDY } [ 1637.688064] ata3.00: failed command: READ FPDMA QUEUED [ 1637.688075] ata3.00: cmd 60/80:90:80:b0:af/00:00:02:00:00/40 tag 18 ncq 65536 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.688081] ata3.00: status: { DRDY } [ 1637.688085] ata3.00: failed command: READ FPDMA QUEUED [ 1637.688096] ata3.00: cmd 60/00:98:00:b1:af/02:00:02:00:00/40 tag 19 ncq 262144 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.688102] ata3.00: status: { DRDY } [ 1637.688107] ata3.00: failed command: READ FPDMA QUEUED [ 1637.688118] ata3.00: cmd 60/00:a0:00:b3:af/01:00:02:00:00/40 tag 20 ncq 131072 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.688124] ata3.00: status: { DRDY } [ 1637.688129] ata3.00: failed command: READ FPDMA QUEUED [ 1637.688140] ata3.00: cmd 60/00:a8:00:b4:af/01:00:02:00:00/40 tag 21 ncq 131072 in res 40/00:ac:00:b4:af/00:00:02:00:00/40 Emask 0x50 (ATA bus error) [ 1637.688146] ata3.00: status: { DRDY } [ 1637.688154] ata3: hard resetting link [ 1638.179398] ata3: SATA link up 3.0 Gbps (SStatus 123 SControl 300) [ 1638.192977] ata3.00: configured for UDMA/133 [ 1638.193029] ata3: EH complete [ 1640.259492] md: export_rdev(sdb1) [ 1640.326109] md: bind<sdb1> [ 1640.346712] RAID1 conf printout: [ 1640.346724] --- wd:1 rd:2 [ 1640.346731] disk 0, wo:0, o:1, dev:sda1 [ 1640.346736] disk 1, wo:1, o:1, dev:sdb1 [ 1640.346893] md: delaying recovery of md1 until md0 has finished (they share one or more physical units) [ 1657.987964] ata3.00: exception Emask 0x50 SAct 0x40000 SErr 0x280900 action 0x6 frozen [ 1657.987975] ata3.00: irq_stat 0x08000000, interface fatal error [ 1657.987984] ata3: SError: { UnrecovData HostInt 10B8B BadCRC } [ 1657.987992] ata3.00: failed command: READ FPDMA QUEUED [ 1657.988006] ata3.00: cmd 60/00:90:00:30:2e/03:00:09:00:00/40 tag 18 ncq 393216 in res 40/00:94:00:30:2e/00:00:09:00:00/40 Emask 0x50 (ATA bus error) [ 1657.988013] ata3.00: status: { DRDY } [ 1657.988022] ata3: hard resetting link [ 1658.479548] ata3: SATA link up 3.0 Gbps (SStatus 123 SControl 300) [ 1658.493107] ata3.00: configured for UDMA/133 [ 1658.493147] ata3: EH complete [ 1670.547791] ata3: limiting SATA link speed to 1.5 Gbps [ 1670.547805] ata3.00: exception Emask 0x50 SAct 0x7f SErr 0x280900 action 0x6 frozen [ 1670.547812] ata3.00: irq_stat 0x08000000, interface fatal error [ 1670.547820] ata3: SError: { UnrecovData HostInt 10B8B BadCRC } [ 1670.547826] ata3.00: failed command: READ FPDMA QUEUED [ 1670.547839] ata3.00: cmd 60/80:00:00:1f:2e/01:00:0c:00:00/40 tag 0 ncq 196608 in res 40/00:2c:00:26:2e/00:00:0c:00:00/40 Emask 0x50 (ATA bus error) [ 1670.547846] ata3.00: status: { DRDY } [ 1670.547852] ata3.00: failed command: READ FPDMA QUEUED [ 1670.547863] ata3.00: cmd 60/80:08:80:20:2e/00:00:0c:00:00/40 tag 1 ncq 65536 in res 40/00:2c:00:26:2e/00:00:0c:00:00/40 Emask 0x50 (ATA bus error) [ 1670.547869] ata3.00: status: { DRDY } [ 1670.547875] ata3.00: failed command: READ FPDMA QUEUED [ 1670.547886] ata3.00: cmd 60/00:10:00:21:2e/02:00:0c:00:00/40 tag 2 ncq 262144 in res 40/00:2c:00:26:2e/00:00:0c:00:00/40 Emask 0x50 (ATA bus error) [ 1670.547892] ata3.00: status: { DRDY } [ 1670.547896] ata3.00: failed command: READ FPDMA QUEUED [ 1670.547907] ata3.00: cmd 60/00:18:00:23:2e/02:00:0c:00:00/40 tag 3 ncq 262144 in res 40/00:2c:00:26:2e/00:00:0c:00:00/40 Emask 0x50 (ATA bus error) [ 1670.547913] ata3.00: status: { DRDY } [ 1670.547918] ata3.00: failed command: READ FPDMA QUEUED [ 1670.547929] ata3.00: cmd 60/00:20:00:25:2e/01:00:0c:00:00/40 tag 4 ncq 131072 in res 40/00:2c:00:26:2e/00:00:0c:00:00/40 Emask 0x50 (ATA bus error) [ 1670.547935] ata3.00: status: { DRDY } [ 1670.547940] ata3.00: failed command: READ FPDMA QUEUED [ 1670.547951] ata3.00: cmd 60/00:28:00:26:2e/02:00:0c:00:00/40 tag 5 ncq 262144 in res 40/00:2c:00:26:2e/00:00:0c:00:00/40 Emask 0x50 (ATA bus error) [ 1670.547957] ata3.00: status: { DRDY } [ 1670.547961] ata3.00: failed command: READ FPDMA QUEUED [ 1670.547972] ata3.00: cmd 60/00:30:00:28:2e/02:00:0c:00:00/40 tag 6 ncq 262144 in res 40/00:2c:00:26:2e/00:00:0c:00:00/40 Emask 0x50 (ATA bus error) [ 1670.547978] ata3.00: status: { DRDY } [ 1670.547987] ata3: hard resetting link [ 1671.039264] ata3: SATA link up 1.5 Gbps (SStatus 113 SControl 310) [ 1671.053386] ata3.00: configured for UDMA/133 [ 1671.053444] ata3: EH complete [ 2422.512002] md: md0: recovery done. [ 2422.547344] md: recovery of RAID array md1 [ 2422.547355] md: minimum _guaranteed_ speed: 1000 KB/sec/disk. [ 2422.547360] md: using maximum available idle IO bandwidth (but not more than 200000 KB/sec) for recovery. [ 2422.547378] md: using 128k window, over a total of 4877312k. [ 2422.668465] RAID1 conf printout: [ 2422.668474] --- wd:2 rd:2 [ 2422.668480] disk 0, wo:0, o:1, dev:sda3 [ 2422.668486] disk 1, wo:0, o:1, dev:sdb3 [ 2469.990451] md: md1: recovery done. [ 2470.049986] RAID1 conf printout: [ 2470.049997] --- wd:2 rd:2 [ 2470.050003] disk 0, wo:0, o:1, dev:sda1 [ 2470.050009] disk 1, wo:0, o:1, dev:sdb1 [ 3304.445149] PM: Hibernation mode set to 'platform' [ 3304.782375] PM: Syncing filesystems ... done. [ 3307.028591] Freezing user space processes ... (elapsed 0.001 seconds) done. (...)
Now provide the response and nothing else.
| First, keep in mind that SMART saying that your drive is healthy doesn't necessarily mean that the drive is healthy. SMART reports are an aid , not an absolute truth. If all you are interested in is what to do, rather than why, then feel free to scroll down to the last few paragraphs; however, the interim text will tell you why I think what I propose is the correct course of action, and how to derive that from what you posted. With that said, let's look at what one of those errors are telling us. [ 1670.547805] ata3.00: exception Emask 0x50 SAct 0x7f SErr 0x280900 action 0x6 frozen[ 1670.547812] ata3.00: irq_stat 0x08000000, interface fatal error[ 1670.547820] ata3: SError: { UnrecovData HostInt 10B8B BadCRC }[ 1670.547826] ata3.00: failed command: READ FPDMA QUEUED[ 1670.547839] ata3.00: cmd 60/80:00:00:1f:2e/01:00:0c:00:00/40 tag 0 ncq 196608 in res 40/00:2c:00:26:2e/00:00:0c:00:00/40 Emask 0x50 (ATA bus error)[ 1670.547846] ata3.00: status: { DRDY }[ 1670.547852] ata3.00: failed command: READ FPDMA QUEUED (I hope I got the parts that should go together, but you were getting a bundle of those so it should be okay either way.) The Linux ata Wiki has a page explaining how to read these errors . Particularly, A status value of DRDY means "Device ready. Normally 1, when all is OK." Seeing a status value of DRDY is perfectly normal and expected. SError has multiple component values, of which you are seeing (in this particular snippet): UnrecovData "Data integrity error occurred, interface did not recover" HostInt "Host bus adapter internal error" 10B8B "10b to 8b decoding error occurred" BadCRC "Link layer CRC error occurred" 10b8b coding, which encodes 8 bits as 10 bits to aid with both signal synchronization and error detection, is used on the physical cabling, not necessarily on the drive itself. The drive most likely uses other forms of FEC or ECC coding, and an error there would normally show up as some form of I/O error, likely with an error value of UNC ("uncorrectable error - often due to bad sectors on the disk"), likely with "media error" ("software detected a media error") in parenthesis at the end of the res line. This latter is not what you are seeing, so while we can't completely rule it out, it seems unlikely. The "link layer" is the physical cables and circuit board traces between the drive's own controller, and the disk drive interface chip (likely part of the southbridge on your computer's motherboard, but could be located at an offboard HBA). A host bus adapter, also known as a HBA, is the circuitry that connects to storage equipment. Also colloquially known as a "disk controller", a term which is a bit of a misnomer with modern systems. The most visible part of the HBA is generally the connection ports, most often these days either SATA or some SAS form factor. The UnrecovData and HostInt flags basically tell us that "something just went horribly wrong, and there was no way to recover or no attempt at recovery was made". The opposite would likely be RecovData , which indicates that a "data integrity error occurred, but the interface recovered". (As an aside, I probably would have used HBAInt instead of HostInt , as the "host" refers to the HBA, not the whole system.) The combination of 10B8B and BadCRC , which both point to the physical link layer, makes me suspect a cabling issue. This suspicion is also supported by the fact that the SMART self-tests, which are completely internal to the drive except for status reporting, are finding no errors that the manufacturer feels are serious enough to warrant reporting in the results. If the drive was having problems storing or reading data, the long SMART self-test in particular should have reported that. TL;DR: The first thing I would do is thus simply to unplug and re-plug the SATA cable at both ends; it may be slightly loose, causing it to lose electrical contact intermittently. See if that resolves the problem. It might even be worth doing this to all SATA cabling in your computer, not just the affected disk. If you are using an off-board HBA, I would also remove and re-seat that card, mainly because it's an easy thing to try while you are already messing around with the cabling. Failing that, try throwing away and replacing the SATA cable, preferably with a high-quality cable. A high-quality cable will be slightly more expensive, but I find that it's usually well worth the small extra expense if it helps avoid headaches like this. Nobody likes seeing their storage spewing errors! | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/304661', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/22838/']} | jdg_81667 |
stackexchange | llm_judgeable_groundtruth_similarity | 8190926 |
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 method annotated with @Transactional. I retrieve an object from my Oracle DB, change a field, and then return from the method. I forgot to save the object, but discovered that the database gets updated anyway. applicationContext <tx:annotation-driven /><bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /></bean> my method @Transactionalpublic void myMethod(long id) { MyObject myObj = dao.getMstAttributeById(id); myObj.setName("new name"); //dao.update(myObj);} my question is why does MyObject get persisted to the database?
Now provide the response and nothing else.
| Because hibernate will automatically detect changes made to persistent entities and update the database accordingly. This behaviour is documented in chapter 11 of the hibernate reference manual. The relevant part reads: Hibernate defines and supports the following object states: Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition). Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient. Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8190926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1017327/']} | jdg_81668 |
stackexchange | llm_judgeable_groundtruth_similarity | 319188 |
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 $\displaystyle \lim_{x\to 1}\frac {\sqrt{x+3}-2}{\sqrt{x+8}-3}$. I tried to rationalize it, but doesn't help either. Please give me some hints. Thank you.
Now provide the response and nothing else.
| Hint:$$\frac {\sqrt{x+3}-2}{\sqrt{x+8}-3}=\left(\frac {\sqrt{x+3}-2}{\sqrt{x+8}-3}\frac {\sqrt{x+3}+2}{\sqrt{x+8}+3}\right)\frac {\sqrt{x+8}+3}{\sqrt{x+3}+2}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/319188', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25841/']} | jdg_81669 |
stackexchange | llm_judgeable_groundtruth_similarity | 297721 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What are some common ways to determine if a grammar is ambiguous or not? What are some common attributes that ambiguous grammars have? For example, consider the following Grammar G: $S \rightarrow S(E)|E$ $E \rightarrow (S)E|0|1|\epsilon$ My guess is that this grammar is not ambiguous, because of the parentheses I could not make an equivalent strings with distinct parse trees. I could have easily made a mistake since I am new to this. What are some common enumeration techniques for attempting to construct the same string with different parse trees? How can I know that I am right or wrong? What are common attributes of ambiguous grammars? How could I prove this to myself intuitively? How could I prove this with formal mathematics?
Now provide the response and nothing else.
| To determine if a context free grammar is ambiguous is undecidable (there is no algorithm which will correctly say "yes" or "no" in a finite time for all grammars). This doesn't mean there aren't classes of grammars where an answer is possible. To prove a grammar ambiguous, you do as you outline: Find a string with two parses. To prove it unambiguous is harder: You have to prove the above isn't possible. It is known that the $LL(k)$ and $LR(k)$ grammars are unambiguous, and for $k = 1$ the conditions are relatively easy to check. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/297721', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38879/']} | jdg_81670 |
stackexchange | llm_judgeable_groundtruth_similarity | 45430816 |
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 a newbie in Spark SQL world. I am currently migrating my application's Ingestion code which includes ingesting data in stage,Raw and Application layer in HDFS and doing CDC(change data capture), this is currently written in Hive queries and is executed via Oozie. This needs to migrate into a Spark application(current version 1.6). The other section of code will migrate later on. In spark-SQL, I can create dataframes directly from tables in Hive and simply execute queries as it is (like sqlContext.sql("my hive hql") ). The other way would be to use dataframe APIs and rewrite the hql in that way. What is the difference in these two approaches? Is there any performance gain with using Dataframe APIs? Some people suggested, there is an extra layer of SQL that spark core engine has to go through when using "SQL" queries directly which may impact performance to some extent but I didn't find any material substantiating that statement. I know the code would be much more compact with Datafrmae APIs but when I have my hql queries all handy would it really worth to write complete code into Dataframe API? Thank You.
Now provide the response and nothing else.
| Question : What is the difference in these two approaches? Is there any performance gain with using Dataframe APIs? Answer : There is comparative study done by horton works. source ... Gist is based on situation/scenario each one is right. there is no hard and fast rule to decide this. pls go through below.. RDDs, DataFrames, and SparkSQL (infact 3 approaches not just 2): At its core, Spark operates on the concept of Resilient Distributed Datasets, or RDD’s: Resilient - if data in memory is lost, it can be recreated Distributed - immutable distributed collection of objects in memory partitioned across many data nodes in a cluster Dataset - initial data can from from files, be created programmatically, from data in memory, or from another RDD DataFrames API is a data abstraction framework that organizes your data into named columns: Create a schema for the data Conceptually equivalent to a table in a relational database Can be constructed from many sources including structured data files, tables in Hive, external databases, or existing RDDs Provides a relational view of the data for easy SQL like data manipulations and aggregations Under the hood, it is an RDD of Row’s SparkSQL is a Spark module for structured data processing. You can interact with SparkSQL through: SQL DataFrames API Datasets API Test results: RDD’s outperformed DataFrames and SparkSQL for certain types of data processing DataFrames and SparkSQL performed almost about the same, although with analysis involving aggregation and sorting SparkSQL had a slight advantage Syntactically speaking, DataFrames and SparkSQL are much more intuitive than using RDD’s Took the best out of 3 for each test Times were consistent and not much variation between tests Jobs were run individually with no other jobs running Random lookup against 1 order ID from 9 Million unique order ID'sGROUP all the different products with their total COUNTS and SORT DESCENDING by product name | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45430816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5245918/']} | jdg_81671 |
stackexchange | llm_judgeable_groundtruth_similarity | 15653676 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why can I not see the _timestamp field while being able to filter a query by it? The following query return the correct documents, but not the timestamp itself. How can I return the timestamp? { "fields": [ "_timestamp", "_source" ], "query": { "filtered": { "query": { "match_all": {} }, "filter": { "range": { "_timestamp": { "from": "2013-01-01" } } } } }} The mapping is: { "my_doctype": { "_timestamp": { "enabled": "true" }, "properties": { "cards": { "type": "integer" } } }} sample output: { "took" : 1, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "failed" : 0 }, "hits" : { "total" : 2, "max_score" : 1.0, "hits" : [ { "_index" : "test1", "_type" : "doctype1", "_id" : "HjfryYQEQL6RkEX3VOiBHQ", "_score" : 1.0, "_source" : {"cards": "5"} }, { "_index" : "test1", "_type" : "doctype1", "_id" : "sDyHcT1BTMatjmUS0NSoEg", "_score" : 1.0, "_source" : {"cards": "2"} }] }
Now provide the response and nothing else.
| When timestamp field is enabled, it's indexed but not stored by default. So, while you can search and filter by the timestamp field, you cannot easily retrieve it with your records. In order to be able to retrieve the timestamp field you need to recreate your index with the following mapping: { "my_doctype": { "_timestamp": { "enabled": "true", "store": "yes" }, "properties": { ... } }} This way you will be able to retrieve timestamp as the number of milliseconds since the epoch. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15653676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1724926/']} | jdg_81672 |
stackexchange | llm_judgeable_groundtruth_similarity | 39382032 |
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 a beginner with Vue.js and I'm trying to create an app that caters my daily tasks and I ran into Vue Components. So below is what I've tried but unfortunately, it gives me this error: vue.js:1023 [Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option. Any ideas, help, please? new Vue({ el : '#app', data : { tasks : [ { name : "task 1", completed : false}, { name : "task 2", completed : false}, { name : "task 3", completed : true} ] }, methods : { }, computed : { }, ready : function(){ }});Vue.component('my-task',{ template : '#task-template', data : function(){ return this.tasks }, props : ['task']}); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.js"></script><div id="app"> <div v-for="task in tasks"> <my-task :task="task"></my-task> </div> </div><template id="task-template"> <h1>My tasks</h1> <div class="">{{ task.name }}</div></template>
Now provide the response and nothing else.
| You forgot about the components section in your Vue initialization . So Vue actually doesn't know about your component. Change it to: var myTask = Vue.component('my-task', { template: '#task-template', data: function() { return this.tasks; //Notice: in components data should return an object. For example "return { someProp: 1 }" }, props: ['task']});new Vue({ el: '#app', data: { tasks: [{ name: "task 1", completed: false }, { name: "task 2", completed: false }, { name: "task 3", completed: true } ] }, components: { myTask: myTask }, methods: { }, computed: { }, ready: function() { }}); And here is jsBin, where all seems to works correctly: http://jsbin.com/lahawepube/edit?html,js,output UPDATE Sometimes you want your components to be globally visible to other components. In this case you need to register your components in this way, before your Vue initialization or export (in case if you want to register component from the other component) Vue.component('exampleComponent', require('./components/ExampleComponent.vue')); //component name should be in camel-case After you can add your component inside your vue el : <example-component></example-component> | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39382032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1292042/']} | jdg_81673 |
stackexchange | llm_judgeable_groundtruth_similarity | 30135387 |
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 print only one component on click of a button. I know this solution: window.frames["print_frame"].window.focus();window.frames["print_frame"].window.print();$('.print_frame').remove(); But React doesn't want to work with a frame. Any solutions? Thank you.
Now provide the response and nothing else.
| There is kind of two solutions on the client. One is with frames like you posted. You can use an iframe though: var content = document.getElementById("divcontents");var pri = document.getElementById("ifmcontentstoprint").contentWindow;pri.document.open();pri.document.write(content.innerHTML);pri.document.close();pri.focus();pri.print(); This expects this html to exist <iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe> The other solution is to use the media selector and on the media="print" styles hide everything you don't want to print. <style type="text/css" media="print"> .no-print { display: none; }</style> Last way requires some work on the server. You can send all the HTML+CSS to the server and use one of many components to generate a printable document like PDF. I've tried setups doing this with PhantomJs. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30135387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4535552/']} | jdg_81674 |
stackexchange | llm_judgeable_groundtruth_similarity | 7880 |
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:
How close can I place two 0603 resistors on a PCB?
Now provide the response and nothing else.
| I have a silk layer bounding box of 2.6mm x 1.4mm around the pads of 0603s, and I often place resistors with touching bounding boxes. Lengthwise placed next to each other this leaves 0.2mm between pads. For reflow soldering this has never caused problems. For wave soldering you will need more space, esp. in the wave direction. For hand soldering it depends on the soldering skills of the person who assembles the board. 0.2mm may be possible if you don't use too much solder. While 0.2mm may look like very tight, remember that this is reflow soldering. When the solder paste melts it's capillarily drawn to the contact surfaces of the resistor, so it won't flow to adjacent pads. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/7880', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1688/']} | jdg_81675 |
stackexchange | llm_judgeable_groundtruth_similarity | 20069629 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
/ (directory/?param=value) cannot change this url directory/?param=value to directory/value It's not work: RewriteCond %{REQUEST_URI} ^/directory/.*RewriteRule ^/directory/\?param=(.*) /directory/$1 [L] My problem is how to replace ?param= ???
Now provide the response and nothing else.
| Naruto: I was interested in printing Linux's page tables as well and I stumbled upon the nifty utility in the kernel source arch/x86/mm/dump_pagetables.c If you build your kernel with CONFIG_X86_PTDUMP set, you can do cat /sys/kernel/debug/kernel_page_tables And it will walk the kernel's page table hierarchy and print it out. There are 2 issues with the output however: It only lists the virtual addresses and not their associated physical address. This disappointed me because I was mostly interested in the virtual mappings into non-RAM system adresses (like PCI-space, etc) -- in other works I wanted to visually match up what I was seeing in /proc/iomem with /sys/kernel/debug/kernel_page_tables. It doesn't provide a way to print out the per-process page tables. As I understand, each linux process and init_level_4_pgt (the kernel's original (post-bootup) page table) share a large portion of their virtual address spaces: from PAGE_OFFSET on wards to be exact. I guess this is done so kernel code running in the context of a user process (via a system call) can access kernel memory. At any rate I, thought it would be pretty neat to see all this in action. Here is the link to my patched 3.13.11 kernel with these 2 issues fixed (the branch with the fix is page_table_print). To use, simply do echo <pid_of_interest> > /proc/sys/debug/pgt_dump_process_id where pid_of_interest if the pid of the process whose page table's you wish to monitor. NOTE: by doing echo -1 > /proc/sys/debug/pgt_dump_process_id this will dump the kernel's page tables. Here is an example output for the kernel's page tables: cat /sys/kernel/debug/kernel_page_tables | moreCR3= 0x196b70000, va_CR3 = 0xffff880196b70000Page tables for kernelPGT localtion in memory: phs = 0x1c0e000, virt = 0xffffffff81c0e000---[ User Space ]---0x0000000000000000-0xffff800000000000, phy: 0x0000000000000000-0x0000800001c0e000 16777088T pgd---[ Kernel Space ]---0xffff800000000000-0xffff880000000000, phy: 0x0000800001c0e000-0x0000000001fe1000 8T pgd---[ Low Kernel Mapping ]---0xffff880000000000-0xffff880000096000, phy: 0x0000000001fe1000-0x0000000002077000 600K RW GLB NX pte0xffff880000096000-0xffff880000097000, phy: 0x0000000002077000-0x0000000002078000 4K ro GLB NX pte0xffff880000097000-0xffff880000098000, phy: 0x0000000002078000-0x0000000002079000 4K ro GLB x pte0xffff880000098000-0xffff880000200000, phy: 0x0000000002079000-0x00000000021e0000 1440K RW GLB NX pte0xffff880000200000-0xffff880001000000, phy: 0x00000000021e0000-0x0000000002fe0000 14M RW PSE GLB NX pmd0xffff880001000000-0xffff880001600000, phy: 0x0000000002fe0000-0x00000001b14a1000 6M ro PSE GLB NX pmd0xffff880001600000-0xffff880001734000, phy: 0x00000001b14a1000-0x00000001b15d5000 1232K ro GLB NX pte0xffff880001734000-0xffff880001800000, phy: 0x00000001b15d5000-0x00000000037e0000 816K RW GLB NX pte0xffff880001800000-0xffff880001a00000, phy: 0x00000000037e0000-0x00000001b14a2000 2M ro PSE GLB NX pmd And here is the output after doing echo 1 > /proc/sys/debug/pgt_dump_process_idcat /sys/kernel/debug/kernel_page_tables | moreCR3= 0x17312f000, va_CR3 = 0xffff88017312f000Page tables for process id = 1PGT localtion in memory: phs = 0x3623f000, virt = 0xffff88003623f000---[ User Space ]---0x0000000000000000-0x00007f8000000000, phy: 0x0000000000000000-0x0000000036277000 130560G pgd0x00007f8000000000-0x00007ff200000000, phy: 0x0000000036277000-0x000000003627a000 456G pud0x00007ff200000000-0x00007ff207800000, phy: 0x000000003627a000-0x0000000036097000 120M pmd0x00007ff207800000-0x00007ff2079b5000, phy: 0x0000000036097000-0x000000003624c000 1748K pte0x00007ff2079b5000-0x00007ff2079b8000, phy: 0x000000003624c000-0x000000003624f000 12K USR ro x pte0x00007ff2079b8000-0x00007ff207bbf000, phy: 0x000000003624f000-0x00000000363c3000 2076K pte0x00007ff207bbf000-0x00007ff207bc1000, phy: 0x00000000363c3000-0x00000000363c5000 8K USR ro NX pte0x00007ff207bc1000-0x00007ff207bc4000, phy: 0x00000000363c5000-0x00000000363c8000 12K USR ro x pte0x00007ff207bc4000-0x00007ff207bc6000, phy: 0x00000000363c8000-0x00000000363ca000 8K pte0x00007ff207bc6000-0x00007ff207bc7000, phy: 0x00000000363ca000-0x00000000363cb000 4K USR ro x pte0x00007ff207bc7000-0x00007ff207dcb000, phy: 0x00000000363cb000-0x00000000363d0000 2064K pte0x00007ff207dcb000-0x00007ff207dcd000, phy: 0x00000000363d0000-0x00000000363d2000 8K USR ro NX pte0x00007ff207dcd000-0x00007ff207dd2000, phy: 0x00000000363d2000-0x00000000363d7000 20K USR ro x pte0x00007ff207dd2000-0x00007ff207fe3000, phy: 0x00000000363d7000-0x00000000363fe000 2116K pte0x00007ff207fe3000-0x00007ff207fe5000, phy: 0x00000000363fe000-0x0000000036400000 8K USR ro NX pte0x00007ff207fe5000-0x00007ff207fe7000, phy: 0x0000000036400000-0x0000000036402000 8K pte0x00007ff207fe7000-0x00007ff207fec000, phy: 0x0000000036402000-0x0000000036407000 20K USR ro x pte0x00007ff207fec000-0x00007ff207fed000, phy: 0x0000000036407000-0x0000000036408000 4K pte0x00007ff207fed000-0x00007ff207fef000, phy: 0x0000000036408000-0x000000003640a000 8K USR ro x pte0x00007ff207fef000-0x00007ff2081ef000, phy: 0x000000003640a000-0x0000000036214000 2M pte0x00007ff2081ef000-0x00007ff2081f1000, phy: 0x0000000036214000-0x0000000036216000 8K USR ro NX pte I think this is pretty neat, I hope others think the same. :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20069629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1166282/']} | jdg_81676 |
stackexchange | llm_judgeable_groundtruth_similarity | 3318476 |
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 was wondering : if $f,g : X \rightarrow Y$ are continuous maps between CW-complexes, if they induce the same morphisms on homotopy groups, does that imply that $f$ and $g$ are homotopic? It would seem plausible, similar to a Whitehead theorem.
Now provide the response and nothing else.
| This is not true. Take $S^n\times S^n$ and consider the quotient map $$q_n:S^n\times S^n\rightarrow S^n\wedge S^n\cong S^{2n}$$ where $S^n\wedge S^n=S^n\times S^n/S^n\vee S^n$ is the smash product. Then $q_n$ induces the trivial morphism on homotopy groups in all dimensions, since if $\alpha:S^r\rightarrow S^n\times S^n$ is any map, then by naturality $q_{n*}\alpha$ factors as $q\circ\alpha:S^r\xrightarrow\Delta S^r\times S^r\xrightarrow{q_{r*}}S^r\wedge S^r\cong S^{2r}\rightarrow S^{2n} $ which is trivial since $\pi_rS^{2r}=0$ . On the other hand $q_n\not\simeq\ast$ , since in homology the induced map $$q_{n*}:H_{2n}(S^n\times S^n)\xrightarrow{}H_{2n}(S^n\wedge S^n)$$ is an isomorphism. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3318476', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/694728/']} | jdg_81677 |
stackexchange | llm_judgeable_groundtruth_similarity | 1858 |
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Lifting Body The idea of a lifting body design is to shape a vehicle's body in such a way as to produce lift without wings. Research has shown that this can be an efficient method of reducing drag while still providing lift. This has typically done for aircraft or spacecraft: Could a similar approach help to make trains more efficient? Passenger trains already look streamlined and aerodynamic: Freight trains do not: Air resistance is not the only form of resistance that trains must overcome. They must also overcome the resistance of their wheels on the track. This is where I would think that the energy savings from a lifting body design would come from. Any additional lift created by the lifting body design would reduce the friction between the wheels and rail, thus saving energy. Train wheels have flanges on them, so they don't need traction to steer. The cars also don't need traction on the rails since the driving wheels are only on the engines. Could a lifting body create enough lift at typical train speeds to make a noticeable difference?
Now provide the response and nothing else.
| I won't say it's not possible to make a noticeable difference. But I would say that it's pretty darn unlikely. The lift and drag forces on any body generally depend on the velocity of the body ($v$), the density of the fluid ($\rho$), the area of the object ($A$) and a dimensionless coefficient ($C_L$ or $C_D$). The applicable area can be a bit fuzzy in terms of whether you're talking about frontal area or planform area, but for a train this is going to basically be the area in the plane normal to the direction of travel (given that most of the train cars are simply in the wake of the locomotive). The coefficients can vary a bit with velocity due to turbulence, but will generally be between 0 and 2. The functional form is: $$ F_L = 1/2\rho A C_L v^2$$ Crudely estimating a freight train as being $4\, m$ tall and wide, moving at $16 \, m/s$ ($57 \, kph$). This gives us that lift will be around $2500 N$ for the entire train (not enough to lift an ordinary automobile). This calculation is not meant to be extremely precise, but even it's off by a factor of ten, lift would be minimal compared to the overall weight of the vehicle. Given that, you might consider the merits of adding additional aerodynamic elements. Here you get into a tradeoff between generating lift (to reduce downward force on the wheels) and generating drag. While lift-to-drag ratios can get high (~50 in good cases) the rolling resistance of train wheels is actually very low ($C_{rr} \sim 0.00035$). So although the lift will reduce the losses due to friction, it will increase the losses due to drag more. So, reducing drag is good but providing lift is probably not worth it. In fact, reducing drag at the cost of adding some weight could be beneficial because wheels are so very good at bearing that load efficiently. N.B. I consulted Wikipedia and engineering toolbox for $C_{rr}$ data. I could not verify sources for railroad wheels, but was able to confirm that values for road tires were correct via "Fundamentals of Vehicle Dynamics" by Gillespie. Any ideas on verification would be welcome. | {} | {'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/1858', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/33/']} | jdg_81678 |
stackexchange | llm_judgeable_groundtruth_similarity | 5438 |
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:
We bring in hard drives from un-trusted sources and would like to ensure that they will not contain any harmful content. What kind of risk is there for Solaris? As in, if Solaris is running, and I attach a drive, I would run format and then check there is only one fdisk partition and it covers the whole drive, then I would run verify in format in order to erase all the data (and test the drive). Is this foolproof? (short of an actual computer inside the hard drive) I know on Windows there are or have been all kinds of vulnerabilities or auto-run functions. I want to know if I can use Solaris in order to eliminate this problem entirely.
Now provide the response and nothing else.
| An adversary who is aware of your procedure could manipulate the hardware to exploit the tools you are using. The filesystem driver itself and any automatically executed programs after mounting the drive can be attractive candidates for this. However, this would be a rather obscure attack. Since you only look at the partition table and the format tool likely also considers inconsistent drive data, your risk is probably rather low. As long as you don't mount partitions from unknown sources, there should be no problem. Another even more obscure attack would be to manipulate the hard drive such that it uses DMA to compromise your system. This is even less likely and probably what you mean by "computer inside the hard drive". | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/5438', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/764/']} | jdg_81679 |
stackexchange | llm_judgeable_groundtruth_similarity | 40089316 |
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 application, I have two different bootstrap module ( @NgModule ) running independently in one application. There are not one angular app bit separate bootstrap module and now I want they should communicate to each other and share data. I know through @Injectable service as the provider in the module, I can share data in all component under @NgModule but how I will share data between two different module ( not component inside module ). Is there a way one service object can be accessed in another module? Is there a way I can access the object of Service available in browser memory and use it in my other angular module?
Now provide the response and nothing else.
| As per the final version of Angular 2, services provided by a module are available to every other module that imports it.The Official Style Guide advice that application-wide services (singletons) that are to be reused anywhere in the application should be provided by some Core Module , that is to be imported in the main App Module so it would be injectable everywhere. If you do not use a structure that involves a Core Module with shared singletons, and you are independently developing two NgModules, and you want a service in one of them to be used in the other, then the only solution is to import the provider into the other : Here's the provider module: /// some.module.tsimport { NgModule } from '@angular/core';import { SomeComponent } from './some.component';@NgModule({ imports: [], exports: [], declarations: [SomeComponent], providers: [ MyService ], // <======================= PROVIDE THE SERVICE})export class SomeModule { } Here's the other module, that wants to use MyService /// some-other.module.tsimport { NgModule } from '@angular/core';import { SomeModule } from 'path/to/some.module'; // <=== IMPORT THE JSMODULEimport { SomeOtherComponent } from './some.other.component';@NgModule({ imports: [ SomeModule ], // <======================== IMPORT THE NG MODULE exports: [], declarations: [SomeOtherComponent], providers: [],})export class SomeOtherModule { } This way, the service should be injectable in any component SomeOtherModule declares, and in SomeModule itself - just ask for it in the constructor: /// some-other.module.tsimport { MyService } from 'path/to/some.module/my-service';/* ... rest of the module*/export class SomeOtherModule { constructor( private _myService: MyService) { <====== INJECT THE SERVICE this._myService.dosmth(); }} If this doesn't answer your question, I invite you to re-formulate it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40089316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/537647/']} | jdg_81680 |
stackexchange | llm_judgeable_groundtruth_similarity | 610275 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Energy came from nothing as many scientists know. So, is it possible to create energy from nothing and break the laws of physics.
Now provide the response and nothing else.
| No, it isn't. When studying the transfer of energy in nature, we have found that very strict book-keeping rules apply always and forever. These rules are called conservation laws and in the universe we happen to inhabit, there is no way to break them, and when it appears that they are broken what it really means is that something is wrong with the way we are doing the book keeping. The conservation of energy in all processes in our universe is rooted mathematically in the fact that the laws of nature do not change with time. If we could turn off one physical law or another at a chosen point in time, magic would become possible; the absence of magic is a good indication that energy is conserved- and that it cannot be created out of nothing. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/610275', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/285597/']} | jdg_81681 |
stackexchange | llm_judgeable_groundtruth_similarity | 173621 |
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 question is inspired from the long discussion in comments here: How does linear regression use the normal distribution? In the usual linear regression model, for simplicity here written with only one predictor:$$ Y_i = \beta_0 + \beta_1 x_i + \epsilon_i$$where the $x_i$ are known constants and $\epsilon_i$ are zero-mean independent error terms. If we in addition assume normal distributions for the errors, then the usual least squares estimators and the maximum likelihood estimators of $\beta_0, \beta_1$ are identical. So my easy question: do there exist any other distribution for the error terms such that the mle are identical with the ordinary least squaeres estimator? The one implication is easy to show, the other one not so.
Now provide the response and nothing else.
| In maximum likelihood estimation, we calculate $$\hat \beta_{ML}: \sum \frac {\partial \ln f(\epsilon_i)}{\partial \beta} = \mathbf 0 \implies \sum \frac {f'(\epsilon_i)}{f(\epsilon_i)}\mathbf x_i = \mathbf 0$$ the last relation taking into account the linearity structure of the regression equation. In comparison , the OLS estimator satisfies $$\sum \epsilon_i\mathbf x_i = \mathbf 0$$ In order to obtain identical algebraic expressions for the slope coefficients we need to have a density for the error term such that $$\frac {f'(\epsilon_i)}{f(\epsilon_i)} = \pm \;c\epsilon_i \implies f'(\epsilon_i)= \pm \;c\epsilon_if(\epsilon_i)$$ These are differential equations of the form $y' = \pm\; xy$ that have solutions $$\int \frac 1 {y}dy = \pm \int x dx\implies \ln y = \pm\;\frac 12 x^2$$ $$ \implies y = f(\epsilon) = \exp\left \{\pm\;\frac 12 c\epsilon^2\right\}$$ Any function that has this kernel and integrates to unity over an appropriate domain, will make the MLE and OLS for the slope coefficients identical. Namely we are looking for $$g(x)= A\exp\left \{\pm\;\frac 12 cx^2\right\} : \int_a^b g(x)dx =1$$ Is there such a $g$ that is not the normal density (or the half-normal or the derivative of the error function)? Certainly. But one more thing one has to consider is the following: if one uses the plus sign in the exponent, and a symmetric support around zero for example, one will get a density that has a unique minimum in the middle, and two local maxima at the boundaries of the support. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/173621', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/11887/']} | jdg_81682 |
stackexchange | llm_judgeable_groundtruth_similarity | 203839 |
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've spent a bunch of time perusing Stack Exchange to try to find an answer and found nothing; hopefully this isn't a duplicate. I have a time-dependent vector field $\Phi_t(x,y,z)=(x\lambda^t,y\lambda^{-t},z+t)$ , $\lambda>1$ arbitrary; for my example, I'm restricting to the region $[0,1]\times[0,1]\times\mathbb{R}$ . What I would like to do is: fix some $\lambda>1$ ; generate some number of random initial points; compute / store the orbits of these points over some length of time; plot these orbits in 3D with animation . I've currently managed to do all of this except animate the flow lines. Here's my current code: seeds = RandomReal[{-1, 1}, {250, 3}]; (* 250 random initial points *)lam = 1.5; (* \[Lambda]>1 fixed *)func[{x_, y_, z_}, t_] := {x lam^t, y lam^(-t), z + t}; (* the vector field itself *)orbit[k_] := Table[func[seeds[[k]], n], {n, 0, 9.75, 0.25}]; (* function to compute the orbit for a single initial point *)orbits = orbit[#] & /@ Range[1, Length[seeds], 1]; (* computes orbits for all initial points *)Graphics3D[{ {Red, Arrowheads[{-.01, .01}], Arrow[BezierCurve[orbits[[#]]]] & /@ Range[1, Length[seeds], 1]}}, PlotRange -> {{-1, 1}, {-1, 1}, {-1, 1}}, Boxed -> False, Axes -> True, AxesEdge -> {{-1, -1}, {-1, -1}, {-1, -1}}, ViewPoint -> {2.6056479300835718`, 2.1387445365836095`, 0.29388887642263006`}, ViewVertical -> {0.3985587476649791`, 0.332086389794556`, 0.8549090912915488`}, ImageSize -> 400] Here's the output: This is okay, but what I'd really like is something that can either animate one entire flow line a little at a time, then the next flow line a little at a time, etc. (in the same plot); or animate all flow lines simultaneously, a little at a time. Can anyone help me with this? Note: By defining an auxiliary function buildorbits[k_,n_]:=orbits[[k, 1 ;; n]]; , I can animate single orbits using a very "hackish-feeling" implementation of ListAnimate . For instance: ; is this really my best option, though?
Now provide the response and nothing else.
| You can use ParametricPlot3D to get smoother orbits: SeedRandom[1]n = 50;seeds = RandomReal[{-1, 1}, {n, 3}];tbar = 10;Animate[ParametricPlot3D[Evaluate[func[seeds[[#]], t] & /@ Range[Length@seeds]], {t, 0, tmax}, BoxRatios -> 1, PlotStyle -> Arrowheads[Medium], ImageSize -> 400, PlotRange -> {{-60, 60}, {-1, 1}, {-10, 10}}] /. Line -> Arrow, {tmax, .01, tbar}] Update: "Is there a way to use this this implementation to animate as all of orbit 1, followed by all of orbit 2, followed by....?" colors = Table[Hue@RandomReal[], {n}];Animate[ParametricPlot3D[Evaluate[ConditionalExpression[func[seeds[[#]], t - (#-1) tbar], (# - 1) tbar <= t <= # tbar] & /@ Range[n]], {t, 0, tmax}, BaseStyle -> Arrowheads[Medium], BoxRatios -> 1, ImageSize -> 400, PlotStyle -> colors, PerformanceGoal -> "Quality", PlotRange -> {{-50, 60}, {-1, 1}, {-5, 15}}] /. Line -> Arrow, {tmax, .01, n tbar}, AnimationRate -> 10] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/203839', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/20079/']} | jdg_81683 |
stackexchange | llm_judgeable_groundtruth_similarity | 19815907 |
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 a newbie to Java world, coming from .Net. In the .net world we don't have so many options. I have some basic questions to help me get some more context. Is the Spring Framework built on top of Java SE or Java EE? Or are Java EE and Java SE Oracles products? Meaning Java SE is Oracle's implementation of Java? What is Spring Framework built on? In other words, if I wanted to build a Spring like Framework would I start with Java SE as a base? Thanks
Now provide the response and nothing else.
| Java SE is plain old Java, hence SE (Standard Edition). Java EE (Enterprise edition) is a set of APIs that a server has to implement to be licensed as Java EE compatible. Oracle / Sun has created the SE and a reference implementation of EE ( Glassfish ), but EE is usually implemented by Application servers (JBoss, WebSphere etc.). Spring is built on Java SE, but can run (and use some of the features of) Java EE. It can also be an alternative for when the full EE stack is not available, allowing non-EE platforms to integrate EE technologies like JPA or JMS. Spring vs Java EE is an ongoing holy war, although it doesn't need to be. I personally prefer Spring because it doesn't require a special server infrastructure and runs in any environment (Java App, Applet, Servlet, Android, you name it), but the other side has very convincing arguments also (at least for EE 6+). And then there are those who advocate using Spring together with EE, but I guess that's no longer very relevant for EE 6. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19815907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2686375/']} | jdg_81684 |
stackexchange | llm_judgeable_groundtruth_similarity | 5037762 |
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 needed to read a byte from the file, xor it with 0x71 and write it back to another file. However, when i use the following, it just reads the byte as a string, so xoring creates problems. f = open('a.out', 'r')f.read(1) So I ended up doing the same in C. #include <stdio.h>int main() { char buffer[1] = {0}; FILE *fp = fopen("blah", "rb"); FILE *gp = fopen("a.out", "wb"); if(fp==NULL) printf("ERROR OPENING FILE\n"); int rc; while((rc = fgetc(fp))!=EOF) { printf("%x", rc ^ 0x71); fputc(rc ^ 0x71, gp); } return 0;} Could someone tell me how I could convert the string I get on using f.read() over to a hex value so that I could xor it with 0x71 and subsequently write it over to a file?
Now provide the response and nothing else.
| If you want to treat something as an array of bytes, then usually you want a bytearray as it behaves as a mutable array of bytes: b = bytearray(open('a.out', 'rb').read())for i in range(len(b)): b[i] ^= 0x71open('b.out', 'wb').write(b) Indexing a byte array returns an integer between 0x00 and 0xff, and modifying in place avoid the need to create a list and join everything up again. Note also that the file was opened as binary ('rb') - in your example you use 'r' which isn't a good idea. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5037762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_81685 |
stackexchange | llm_judgeable_groundtruth_similarity | 22206274 |
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 send a HTTP request with NSURLSession . It works fine, but when the server doesn't respond I can't find where the HTTP error code is stored. The third parameter of completionHandler is just a very general NSError . I read the reference of NSURLResponse but found nothing. NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:[self postRequestWithURLString:apiEntry parameters:parameters] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if(!error) NSLog([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } ];[dataTask resume];
Now provide the response and nothing else.
| The second parameter of the completionHandler is the NSURLResponse , which when doing a HTTP request, is generally a NSHTTPURLResponse . So, you'd generally do something like: NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:[self postRequestWithURLString:apiEntry parameters:parameters] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // handle basic connectivity issues here if (error) { NSLog(@"dataTaskWithRequest error: %@", error); return; } // handle HTTP errors here if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode]; if (statusCode != 200) { NSLog(@"dataTaskWithRequest HTTP status code: %d", statusCode); return; } } // otherwise, everything is probably fine and you should interpret the `data` contents NSLog(@"data: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);}];[dataTask resume]; | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22206274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/590083/']} | jdg_81686 |
stackexchange | llm_judgeable_groundtruth_similarity | 43412140 |
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 .NET Core to build a cross platform class library. Depending on the operating system that the C# .NET Core project is built for using a .csproj file, I need to copy a native library to the project's output directory. E.g., for OS X I want to copy a .dylib file, for Windows I want to copy a .DLL file, for Linux I want to copy a .so file. How can I do this with a Condition clause in a .csproj ItemGroup? <ItemGroup> <Content Include="libNative.dylib" Condition=" '$(Configuration)|$(Platform)' == 'Debug|OSX' "> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> </ItemGroup> $(Platform) does not seem to work. Is there a different variable I can use?
Now provide the response and nothing else.
| For differentiating between Windows & Mac/Linux you can use the $(os) property: this gives you Windows_NT for Windows and UNIX for Mac/Linux. For differentiating between Mac & Linux, at least on recent versions of MSBuild, you can use RuntimeInformation.IsOSPlatform . So, combined, your csproj can have something like this: <ItemGroup> <Content Include="libNative.dll" Condition=" '$(OS)' == 'Windows_NT' "> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="libNative.so" Condition=" '$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Linux)))' "> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content> <Content Include="libNative.dylib" Condition=" '$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::OSX)))' "> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </Content></ItemGroup> To the best of my knowledge, this should work in all recent versions of .Net Core, Mono and .Net Framework. In older versions, you'd need to resort to evil trickery for differentiating between Mac & Linux: For Linux -> Condition=" '$(OS)' == 'Unix' and ! $([System.IO.File]::Exists('/usr/lib/libc.dylib')) " For Mac -> Condition=" '$(OS)' == 'Unix' and $([System.IO.File]::Exists('/usr/lib/libc.dylib')) " Sources: https://github.com/Microsoft/msbuild/issues/539 https://github.com/Microsoft/msbuild/issues/2468 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43412140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112955/']} | jdg_81687 |
stackexchange | llm_judgeable_groundtruth_similarity | 4486647 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
say, I have a generic command trait with an execute method that takes an Input and returns an Output. Something like trait Input;trait Output;trait Command[I <: Input, O <: Output] { def execute(input: I): O;} Then, I am going to create various Commands, something like class SampleInput extends Inputclass SampleOutput extends Outputclass SampleCommand extends Command[SampleInput, SampleOutput] { def execute(input:SampleInput):SampleOutput = new SampleOutput()} The problem with this is I could create a Command with a SampleAInput and SampleBOutput and the compiler will accept that happily. How do I enforce that so the compiler fails with type mismatch error ? Somehow, I need to group Input and Output under a type and pass that type to create a command. How do I do that?
Now provide the response and nothing else.
| trait InputOutput { type Input type Output}trait Command[IO <: InputOutput] { def execute(input: IO#Input): IO#Output} Here's some usage: scala> trait SampleIO extends InputOutput {type Input = String; type Output = String}defined trait SampleIOscala> class SampleCommand extends Command[SampleIO] {def execute(input: String) = input}defined class SampleCommandscala> class SampleCommand extends Command[SampleIO] {def execute(input: String) = 1}<console>:13: error: type mismatch; found : Int(1) required: SampleIO#Output class SampleCommand extends Command[SampleIO] {def execute(input: String) = 1} ^ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4486647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/366585/']} | jdg_81688 |
stackexchange | llm_judgeable_groundtruth_similarity | 2860089 |
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:
$$(-1)^ \frac{2}{4} = \sqrt[4]{(-1)^2} = \sqrt[4]{1} = 1$$ $$(-1)^ \frac{2}{4} = (-1)^ \frac{1}{2} = i$$ Came across an interesting Y11 question that made pose this one to my self. I can't for the life of me, find the flaw in the initial reasoning.
Now provide the response and nothing else.
| The question is essentially the same as asking what's wrong with: $1=\sqrt{(1)^2}=\sqrt{(-1)^2}=-1$. The error stems from being ambiguous about the meaning of $\sqrt{x}$ or, more generally, of $\sqrt[p]{x}$. A (real or) complex number $x\neq 0$ has a set of $p$ complex $p^{th}$ roots. If $x$ is a positive real number, exactly one of those roots is going to be a positive real number, so in some contexts (mostly when one is considering only positive real numbers), one talks about that single positive real root as the $p^{th}$ root of $x$, ignoring the other roots. But you have to be consistent. You can't say "look, $-2$ is a square root of $4$, but the square root of $4$ is $2$, so $-2=2$". | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2860089', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/355759/']} | jdg_81689 |
stackexchange | llm_judgeable_groundtruth_similarity | 22973701 |
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 connect with MailChimp's API, but keep getting errors: Error. API call to lists/list failed: SSL peer certificate or SSH remote key was not OK Then, I created a cacert.pem file and set it in the Mailchimp.php file: $this->ssl_cainfo = ROOT . DS . 'cacert.pem'; And get this: Error. API call to lists/list failed: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed or Error. API call to lists/list failed: SSL peer certificate or SSH remote key was not OK Per this page: I tried using the http://curl.haxx.se/docs/caextract.html file for my cacert.pem file, but that gives the "not OK" error listed above. I also tried making my own with the info provided by our host (a text file, changed extension to .pem, and pasted one and/or both chunks of data into it, making it look like this): -----BEGIN CERTIFICATE-----adjkflsdjflkasjdflkajdflksdflsdfkjasldfkjaadsfhjkfhdsajkfhakjdhfkjdh....-----END CERTIFICATE----------BEGIN CERTIFICATE-----adjkflsdjflkasjdflkajdflksdflsdfkjasldfkjaadsfhjkfhdsajkfhakjdhfkjdh....-----END CERTIFICATE----- or just one: -----BEGIN CERTIFICATE-----adjkflsdjflkasjdflkajdflksdflsdfkjasldfkjaadsfhjkfhdsajkfhakjdhfkjdh....-----END CERTIFICATE----- At a loss for where to go from here, what to try...etc Using the example code from here: https://github.com/mailchimp/mcapi2-php-examples And getting the Vendor files via composer: "require": { "mailchimp/mailchimp": ">=2.0.0"},
Now provide the response and nothing else.
| Having spoken to MailChimp, the certificate they're still (Jan 2016) using – for compatibility reasons, they told me – is the GTE CyberTrust Global Root (note GTE was bought by Digicert), so you don't need to replace the entire bundle, just add or force PHP to read this certificate: https://gte-cybertrust-global-root.digicert.com/info/index.html (note you'll get an 'insecure connection' warning if you try and load that in Firefox, for hopefully obvious reasons – you can add an exception.) It's in standard .crt format, which is what you need. Guide to certificate formats You didn't specify what the server was but here's how to add an extra one on Linux without having to replace an entire bundle etc: On Debian/Ubuntu, certificates live in /etc/ssl/certs/ Copy and paste the signature into a new file in that directory, e.g. mailchimp-legacy.crt run sudo c_rehash /etc/ssl/certs - What's going on here: c_rehash calculates a short hash of each certificate and creates a symlink from that to the original .pem or .crt file. Basically it's a quick lookup table for openssl - openssl will perform the hash as well and look for the symlink, rather than having to have a database of certificate names or open every file in turn to find the right one. check it's worked with this: ls -lh *.0 | grep 'mailchimp-legacy.crt' You should see something like this: lrwxrwxrwx 1 root root 20 Feb 13 14:17 4d654d1d.0 -> mailchimp-legacy.crtlrwxrwxrwx 1 root root 20 Feb 13 14:17 c692a373.0 -> mailchimp-legacy.crt Alternatively: On Debian, there's also a file called /etc/ca-certificates.conf and the exclamation mark in the line !mozilla/GTE_CyberTrust_Global_Root.crt indicates not to use that one. I believe it's possible to put a copy of the certificate with that name under /usr/share/ca-certificates/mozilla and run sudo update-ca-certificates , but it seems to me it be likely to be removed again when the package & config file are next updated. Remember to remove any workarounds you were using - e.g. - old CA bundles in your certificate directory- anywhere you override CURLOPT_CAINFO in your PHP - an openssl.cainfo line in your php.ini Check your application works correctly. I didn't need to restart PHP or my webserver, the change was instant. Worth using apt-get update/upgrade to check you have the most recently certificate packages. Here's a way to verify SSL connection (and verification) to a specific server from the command line: echo GET | openssl s_client -CApath /etc/ssl/certs/ -connect us3.api.mailchimp.com:443 2>&1 Monitoring: (updated) MailChimp's v2.0 API (deprecated) has an endpoint called ' helper/ping ' which returns some text to indicate the API status - useful as an automated test of API health and that your certificates are all still working. If you're using v3.0, they recommend using the API Root Resource and appending ?fields=account_name if you don't actually need to check any of the data. Someone asked in the comments if this was related to Heartbleed . No. Heartbleed is an openssl vulnerability related to eavesdropping on data in RAM. Mozilla removed GTE CyberTrust (twice) because they wanted to remove all 1024-bit root certificates - research has suggested a nation state could break a 1024-bit prime. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22973701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/673664/']} | jdg_81690 |
stackexchange | llm_judgeable_groundtruth_similarity | 27451132 |
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 change the height growth path from top-down to bottom-up. Is it possible in CSS? .button { margin-top:200px; margin-right:34px; width:150px; height:45px; background:black; float:right; transition-duration:2s; }.buttom:hover{ height:180px; transition-duration:2s;} <div class='button'> </div> http://jsfiddle.net/yasharshahmiri/1pkemq1p/3/
Now provide the response and nothing else.
| All you need is to set position: absolute and bottom position like this: .buttom{ margin-top:200px; margin-right:34px; width:150px; height:45px; background:black; float:right; position:absolute; bottom: 10px; transition: height 2s ease-in-out }.buttom:hover{ height:180px} <div class='buttom'> </div> Use Rotate and transform-origin to be able to set position relative to the element .buttom{ margin-top:200px; /* this shall be higher than the height on hover*/ margin-right:34px; width:150px; height:45px; background:black; transition: height 2s ease-in-out ; transform: rotatex(180deg); transform-origin: top;}.buttom:hover{ height:180px} <div class='buttom'> </div> Or this way: .buttom{ width:150px; height:45px; background:black; transition: height .3s cubic-bezier(0.175, 0.885, 0.32, 1.275) ; transform: rotatex(180deg) translate3d(0, -200px,0);/* the Y-Value shall be higher than the height on hover*/ transform-origin: top;}.buttom:hover{ height:180px} <div class='buttom'></div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27451132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4355306/']} | jdg_81691 |
stackexchange | llm_judgeable_groundtruth_similarity | 19326232 |
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 small time based question > I want to get timer in activity I already tryed this code but it runs so fast I offen get " 0 " I want to program to run with no sleep . but to count from 0 to 60 sec package com.okok; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.os.Handler; import android.os.SystemClock; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.SurfaceHolder.Callback; import android.widget.Chronometer; class GameView extends SurfaceView { //private Bitmap bmp; // Chronometer mChronometer; private SurfaceHolder holder; private GameLoopThread gameLoopThread; private List<Sprite> sprites = new ArrayList<Sprite>(); private long lastClick;private Bitmap bmpBlood; Handler m_handler; Runnable m_handlerTask ;private List<TempSprite> temps = new ArrayList<TempSprite>(); public GameView(Context context) { super(context); gameLoopThread = new GameLoopThread(this); holder = getHolder(); holder.addCallback(new Callback() { @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void surfaceCreated(SurfaceHolder holder) { createSprites(); gameLoopThread.setRunning(true); gameLoopThread.start(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } }); bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blast2); } private void createSprites() { sprites.add(createSprite(R.drawable.greenenact)); // sprites.add(createSprite(R.drawable.greenenact)); // sprites.add(createSprite(R.drawable.greenenact)); } private Sprite createSprite(int resouce) { Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce); return new Sprite(this, bmp); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.rgb(21, 181, 195)); for (int i = temps.size() - 1; i >= 0; i--) { temps.get(i).onDraw(canvas); } final int count=0; m_handler = new Handler(); m_handlerTask = new Runnable() { @Override public void run() { // do something if(count=60) { m_handler.removeCallbacks(m_handlerTask); } count++; m_handler.postDelayed(m_handlerTask, 5000); for (Sprite sprite : sprites) { sprite.onDraw(canvas); } } }; m_handlerTask.run(); }@Override public boolean onTouchEvent(MotionEvent event) { if (System.currentTimeMillis() - lastClick > 500) { lastClick = System.currentTimeMillis(); synchronized (getHolder()) { float x = event.getX(); float y =event.getY(); for (int i = sprites.size() - 1; i >= 0; i--) { Sprite sprite = sprites.get(i); if (sprite.isCollition(x, y)) { sprites.remove(sprite); temps.add(new TempSprite(temps, this, x, y, bmpBlood)); break; } } } } return true; } } this is my program I have only one error can not change count from int to a boolean error I don't want to use sleep method because my application have sleep method that affect my animation or give me a program that counts 0 to 60 sec and displays which runs without a sleep method
Now provide the response and nothing else.
| What you should do: Add a constructor to your super class: public Superclass { public SuperClass(String flavour) { // super class constructor this.flavour = flavour; }} In the Crisps class: public Crisps(String flavour, int quantity) { super(flavour); // send flavour to the super class constructor this.quantity = quantity;} Comments Some comments to your question: "In the superclass I have initialised the field with " private String flavour; This is not an initialization, it is a declaration. An initialization is when you set a value. "I am getting an error " flavour has private access in the superclass" but I believe this shouldn't matter as I am calling the accessor method that returns it to the field?" When you call a accessor (aka getter), it is ok - depends on the getter visibility.The problem in you code is the: this.flavour = because flavour is not a field declared on Crisps class, but on the supper class, so you can't do a direct access like that. you should use my suggestion or declare a setter on the super class : public void setFlavour(String flavour) { this.flavour = flavour;} Then you can use it on the child class: public Crisps(String flavour, int quantity) { this.quantity = quantity; super.setFlavour(flavour);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19326232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2870200/']} | jdg_81692 |
stackexchange | llm_judgeable_groundtruth_similarity | 18578258 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Some dynamically-typed languages use pointer tagging as a quick way to identify or narrow down the runtime type of the value being represented. A classic way to do this is to convert pointers to a suitably sized integer, and add a tag value over the least significant bits which are assumed to be zero for aligned objects. When the object needs to be accessed, the tag bits are masked away, the integer is converted to a pointer, and the pointer is dereferenced as normal. This by itself is all in order, except it all hinges on one colossal assumption: that the aligned pointer will convert to an integer guaranteed to have zero bits in the right places. Is it possible to guarantee this according to the letter of the standard? Although standard section 6.3.2.3 (references are to the C11 draft) says that the result of a conversion from pointer to integer is implementation-defined, what I'm wondering is whether the pointer arithmetic rules in 6.5.2.1 and 6.5.6 effectively constrain the result of pointer->integer conversion to follow the same predictable arithmetic rules that many programs already assume. (6.3.2.3 note 67 seemingly suggests that this is the intended spirit of the standard anyway, not that that means much.) I'm specifically thinking of the case where one might allocate a large array to act as a heap for the dynamic language, and therefore the pointers we're talking about are to elements of this array. I'm assuming that the start of the C-allocated array itself can be placed at an aligned position by some secondary means (by all means discuss this too though). Say we have an array of eight-byte "cons cells"; can we guarantee that the pointer to any given cell will convert to an integer with the lowest three bits free for a tag? For instance: typedef Cell ...; // such that sizeof(Cell) == 8Cell heap[1024]; // such that ((uintptr_t)&heap[0]) & 7 == 0((char *)&heap[11]) - ((char *)&heap[10]); // == 8(Cell *)(((char *)&heap[10]) + 8); // == &heap[11]&(&heap[10])[0]; // == &heap[10]0[heap]; // == heap[0]// So...&((char *)0)[(uintptr_t)&heap[10]]; // == &heap[10] ?&((char *)0)[(uintptr_t)&heap[10] + 8]; // == &heap[11] ?// ...implies?(Cell *)((uintptr_t)&heap[10] + 8); // == &heap[11] ? (If I understand correctly, if an implementation provides uintptr_t then the undefined behaviour hinted at in 6.3.2.3 paragraph 6 is irrelevant, right?) If all of these hold, then I would assume that it means that you can in fact rely on the low bits of any converted pointer to an element of an aligned Cell array to be free for tagging. Do they && does it? (As far as I'm aware this question is hypothetical since the normal assumption holds for common platforms anyway, and if you found one where it didn't, you probably wouldn't want to look to the C standard for guidance rather than the platform docs; but that's beside the point.)
Now provide the response and nothing else.
| This by itself is all in order, except it all hinges on one colossal assumption: that the aligned pointer will convert to an integer guaranteed to have zero bits in the right places. Is it possible to guarantee this according to the letter of the standard? It's possible for an implementation to guarantee this. The result of converting a pointer to an integer is implementation-defined, and an implementation can define it any way it likes, as long as it meets the standard's requirements. The standard absolutely does not guarantee this in general. A concrete example: I've worked on a Cray T90 system, which had a C compiler running under a UNIX-like operating system. In the hardware, an address is a 64-bit word containing the address of a 64-bit word; there were no hardware byte addresses. Byte pointers ( void* , char* ) were implemented in software by storing a 3-bit offset in the otherwise unused high-order 3 bits of a 64-bit word pointer. All pointer-to-pointer, pointer-to-integer, and integer-to-pointer conversions simply copied the representation. Which means that a pointer to an 8-byte aligned object, when converted to an integer, could have any bit pattern in its low-order 3 bits. Nothing in the standard forbids this. The bottom line: A scheme like the one you describe, that plays games with pointer representations, can work if you make certain assumptions about how the current system represents pointers -- as long as those assumptions happen to be valid for the current system. But no such assumptions can be 100% reliable, because the standard says nothing about how pointers are represented (other than that they're of a fixed size for each pointer type, and that the representation can be viewed as an array of unsigned char ). (The standard doesn't even guarantee that all pointers are the same size.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18578258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1366431/']} | jdg_81693 |
stackexchange | llm_judgeable_groundtruth_similarity | 395086 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create 50 directories (dir-01..dir-50). And I want to create 50 files (01.txt..50.txt) inside each of the 50 directories. For example: dir-01/01.txt..50.txt dir-02/02.txt..50.txt etc... I am able to create the the directories, but I am having trouble with creating the files inside each. I am also trying to compress all these afterwards into a tar file. This is where I am at so far: for i in {1..50}; do mkdir dir-$i;done;for j in {1..50}; do touch $j.txt.dir-*;done;tar -cf final.tar dir-{1..50} I know that second loop is wrong, but I am unsure how to proceed. Any advice is appreciated. This seems to work, but I am unsure if it is correct in syntax or format: for i in {1..50}; do mkdir "dir-$i"; for j in {1..50}; do touch "./dir-$i/$j.txt"; done;done;tar -cf final.tar dir-{1..50}
Now provide the response and nothing else.
| With zsh or bash or yash -o braceexpand : $ mkdir dir-{01..50}$ touch dir-{01..50}/file{01..50}.txt$ ls dir-45file01.txt file09.txt file17.txt file25.txt file33.txt file41.txt file49.txtfile02.txt file10.txt file18.txt file26.txt file34.txt file42.txt file50.txtfile03.txt file11.txt file19.txt file27.txt file35.txt file43.txtfile04.txt file12.txt file20.txt file28.txt file36.txt file44.txtfile05.txt file13.txt file21.txt file29.txt file37.txt file45.txtfile06.txt file14.txt file22.txt file30.txt file38.txt file46.txtfile07.txt file15.txt file23.txt file31.txt file39.txt file47.txtfile08.txt file16.txt file24.txt file32.txt file40.txt file48.txt$ tar -cf archive.tar dir-{01..50} With ksh93 : $ mkdir dir-{01..50%02d}$ touch dir-{01..50%02d}/file{01..50%02d}.txt$ tar -cf archive.tar dir-{01..50%02d} The ksh93 brace expansion takes a printf() -style format string that can be used to create the zero-filled numbers. With a POSIX sh : i=0 while [ "$(( i += 1 ))" -le 50 ]; do zi=$( printf '%02d' "$i" ) mkdir "dir-$zi" j=0 while [ "$(( j += 1 ))" -le 50 ]; do zj=$( printf '%02d' "$j" ) touch "dir-$zi/file$zj.txt" donedonetar -cf archive.tar dir-* # assuming only the folders we just created exists An alternative for just creating your tar archive without creating so many files, in bash : mkdir dir-01touch dir-01/file{01..50}.txttar -cf archive.tar dir-01for i in {02..50}; do mv "dir-$(( i - 1 ))" "dir-$i" tar -uf archive.tar "dir-$i"done This just creates one of the directories and adds it to the archive.Since all files in all 50 directories are identical in name and contents, it then renames the directory and appends it to the archive in successive iterations to add the other 49 directories. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/395086', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/253375/']} | jdg_81694 |
stackexchange | llm_judgeable_groundtruth_similarity | 189737 |
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:
Suppose $A$ is a $n \times n$ matrix from $M_n(\mathbb{C})$ with eigenvalues $\lambda_1, \ldots, \lambda_s$. Let $$m(\lambda) = (\lambda - \lambda_1)^{m_1} \ldots (\lambda - \lambda_s)^{m_s}$$ be the minimal polynomial of $A$. We define $f(A)$ in general to be $p(A)$ for some polynomial interpolating $f(\lambda_k), f'(\lambda_k), \ldots, f^{(m_k - 1)}(\lambda_k)$ for all $k$, assuming that $f$ is defined at these points. This is well defined because for any such two interpolating polynomials $p$ and $q$ we have $p(A) = q(A)$ and such a polynomial always exists. We can also find a polynomial $p$ which has degree less than the minimal polynomial $m$. Also, then there exist linearly independent matrices $Z_{ij}$ such that for any $f$ defined at $f(\lambda_k), f'(\lambda_k), \ldots, f^{(m_k - 1)}(\lambda_k)$ for all $k$, we have $$f(A) = \sum_{k = 1}^{s} ( f(\lambda_k)Z_{k0} + f'(\lambda_k)Z_{k1} + \ldots + f^{(m_k - 1)}(\lambda_k)Z_{k, m_k - 1})$$ Okay, with the definitions and such out of the way here's the actual question.. We can use this definition to calculate $f(A)$ for $f$ such as $f(x) = 1/x$ which gives us the inverse of $A$, or $f(x) = \sqrt{x}$ which gives us the square root of $A$, or $f(A)$ for any polynomial $f(x)$. The power series definition of $\sin(A)$, $\cos(A)$, etc also agrees with the definition. Now this is all really awesome and interesting in my opinion, but why on earth does this work? I have no idea why the properties of the inverse function $1/x$ or the square root $\sqrt{x}$ are "passed on" to matrices this way. Also, what is this called? Spectral something, but I'm not sure. I tried looking it up on Wikipedia and Google but couldn't find anything. Besides answers to help me understand what this is all about, I'll appreciate any references, keywords and so on.
Now provide the response and nothing else.
| Two classic books where you can find all the details about this stuff: Gantmacher, Matrix theory, Chelsea. Lancaster-Titsmenesky, The theory of matrices, Academic Press. Actually, for "hand" calculations, this works through the Jordan canonical form: you find the Jordan canonical form of your matrix, together with the change of basis matrix $$A = SJS^{-1} \ .$$ Then you prove that, for any polynomial $p(t)$, you have $$p(A) = S p(J) S^{-1} \ .$$ Hence, $$f(A) = S f(J) S^{-1}$$ and you only need to compute $p(J)$ for Jordan matrices. Which you do as follows: first, if you have a diagonal block matrix $$J =\begin{pmatrix}J_1 & 0 & \dots & 0 \\0 & J_2 & \dots & 0 \\\vdots & \vdots & \ddots & \vdots \\0 & 0 & \dots & J_r\end{pmatrix}$$ you can easily prove that $$p(J) =\begin{pmatrix}p(J_1) & 0 & \dots & 0 \\0 & p(J_2) & \dots & 0 \\\vdots & \vdots & \ddots & \vdots \\0 & 0 & \dots & p(J_r)\end{pmatrix}$$ So again, on one hand, $$f(J) =\begin{pmatrix}f(J_1) & 0 & \dots & 0 \\0 & f(J_2) & \dots & 0 \\\vdots & \vdots & \ddots & \vdots \\0 & 0 & \dots & f(J_r)\end{pmatrix}$$ and, on the other hand, you just need to know $p(J)$ when $J$ is a Jordan block. If : $$J =\begin{pmatrix}\lambda & 0 & 0 & \dots & 0 & 0 \\1 & \lambda & 0 & \dots & 0 & 0 \\0 & 1 & \lambda & \dots & 0 & 0 \\\vdots & \vdots & \ddots & \ddots & \vdots & \vdots \\0 & 0 & \dots & 1 & \lambda & 0 \\0 & 0 & \dots & 0 & 1 & \lambda\end{pmatrix}$$ is an $r\times r$ Jordan block, then $$p(J) =\begin{pmatrix}p(\lambda ) & 0 & 0 & \dots & 0 & 0 \\p'(\lambda)/ 1! & p(\lambda) & 0 & \dots & 0 & 0 \\p''(\lambda)/ 2! & p'(\lambda)/ 1! & p(\lambda) & \dots & 0 & 0 \\\vdots & \vdots & \ddots & \ddots & \vdots & \vdots \\p^{(r-2)}(\lambda)/(r-2)! &p^{(r-3)}(\lambda)/(r-3)! & \dots & p'(\lambda)/ 1! & p(\lambda) & 0 \\p^{(r-1)}(\lambda)/(r-1)! &p^{(r-2)}(\lambda)/(r-2)! & \dots & p''(\lambda)/2! & p'(\lambda)/ 1! & p(\lambda)\end{pmatrix}$$ Hence, again you have all in terms of $f$ in fact: $$f(J) =\begin{pmatrix}f(\lambda ) & 0 & 0 & \dots & 0 & 0 \\f'(\lambda)/ 1! & f(\lambda) & 0 & \dots & 0 & 0 \\f''(\lambda)/ 2! & f'(\lambda)/ 1! & f(\lambda) & \dots & 0 & 0 \\\vdots & \vdots & \ddots & \ddots & \vdots & \vdots \\f^{(r-2)}(\lambda)/(r-2)! &f^{(r-3)}(\lambda)/(r-3)! & \dots & f'(\lambda)/ 1! & f(\lambda) & 0 \\f^{(r-1)}(\lambda)/(r-1)! &f^{(r-2)}(\lambda)/(r-2)! & \dots & f''(\lambda)/2! & f'(\lambda)/ 1! & f(\lambda)\end{pmatrix}$$ And, in this version of the story, you actually don't need to know your polynomial $p(t)$ for your function $f(t)$ and matrix $A$ -but it's not difficult to find it, anyway: it's called the Lagrange-Sylvester polynomial, which is some sort of mixture between the classic Lagrange interpolation polynomial and a Taylor series. EDIT Nevertheless, seems that I forgot to answer the most important question: "Why does this whole thing actually work?" That is, why defining $$f(A) = p(A)$$ for some polynomial $p(t)$ that agrees with $f(t)$ on the spectrum of $A$ all this makes sense? That is, for what reason can we actually call $p(A)$ (the computable thing) the "value" of $f(t)$ on the matrix $A$? Because of the following: Theorem. (Gantmacher, chapter V, $\S 4$, theorem 2). If the function $f(t)$ can be expanded in a power series in the circle $\vert t - \lambda \vert < r$, $$f(t) = \sum_{n=0}^\infty a_n(t-\lambda)^n \ ,$$ then this expansion remains valid when the scalar argument $t$ is replaced by a matrix $A$ whose eigenvalues lie within the circle of convergence. That is, under the hypotheses of the theorem, you have $$f(A) = \sum_{n=0}^\infty a_n(A-\lambda I)^n \ ,$$ where the $f(A)$ in the left hand-side means $p(A)$, the value of the Lagrange-Sylvester polynomial on $A$. So, why not define $f(A)$ as this last power series (i.e., the Taylor series of $f(t)$)? Well, because then you would have to talk a long time about convergence issues of matrix series ... And you would end, finally, at the same point: relying on the Jordan canonical form for actual computations. So, the Lagrange-Sylvester device allows you to get rid of convergence issues -if you're willing to accept $f(A) = p(A)$ as a sound definition. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/189737', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17384/']} | jdg_81695 |
stackexchange | llm_judgeable_groundtruth_similarity | 73398 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've just read that 68 years ago Little Boy was dropped on Hiroshima, which made me wonder about some rather historical facts about the development of the first nuclear bombs; they seem to be several questions, but they boil down to the same thing: the theoretical aspects of the development of the bombs. As far as I know, nuclear fission was already understood at the time, so was all the competition between the american team and the german team to develop the bomb first, a mere matter of engineering? Or what was the role of theoretical physicists such as Richard Feynman? Also, I've heard things like that the team led by Werner Heisenberg had misconceptions about nuclear fission, so that his team could not develop the bomb first. Can anyone put in perspective the theoretical aspects of the development of the bombs taking care of this historical issues?
Now provide the response and nothing else.
| As far as I know, nuclear fission was already understood at the time, so was all the competition between the american team and the german team to develop the bomb first, a mere matter of engineering? Only some very, very basic knowledge about the physics of nuclear fission was available at this time. I'll give a few details about this below. Also, according to this 1967 interview with Heisenberg, it's probably not accurate to imagine a competition between the US and the Nazis to build a bomb; the Germans were struggling to keep fighting at all in Europe, and didn't think it was realistic to produce more than research reactors given the time and resources they had available. The liquid drop model dated back to 1935, so physicists, even non-specialists like Einstein, could readily understand the basic idea that fission was possible and that it should release neutrons, making a chain reaction possible. However, fission is a tunneling process, and tunneling depends exponentially on the width and height of the barrier, making it extremely difficult, even today, to calculate fission rates from first principles to even order-of-magnitude precision. People today would typically approach this kind of calculation using the Strutinsky smearing technique, which wasn't invented until 1968 (Strutinsky, Nucl. Phys. A122 (1968) 1; described in http://arxiv.org/abs/1004.0079 ). A primitive version of the nuclear shell model had been proposed, but it wasn't until Maria Goeppert-Mayer in the 50's that it was really developed into a detailed theory, and it only worked for spherical nuclei -- uranium and plutonium are deformed. Even gross features of the barrier, like the existence of a metastable minimum (fission isomers), were not to be discovered until the 60's. So induced fission cross-sections and average neutron multiplicities had to be measured empirically: [W]hile Glenn Seaborg's team had proven in March 1941 that plutonium underwent neutron-induced fission, it was not known yet if plutonium released secondary neutrons during bombardment. Further, the exact sizes of the "cross sections" of various fissionable substances had yet to be determined in experiments using the various particle accelerators then being shipped to Los Alamos. ( source ) The Germans also set themselves back because of Heisenberg's decision to use heavy water as a moderator, when graphite would have been easier. This was apparently partly based on a mistake in a 1940 measurement by Bothe. There have been lots of hints (possibly involving wishful thinking and retroactive rewriting of history) by the German physicists that they may have dragged their feet or intentionally made mistakes, because they didn't want their own country to get the bomb. The true nature of Heisenberg’s role in the Nazi atomic bomb effort isa fascinating question, and dramatic enough to have inspired a well-received 1998 theatrical play, “Copenhagen.” The real story, however,may never be completely unraveled. Heisenberg was the scientific leaderof the German bomb program up until its cancellation in 1942, when theGerman military decided that it was too ambitious a project to undertakein wartime, and too unlikely to produce results.Some historians believe that Heisenberg intentionally delayed and obstructed the project because he secretly did not want the Nazis to getthe bomb. Heisenberg’s apologists point out that he never joined theNazi party, and was not anti-Semitic. He actively resisted the government’s Deutsche-Physik policy of eliminating supposed Jewish influences from physics, and as a result was denounced by the S.S. as atraitor, escaping punishment only because Himmler personally declaredhim innocent. One strong piece of evidence is a secret message carriedto the U.S. in 1941, by one of the last Jews to escape from Berlin, andeventually delivered to the chairman of the Uranium Committee, whichwas then studying the feasibility of a bomb. The message stated “...thata large number of German physicists are working intensively on theproblem of the uranium bomb under the direction of Heisenberg, [and]that Heisenberg himself tries to delay the work as much as possible,fearing the catastrophic results of success. But he cannot help fulfilling the orders given to him, and if the problem can be solved, it will besolved probably in the near future. So he gave the advice to us to hurryup if U.S.A. will not come too late.” The message supports the view thatHeisenberg intentionally misled his government about the bomb’s technical feasibility; German Minister of Armaments Albert Speer wrote thathe was convinced to drop the project after a 1942 meeting with Heisenberg because “the physicists themselves didn’t want to put too muchinto it.” Heisenberg also may have warned Danish physicist Niels Bohrpersonally in September 1941 about the existence of the Nazi bombeffort. On the other side of the debate, critics of Heisenberg say that he clearlywanted Germany to win the war, that he visited German-occupied territories in a semi-official role, and that he simply may not have beenvery good at his job directing the bomb project. On a visit to the occupied Netherlands in 1943, he told a colleague, “Democracy cannotdevelop sufficient energy to rule Europe. There are, therefore, only twoalternatives: Germany and Russia. And then a Europe under Germanleadership would be the lesser evil.” Cassidy 2000 argues that thereal point of Heisenberg’s meeting with Bohr was to try to convince theU.S. not to try to build a bomb, so that Germany, possessing a nuclearmonopoly, would defeat the Soviets — this was after the June 1941 entry of the U.S.S.R. into the war, but before the December 1941 PearlHarbor attack brought the U.S. in. Bohr apparently considered Heisenberg’s account of the meeting, published after the war was over, to beinaccurate. The secret 1941 message also has a curious moral passivity to it, as if Heisenberg was saying “I hope you stop me before I dosomething bad,” but we should also consider the great risk Heisenbergwould have been running if he actually originated the message. David C. Cassidy, "A Historical Perspective on Copenhagen," Physics Today,July 2000, p. 28, http://www.aip.org/pt/vol-53/iss-7/p28.html | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/73398', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']} | jdg_81696 |
stackexchange | llm_judgeable_groundtruth_similarity | 354098 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Lets say we have a closed system with states in a Hilbert space $\mathcal{H}$. Every state can be expressed as a sum of energy eigenstates. In a closed system, like a box of atoms, entropy will increase until the entire system is in thermal equilibrium. However, when we write a state as a sum of energy eigenstates, time evolution merely contributes a phase to each basis state. It doesn't seem to me as though states get any more "disordered" over time, so how can the entropy increase? Let me phrase my question differently. I recall a professor once writing $$S = k \log (\dim \mathcal{H})$$on the board. Certainly, the dimensionality of a Hilbert space does not change under time evolution. So how can entropy increase under time evolution? Is the above equation only correct under certain conditions? There must be a big flaw in my reasoning/memory.
Now provide the response and nothing else.
| The total entropy of an isolated system indeed does not change under Schrodinger time evolution. To see this, note that (assuming for simplicity that the Hamiltonian does not depend explicitly on time) the system's density matrix satisfies the Von Neumann equation $\rho(t) = e^{-i H t / \hbar}\, \rho(0)\, e^{i H t / \hbar}$, so $\rho(t)$ and $\rho(0)$ are always unitarily equivalent, and therefore have the same eigenvalue spectra. Therefore any entropy measure that depends only on the density matrix weights (which, practically speaking, is all of them), is constant in time. But the entanglement entropy between subsystems can indeed increase, because the subsystems are not isolated. So if the system, say, starts in a product state with no spatial entanglement between its subsystems, then generically Schrodinger time-evolution will lead to increasing entanglement between the subsystems, so the local entropy associated with each little piece of the whole system will indeed increase, even as the total entropy remains constant. This fact relies on a very non-classical feature of Von Neumann entropy, which is that the sum of the entropies of the subsystems can be greater than the entropy of the system as a whole. (Indeed, in studying the entanglement of the ground state, we often consider systems where the subsystems have very large entanglement entropy, but the system as a whole is in a pure state and so has zero entropy!) The subfields of "eigenstate thermalization", "entanglement propagation", and "many-body localization" - which are all under very active research today - study the ways in which the Schrodinger time-evolution of various systems do or do not lead to increasing entanglement entropy of subsystems, even as the entropy of the system as a whole always stays the same. | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/354098', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/157704/']} | jdg_81697 |
stackexchange | llm_judgeable_groundtruth_similarity | 18660916 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to be able to extend the mocha test results and listen to them from the available mocha object. First, I'm looking at getting the "passes" results. It looks like they might be subscribed to from suite but I'm not sure how... I've tried the following which I thought would listen to the end of all of my tests: var suite = mocha.suite.suites[0];suite.on("end", function(e){ console.log(e, "mocha - heard the end of my test suite"); } ); My simple hack which works but isn't elegant at all - sad really: setTimeout(function(){ var passes = $(".passes").find("em").text(); console.log("ui - heard the end of my test suite - passes: " + passes); }, 500);
Now provide the response and nothing else.
| I did some more digging in mocha.js and finally discovered that mocha.run() actually returns the runner which emits all the events I was looking. The original example I was using only had: mocha.run() So if Mocha.run() returns a runner, then I realized that I could subscribe to it: var runner = mocha.run(); var testsPassed = 0; var onTestPassedHandler = function(e){ testsPassed++; console.log("onTestPassedHandler - title: " + e.title + " - total:" + testsPassed); }; runner.on("pass", onTestPassedHandler); /** * These are all the events you can subscribe to: * - `start` execution started * - `end` execution complete * - `suite` (suite) test suite execution started * - `suite end` (suite) all tests (and sub-suites) have finished * - `test` (test) test execution started * - `test end` (test) test completed * - `hook` (hook) hook execution started * - `hook end` (hook) hook complete * - `pass` (test) test passed * - `fail` (test, err) test failed */ much better! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18660916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/581803/']} | jdg_81698 |
stackexchange | llm_judgeable_groundtruth_similarity | 110923 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I read about NPC and its relationship to PSPACE and I wish to know whether NPC problems can be deterministicly solved using an algorithm with worst case polynomial space requirement, but potentially taking exponential time (2^P(n) where P is polynomial). Moreover, can it be generalised to EXPTIME in general? The reason I am asking this is that I wrote some programs to solve degenerate cases of an NPC problem, and they can consume very large amounts of RAM for hard instances, and I wonder if there is a better way. For reference see https://fc-solve.shlomifish.org/faq.html .
Now provide the response and nothing else.
| Generally speaking, the following is true for any algorithm: Suppose $A$ is an algorithm that runs in $f(n)$ time. Then $A$ could not take more than $f(n)$ space, since writing $f(n)$ bits requires $f(n)$ time. Suppose $A$ is an algorithm that requires $f(n)$ space. Then in $2^{f(n)}$ time, $A$ can visit each of its different states, therefore can gain nothing by running more than $2^{f(n)}$ time. It follows that: $\mathbf{NP}$ $\subseteq \mathbf{PSPACE}$ The statemement is known as part of the relations between the classes, as depicted by the following diagram: The explanation is simple: a problem $Q$ $\in$ $\mathbf{NP}$ has a polynomial length certificate $y$ . An algorithm that tests all possible certificates is an algorithm that decides $Q$ in time $\large 2^{n^{O(1)}}$ . Its space requirement is: $y$ (polynomial in $n$ ) space required to verify $y$ . Since $y$ is a polynomial certificate, it can be verified in polynomial time, hence cannot possibly require more than polynomial space. Since the sum of two polynomials is also a polynomial, $Q$ can be decided with polynomial space. Example: Suppose $\varphi$ is an instance of 3-CNF on literals $x_1 \dots x_n$ , with $m$ clauses. An assignment $f$ is some function $f:\{x_1\dots x_n\} \rightarrow \{0,1\}$ . It holds that: There are $2^n$ different assignments. Given an assignment $f$ , it takes $O(m)$ time to calculate the value of $\varphi$ , therefore it cannot require more than $O(m)$ space. So an algorithm $A$ that checks all possible assignments will use polynomial space, run in exponential time and decide 3-SAT. It follows that: 3-SAT $\in \mathbf{PSPACE}$ , and since 3-SAT is NP-Complete, $\mathbf{NP}$ $\subseteq \mathbf{PSPACE}$ | {} | {'log_upvote_score': 6, 'links': ['https://cs.stackexchange.com/questions/110923', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/106701/']} | jdg_81699 |
stackexchange | llm_judgeable_groundtruth_similarity | 344813 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The Higgs boson is lighter than the top quark. But the top quark was discovered in the mid-1990s where the Higgs boson escaped detection for two more decades. So if the energy has already been achieved to produce Higgs boson, why did it escape detection so far? I understand that the couplings of Higgs boson to fermions is small and doesn't interact with the detector appreciably. Does it mean that in LHC, with the increase in energy, the Higgs coupling increased and we finally detected Higgs?
Now provide the response and nothing else.
| With both particles you cannot detect them within their own lifetimes, only look at what they decay into. The top decays to a b jet and W (which can then become fermion anti-fermion or leptons) and is fairly distinctive. The dominant Higgs decay, however, is to two b jets. B jets are very common within the LHC and we cannot infer from two b jets that a Higgs detection has been made. It's all about the statistics. With the top, its decay mode was distinctive enough that fewer events were needed before a statistically significant signal was seen above the background, whereas the Higgs needed many more events. | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/344813', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/36793/']} | jdg_81700 |
stackexchange | llm_judgeable_groundtruth_similarity | 19130321 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let me exemplify this, int a = 100;int b = a;int main(int argc, char **argv, char ** env){ printf("The value of b=%d\r\n",b); return 0;} Now, I get the compilation error as expected. [joshis1@localhost global_var]$ gcc global_var.c -o global_var.outglobal_var.c:4:1: error: initializer element is not constant int b = a; ^ What I want to learn here is why do I get the error? why compiler restricts this operation.I understand that initialized global variables are stored in Data segments. The compiler could have first resolved the value of a,and then could have assigned the same value to b. Why it lacks this feature? Is it complex for compiler to do? Is there any rationale behind this functionality or just a pitfall of C?
Now provide the response and nothing else.
| The official documentation, taken from line 1644, 6.7.8 Initialization , says: All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals. Why the rule exists is a more difficult question - perhaps as you suggest it is difficult for the compiler to do. In C++ such an expression is valid, but global initialiser may invoke constructors, etc, whereas for C, to keep things compact, globals are evaluated at the compile phase. int b = a; is evaluable at compile time, but what about int b = a + c; ? int b = pow(a, 2); ? Where would you stop? C decides that not allowing you to start is the best solution. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19130321', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2735434/']} | jdg_81701 |
stackexchange | llm_judgeable_groundtruth_similarity | 45210430 |
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 problem I'm using RestSharp for accessing my API. But when I'm sending a DateTime it seems to be converted to UTC.I'm sending '10.06.1991 00:00' and the API gets '09.06.1991 22:00' So, I would always need to add 2 hours when my API gets a DateTime-object? I checked the JSON RestSharp sends to the API. public class Test{ public int IntProperty {get;set;} public string StringProperty {get;set;} public DateTime DateTimeProperty {get;set;}} My object is Test t = new Test{ IntProperty=3, StringProperty="string", DateTimeProperty=new DateTime(1991,06,10) } when I'm sending the object via RestSharp, the JSON my API receives is { "IntProperty":3, "StringProperty":"string", "DateTimeProperty":"09.06.1991 22:00:00"} Any idea what I could do?Thanks
Now provide the response and nothing else.
| It's not your API that receives wrong data, it's your client that sends "wrong" data. I got the same problem with my API. No, it's correct data but converted to UTC. The exact problem is described here: https://github.com/restsharp/RestSharp/issues/834 So, don't add 2 hours to each DateTime you get it in your API. You would perhaps change correct data when another client sends unconverted dates. You could check, whether on GET you receive the right date. Maybe RestSharp is converting that "wrong" datetime back to 10.06.1991 00:00 - maybe you are okay with it if you want the database to not contain UTC but the data you original wanted to send, don't use the default serializer, use JSON.Net ( http://www.newtonsoft.com/json ). It won't convert to UTC and sends the original DateTime. Here is one really good example on how to implement: http://bytefish.de/blog/restsharp_custom_json_serializer/ you write a custom class that implements ISerializer and IDeserializer in serialize you call JSON.Net Serialize while in deserialize you call JSON.Net Deserialize you just need to add a handler to your RestClient like this: (I'm using the static Default-instance described in the mentioned blog) my client looks like: private readonly RestClient _client;public RestApiClient(string apiAdress){ _client = new RestClient(apiAdress); _client.AddHandler("application/json", () => NewtonsoftJsonSerializer.Default);} and in requests you can set the JsonSerializer : IRestRequest restRequest = new RestRequest(request.GetRestfulUrl(), request.Method) { RequestFormat = request.DataFormat, JsonSerializer = NewtonsoftJsonSerializer.Default }; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45210430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7326355/']} | jdg_81702 |
stackexchange | llm_judgeable_groundtruth_similarity | 9346261 |
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 three models, all for a has_many :through relationship. They look like this: class Company < ActiveRecord::Base has_many :company_users, dependent: :destroy has_many :users, through: :company_users accepts_nested_attributes_for :company_users, :usersendclass CompanyUser < ActiveRecord::Base self.table_name = :companies_users #this is because this was originally a habtm relationship belongs_to :company belongs_to :userendclass User < ActiveRecord::Base # this is a devise model, if that matters has_many :company_users, dependent: :destroy has_many :companies, through: :company_users accepts_nested_attributes_for :company_users, :companiesend this loads fine, and the joins are built fine for queries. However, whenever i do something like @company = Company.last@user = @company.users.build(params[:user])@user.save #=> [email protected] #=> true both the User record and the CompanyUser records get created, but the company_id field in the CompanyUser record is set to NULL INSERT INTO `companies_users` (`company_id`, `created_at`,`updated_at`, `user_id`) VALUES (NULL, '2012-02-19 02:09:04', '2012-02-19 02:09:04', 18) it does the same thing when you @company.users << @user I'm sure that I'm doing something stupid here, I just don't know what.
Now provide the response and nothing else.
| You can't use a has_many :through like that, you have to do it like this: @company = Company.last@user = User.create( params[:user] ) @company.company_users.create( :user_id => @user.id ) Then you will have the association defined correctly. update In the case of the comment below, as you already have accepts_nested_attributes_for , your parameters would have to come like this: { :company => { :company_users_attributes => [ { :company_id => 1, :user_id => 1 } , { :company_id => 1, :user_id => 2 }, { :company_id => 1, :user_id => 3 } ] } } And you would have users being added to companies automatically for you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9346261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/557279/']} | jdg_81703 |
stackexchange | llm_judgeable_groundtruth_similarity | 82858 |
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 textbooks I have read introduce LCAO by considering the H2 molecule. In this example, there are only two possible combinations of the two 1s orbitals (in phase and out of phase). When there are more than two valence orbitals, however, a greater amount of combinations arise. A common description of the pi-MOs in butadiene is shown below: There are two (and I think only these two, assuming all combining p-orbitals are identical) possible combinations of the p-orbitals which (apparently) do not contribute to the bonding in butadiene. These are shown at the bottom of the illustration above. Why is it that n AOs only form n MOs, even when more than n LCAO are possible? You would think that all possible combinations would contribute a possible electron energy state to the molecule.
Now provide the response and nothing else.
| If you have $n$ functions (e.g. AOs) you can make a maximum of $n$ new linearly independent functions (e.g. MOs). If you try to make $n+1$ MOs, then any one of them can be expressed as a linear combination of the other $n$ MOs. The most usual way to enforce linear independence is to enforce orthogonality, i.e. all your MOs have to have zero net overlap with each other. All the "correct" MOs you drew are orthogonal to each other, but the "incorrect" MOs are not orthogonal to any of the "correct" MOs. | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/82858', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/36007/']} | jdg_81704 |
stackexchange | llm_judgeable_groundtruth_similarity | 53005174 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Starting from iOS 12 the CLLocationManager doesn't run endless anymore in the background. The app get's terminated without a crashlog at random times. This was working fine before iOS 12. To demonstrate this problem I've created an sample app here The demo app just launches an CLLocationManager and keep this running in the background. While running on the background we keep track of it by logging it. The problem is that the app get terminated by iOS. The demo app is created to demonstrate this problem. Steps to reproduce Run the app on the device Grand access to locationmanager Put the app to the background Wait for 1-48hours Result: The app is terminated App is terminated without any reason after random time. Expected result: The app is still running. How it should work This is confirmed by an Apple engineer: Once the CLLocationManager updates are started in the foreground and you did all the work to have it running in the background, the location updates should run endless in the background until: app is force quit device is rebooted app stops location updates app releases the CLLocationManager object app crashes iOS terminates the app due to memory shortage, the locationManager object is released, overreleased, or overwritten. You should make sure that your view controller is not being instantiated, which then resets the locationController class. If that happens when the app is in the background, you will restart updates, which will cause the app to be eventually suspended. You should make sure the locationController is a singleton. app is crashing. Check to see if there are crash logs on the device you are testing iOS is terminating the app due to memory shortage. In this case, you will find JetsamEvent logs on the device that shows your app being terminated. You can check the timestamps and locate the one that is around the time your app stopped working.
Now provide the response and nothing else.
| Updated answer: Apple fixed this bug in iOS 12.2 beta 2 (16E5191d) Original analyse and bug detection: Together with Apple Developer Technical Support we have analyzed this issue with Sysdiagnose files. Following these guidelines you can install profiles to have more logging on your device. I don't know exactly how these logs work and where to find this issue, but Apple did this for me and came with this first analyse: On the suspension event you observed on 2018/10/22 01:01:12:587, this is what I see (about a minute after your last activity logging) [CllocationManag:2725] Terminating with description: { owner = ; target = rw.sp.flitsmeister.frameworks.CllocationManagerBackgroundTest; } This is basically saing that your app was terminated, because the system needed drive space, and killed a bunch of apps so it can delete their /tmp and /Library/Caches directories. I have seen this process to be a little more aggressive in iOS 12, but seeing you are on a 256GB device, and have ~179 GB free after the cleanup, I am finding it hard to believe this was justified. After sending some more sysdiagnose and reproduction cases Apple did his best to analyse and ended with the following conclusion: Unfortunately I don’t bring good news. It turned out that, currently in iOS 12 there is a new mechanism that will terminate long running background apps periodically as the system needs to free resources. At this time, this process is a bit too aggressive, and I am working with the relevant teams to get this to behave better. So, at this point, I would like you to file a bug report. Explain the symptoms. And make sure you upload the sysdiagnose files along with the bug report. (I already sent yours in, but it doesn’t hurt to have the new ones as well). And let me know the bug number please. So this means that currently in iOS 12 you app won't run endless on the background. I've filled in a bug report, the number is 45581276 and will try to keep this thread updated. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53005174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/981968/']} | jdg_81705 |
stackexchange | llm_judgeable_groundtruth_similarity | 1608168 |
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:
After playing a little with a Rubik cube I thought of the following problem : Suppose we start with a solved Rubik cube (a general one , with $n^3$ cubes) . Then we choose one of the moves , each having a probability of $\frac{1}{6n}$ of being chosen , and apply it on our cube . We continue doing so ( choosing a new move randomly and then applying it and so on...) , until we reach the solved position again . What is the expected number of moves needed to solve the cube in this way ? I thought about it and I think the answer should be $\infty$ (at least for $n \geq 3$) because there are a lot of random sequences of moves that will take a long time to solve the cube but I don't have a rigorous way to prove it. For $n=2$ I'm not that sure if the answer should be finite or infinite (but I still tend to think it's infinite). Thank you for your time to help me!
Now provide the response and nothing else.
| Consider a simpler scenario: suppose you have a biased coin, which shows Heads with probability $p > 0$. What is the expected number of attempts required to throw a Head? The probability that exactly $n$ throws are required is $q^{n-1}p$, where $q = 1-p$. So the expected number of throws is $\sum_{n=1}^\infty nq^{n-1}p = \dfrac{p}{(1-q)^2} = \dfrac{1}{p}$. Note in particular that this is finite! Now, let $N$ be the maximum number of moves required to solve an $n \times n \times n$ Rubik's cube. Thanks to the efforts of countless dedicated investigators, we know that for $n=3$, we have $N=20$ according to the half-turn metric, and $N=26$ according to the quarter-turn metric (see for instance this link ). But the exact value of $N$ doesn't matter; the number of positions is finite, and therefore the maximum number of moves required to solve a solvable position is also finite. Suppose the number of moves available at each turn is $m$. You say that $m=6n$, and I won't argue with that; again, the important thing is that $m$ is finite. Then all you have to do to solve a position in $N$ moves or less is to pick the optimal move each time. The probability of doing this by chance is at least $p=m^{-N}$. So if you consider a "coin flip" to be $N$ random moves in your Rubik's cube, then the expected number of coin flips is at most $\dfrac{1}{p} = m^N$. So the expected number of moves is at most $\dfrac{N}{p} = Nm^N$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1608168', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_81706 |
stackexchange | llm_judgeable_groundtruth_similarity | 650108 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $x\in X$ be a non reduced point. Then I can find a nilpotent $f\in \Gamma(U, \mathcal O_X)$, where $U$ is some open neighborhood of $x$. I also know that when $X$ is assumed to be quasicompact, every point has a closed point in its closure. Now, if the $\operatorname{cl} (x) \subset U$, I'm done. But how do I proceed if this is not the case? Can I find a $W\supset \bar U$, and $\tilde f$ such that $\operatorname{res_{W\rightarrow U}} \tilde f = f$?
Now provide the response and nothing else.
| Let $x$ be a non-reduced point and let $y$ be a closed point lying in the closure of $\{x\}$. Let $U=\mathrm{Spec}(A)$ be an affine open around $y$, so that we necessarily also have $x\in U$. Let $\mathfrak{p}_x$ and $\mathfrak{p}_y$ be the corresponding primes of $A$. Then $\mathfrak{p}_x\subseteq\mathfrak{p}_y$, and $A_{\mathfrak{p}_x}=\mathscr{O}_{U,x}=\mathscr{O}_{X,x}$ is a localization of $A_{\mathfrak{p}_y}=\mathscr{O}_{U,y}=\mathscr{O}_{X,y}$. Since localizations of reduced rings are reduced, $y$ must be a non-reduced point. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/650108', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/81994/']} | jdg_81707 |
stackexchange | llm_judgeable_groundtruth_similarity | 26869550 |
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 the Scanner class, and keep coming across warnings, saying I should close a resource leak. It has not affected me before, so I have disregarded it. Will this cause any problems for me in the future? How do I close the Scanner?
Now provide the response and nothing else.
| You got that error because that is not the right for checking the existence of a object(procedure) and if not exists then creating it . try something like this. IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = Object_id(N'[dbo].[ELMAH_GetErrorXml]') AND type IN ( N'P', N'PC' )) BEGIN EXEC('CREATE PROCEDURE [dbo].[Elmah_geterrorxml] (@Application NVARCHAR(60), @ErrorId UNIQUEIDENTIFIER) AS BEGIN SET NOCOUNT ON SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = @ErrorId AND [Application] = @Application END') END But the simple way is IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = 'dbo' AND ROUTINE_NAME = 'ELMAH_GetErrorXml') BEGIN DROP PROCEDURE [dbo].[Elmah_geterrorxml] ENDGOCREATE PROCEDURE [dbo].[Elmah_geterrorxml] (@Application NVARCHAR(60), @ErrorId UNIQUEIDENTIFIER)AS BEGIN SET NOCOUNT ON SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = @ErrorId AND [Application] = @Application END | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26869550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4236526/']} | jdg_81708 |
stackexchange | llm_judgeable_groundtruth_similarity | 189907 |
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'm trying to view these functions as the scale goes from local to global. I don't want to manipulate the function, just the domain range. Manipulate[Plot[{x^2,2^x} {x, 0, 10}], {x, 0, 10}]
Now provide the response and nothing else.
| Update: Counts[data] seems to be equivalent to AssociationThread @@ Transpose@Tally[data] . The OP's problem arises because in constructing an Association , keys are checked for uniqueness and later entries with a duplicate key replace earlier entries. (Simple example: Association[{1. -> 1, 1. -> 2}] .) Uniqueness is determined by MatchQ , I believe, which has problems discussed below in the original answer. The problem with SameQ not strictly being an equivalence relation due nontransitivity is still an issue. This update principally clarifies the role of forming an association: It discards entries of the Tally with duplicate keys, which results in an undercount. Original answer: Working with floating-point numbers is tricky. I'd say the most important, common issue is that rounding errors lead to different but close numbers that users wish would be treated the same. Introductory programming courses teach that comparing floats should be done with something like Abs[x - y] < $MyTolerance . In Mathematica similar (but relative) tolerances are built into SameQ and Equal , which are controlled by the the internal system parameters Internal`$ SameQTolerance and Internal`$EqualTolerance respectively (see also this ; this question has similar issues as the OP). Perhaps less well known is that MatchQ has a small tolerance like SameQ but is slightly more restrictive. The most important difference is that MatchQ is transitive but SameQ is not. These functions play various roles in pattern-matching and comparing numbers, and their issues affect functions like Counts[] when applied to floating-point data. When constructing classes from data, as in Counts[] , some reflection should lead one to think that using a comparison that is an equivalence relation, and therefore transitive, would be desirable. And if not transitive, it should be at least "locally transitive" on the actual data being used. By "locally transitive," I mean that the relation is transitive when restricted to the data set, even if it is not transitive on all floating-point numbers. This seems to be the problem with the OP's example: SameQ is not transitive on xs . I say "seems" because I cannot check the internal workings of Counts[] . It's possible that SameQ is used to construct the keys and MatchQ to tally the counts. It seems to me that Counts[] uses SameQ and CountsBy[] uses MatchQ to construct the keys, however the counting is done. Since SameQ is not transitive, the order that the data is processed can make a difference. Nevertheless, the problem can be fixed by making SameQ locally transitive on xs . The reason this comes up in this example is that in constructing the data xs , the rounding drift amounts to 2 bits (2 ulp), which is one too many for SameQ to be locally transitive. Here is the best fix (that fixes SameQ -- Chip Hurst points out that the tolerance can be as small as 0.55 , which is close to the value of Log10[4.] = 0.60.. that would be predicted by the observed rounding error): Block[{Internal`$SameQTolerance = Internal`$EqualTolerance}, Total@Counts[xs]](* 100 *) Another fix is to use MatchQ via CountsBy[] : Total@CountsBy[xs, # &](* 100 *) The CountsBy[] association has several keys for equal numbers, but it does have the correct total. The first solution seems better because it has one key for each cluster of equal numbers. (It likely that in some applications one would like distinct floating-point numbers to have distinct entries; then something like CountsBy[xs, ToString@*FullForm] would do the trick.) Appendix Some pictures showing the properties of SameQ and MatchQ on consecutive machine-precision floats: Block[{x1}, x1 = Table[1 + n*$MachineEpsilon, {n, 0, 5}]; {Outer[Boole@*SameQ, x1, x1] // MatrixPlot[#, PlotLabel -> SameQ] &, Outer[Boole@*MatchQ, x1, x1] // MatrixPlot[#, PlotLabel -> MatchQ] &} // GraphicsRow ] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/189907', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/62488/']} | jdg_81709 |
stackexchange | llm_judgeable_groundtruth_similarity | 199173 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to plot exactly N bounce of a ball. I'm using DSolve to solve the differential equation and WhenEvent to change the velocity. The code below plots only the first 10 seconds. DSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0, WhenEvent[y[t] == 0, {y'[t] -> -0.95 y'[t], k -> k++}]}, y, {t, 0, 10}]Plot[y[t] /. %, {t, 0, 10}]
Now provide the response and nothing else.
| You have to declare a discrete variable to count the events nevent=5; (*number of bounces*)NDSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0, k[0]== 0, WhenEvent[y[t] == 0, {y'[t] -> -0.95 y'[t], k[t] ->k[t] + 1}],WhenEvent[k[t] == nevent, {te = t, "StopIntegration"}]}, y, {t, 0, 50}, DiscreteVariables -> {k} ]Plot[y[t] /. %, {t, 0, te}] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/199173', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/65815/']} | jdg_81710 |
stackexchange | llm_judgeable_groundtruth_similarity | 8052930 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are having two replica sets and one artiber node. In the replica set one is designated as primary and other as secondary. When one of them is shut down, automatically the other one takes over as primary. But under unforseen situations, when both the primary and secondary are down (also the arbiter) and when we restart them, the rs.status shows both as SECONDARY. None of them gets elected as primary. rs.status displays an error as below (NOTE: We tried changing the priority of pri/secondary nodes manually. We are using mongodb version 2.0 with --keyfile for authentication. All basic checks done for preliminary debugging but no clue so far). Pls suggest. SECONDARY> rs.status();{ "set" : "testdata1", "date" : ISODate("2011-11-08T15:30:14Z"), "myState" : 2, "members" : [ { "_id" : 0, "name" : "192.162.1.19:10001", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "optime" : { "t" : 1320763306000, "i" : 1 }, "optimeDate" : ISODate("2011-11-08T14:41:46Z"), "self" : true }, { "_id" : 1, "name" : "192.162.1.29:10002", "health" : 0, "state" : 8, "stateStr" : "(not reachable/healthy)", "uptime" : 0, "optime" : { "t" : 0, "i" : 0 }, "optimeDate" : ISODate("1970-01-01T00:00:00Z"), "lastHeartbeat" : ISODate("2011-11-08T15:30:13Z"), "pingMs" : 0, "errmsg" : "need to login" }, { "_id" : 2, "name" : "192.162.1.29:10003", "health" : 0, "state" : 8, "stateStr" : "(not reachable/healthy)", "uptime" : 0, "optime" : { "t" : 0, "i" : 0 }, "optimeDate" : ISODate("1970-01-01T00:00:00Z"), "lastHeartbeat" : ISODate("2011-11-08T15:30:13Z"), "pingMs" : 0, "errmsg" : "need to login" } ], "ok" : 1}Below of the log details which we have configured and getting the log details.===============================================================================[192.162.1.19]nohup mongod --rest --shardsvr --replSet testdata1 --port 10001 --oplogSize 50 --nojournal --keyFile /data/mongopwdkey/shardkey --dbpath /data/db/shardrepl_pri_1 > /tmp/shardrepl_pri_1.txt &[192.162.1.29]nohup mongod --rest --shardsvr --replSet testdata1 --port 10002 --oplogSize 50 --nojournal --keyFile /data/mongopwdkey/shardkey --dbpath /data/db/shardrepl_sec_1 > /tmp/shardrepl_sec_1.txt &nohup mongod --rest --shardsvr --replSet testdata1 --port 10003 --oplogSize 10 --nojournal --keyFile /data/mongopwdkey/shardkey --dbpath /data/db/shardrepl_arb_1 > /tmp/shardrepl_arb_1.txt &[192.162.1.19]mongo --port 10001conf = {_id : "testdata1",members : [{_id : 0, host : "192.162.1.19:10001", votes : 2},{_id : 1, host : "192.162.1.29:10002", votes : 1},{_id:2, host: "192.162.1.29:10003", votes : 3, arbiterOnly: true}]}rs.initiate(conf)rs.status()use admin;db.addUser("admin","admin");exit;# mongo -port 10001 admin -u admin -pMongoDB shell version: 2.0.1Enter password:connecting to: 127.0.0.1:10001/adminSECONDARY> rs.status();{ "set" : "testdata1", "date" : ISODate("2011-11-09T10:11:46Z"), "myState" : 2, "members" : [ { "_id" : 0, "name" : "192.162.1.19:10001", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "optime" : { "t" : 1320763306000, "i" : 1 }, "optimeDate" : ISODate("2011-11-08T14:41:46Z"), "self" : true }, { "_id" : 1, "name" : "192.162.1.29:10002", "health" : 0, "state" : 8, "stateStr" : "(not reachable/healthy)", "uptime" : 0, "optime" : { "t" : 0, "i" : 0 }, "optimeDate" : ISODate("1970-01-01T00:00:00Z"), "lastHeartbeat" : ISODate("2011-11-09T10:11:45Z"), "pingMs" : 0, "errmsg" : "need to login" }, { "_id" : 2, "name" : "192.162.1.29:10003", "health" : 0, "state" : 8, "stateStr" : "(not reachable/healthy)", "uptime" : 0, "optime" : { "t" : 0, "i" : 0 }, "optimeDate" : ISODate("1970-01-01T00:00:00Z"), "lastHeartbeat" : ISODate("2011-11-09T10:11:45Z"), "pingMs" : 0, "errmsg" : "need to login" } ], "ok" : 1}[192.162.1.29][root@dev_bmapp ~]# mongo -port 10002 admin -u admin -pMongoDB shell version: 2.0.1Enter password:connecting to: 127.0.0.1:10002/adminSECONDARY> rs.status();{ "set" : "testdata1", "date" : ISODate("2011-11-09T10:13:41Z"), "myState" : 2, "members" : [ { "_id" : 0, "name" : "192.162.1.19:10001", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "uptime" : 67411, "optime" : { "t" : 1320763306000, "i" : 1 }, "optimeDate" : ISODate("2011-11-08T14:41:46Z"), "lastHeartbeat" : ISODate("2011-11-09T10:13:40Z"), "pingMs" : 0 }, { "_id" : 1, "name" : "192.162.1.29:10002", "health" : 1, "state" : 2, "stateStr" : "SECONDARY", "optime" : { "t" : 1320763306000, "i" : 1 }, "optimeDate" : ISODate("2011-11-08T14:41:46Z"), "self" : true }, { "_id" : 2, "name" : "192.162.1.29:10003", "health" : 1, "state" : 5, "stateStr" : "STARTUP2", "uptime" : 67411, "optime" : { "t" : 0, "i" : 0 }, "optimeDate" : ISODate("1970-01-01T00:00:00Z"), "lastHeartbeat" : ISODate("2011-11-09T10:13:41Z"), "pingMs" : 0 } ], "ok" : 1}Primary Node Log [192.162.1.19]==============================Tue Nov 8 20:45:19 [initandlisten] MongoDB starting : pid=31771 port=10001 dbpath=/usr/db/shardrepl_pri_1 64-bit host=tedst.comTue Nov 8 20:45:19 [initandlisten] db version v2.0.1, pdfile version 4.5Tue Nov 8 20:45:19 [initandlisten] git version: 3a5cf0e2134a830d38d2d1aae7e88cac31bdd684Tue Nov 8 20:45:19 [initandlisten] build info: Linux bs-linux64.10gen.cc 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_41Tue Nov 8 20:45:19 [initandlisten] options: { dbpath: "/usr/db/shardrepl_pri_1", keyFile: "/data/mongopwdkey/shardkey", nojournal: true, oplogSize: 50, port: 10001, replSet: "testdata1", rest: true, shardsvr: true }Tue Nov 8 20:45:19 [initandlisten] waiting for connections on port 10001Tue Nov 8 20:45:19 [websvr] admin web console waiting for connections on port 11001Tue Nov 8 20:45:19 [rsStart] warning: getaddrinfo("localhost") failed: Name or service not knownTue Nov 8 20:45:19 [initandlisten] connection accepted from 127.0.0.1:44334 #1Tue Nov 8 20:45:19 [conn1] authenticate: { authenticate: 1, nonce: "ef53058aadd66cdb", user: "__system", key: "cbb8f221a881a90f8335edfb872a2300" }Tue Nov 8 20:45:19 [conn1] end connection 127.0.0.1:44334Tue Nov 8 20:45:19 [initandlisten] connection accepted from 127.0.0.1:44335 #2Tue Nov 8 20:45:19 [conn2] authenticate: { authenticate: 1, nonce: "86291a3e4c0c34e7", user: "__system", key: "2767d3377e700e50ab5a981a1c912516" }Tue Nov 8 20:45:19 [rsStart] replSet STARTUP2Tue Nov 8 20:45:19 [rsMgr] replSet total number of votes is even - add arbiter or give one member an extra voteTue Nov 8 20:45:19 [rsSync] replSet SECONDARYTue Nov 8 20:45:19 [rsHealthPoll] couldn't connect to 192.162.1.29:10002: couldn't connect to server 192.162.1.29:10002Tue Nov 8 20:45:19 [rsHealthPoll] couldn't connect to 192.162.1.29:10003: couldn't connect to server 192.162.1.29:10003Tue Nov 8 20:45:19 [rsHealthPoll] replSet info 192.162.1.29:10002 is down (or slow to respond): socket exceptionTue Nov 8 20:45:19 [rsHealthPoll] replSet member 192.162.1.29:10002 is now in state DOWNTue Nov 8 20:45:19 [rsMgr] replSet can't see a majority, will not try to elect selfTue Nov 8 20:45:19 [rsHealthPoll] replSet info 192.162.1.29:10003 is down (or slow to respond): socket exceptionTue Nov 8 20:45:19 [rsHealthPoll] replSet member 192.162.1.29:10003 is now in state DOWNTue Nov 8 20:45:34 [rsSync] waiting for 6 pings from other members before syncingTue Nov 8 20:45:45 [initandlisten] connection accepted from 192.162.1.29:39967 #3Tue Nov 8 20:45:45 [conn3] authenticate: { authenticate: 1, nonce: "fedd49f05b5d622a", user: "__system", key: "e935b883e38f43df80ec4d2f0dc44203" }Tue Nov 8 20:45:49 [rsSync] waiting for 6 pings from other members before syncingTue Nov 8 20:46:04 [rsSync] waiting for 6 pings from other members before syncingTue Nov 8 20:46:19 [clientcursormon] mem (MB) res:32 virt:338 mapped:80Tue Nov 8 20:46:19 [rsSync] waiting for 6 pings from other members before syncingTue Nov 8 20:46:32 [initandlisten] connection accepted from 127.0.0.1:59064 #4Tue Nov 8 20:46:32 [conn4] authenticate: { authenticate: 1.0, user: "admin", nonce: "5a933fe3ff7d0f19", key: "f5a9f4d430188708bc1bfc599ce0cfd8" }Tue Nov 8 20:46:34 [rsSync] waiting for 6 pings from other members before syncingTue Nov 8 20:46:49 [rsSync] waiting for 6 pings from other members before syncingTue Nov 8 20:47:04 [rsSync] waiting for 6 pings from other members before syncingTue Nov 8 20:47:19 [clientcursormon] mem (MB) res:48 virt:419 mapped:160Tue Nov 8 20:47:19 [rsSync] waiting for 6 pings from other members before syncingTue Nov 8 20:47:34 [rsSync] waiting for 6 pings from other members before syncingSecond Node Log [192.162.1.29]==============================Tue Nov 8 21:00:10 [initandlisten] MongoDB starting : pid=26348 port=10002 dbpath=/usr/db/shardrepl_sec_1 64-bit host=dev_bmappTue Nov 8 21:00:10 [initandlisten] db version v2.0.1, pdfile version 4.5Tue Nov 8 21:00:10 [initandlisten] git version: 3a5cf0e2134a830d38d2d1aae7e88cac31bdd684Tue Nov 8 21:00:10 [initandlisten] build info: Linux bs-linux64.10gen.cc 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_41Tue Nov 8 21:00:10 [initandlisten] options: { dbpath: "/usr/db/shardrepl_sec_1", keyFile: "/data/mongopwdkey/shardkey", nojournal: true, oplogSize: 50, port: 10002, replSet: "testdata1", rest: true, shardsvr: true }Tue Nov 8 21:00:10 [initandlisten] waiting for connections on port 10002Tue Nov 8 21:00:10 [websvr] admin web console waiting for connections on port 11002Tue Nov 8 21:00:10 [rsStart] warning: getaddrinfo("localhost") failed: Name or service not knownTue Nov 8 21:00:10 [initandlisten] connection accepted from 127.0.0.1:49277 #1Tue Nov 8 21:00:10 [conn1] authenticate: { authenticate: 1, nonce: "d70feca6820c2618", user: "__system", key: "5a722a819e43d1d7d71732206c39bac8" }Tue Nov 8 21:00:10 [conn1] end connection 127.0.0.1:49277Tue Nov 8 21:00:10 [initandlisten] connection accepted from 127.0.0.1:49278 #2Tue Nov 8 21:00:10 [conn2] authenticate: { authenticate: 1, nonce: "ec42a3430be2cea3", user: "__system", key: "b2d06709594afb1a747784a2a98aee68" }Tue Nov 8 21:00:10 [rsStart] replSet STARTUP2Tue Nov 8 21:00:10 [rsMgr] replSet total number of votes is even - add arbiter or give one member an extra voteTue Nov 8 21:00:10 [rsSync] replSet SECONDARYTue Nov 8 21:00:10 [rsHealthPoll] replSet info member 192.162.1.29:10003 is upTue Nov 8 21:00:10 [rsHealthPoll] replSet member 192.162.1.29:10003 is now in state STARTUP2Tue Nov 8 21:00:10 [rsHealthPoll] replSet info member 192.162.1.19:10001 is upTue Nov 8 21:00:10 [rsHealthPoll] replSet member 192.162.1.19:10001 is now in state SECONDARYTue Nov 8 21:00:10 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:10 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:11 [initandlisten] connection accepted from 192.162.1.29:45450 #3Tue Nov 8 21:00:11 [initandlisten] connection accepted from 192.168.1.19:56403 #4Tue Nov 8 21:00:16 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:22 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:26 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:28 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:34 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:40 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:41 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:46 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:52 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:56 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:00:58 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:01:04 [rsMgr] not electing self, 192.162.1.29:10003 would vetoTue Nov 8 21:01:10 [clientcursormon] mem (MB) res:32 virt:329 mapped:80Tue Nov 8 21:01:10 [rsMgr] not electing self, 192.162.1.29:10003 would vetoArbitor Log [192.162.1.29]========================Tue Nov 8 20:45:43 [initandlisten] MongoDB starting : pid=25602 port=10003 dbpath=/usr/db/shardrepl_arb_1 64-bit host=dev_bmappTue Nov 8 20:45:43 [initandlisten] db version v2.0.1, pdfile version 4.5Tue Nov 8 20:45:43 [initandlisten] git version: 3a5cf0e2134a830d38d2d1aae7e88cac31bdd684Tue Nov 8 20:45:43 [initandlisten] build info: Linux bs-linux64.10gen.cc 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_41Tue Nov 8 20:45:43 [initandlisten] options: { dbpath: "/usr/db/shardrepl_arb_1", keyFile: "/data/mongopwdkey/shardkey", nojournal: true, oplogSize: 10, port: 10003, replSet: "testdata1", rest: true, shardsvr: true }Tue Nov 8 20:45:43 [initandlisten] waiting for connections on port 10003Tue Nov 8 20:45:43 [websvr] admin web console waiting for connections on port 11003Tue Nov 8 20:45:43 [rsStart] warning: getaddrinfo("localhost") failed: Name or service not knownTue Nov 8 20:45:43 [initandlisten] connection accepted from 127.0.0.1:35243 #1Tue Nov 8 20:45:43 [conn1] authenticate: { authenticate: 1, nonce: "58de2a6831f1e8d9", user: "__system", key: "6a91a713f03914981bf02291ed2be857" }Tue Nov 8 20:45:43 [conn1] end connection 127.0.0.1:35243Tue Nov 8 20:45:43 [initandlisten] connection accepted from 127.0.0.1:35244 #2Tue Nov 8 20:45:43 [conn2] authenticate: { authenticate: 1, nonce: "5b004a2a3b5dc6aa", user: "__system", key: "6b558e1b9f108f1b0ddfa2186d037fd7" }Tue Nov 8 20:45:43 [rsStart] replSet STARTUP2Tue Nov 8 20:45:43 [rsMgr] replSet total number of votes is even - add arbiter or give one member an extra voteTue Nov 8 20:45:43 [rsHealthPoll] couldn't connect to 192.162.1.29:10002: couldn't connect to server 192.162.1.29:10002Tue Nov 8 20:45:43 [rsHealthPoll] replSet info 192.162.1.29:10002 is down (or slow to respond): socket exceptionTue Nov 8 20:45:43 [rsHealthPoll] replSet member 192.162.1.29:10002 is now in state DOWNTue Nov 8 20:45:43 [initandlisten] connection accepted from 192.168.1.19:58278 #3Tue Nov 8 20:45:45 [rsHealthPoll] replSet info member 192.162.1.19:10001 is upTue Nov 8 20:45:45 [rsHealthPoll] replSet member 192.162.1.19:10001 is now in state SECONDARYTue Nov 8 20:46:43 [clientcursormon] mem (MB) res:32 virt:254 mapped:80Tue Nov 8 20:51:43 [clientcursormon] mem (MB) res:32 virt:254 mapped:80Tue Nov 8 20:56:43 [clientcursormon] mem (MB) res:32 virt:254 mapped:80Tue Nov 8 21:00:10 [initandlisten] connection accepted from 192.162.1.29:51209 #4Tue Nov 8 21:00:10 [conn4] authenticate: { authenticate: 1, nonce: "645eb986e2df4ea6", user: "__system", key: "11937268ef824799913b556c48cbd146" }Tue Nov 8 21:01:43 [clientcursormon] mem (MB) res:32 virt:255 mapped:80Tue Nov 8 21:02:43 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:07:43 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:12:43 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:17:43 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:22:43 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:27:43 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:32:43 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:37:43 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:42:43 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:47:44 [clientcursormon] mem (MB) res:32 virt:319 mapped:80Tue Nov 8 21:52:44 [clientcursormon] mem (MB) res:32 virt:319 mapped:80"/tmp/shardrepl_arb_1.txt" 249L, 18928C
Now provide the response and nothing else.
| The accepted answer does not address the problem of 'activating' a virtualenv in a subprocess. If you start your application with a call to the python executable, like in your example it is actually very simple: you only have to explicitly point to the executable in the virtualenv. import subprocesssubprocess.Popen(["virtualenv1/bin/python", "my_script.py"])subprocess.Popen(["virtualenv2/bin/python", "my_other_script.py"]) will start the processes in the respective virtualenvs. Important To address the concerns voiced in the comments: If you want to run a subprocess and be sure to use the same interpreter that the current process is running in you have to use sys.executable . Also available: sys.exec_prefix to access the site-specific directory prefix where the platform-dependent Python files are installed. If you want a much more in depth discussion of this topic, have a look at this pull request . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8052930', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/912111/']} | jdg_81711 |
stackexchange | llm_judgeable_groundtruth_similarity | 86754 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There is some code which is GPL or LGPL that I am considering using for an iPhone project. If I took that code (JavaScript) and rewrote it in a different language for use on the iPhone would that be a legal issue? In theory the process that has happened is that I have gone through each line of the project, learnt what it is doing, and then reimplemented the ideas in a new language. To me it seems this is like learning how to implement something, but then reimplementing it separately from the original licence. Therefore you have only copied the algorithm, which arguably you could have learnt from somewhere else other than the original project. Does the licence cover the specific implementation or the algorithm as well? EDIT------ Really glad to see this topic create a good conversation. To give a bit more backing to the project, the code involved does some kind of audio analysis. I believe it is non-trivial to learn or implement, although I was prepared to embark on this task (I'm at the level where I can implement an FFT algorithm, and this was going to go beyond that.) It is a fairly low LOC script, so I didn't think it would be too hard to do a straight port. I really like the idea of rereleasing my port as well as using it in the application. I don't see any problem with that, and it would be a great way to give something back to the community. I was going to add a line about not wanting to discuss the moral issues, but I'm quite glad I didn't as it seems to have fired the debate a bit. I still feel a bit odd about using open source code to learn from. Does this mean that anything one learns from an open source project is not allowed to be used in a closed source project? And how long after or different does an implementation have to be to not be considered violation of the licence? Murky! EDIT 2 -------- Follow up question
Now provide the response and nothing else.
| I am not a lawyer. This is not legal advice. That said, taking every line of an application and changing it slightly for the sole purpose of circumventing copyright law is blatantly, obviously, creating a derived work with no plausible defense whatsoever. Even the boughtest judge and jury will definitely find against you if you ever get dragged into court. Just as a comparison: companies who do need to rewrite something for interoperability usually hire different sets of people to understand the source, and to create the port ("clean-room implementation"), so that no one can accuse them of creating a derived work. What you propose is the exact opposite. | {} | {'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/86754', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/1718/']} | jdg_81712 |
stackexchange | llm_judgeable_groundtruth_similarity | 531779 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a question about comparing a string with the empty string in Java. Is there a difference, if I compare a string with the empty string with == or equals ? For example: String s1 = "hi";if (s1 == "") or if (s1.equals("")) I know that one should compare strings (and objects in general) with equals , and not == , but I am wondering whether it matters for the empty string.
Now provide the response and nothing else.
| s1 == "" is not reliable as it tests reference equality not object equality (and String isn't strictly canonical). s1.equals("") is better but can suffer from null pointer exceptions. Better yet is: "".equals(s1) No null pointer exceptions. EDIT: Ok, the point was asked about canonical form . This article defines it as: Suppose we have some set S of objects, with an equivalence relation. A canonical form is given by designating some objects of S to be "in canonical form", such that every object under consideration is equivalent to exactly one object in canonical form. To give you a practical example: take the set of rational numbers (or "fractions" are they're commonly called). A rational number consists of a numerator and a denomoinator (divisor), both of which are integers. These rational numbers are equivalent: 3/2, 6/4, 24/16 Rational nubmers are typically written such that the gcd (greatest common divisor) is 1. So all of them will be simplified to 3/2. 3/2 can be viewed as the canonical form of this set of rational numbers. So what does it mean in programming when the term "canonical form" is used? It can mean a couple of things. Take for example this imaginary class: public class MyInt { private final int number; public MyInt(int number) { this.number = number; } public int hashCode() { return number; }} The hash code of the class MyInt is a canonical form of that class because for the set of all instances of MyInt, you can take any two elements m1 and m2 and they will obey the following relation: m1.equals(m2) == (m1.hashCode() == m2.hashCode()) That relation is the essence of canonical form. A more common way this crops up is when you use factory methods on classes such as: public class MyClass { private MyClass() { } public MyClass getInstance(...) { ... }} Instances cannot be directly instantiated because the constructor is private. This is just a factory method. What a factory method allows you to do is things like: Always return the same instance (abstracted singleton); Just create a new intsance with every call; Return objects in canonical form (more on this in a second); or whatever you like. Basically the factory method abstracts object creation and personally I think it would be an interesting language feature to force all constructors to be private to enforce the use of this pattern but I digress. What you can do with this factory method is cache your instances that you create such that for any two instances s1 and s2 they obey the following test: (s1 == s2) == s1.equals(s2) So when I say String isn't strictly canonical it means that: String s1 = "blah";String s2 = "blah";System.out.println(s1 == s2); // true But as others have poitned out you can change this by using: String s3 = new String("blah"); and possibly: String s4 = String.intern("blah"); So you can't rely on reference equality completely so you shouldn't rely on it at all. As a caveat to the above pattern, I should point out that controlling object creation with private constructors and factory methods doesn't guarantee reference equality means object equality because of serialization. Serialization bypasses the normal object creation mechanism. Josh Bloch covers this topic in Effective Java (originally in the first edition when he talked about the typesafe enum pattern which later became a language feature in Java 5) and you can get around it by overloading the (private) readResolve() method. But it's tricky. Class loaders will affect the issue too. Anyway, that's canonical form. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/531779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42155/']} | jdg_81713 |
stackexchange | llm_judgeable_groundtruth_similarity | 20009351 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When writing a function in C++ that takes a timeout as one of its arguments, what type should I use for the timeout argument itself? An example of such a function might be: void my_function(bool work_really_hard, timeout_type timeout){// Do stuff, until timeout is reached.} I have thought about using std::chrono::seconds for timeout_type , but that disallows using any timeout in the sub-second realm. When using std::chrono::nanoseconds instead, it is cumbersome to specify, say, 10 minutes. Any way to resolve this in a reasonable way, while keeping the function signature and calls neat and simple?
Now provide the response and nothing else.
| When using std::chrono::nanoseconds instead, it is cumbersome to specify, say, 10 minutes. Actually, it doesn't make it cumbersome in the least: #include <chrono>#include <iostream>void my_function(bool work_really_hard, std::chrono::nanoseconds timeout){ std::cout << timeout.count() << '\n';}int main(){ my_function(true, std::chrono::minutes(10));} Output: 600000000000 The only time you'll have trouble with nanoseconds is if you want to pass in something that won't exactly convert to nanoseconds , such as picoseconds , or duration<long, ratio<1, 3>> (1/3 second units). Update I intended this answer to be additional information for an already accepted answer that I thought was a good answer (by sehe). sehe recommended a templated solution, which I also consider fine. If you want to accept any std::chrono::duration , even one that you may have to truncate or round , then going with sehe's deleted answer is the way to go: template <typename Rep, typename Period>void my_function(bool work_really_hard, std::chrono::duration<Rep, Period> timeout){ // Do stuff, until timeout is reached. std::this_thread::sleep_for(timeout);} If for some reason you do not want to deal with templates and/or you are content with having your clients having to specify only units that are exactly convertible to std::chrono:nanoseconds , then using std::chrono:nanoseconds as I show above is also completely acceptable. All of the std::chrono "pre-defined" units: hoursminutessecondsmillisecondsmicrosecondsnanoseconds are implicitly convertible to nanoseconds , and will not involve any truncation or round off error. Overflow will not happen as long as you keep it within the two bright white lines (obscure reference to keeping your car in your own lane). As long as the duration is within +/- 292 years, you don't have to worry about overflow with these pre-defined units. The std-defined functions such as std::this_thread::sleep_for are templated as sehe suggests for exactly the reason of wanting to be interoperable with every chrono:duration imaginable (e.g. 1/3 of a floating-point femtosecond). It is up to the API designer to decide if they need that much flexibility in their own API. If I've now managed to confuse you instead of clarify, don't worry too much. If you choose to use nanoseconds , things will either work exactly, with no truncation or round off error, or the client will get a compile time error. There will be no run time error. void my_function(bool work_really_hard, std::chrono::nanoseconds timeout){ std::cout << timeout.count() << '\n';}intmain(){ using namespace std; using namespace std::chrono; typedef duration<double, pico> picoseconds; my_function(true, picoseconds(100000.25));}test.cpp:15:9: error: no matching function for call to 'my_function' my_function(true, picoseconds(100000.25)); ^~~~~~~~~~~test.cpp:4:10: note: candidate function not viable: no known conversion from 'duration<double, ratio<[...], 1000000000000>>' to 'duration<long long, ratio<[...], 1000000000>>' for 2nd argument void my_function(bool work_really_hard, std::chrono::nanoseconds timeout) ^1 error generated. And if the client gets a compile-time error, he can always use duration_cast to work around it: my_function(true, duration_cast<nanoseconds>(picoseconds(100000.25))); // Ok For further details, please see: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm Sweet update to the original code at the top of this answer. In C++1y, which we hope means C++14: using namespace std::literals;my_function(true, 10min); // also ok, is equal to 600000000000 nanoseconds Question: What would you recommend as a timeout of "infinity" (i.e. don't time out) I would first try to use an API that didn't take a timeout, and which implied "doesn't time out." For example condition_variable::wait . If I had control over the API, I would create such a signature without a timeout. Failing that, I would create a series a "large" chrono::durations : using days = std::chrono::duration< std::int32_t, std::ratio_multiply<std::chrono::hours::period, std::ratio<24>>>;using weeks = std::chrono::duration< std::int32_t, std::ratio_multiply<days::period, std::ratio<7>>>;using years = std::chrono::duration< std::int32_t, std::ratio_multiply<days::period, std::ratio<146097, 400>>>;using months = std::chrono::duration< std::int32_t, std::ratio_divide<years::period, std::ratio<12>>>; And then I would use one of these large durations in my call, for example: std::this_thread::sleep_for(years(3)); I would not try to push_things to the maximum (you might break the underlying assumptions the OS has made for example). Just arbitrarily pick something ridiculously large (like 3 years). That will catch your code reviewer's eye, and likely strike up an informative conversation. :-) Now available in video: https://www.youtube.com/watch?v=P32hvk8b13M :-) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20009351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2228370/']} | jdg_81714 |
stackexchange | llm_judgeable_groundtruth_similarity | 97304 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $G$ be a group acting on a locally finite tree $T$. Then the boundary $\partial T$ is a Cantor set on which $G$ acts by homeomorphisms (indeed by quasi-isometries under a suitable metric). However, even if $G$ is the full automorphism group of $T$, we can't get the full quasi-isometry group of $\partial T$, as the tree structure puts further restrictions on the action. What ways are known of identifying those group actions by homeomorphisms on the Cantor set which arise as actions on the boundary of a locally finite tree? Is there a nice algebraic description of $\mathrm{Aut}(T)$ as a subgroup of $\mathrm{Homeo}(\partial T)$? Edit: Here is an example of a sufficient criterion to show what I mean. Suppose that $G$ acts on the Cantor set $X$ by homeomorphisms, with finite orbits on the clopen subsets. Then one can produce a tree $T$ such that $G$ acts on $T$ with a global fixed point and $\partial T$ is $G$-homeomorphic to $X$. So an action with finite orbits on the clopen subsets is automatically 'arboreal' (we do not care about which tree appears, just that it exists).
Now provide the response and nothing else.
| Besides our paper that Alessandro mentions, Sageev, Whyte and I also have a paper "Maximally Symmetric Trees" which comes pretty close to doing what you ask. For certain trees it gives nice descriptions of $Aut(T)$ in terms of the representation into the quasi-isometry group $QI(T)$ (which, by the paper "Un groupe hyperbolique est determine par son bord" of Paulin, is characterized as the quasiconformal subgroup of $Homeo(\partial T)$ in the appropriate sense). Although our paper applies only indirectly to all the trees $T$ relevant to your question, it applies very directly to all those trees which are "maximally symmetric", meaning that any continuous, proper, cocompact monomorphism from $Aut(T)$ into $Aut(T')$ for some other tree $T'$ is an isomorphism. Furthermore, the paper describes an explicit way to "expand" any tree $T$ to a maximally symmetric tree $T'$ (equivalently, to embed $Aut(T)$ continuously, properly, and cocompactly in $Aut(T')$), and it gives an explicit enumeration of maximally symmetric trees. The main theorem says that $T$ is maximally symmetric if and only if $Aut(T)$ is a maximal uniform cobounded subgroup of $QI(T)$. In all of this, I should clarify by saying that the trees in question are always finite valence trees on which the automorphism group acts cocompactly. ADDED LATER: I'll admit that this characterization of $Aut(T)$ is more geometric than algebraic, but it at least has well-known analogues in quasi-isometric geometry. For instance it is the analogue of the fact that $Isom(H^3)$, the isometry group of hyperbolic 3-space, is a maximal uniform cobounded subgroup of $QI(H^3)$ (the latter being identified with $Conf(S^2)$, the group of conformal homeomorphisms of the 2-sphere at infinity). The difference is that up to conjugacy there is only one maximal uniform cobounded subgroup of $QI(H^3)$, whereas maximally symmetric trees give countably many different conjugacy classes of maximal uniform cobounded subgroups of $QI(T)$. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/97304', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4053/']} | jdg_81715 |
stackexchange | llm_judgeable_groundtruth_similarity | 26294360 |
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 line chart based on a simple list of numbers. By default the x-axis is just the an increment of 1 for each value plotted. I would like to be a percentage instead but can't figure out how. So instead of having an x-axis from 0 to 5, it would go from 0% to 100% (but keeping reasonably spaced tick marks. Code below. Thanks! from matplotlib import pyplot as pltfrom mpl_toolkits.axes_grid.axislines import Subplotdata=[8,12,15,17,18,18.5]fig=plt.figure(1,(7,4))ax=Subplot(fig,111)fig.add_subplot(ax)plt.plot(data)
Now provide the response and nothing else.
| The code below will give you a simplified x-axis which is percentage based, it assumes that each of your values are spaces equally between 0% and 100%. It creates a perc array which holds evenly-spaced percentages that can be used to plot with. It then adjusts the formatting for the x-axis so it includes a percentage sign using matplotlib.ticker.FormatStrFormatter . Unfortunately this uses the old-style string formatting, as opposed to the new style, the old style docs can be found here . import matplotlib.pyplot as pltimport numpy as npimport matplotlib.ticker as mtickdata = [8,12,15,17,18,18.5]perc = np.linspace(0,100,len(data))fig = plt.figure(1, (7,4))ax = fig.add_subplot(1,1,1)ax.plot(perc, data)fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'xticks = mtick.FormatStrFormatter(fmt)ax.xaxis.set_major_formatter(xticks)plt.show() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26294360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2827060/']} | jdg_81716 |
stackexchange | llm_judgeable_groundtruth_similarity | 9052482 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What's the best way of saving sensitive data to a local file in Windows 8? I'm developing a C# application that needs to store oAuth tokens/passwords. I've heard it was common in .NET to encrypt/decrypt data, but I don't have any experience with those mechanics. Is encryption still recommended/neccesary given that Windows 8 apps have their own personal/protected storage area similar to Windows Phone? Also, doesn't encrypting/decrypting each time when you request the data causes a performance issue? (would it be better to write a custom/lite algorithm?)
Now provide the response and nothing else.
| UPDATE: Please be aware that while modern/metro apps are restricted from poking at each other's stuff, desktop applications will have unrestricted access to all data stored through these APIs. See http://www.hanselman.com/blog/SavingAndRetrievingBrowserAndOtherPasswords.aspx which includes code demonstrating this. Win8 has a new API called PasswordVault that's designed for taking care of all these hard problems for you. Really easy to use, secure, and can be configured by users to roam between their machines so they only have to enter credentials once. I've successfully used this for OAuth tokens Retrieving credentials (note the stupid exception that WinRT raises... they really should just return null): const string VAULT_RESOURCE = "[My App] Credentials";string UserName { get; set; };string Password { get; set; };var vault = new PasswordVault();try{ var creds = vault.FindAllByResource(VAULT_RESOURCE).FirstOrDefault(); if (creds != null) { UserName = creds.UserName; Password = vault.Retrieve(VAULT_RESOURCE, UserName).Password; }}catch(COMException) { // this exception likely means that no credentials have been stored} Storing credentials: vault.Add(new PasswordCredential(VAULT_RESOURCE, UserName, Password)); Removing credentials (when the user clicks the logout button in your app): vault.Remove(_vault.Retrieve(VAULT_RESOURCE, UserName)); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9052482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/758070/']} | jdg_81717 |
stackexchange | llm_judgeable_groundtruth_similarity | 2052000 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking for a some clarification to the proof of the Bertrand's ballot problem . I understood the the trick with swapping B(A) for A(B) in every position up to the first tie. What I don't quite get is why the probability of beginning a sequence with B expressed as $\frac{b}{a+b}$ represents the probability of getting at least one tie when starting with B. It seems those are two different things. Secondly how does it account for many combinations giving the sequencies with a tie. Can anybody explain this link please?
Now provide the response and nothing else.
| The argument given at your link shows that there is a bijection between sequences that reach a tie at some point and sequences that begin with $B$ . Thus, there are exactly as many sequences that reach a tie at some point as there are sequences that begin with $B$ . Let $n$ be the number of sequences that reach a tie at some point (and hence also the number that begin with $B$ ). There are $\binom{a+b}a$ sequences altogether, since a sequence is completely determined once you know the $a$ positions of the $A$ s, so the probability that a randomly chosen sequence reaches a tie at some point is $\frac{n}{\binom{a+b}a}$ , and this is also the probability that a randomly chosen sequence begins with $B$ . But we can directly evaluate that probability as $\frac{b}{a+b}$ , since each sequence has $b$ $B$ s and $a$ $A$ s. Thus $$\begin{align*}\operatorname{Pr}(\text{there is a tie at some point})&=\frac{n}{\binom{a+b}a}\\&=\operatorname{Pr}(\text{sequence starts with }B)\\&=\frac{b}{a+b}\;.\end{align*}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2052000', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/255381/']} | jdg_81718 |
stackexchange | llm_judgeable_groundtruth_similarity | 1117 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Are there any benefits of a self signed certificate on a live site? I know in IIS 7 you have the ability to self sign a certificate and I was wondering if using that as a precurser to buying one from a CA would be a good idea. Do you get the same encryption benefits that you get from a CA signed cert or am I confusing terms? (running off the https protocol)
Now provide the response and nothing else.
| The encryption is not a property of the certificate or where it is signed from. The benefit you get from a CA signed cert is that it is automatically trusted by web browsers (and other SSL-aware applications). A self-signed certificate will pop up a warning that the certificate is not trusted. In more recent browsers, such as FireFox 3, the default action is to refuse to show the page and the user has to take deliberate actions to enable use of a self-signed (or expired, for that matter) certificate. If you can talk to everyone who will use the web page (if this is for your family only, for example), this isn't a problem. Tell them to expect that warning and how to handle it in their browser and it's a one-time issue. However, if this is for any use that requires anything approaching real security, you probably want a true, signed, not self-signed certificate. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/1117', 'https://serverfault.com', 'https://serverfault.com/users/710/']} | jdg_81719 |
stackexchange | llm_judgeable_groundtruth_similarity | 203408 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following SHA256 wrapper. public static string SHA256(string plainText) { StringBuilder sb = new StringBuilder(); SHA256CryptoServiceProvider provider = new SHA256CryptoServiceProvider(); var hashedBytes = provider.ComputeHash(Encoding.UTF8.GetBytes(plainText)); for (int i = 0; i < hashedBytes.Length; i++) { sb.Append(hashedBytes[i].ToString("x2").ToLower()); } return sb.ToString(); } Do I want to be testing it? If so, what do you recommend? My thought process is as follows: What logic is there here. The answer is my for loop and ToString("x2" ) so from my understanding I want to be testing this part? I can assume Encoding.UTF8.GetBytes(plainText ) works. Correct assumption?I can assume SHA256CryptoServiceProvider.ComputeHash() works. Correct assumption? I want to be only testing my logic. In this case is limited to the printing of hex encoded hash. Correct? Thanks. EDIT: Update method based on MainMa's excellent answer: /// <summary> /// Returns a SHA256 hash of the plain text. /// </summary> /// <param name="plainText">The pain text.</param> /// <returns>The hash.</returns> public static string SHA256(string plainText) { if (string.IsNullOrWhiteSpace(plainText)) throw new ArgumentNullException("The plain text cannot be empty."); StringBuilder sb = new StringBuilder(); Byte[] hashedBytes; using (SHA256CryptoServiceProvider sha256Provider = new SHA256CryptoServiceProvider()) { hashedBytes = sha256Provider.ComputeHash(Encoding.UTF8.GetBytes(plainText)); } foreach(Byte b in hashedBytes) { sb.Append(b.ToString("x2").ToLower(CultureInfo.InvariantCulture)); } return sb.ToString(); }
Now provide the response and nothing else.
| Note: a more detailed discussion of the code is available at my website. It covers nearly all the points covered here, and shows, step by step, how this piece of code can be refactored into a piece of reliable software. First, you may want to test the edge cases. What if plainText is null? You don't check the inputs. Is this intentional, i.e. you rely on GetBytes to throw ArgumentNullException in your place? Is this a mistake? What if plainText is long, and by long, I mean the maximum allowed by Windows? This is a complicated case, since unit testing it is not obvious (including in terms of performance and memory consumption: nobody wants their unit tests taking all memory available), but you still should consider it. Hint: the easiest and fastest way to handle this case is to specify the maximum supported length in the product requirements, and then enforce this limit at input validation step. What if plainText is an empty string? What if you are calling the method plenty of times? You don't dispose SHA256CryptoServiceProvider , despite the fact that you should, which means that sooner or later, it will fail more or less unpredictably. This is another case where unit testing is complicated/practically impossible. Second, you're right, you can rely on the methods from .NET Framework and assume they are correctly implemented. This means that you have to test your logic and the way you use those methods: Write a simple test which calls the method with "Hello World!" as input. Take any non-.NET language: JavaScript, Python, whatever. Compute the SHA256 hash with this language and hardcode the result in your unit test. Compare. Analyse your code (note: in TDD, you don't do that: you write tests from the use cases, not the actual code). Such analysis should give you the overall view of the flow: where are the conditions, how do you exit the loops, are there guard clauses, etc. The actual flow is easy: a sequence of calls to different methods, then a for . Aside the missing using , the sequence of calls can create a risk of using a variable while it is null . For example: var product = this.GetProductById(productId);var category = product.GetCategory(); is wrong, unless there is a guarantee that GetProductById cannot return null . The previous piece of code should have been: var product = this.GetProductById(productId);if (product == null){ // Handle the situation and either throw an exception or prematurely return/break.}var category = product.GetCategory(); or: var product = this.GetProductById(productId);Debug.Assert( product != null, "The null result is unexpected from ProductsManager.GetProductById method.");var category = product.GetCategory(); or: var product = this.GetProductById(productId);Contract.Assume(product != null);var category = product.GetCategory(); In your case, there are only constructors, so you don't have to care about null references. for that you erroneously use (it should have been foreach ) is another point to consider. Is the loop made correctly? Do you have to do i < hashedBytes.Length or i <= hashedBytes.Length ? When you access the hashedBytes by index, are you sure that the index is never out of range? Could the length be bigger than int.MaxValue ? What would happen? Finally, you're using both byte.ToString and ToLower without specifying the culture. Since you don't say neither that you're expecting the InvariantCulture to be used, it may indicate that you simply forgot to clearly indicate your intent. Both methods use the current culture. This means that you have also to unit test cases where the current culture is not en-US , since the final result of your SHA256 method depends on it (or use formal methods to show that the result would be the same for any culture). Moreover, byte.ToString("x2") already produces a lowercase string. Converting a lowercase string to lowercase is not needed. Always get rid of the code you don't need. Conclusion: Your assumption that you can rely on methods from .NET Framework is true. However, the way you use them should be unit tested. As you can see, in this very short method with simple logic , there is a potential severe bug which will appear sooner or later when somebody will start to modify this method. by not disposing objects properly, created a bug which will be very hard to debug later , made it error prone by wrongly using for when foreach was expected, made it potentially vulnerable by not checking your inputs (while this is a public method), made it difficult to guess which exceptions may be thrown by this method, made its behavior very random when it comes to edge cases (strings too long, null , etc.) You could have avoided few of those issues with severe testing, but testing alone is not enough. Using other techniques, such as informal code reviews or static checking should be systematic and cover if not all, at least most non-CRUD code you write. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/203408', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/59420/']} | jdg_81720 |
stackexchange | llm_judgeable_groundtruth_similarity | 74009 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I have a very simple question, because I basically just need to know if a certain train of thought I've had is correct. My reference is Liu's book "Algebraic Geometry and Arithmetic Curves", in particular Proposition 8.1.15, and of course Hartshorne. Consider the following situation: Let $f:W\to X$ be a morphism of locally Noetherian schemes. Let $\mathcal{I}$ be a quasi-coherent sheaf of ideals on $X$. Now, I will only require $\mathcal{K}\supseteq(f^{-1}\mathcal{I})\mathcal{O}_W=:\mathcal{J}$ to be a quasi-coherent sheaf of ideals on $W$ which contains the inverse image ideal sheaf. Let $\pi:\widetilde{X}\to X$ and $\rho:\widetilde{W}\to W$ denote the blowing-ups of $X$ and $W$ with respective centers $\mathcal{I}$ and $\mathcal{K}$. Then there exists a map $\widetilde{f}:\widetilde{W}\to\widetilde{X}$ such that $\begin{matrix}\widetilde{W} & \xrightarrow{\quad\widetilde{f}\quad} & \widetilde{X} \\\hphantom{\scriptstyle\rho} \downarrow {\scriptstyle\rho} & {\scriptstyle\circlearrowleft} & \hphantom{\scriptstyle\pi} \downarrow {\scriptstyle\pi} \\W & \xrightarrow{\quad f\quad} & X\end{matrix}$ This can be shown exactly as in Liu's book, but the more important point is this: It would seem to me that $(\rho^{-1}\mathcal{J})\mathcal{O}_{\widetilde{W}}$ is an invertible sheaf on $\widetilde{W}$, so I would also get uniqueness of $\widetilde{f}$. My question is very simple: Have I missed anything or made some mistake? I am asking because both Hartshorne and Liu require $\mathcal{K}=\mathcal{J}$ in their respective propositions, but I see no reason why it could not be weakened to $\mathcal{K}\supseteq\mathcal{J}$.
Now provide the response and nothing else.
| Suppose $f={\rm Id}_X$, $X={\bf A}^3_{\bf C}$ (affine space of dimension $3$ over the complex numbers). Suppose that $\cal I$ is the sheaf of ideals of a smooth curve going through $0$ and that $\cal K$ is the sheaf of ideals of the point $0$ in ${\bf A}^3_{\bf C}$. Then the pull-back of ${\cal J}={\cal I}$ to $\widetilde{W}$ defines a subscheme $Z$ of $\widetilde{W}$ and the dimension of the intersection of $Z$ with the complement of the exceptional divisor of $\widetilde{W}$ is of dimension $1$ and thus $Z$ is not a Cartier divisor (ie $(\rho^{-1}J){\cal O}_{\widetilde{W}}$ is not an invertible sheaf). | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/74009', 'https://mathoverflow.net', 'https://mathoverflow.net/users/9947/']} | jdg_81721 |
stackexchange | llm_judgeable_groundtruth_similarity | 227830 |
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 ran into the following problem and its solution: The integration by parts formula $$\int_{a}^{b}u\frac{dv}{dx}\,dx=uv\bigg|_{a}^{b}-\int_{a}^{b}v\frac{du}{dx}\,dx$$ is known to be valid for functions $u(x)$ and $v(x)$, which are continuous and have continuous first derivatives. However, we will assume that $u$, $v$, $du/dx$, and $dv/dx$ are continuous only for $a\leqslant x\leqslant c$ and $c\leqslant x \leqslant b$; we assume that all quantities may have a jump discontinuity at $x=c$. (a) Derive an expression for $\int_{a}^{b}u\,dv/dx\,dx$ in terms of $\int_{a}^{b}v\,du/dx\,dx$. $$\int_{a}^{b}u\frac{dv}{dx}\,dx=uv\bigg|_{a}^{b}+uv\bigg|_{c^+}^{c^-}-\int_{a}^{b}v\frac{du}{dx}\,dx.$$ Could anyone clarify to me how this was obtained? Edit : Following the advice of Muphrid , I obtained the following: $$\begin{align}\int_{a}^{c^-}u\frac{dv}{dx}\,dx+\int_{c^+}^{b}u\frac{dv}{dx}\,dx&=uv\bigg|_{a}^{c^-}-\int_{a}^{c^-}v\frac{du}{dx}\,dx+uv\bigg|_{c^+}^{b}-\int_{c^+}^{b}v\frac{du}{dx}\,dx,\\\int_{a}^{b}u\frac{dv}{dx}\,dx&=\color{red}{uv\bigg|_{a}^{c^-}+uv\bigg|_{c^+}^{b}}-\int_{a}^{b}v\frac{du}{dx}\,dx.\end{align}$$ What is the rule for combining the terms in red?
Now provide the response and nothing else.
| In response to your work from Muphrid: $$\begin{align} \color{red}{uv\bigg|_{a}^{c^-}+uv\bigg|_{c^+}^{b}} &= uv(c^-) - uv(a) + uv(b) - uv(c^+) \\&= uv(c^-) - uv(c^+) + uv(b) - uv(a) \\&= uv\bigg|_{c^+}^{c^-} +uv\bigg|^b_a\end{align}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/227830', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25134/']} | jdg_81722 |
stackexchange | llm_judgeable_groundtruth_similarity | 36698955 |
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 2 Hibernate entities: Kennel and Dog . I would like to write a method that determines what the "oldest" Kennel in my database is. This would be trivial if the Kennel Entity had a "created" or similar column, but it does not . However, in my Dog entity there is a born field (DateTime) that maps to the BORN column . Using this Dog field I would like to define the oldest Kennel by which has the oldest dog in it . A Kennel can have many dogs but a dog can only have one kennel. How can I do this? Entities: Kennel: @Entity@Table(name = "KENNEL")public class Kennel{ @Id private String id; @Column(name = "LOCATION") private String location;} Dog: @Entity@Table(name = "DOG")public class Dog{ @Id private String id; @Column(name = "NAME") private String name; @Column(name = "BORN") private DateTime created; @Column(name= "KENNEL_ID) private String kennelId; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "KENNEL_ID") private Kennel kennel;}
Now provide the response and nothing else.
| Solved : There are two parameters taken by aws-sdk : Expression Attribute Name Expression Attribute Value both provide the functionality of replacing placeholders used in the attributes list.Here by Attributes it is a bit ambiguous, where I got confused.The wizards over at aws mean both the key and value when they use the term attribute. So in a case where you want to use a reserved key word as a key attribute use the Expression Attribute Name parameter with #(pound) to denote the placeholder. Similarly where you want to use placeholders for value attribute use the Expression Attribute Value parameter with :(colon) to denote the placeholder. So finally my code (working) looks like this : var param = { TableName: "faasos_orders", FilterExpression: "#order_status = :delivered OR #order_status = :void OR #order_status = :bad", ExpressionAttributeValues: { ":delivered": "delivered", ":void": "void", ":bad": "bad" }, ExpressionAttributeNames: { "#order_status": "status" }}; dynamodb.scan(param, function (err, data) {....}); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36698955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5528751/']} | jdg_81723 |
stackexchange | llm_judgeable_groundtruth_similarity | 3473130 |
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:
$\int \frac{dx}{\sin^4(x)}$ I tried: $$\int \frac{dx}{\sin^4(x)} = \int \frac{dx}{(\frac{1+\cos(2x)}{2})^2} = 4\int\frac{dx}{(1+\cos(2x))^2}$$ What do I do next?
Now provide the response and nothing else.
| You could continue that route, or $$\int \frac{1}{\sin^4 x}dx = \int \csc^4 x dx = \int \csc^2 x + \cot^2 x \csc^2 x \: dx$$ then let $u = \cot x$ $$\implies -\int 1 + u^2 \: du = -u -\frac{1}{3}u^3 + C = -\cot x - \frac{1}{3}\cot^3 x + C$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3473130', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/373635/']} | jdg_81724 |
stackexchange | llm_judgeable_groundtruth_similarity | 13732451 |
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 my portfolio website for my photography business. I've built the site so the portfolios scroll horizontally. This is what I have so far. http://www.dscottclarkphoto.com/portfolio/adventure/adventure.html I would like to be able to include arrows that when clicked jump the viewer to the next photograph. I tried using what was demonstrated in this: jQuery: jump to next <section> I saved the Javascript into it's own file named jump.js. <script src="../jquery.js"></script><script type="text/javascript" src="../jump.js"></script></head><div id="images"> <ul> <li><section id="1"><img src="../space.jpg" /></section></li> <li><section id="2"><img src="adventure/adv-01.jpg" /></section></li> <li><section id="3"><img src="adventure/adv-02.jpg" /></section></li> <li><section id="4"><img src="adventure/adv-03.jpg" /></section></li> <li><section id="5"><img src="adventure/adv-04.jpg" /></section></li> </ul> I also tried saving the sample and it is not behaving correctly either. </div> Are there any suggestions on how to make this work or a better method?
Now provide the response and nothing else.
| I've run a website with similar configuration for many months, with zero down time. I've had a look at your config, and it looks ok. That being said, I did my config quite a while ago. I would consider reducing pm.max_requests = 10000 to something more reasonable like pm.max_requests = 500 . This just means "don't use each instance for more than X number of requests". It is good not to have this number too high, because doing so gives you resilience with respect of possible PHP engine bugs. I think the real problem is most likely in your PHP scripts. It's hard to say without knowing more. EDIT:Consider uncommenting ;request_terminate_timeout = 0 and setting it to something like request_terminate_timeout = 20 . Your scripts will then be required to complete within 20 seconds. You will most likely see a change in behaviour, but I think your site might stay live. That would indicate a PHP script error. EDIT2: My own php-fpm config is as follows: [example.com]listen = /var/run/sockets/example.com.socketuser = www-datagroup = www-datapm = dynamicpm.start_servers = 5pm.max_children = 15pm.min_spare_servers = 5pm.max_spare_servers = 10pm.max_requests = 500php_flag[expose_php] = offphp_flag[short_open_tag] = on EDIT3: I spotted something unexpected in your nginx config, but it may be nothing. You are using fastcgi_ignore_client_abort on; which causes problems in worker processes under older versions of nginx. I haven't seen this problem myself, since I am running a custom compile of a recent version. Here's the description of the problem on the nginx site: In 1.0.2 POST requests are not handled correctly when fastcgi_ignore_client_abort is set to on which can lead to workers processes segfaulting. Switching fastcgi_ignore_client_abort back to default (off) should resolve this issue. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13732451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1880392/']} | jdg_81725 |
stackexchange | llm_judgeable_groundtruth_similarity | 37000407 |
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 developed a POS like application and during testing with 2 PCs I didn't encounter any problems with the speed. It's just a simple LAN cable setup between 2 computers. But when I deployed it in a client, it ran slow. The client has 1 PC serving as the admin and the main server, and there are 2 more PCs serving as the cashier. All connected in a router. The cashiers are connected to the admin's PC (main server) to retrieve, insert, update and delete data. I just want to ask if there are processes that needs to be done in MySQL or are there anything wrong with my codes when connecting to the database. Here's my sample code for connecting to the database, I doubt having problems with it as this has been the standard in connecting to a database and adding records. Just in case I might bore you with codes, you can simply jump to the second code I posted, I have a comment there asking if the initialization of my class is correct. Thanks everyone! class DBConnection{ private MySqlConnection connection; private MySqlCommand cmd; private MySqlDataReader dr; private DataTable tbl; private MySqlDataAdapter da; private DataSet ds; private string connectionString; private string server; private string database; private string uid; private string password; private frmNotifOk myNotification; public DBConnection() { Initialize(); } private void Initialize() { server = "CASHIER"; database = "sampledb"; uid = "root"; password = "samplepassword"; connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";"; connection = new MySqlConnection(connectionString); } private bool OpenConnection() { try { connection.Open(); return true; } catch (MySqlException ex) { switch (ex.Number) { case 0: MessageBox.Show("Cannot connect to server."); break; } return false; }}private void CloseConnection(){ try { connection.Close(); } catch (MySqlException ex) { MessageBox.Show("Error: " + ex.Message); }}public void AddRecord(String DBQuery, bool showNotif){ string query = DBQuery; bool notify = showNotif; try { if (this.OpenConnection() == true) { cmd = new MySqlCommand(query, connection); cmd.ExecuteNonQuery(); if (notify) { MessageBox.Show("Item successfully added."); } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } finally { this.CloseConnection(); }} And finally, here's how I use the method in a form: public partial class frmNewCashier : Form{ private DBConnection dbConnect; string sampleDataSource= "SELECT * FROM SampleTable"; public frmNewCashier() { InitializeComponent(); //Is this the correct place of initializing my DBConnection class? dbConnect = new DBConnection(); } private void frmCashier_Load(object sender, EventArgs e) { try { dgvSearchItems.DataSource = dbConnect.DatabaseToDatagrid(dgvSearchItemsDataSource); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } }} I put the initialization of DBConnection class in public frmNewCashier() , is this the correct place or should I put it in Load event or somewhere? I'm thinking if this has bearing to the slowness of database. Aside from this question, do you know anything that I might have missed that causes the slowness?
Now provide the response and nothing else.
| Actually there might be several such threads, and other threads too, all started in OnStart and shut down/joined in OnStop. On a side note, it's usually simpler to have a single "master" thread that will start/join all the others. Then OnStart / OnStop just deals with the master thread. If I want to instead do this sort of thing in an async/await based Windows Service, it seems like I could have OnStart create cancelable tasks but not await (or wait) on them, and have OnStop cancel those tasks and then Task.WhenAll().Wait() on them. That's a perfectly acceptable approach. If I understand correctly, the equivalent of the "WorkerThreadFunc" shown above might be something like: Probably want to pass the CancellationToken down; cancellation can be used by synchronous code, too: private async Task WorkAsync(CancellationToken cancel){ while (true) { DoSomething(cancel); await Task.Delay(10, cancel).ConfigureAwait(false); }} Question #1: Uh... right? I am new to async/await and still trying to get my head around it. It's not wrong , but it only saves you one thread on a Win32 service, which doesn't do much for you. Question #2: That is bad? I shouldn't be doing synchronous I/O within a Task in an async/await-based program? Because it ties up a thread from the thread pool while the I/O is happening, and threads from the thread pool are a highly limited resource? Please note that I might have dozens of such Workers going simultaneously to different pieces of hardware. Dozens of threads are not a lot. Generally, asynchronous I/O is better because it doesn't use any threads at all, but in this case you're on the desktop, so threads are not a highly limited resource. async is most beneficial on UI apps (where the UI thread is special and needs to be freed), and ASP.NET apps that need to scale (where the thread pool limits scalability). Bottom line: calling a blocking method from an asynchronous method is not bad but it's not the best , either. If there is an asynchronous method, call that instead. But if there isn't, then just keep the blocking call and document it in the XML comments for that method (because an asynchronous method blocking is rather surprising behavior). I am getting the idea that it's bad from articles like Stephen Cleary's "Task.Run Etiquette Examples: Don't Use Task.Run for the Wrong Thing", but that's specifically about it being bad to do blocking work within Task.Run. Yes, that is specifically about using Task.Run to wrap synchronous methods and pretend they're asynchronous. It's a common mistake; all it does is trade one thread pool thread for another. Assuming that's bad too, then if I understand correctly I should instead utilize the nonblocking version of DoSomething (creating a nonblocking version of it if it doesn't already exist) Asynchronous is better (in terms of resource utilization - that is, fewer threads used), so if you want/need to reduce the number of threads, you should use async. Question #3: But... what if DoSomething is from a third party library, which I must use and cannot alter, and that library doesn't expose a nonblocking version of DoSomething? It's just a black box set in stone that at some point does a blocking write to a piece of hardware. Then just call it directly. Maybe I wrap it and use TaskCompletionSource? No, that doesn't do anything useful. That just calls it synchronously and then returns an already-completed task. But that seems like it's just pushing the issue down a bit further rather than resolving it. WorkAsync() will still block when it calls WrappedDoSomething(), and only get to the "await" for that after WrappedDoSomething() has already completed the blocking work. Right? Yup. Given that (if I understand correctly) in the general case async/await should be allowed to "spread" all the way up and down in a program, would this mean that if I need to use such a library, I essentially should not make the program async/await-based? I should go back to the Thread/WorkerThreadFunc/Thread.Sleep world? Assuming you already have a blocking Win32 service, it's probably fine to just keep it as it is. If you are writing a new one, personally I would make it async to reduce threads and allow asynchronous APIs, but you don't have to do it either way. I prefer Task s over Thread s in general, since it's much easier to get results from Task s (including exceptions). The " async all the way" rule only goes one way. That is, once you call an async method, then its caller should be async , and its caller should be async , etc. It does not mean that every method called by an async method must be async . So, one good reason to have an async Win32 service would be if there's an async-only API you need to consume. That would cause your DoSomething method to become async DoSomethingAsync . What if an async/await-based program already exists, doing other things, but now additional functionality that uses such a library needs to be added to it? Does that mean that the async/await-based program should be rewritten as a Thread/etc.-based program? No. You can always just block from an async method. With proper documentation so when you are reusing/maintaining this code a year from now, you don't swear at your past self. :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37000407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1290172/']} | jdg_81726 |
stackexchange | llm_judgeable_groundtruth_similarity | 29297 |
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
While going through some problems as part of self-study I encountered the following True/False question: Q. Steven only consumes two goods: $X$ and $Y$ . If $X$ is a Giffen good for Steven, then $Y$ must be a normal good for Steven. The given answer is True. I am unable to understand why it is necessary for the other good to be normal. Why can't it be inferior/Giffen?
Now provide the response and nothing else.
| Reason: Both goods cannot be inferior. Let's say originally you consume $x$ and $y$ . So your budget constraint looks like $$p_x x + p_y y = I.$$ If both X and Y are inferior, when income goes down from $I_0$ to $I'$ , the quantity demanded for both has to go up (by definition) from $x$ to $x'$ and $y$ to $y'$ . This implies $$p_x x' + p_y y' = I' < I = p_x x + p_y y.$$ This is a contradiction, since $x' > x$ and $y' > y$ . Your question is a bit more specific. But since a Giffen good must be inferior, this answers your question as well. | {} | {'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/29297', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/21361/']} | jdg_81727 |
stackexchange | llm_judgeable_groundtruth_similarity | 231060 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Delphi RAD libraries implement many thread friendly objects in a way which forces one to declare another object for storing the reference returned by that object's locking method. The object thus essentially encapsulates the prime object which is returned on locking. For example; List := ThreadList.Unlocklist;// do something with ListThreadList.LockList; Why is this approach taken? Why is inheriting from the prime object, adding the locking object, overriding constructors and destructors, discouraged? For example the following implementation adds a TMREWSync to a list; IMREWS = interface ['{5B6DE5FA-847B-42D5-8BF4-9EB20A452C54}'] procedure BeginRead; function BeginWrite: Boolean; procedure EndRead; procedure EndWrite;end;TThreadList = class ( TList, IMREWS )private FLock : TMREWSync;public constructor Create; destructor Destroy; override; property Lock : TMREWSync read FLock implements IMREWS;end;constructor TThreadList.Create;begin FLock := TMREWSync.Create; inherited;end;destructor TThreadList.Destroy;begin inherited; FLock.Free;end;// Usage:ThreadList.BeginWrite;// Do something with ThreadListThreadList.EndWrite;
Now provide the response and nothing else.
| In my experience, its best to throw exceptions at the point where the errors occur. You do this because it's the point where you know the most about why the exception was triggered. As the exception unwinds back up the layers, catching and rethrowing is a good way to add additional context to the exception. This can mean throwing a different type of exception, but include the original exception when you do this. Eventually the exception will reach a layer where you are able to make decisions on code flow (e.g a prompt the user for action). This is the point where you should finally handle the exception and continue normal execution. With practice and experience with your code base it becomes quite easy to judge when to add additional context to errors, and where it's most sensible to actually, finally handle the errors. Catch → Rethrow Do this where you can usefully add more information that would save a developer having to work through all the layers to understand the problem. Catch → Handle Do this where you can make final decisions on what is an appropriate, but different execution flow through the software. Catch → Error Return Whilst there are situations where this is appropriate, catching exceptions and returning an error value to the caller should be considered for refactoring into a Catch → Rethrow implementation. | {} | {'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/231060', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/119287/']} | jdg_81728 |
stackexchange | llm_judgeable_groundtruth_similarity | 4674097 |
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 part of a PHP application which assess a long string input by the user, and extracts a number which always begins 20 characters into the string the user supplies. The only problem is that I don't know how long the number for each user will be, all I do know is the end of the number is always followed by a double quote ("). How can I use the PHP substring function to extract a substring starting form a specific point, and ending when it hits a double quote? Thanks in advance.
Now provide the response and nothing else.
| You can use strpos to get the first position of " from the position 20 on: $pos = strpos($str, '"', 20); That position can then be used to get the substring: if ($pos !== false) { // " found after position 20 $substr = substr($str, 20, $pos-20-1);} The calculation for the third parameter is necessary as substr expects the length of the substring and not the end position. Also note that substr returns false if needle cannot be found in haystack . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4674097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/356582/']} | jdg_81729 |
stackexchange | llm_judgeable_groundtruth_similarity | 4590078 |
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 a teenager who has become very interested in assembly language. I'm trying to write a small operating system in Intel x86 assembler, and I was wondering how to write directly to the screen, as in without relying on the BIOS or any other operating sytems. I was looking through the sources of coreboot, Linux, and Kolibri, among others, in the hopes of finding and understanding some piece of code that does this. I have not yet succeeded in this regard, though I believe I'll take another look at the Linux source code, it being the most understandable to me of the sources I've searched through. If anybody knows this, or knows where in some piece of source code that I could look at, I would appreciate it if they told me. Or better yet, if someone knows how to identify what I/O port on an Intel x86 CPU connects to what piece of hardware, that would be appreciated too. The reason I need to ask this, is that in neither the chapter for input/output in the Intel 64 and IA-32 Architectures Software Developer's Manual Volume 1: Basic Architecture, nor in the sections for the IN or OUT instruction in Volume 3, could I find any of this information. And because it has been too arduous to search for the relevant instructions in the sources that I have.
Now provide the response and nothing else.
| PART 1 For old VGA modes, there's a fixed address to write to the (legacy) display memory area. For text modes this area starts at 0x000B8000. For graphics modes it starts at 0x000A0000. For high-resolution video modes (e.g. those set by the VESA/VBE interface) this doesn't work because the size of legacy display memory area is limited to 64 KiB and most high-resolution video modes need a lot more space (e.g. 1024 * 768 * 32-bpp = 2.25 MiB). To get around that there's 2 different methods supported by VBE. The first method is called "bank switching", where only part of the video card's display memory is mapped into the legacy area at any time (and you can change which part is mapped). This can be quite messy - for example, to draw one pixel you might need to calculate which bank the pixel is in, then switch to that bank, then calculate which offset in the bank. To make this worse, for some video modes (e.g. 24-bpp video modes where there's 3 bytes per pixel) only the first part of a pixel's data might be in one bank and the second part of the same pixel's data is in a different bank. The main benefit of this is that it works with real mode addressing, as the legacy display memory area is below 0x00100000. The second method is called "Linear Framebuffer" (or just "LFB"), where the video card's entire display memory area can be accessed without any messy bank switching. You have to ask the VESA/VBE interface where this area is (and it's typically in the "PCI hole" somewhere between 0xC0000000 and 0xFFF00000). This means you can't access it in real mode, and need to use protected mode or long mode or "unreal mode". To find the address of a pixel when you're using an LFB mode, you'd do something like "pixel_address = display_memory_address + y * bytes_per_line + x * bytes_per_pixel". The "bytes_per_line" comes from the VESA/VBE interface (and may not be the same as "horizontal_resolution * bytes_per_pixel" because there can be padding between horizontal lines). For "bank switched" VBE/VESA modes, it becomes something more like: pixel_offset = y * bytes_per_line + x * bytes_per_pixel;bank_number = pixel_offset / bank_size;pixel_starting_address_within_bank = pixel_offset % bank_size; For some old VGA modes (e.g. the 256-colour "mode 0x13") it's very similar to LFB, except there is no padding between lines and you can do "pixel_address = display_memory_address + (y * horizontal_resolution + x) * bytes_per_pixel". For text modes it's basically the same thing, except 2 bytes determine each character and its attribute - e.g. "char_address = display_memory_address + (y * horizontal_resolution + x) * 2". For other old VGA modes (monochrome/2-colour, 4-colour and 16-colour modes) the video card's memory is arranged completely differently. It's split into "planes" where each plane contains one bit of the pixel, and (for e.g.) to update one pixel in a 16-colour mode you need to write to 4 separate planes. For performance reasons the VGA hardware supports different write modes and different read modes, and it can get complicated (too complicated to describe adequately here). PART 2 For I/O ports (on 80x86, "PC compatibles"), there's 3 general categories. The first is "de facto standard" legacy devices which use fixed I/O ports. This includes things like the PIC chips, ISA DMA controller, PS/2 controller, PIT chip, serial/parallel ports, etc. Almost anything that describes how to program each of these devices will tell you which I/O ports the device uses. The next category is legacy/ISA devices, where the I/O ports the devices use is determined by jumpers on the card itself, and there's no sane way to determine which I/O ports they use from software. To get around this the end-user has to tell the OS which I/O ports each device uses. Thankfully this crusty stuff has all become obsolete (although that doesn't necessarily mean that nobody is using it). The third category is "plug & play", where there's some method of asking the device which I/O ports it uses (and in most cases, changing the I/O ports the device uses). An example of this is PCI, where there's a "PCI configuration space" that tells you lots of information about each PCI device. For this categories, there is no way anyone can determine which devices will be using which I/O ports without doing it at run-time, and changing some BIOS settings can cause any/all of these devices to change I/O ports. Also note that an Intel CPU is only a CPU. Nothing prevents those CPUs from being used in something that is radically different to a "PC compatible" computer. Intel's CPU manuals will never tell you anything about hardware that exists outside of the CPU itself (including the chipset or devices). Part 3 Probably the best place to go for more information (that's intended for OS developers/hobbyists) is http://osdev.org/ (their wiki and their forums). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4590078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336462/']} | jdg_81730 |
stackexchange | llm_judgeable_groundtruth_similarity | 33505066 |
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 is simplified code, which uses python3 coroutine and sets handler for SIGING and SIGTERM signals for stopping job properly: #!/usr/bin/env python3# -*- coding: utf-8 -*-import argparseimport asyncioimport signalimport sysdef my_handler(signum, frame): print('Stopping') asyncio.get_event_loop().stop() # Do some staff sys.exit()@asyncio.coroutinedef prob_ip(ip_addr): print('Ping ip:%s' % ip_addr) proc = yield from asyncio.create_subprocess_exec('ping', '-c', '3', ip_addr) ret_code = yield from proc.wait() if ret_code != 0: print("ip:%s doesn't responding" % ip_addr) # Do some staff yield from asyncio.sleep(2) # Do more staff yield from asyncio.sleep(16)@asyncio.coroutinedef run_probing(): print('Start probing') # Do some staff yield from asyncio.sleep(1) while True: yield from asyncio.wait([prob_ip('192.168.1.3'), prob_ip('192.168.1.2')]) yield from asyncio.sleep(60)def main(): parser = argparse.ArgumentParser() parser.description = "Probing ip." parser.parse_args() signal.signal(signal.SIGINT, my_handler) signal.signal(signal.SIGTERM, my_handler) asyncio.get_event_loop().run_until_complete(run_probing())if __name__ == '__main__': main() When i run it via: python3 test1.py It stops by Ctrl-C without any warnings.But when I run it via: python3 -m test1 It prints warning by Ctrl-C: $ python3 -m test1 Start probingPing ip:192.168.1.2Ping ip:192.168.1.3PING 192.168.1.2 (192.168.1.2): 56 data bytesPING 192.168.1.3 (192.168.1.3): 56 data bytes^C--- 192.168.1.2 ping statistics ------ 192.168.1.3 ping statistics ---1 packets transmitted, 0 packets received, 100% packet loss1 packets transmitted, 0 packets received, 100% packet lossStoppingTask was destroyed but it is pending!task: <Task pending coro=<prob_ip() running at /tmp/test1.py:22> wait_for=<Future pending cb=[Task._wakeup()]> cb=[_wait.<locals>._on_completion() at /usr/lib/python3.4/asyncio/tasks.py:394]>Task was destroyed but it is pending!task: <Task pending coro=<prob_ip() running at /tmp/test1.py:22> wait_for=<Future pending cb=[Task._wakeup()]> cb=[_wait.<locals>._on_completion() at /usr/lib/python3.4/asyncio/tasks.py:394]> Same warning I get if I install this script via: from setuptools import setupsetup(name='some_scripts', version='1.0.0.0', author='Some Team', author_email='[email protected]', url='https://www.todo.ru', description='Some scripts', packages=['my_package'], entry_points={'console_scripts': [ 'test1=my_package.test1:main', ]}, ) My python version is "3.4.2"
Now provide the response and nothing else.
| Ok. I think I have figured out how should I stop all tasks. First of all, as far as I understand. BaseEventLoop.stop() is only to stop BaseEventLoop.run_forever() . So one should cancel all tasks via Future.cancel . To get all tasks you can use Task.all_tasks static method. After cancellation all tasks asyncio.CancelledError exception will be raised from run_until_complete. So one should catch it, if one doesn't want to print it to stderr. And also, in some cases, I get this error: TypeError: signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object .I found some topics about this error: https://bugs.python.org/issue23548 https://github.com/buildinspace/peru/issues/98 They all say that it can be fixed by closing loop before exiting application. So we get this code: #!/usr/bin/env python3# -*- coding: utf-8 -*-import asyncioimport signaldef my_handler(): print('Stopping') for task in asyncio.Task.all_tasks(): task.cancel()@asyncio.coroutinedef do_some(some_args): while True: print("Do staff with %s" % some_args) yield from asyncio.sleep(2)def main(): loop = asyncio.get_event_loop() loop.add_signal_handler(signal.SIGINT, my_handler) try: loop.run_until_complete(asyncio.wait([do_some(1), do_some(2)])) except asyncio.CancelledError: print('Tasks has been canceled') finally: loop.close()if __name__ == '__main__': main() It works also with signal.signal . But as Vincent noticed loop.add_signal_handler looks better in this case. But I am still not sure is this the best way to stop all tasks. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33505066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1081184/']} | jdg_81731 |
stackexchange | llm_judgeable_groundtruth_similarity | 10955474 |
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 don't know what I'm doing wrong, but every time I try to test for a redirect, I get this error: "@request must be an ActionDispatch::Request" context "as non-signed in user" do it "should redirect to the login page" do expect { visit admin_account_url(account, host: get_host(account)) }.to redirect_to(signin_path) endend1) AdminAccountPages Admin::Accounts#show as non-signed in user should redirect to the login page Failure/Error: expect { visit admin_account_url(account, host: get_host(account)) }.to redirect_to(signin_path) ArgumentError: @request must be an ActionDispatch::Request # ./spec/requests/admin_account_pages_spec.rb:16:in `block (4 levels) in <top (required)>' I'm using RSpec-rails (2.9.0) with Capybara (1.1.2) and Rails 3.2. I would appreciate it if someone could also explain why this is happening; why can't I use the expect in such a way?
Now provide the response and nothing else.
| Capybara is not a rails-specific solution so it doesn't know anythingabout rails's rendering logic. Capybara is meant specifically for Integration testing, which is essentially running tests from the viewpoint of an end-user interacting with a browser. In these tests, you should not be asserting templates because an end-user can't see that deep into your application. What you should instead be testing is that an action lands you on the correct path. current_path.should == new_user_pathpage.should have_selector('div#erro_div') | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10955474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/276959/']} | jdg_81732 |
stackexchange | llm_judgeable_groundtruth_similarity | 396896 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It is a common approach to use specialized exception types to indicate exceptional results of a method. These exception types are not considered to indicate a programming flaw, but, as I pointed out, are intendend to return exceptional results. Let's assume the following base class: public class MyCollection{ private readonly Dictionary<string, string> underlyingCollection = new Dictionary<string, string>(); public void AddEntry(string key, string value) { this.underlyingCollection.Add(key, value); this.OnEntryAdded(key, value); } /// <summary> /// ... /// </summary> /// <param name="key">...</param> /// <returns>...</returns> /// <exception cref="KeyNotFoundException">An entry with the provided key could not be found.</exception> public string GetValue(string key) { string value = this.underlyingCollection[key]; return this.ProcessEntry(key, value); } protected virtual void OnEntryAdded(string key, string value) { } protected virtual string ProcessEntry(string key, string value) => value;} The consumer of the class expects a KeyNotFoundException when GetValue is called with an unknown key, and can react to it. (In Java a checked exception could be used - just ignore the point whether this would be a good idea or not.) Now someone creates a derived class: public class CustomizedCollection : MyCollection{ private readonly Dictionary<string, int> countByXKeyLookup = new Dictionary<string, int>(); protected override void OnEntryAdded(string key, string value) { base.OnEntryAdded(key, value); if (key.StartsWith("x", StringComparison.OrdinalIgnoreCase)) { string xKey = ExtractKeyPrefix(key); int count; if (!this.countByXKeyLookup.TryGetValue(xKey, out count)) { this.countByXKeyLookup.Add(xKey, count); } else { this.countByXKeyLookup[xKey] = count + 1; } } } // correct implementation protected override string ProcessEntry(string key, string value) { if (!key.StartsWith("x", StringComparison.OrdinalIgnoreCase)) { return value; } int count = this.countByXKeyLookup[ExtractKeyPrefix(key)]; return value + " ** X-Key count is " + count; } private static string ExtractKeyPrefix(string key) => key.Substring(0, 1);} The consumer of the class would write this code, and everything works as expected: var testee = new CustomizedCollection();testee.AddEntry("A", "Alfa");testee.AddEntry("XB", "X-Bravo");testee.AddEntry("XC", "X-Charlie");testee.AddEntry("YD", "Y-Delta");string key = null;try{ key = "A"; Console.WriteLine(testee.GetValue(key)); key = "XB"; Console.WriteLine(testee.GetValue(key)); key = "XC"; Console.WriteLine(testee.GetValue(key)); key = "YD"; Console.WriteLine(testee.GetValue(key)); key = "NA"; Console.WriteLine(testee.GetValue(key));}catch (KeyNotFoundException){ Console.WriteLine("Key '" + key + "' not available.");} The output is: AlfaX-Bravo ** X-Key count is 1X-Charlie ** X-Key count is 1Y-DeltaKey 'NA' not available. Later on, a bug is introduced in method ProcessEntry of the derived class: // buggy implementationprotected override string ProcessEntry(string key, string value){ // bug here! if (!key.StartsWith("x", StringComparison.OrdinalIgnoreCase) && !key.StartsWith("y", StringComparison.OrdinalIgnoreCase)) { return value; } int count = this.countByXKeyLookup[ExtractKeyPrefix(key)]; return value + " ** X-Key count is " + count;} Now running the code results in a misinterpretation of the exception: AlfaX-Bravo ** X-Key count is 1X-Charlie ** X-Key count is 1Key 'YD' not available. But key 'YD' is available! The root cause of this bug lies in the fact that the consumer of this API relies on the documented behavior that a KeyNotFoundException is returned if the requested key is not found. Who caused the bug? Well, the developer of the derived class CustomizedCollection introduced a bug that raises a KeyNotFoundException in a completely different context (namely by accessing the private countByXKeyLookup dictionary). This in turn confuses the developer who just consumes the API, because he would not understand why key 'YD' is reported as not existing though it is. My question is: should the base class take responsibility for filtering out "wrong" exceptions that are part of the API documentation and wrap them into another non-specific exception, e.g. an InvalidOperationException ? Or should developers of derived classes be aware of not letting bubble up exceptions with a special meaning that would result in a misinterpretation? What I do not want to discuss : whether inheritance is a good idea or not. whether using a TryDoReturnBool approach is better than throwing exceptions or not. whether the class should be made sealed or not. whether aggregation is better than inheritance, and whether aggregation would solve the issue or not. whether the root cause of an exception can be parsed from the stack trace, and whether this is a good idea or not. What I want to discuss : whether it is a good idea to make the base class robust enough to mitigate such programming flaws introduced by developers who derive from the base class. whether it is a good idea to keep the base class as simple as possible and delegate the responsibility of only throwing allowed exceptions to developers who derive from the base class. Here is my solution of a more robust but even more complicated implementation (only showing the edited method GetValue ): public class MyCollection{ // ... // some members have been omitted for brevity // ... /// <summary> /// ... /// </summary> /// <param name="key">...</param> /// <returns>...</returns> /// <exception cref="KeyNotFoundException">An entry with the provided key could not be found.</exception> public string GetValue(string key) { string value; ExceptionDispatchInfo approvedEdi; try { this.GetValueImpl(key, out value, out approvedEdi); } catch (KeyNotFoundException exc) { throw new InvalidOperationException("Exception caught from customized code.", exc); } approvedEdi?.Throw(); return value; } private void GetValueImpl(string key, out string value, out ExceptionDispatchInfo approvedEdi) { value = null; approvedEdi = null; try { value = this.underlyingCollection[key]; } catch (KeyNotFoundException exc) { approvedEdi = ExceptionDispatchInfo.Capture(exc); return; } value = this.ProcessEntry(key, value); }} Original post
Now provide the response and nothing else.
| You would prevent those misleading exceptions from bubbling up by catching them and converting them to a non-misleading exception. public class CustomizedFileManager : MyFileManager { protected override string DecorateFilename(string filename) { try { string decoratedFilename = base.DecorateFilename(filename); var allowedNames = File.ReadAllLines("ListOfAllowedFilenames.txt"); // can throw FileNotFoundException if (!allowedNames.Contains(decoratedFilename)) { throw new InvalidOperationException("Filename not allowed"); } return decoratedFilename; } catch (FileNotFoundException e) { throw new DeploymentException("The file \"ListOfAllowedFilenames.txt\" couldn't be found", e); } } } The CustomizedFileManager class would know that the FileNotFound exception refers to a deployment problem and not to a problem related to the file specified by the user, so it can do the proper re-interpretation of the exception. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/396896', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/344770/']} | jdg_81733 |
stackexchange | llm_judgeable_groundtruth_similarity | 3537363 |
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 use strict; in perl and with that I use the following statement. unless(defined($x)){ print "Not defined";} Where $x is not declared anywhere. So I expect it to print " Not defined " but it returns an error Global symbol "$x" requires explicit package name at *********** in line 15.
Now provide the response and nothing else.
| The strict pragma has three parts: strict references, strict variables, and strict subs. The one you're running into is strict vars This generates a compile-time error if you access a variable that wasn't declared via our or use vars , localized via my , or wasn't fully qualified. Because this is to avoid variable suicide problems and subtle dynamic scoping issues, a merely local variable isn't good enough. Because it generates compile-time errors, your non- BEGIN code won't even have a chance to run. You can temporarily allow non-strict variables inside a block as in { no strict 'vars'; print "Not defined!\n" unless defined $x;} but note that Perl's defined operator tells you whether a value is defined, not whether a variable has been declared. Tell us more about your application, and we can give you better advice about how to handle it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3537363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/388350/']} | jdg_81734 |
stackexchange | llm_judgeable_groundtruth_similarity | 58197244 |
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 add authorization header into SwaggerUI api test. below is my Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "API", Description = "QPIN API with ASP.NET Core 3.0", Contact = new OpenApiContact() { Name = "Tafsir Dadeh Zarrin", Url = new Uri("http://www.tdz.co.ir") } }); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement(); securityRequirement.Add(securitySchema, new[] { "Bearer" }); c.AddSecurityRequirement(securityRequirement); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider) { app.UseCors("Cors"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMiddleware<ApiResponseMiddleware>(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } The Authorize button has been added to the Swagger UI and I've entered the required access token as shown below but the issue is when I want to try an API the token is not getting added into API request, and when I click the lock icon over the API it shows that there isn't any available authorization, see below
Now provide the response and nothing else.
| There are two points in your code: For OpenApiSecurityRequirement in OpenApiSecurityRequirement , need to set OpenApiReference Need to specify Scheme with bearer Here is a working demo: services.AddSwaggerGen(c =>{ c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "API", Description = "QPIN API with ASP.NET Core 3.0", Contact = new OpenApiContact() { Name = "Tafsir Dadeh Zarrin", Url = new Uri("http://www.tdz.co.ir") } }); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement(); securityRequirement.Add(securitySchema, new[] { "Bearer" }); c.AddSecurityRequirement(securityRequirement);}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58197244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2084520/']} | jdg_81735 |
stackexchange | llm_judgeable_groundtruth_similarity | 28937106 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What I am trying to do: I am trying to make a custom dialog in android With rounded corners. What is happening: I am able to make custom dialog but it doesn't have rounded corners. I tried adding a selector but still I couldn't achieve rounded corners. Below is my code for the same: Java code: private void launchDismissDlg() { dialog = new Dialog(getActivity(), android.R.style.Theme_Dialog); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dlg_dismiss); dialog.setCanceledOnTouchOutside(true); Button btnReopenId = (Button) dialog.findViewById(R.id.btnReopenId); Button btnCancelId = (Button) dialog.findViewById(R.id.btnCancelId); btnReopenId.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); btnCancelId.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); dialog.setCanceledOnTouchOutside(false); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); dialog.show(); } xml code: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white" android:orientation="vertical" > <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:gravity="center" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text=""I WOULD LIKE TO DISMISS THE VENDOR"" android:textColor="@color/col_dlg_blue_light" android:textSize="14sp" android:textStyle="bold" /> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:gravity="center" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="BECAUSE" android:textColor="@android:color/black" android:textStyle="bold" /> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/btnReopenId" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/col_dlg_green_light" android:text="REOPEN" android:padding="5dp" android:textSize="14sp" android:textColor="@android:color/white" android:textStyle="bold" /> <Button android:id="@+id/btnCancelId" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/col_dlg_pink_light" android:text="CANCEL" android:padding="5dp" android:textSize="14sp" android:textColor="@android:color/white" android:textStyle="bold" /> </TableRow> </TableLayout></LinearLayout>
Now provide the response and nothing else.
| Create an XML file in drawable, say dialog_bg.xml : <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@color/white"/> <corners android:radius="30dp" /> <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" /></shape> set it as the background in your layout XML: android:background="@drawable/dialog_bg" Set the background of the dialog's root view to transparent, because Android puts your dialog layout within a root view that hides the corners in your custom layout. Java: dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); Kotlin: dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/28937106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1083093/']} | jdg_81736 |
stackexchange | llm_judgeable_groundtruth_similarity | 3582344 |
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 would I go about drawing a connection line in Raphael where the mousedown initiates the starting point of the line, the mousemove moves the end point without moving the start point and the mouseup leaves it as it is?
Now provide the response and nothing else.
| Have a look at the source of http://www.warfuric.com/taitems/RaphaelJS/arrow_test.htm . This might get you started. EDIT I made a quick example that will give you a head start (still need some work though: validation of parameters, adding comments, etcetera). Note: you still have to adapt the path to raphael.js <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta http-equiv="edit-Type" edit="text/html; charset=utf-8"><!-- Update the path to raphael js --><script type="text/javascript"src="path/to/raphael1.4.js"></script><script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><style type='text/css'>svg { border: solid 1px #000;}</style></head><body><div id="raphaelContainer"></div><script type='text/javascript'> //<![CDATA[ function Line(startX, startY, endX, endY, raphael) { var start = { x: startX, y: startY }; var end = { x: endX, y: endY }; var getPath = function() { return "M" + start.x + " " + start.y + " L" + end.x + " " + end.y; }; var redraw = function() { node.attr("path", getPath()); } var node = raphael.path(getPath()); return { updateStart: function(x, y) { start.x = x; start.y = y; redraw(); return this; }, updateEnd: function(x, y) { end.x = x; end.y = y; redraw(); return this; } };};$(document).ready(function() { var paper = Raphael("raphaelContainer",0, 0, 300, 400); $("#raphaelContainer").mousedown( function(e) { x = e.offsetX; y = e.offsetY; line = Line(x, y, x, y, paper); $("#raphaelContainer").bind('mousemove', function(e) { x = e.offsetX; y = e.offsetY; line.updateEnd(x, y); }); }); $("#raphaelContainer").mouseup( function(e) { $("#raphaelContainer").unbind('mousemove'); });}); //]]> </script></body></html> See example: http://jsfiddle.net/rRtAq/9358/ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3582344', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/233427/']} | jdg_81737 |
stackexchange | llm_judgeable_groundtruth_similarity | 2329842 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With fwrite returning the number of successful elements written to the file, by saying: if (!(fwrite(...))) { fprintf(stderr, "Failure"); //perror(???) I sometimes see code that says perror here and I don't know //exactly what this does.} Does this check for successful writing to the file? Are there other things to worry about? Thanks.
Now provide the response and nothing else.
| In short, not quite. fwrite returns the number of elements successfully written; you need to check this against the number of elements you intended to write i.e. those you passed in argument to fwrite. What you've done checks that some elements have been written. Here's a reference for perror . Interprets the value of the global variable errno into a string and prints that string to stderr (standard error output stream, usually the screen), optionaly preceding it with the custom message specified in str. errno is an integral variable whose value describes the last error produced by a call to a library function. The error strings produced by perror depend on the developing platform and compiler. If the parameter str is not a null pointer, str is printed followed by a colon (:) and a space. Then, whether str was a null pointer or not, the generated error description is printed followed by a newline character ('\n'). perror should be called right after the error was produced, otherwise it can be overwritten in calls to other functions. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2329842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/207524/']} | jdg_81738 |
stackexchange | llm_judgeable_groundtruth_similarity | 140202 |
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:
I am a high school student who has been studying a bit of chromatography. I came across calibration curve during class and I trying to figure how to read it and use it? I have no clue how to read off the graph nor do I really now the use of it. Can someone please explain what information I can extract from this graph and possibly provide an example if that's fine?
Now provide the response and nothing else.
| I assume your teacher explained the HPLC separation. If injected a mixture of four ions you will get four peaks. Each peak has an area, which is proportional to the concentration of the substance. Imagine you wanted to determine the concentration of chloride ions in your tap water. What you would do is that you will prepare several known concentrations of chloride ions using $\ce{NaCl}$ solutions, say $0$ to $\pu{350 ppm}$ (look at your calibration chart). Inject them one by one, and measure the peak area, let us say the second peak is that of chloride ion. The peak shape is Gaussian in real work but you can "estimate" them as triangles. Recall triangle's area is very easy to calculate. First step: Plot the peak area for concentration. What you get is a calibration curve. The next step is to find a mathematical equation that fits this data. Fortunately it is linear in your case of the form $y=mC$ where $y= \text{peak area}$ , $m=\text{slope}$ , $C=\text{concentration}$ in $\pu{ppm}$ . Now you would inject your tap water in the HPLC, you do not know the concentration ( $C_1$ ) but you do know the peak area. The last step is called interpolation . You go from the known area, and read the corresponding concentration axis. Viola! Now you know the chloride concentration in your tap water! Alternatively, you use the equation, $y=0.1312C$ , so I know the area of the tap water chloride injection, say, it was $\pu{40.0 units}$ , so $C_1 = 40/0.1312 = \pu{304.9 ppm}$ . In typical tap water it is around $\pu{100 ppm}$ , I just made up those numbers. Bonus : Rationalize the units of the peak area on the $y$ -axis! Why it is conductivity times minutes? | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/140202', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/96166/']} | jdg_81739 |
stackexchange | llm_judgeable_groundtruth_similarity | 33307413 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a commit SHA, I'd like to use the GitHub API to determine which pull request it belongs to. GitHub displays this information on the commit page : This information isn't in the API response for that commit, however: curl --silent 'https://api.github.com/repos/hammerlab/pileup.js/commits/ee49f07dba3821109b3cf45404446f434a897558' | grep 328(nothing) Is it possible to get this information using the GitHub API? I realize that I could crawl all the recent PRs for the repo, but this seems inefficient. For context: I'd like to do this from a Travis-CI "push" job, where I have access to the SHA but not any information about whether it's part of a pull request.
Now provide the response and nothing else.
| You should use a library that handles serialization/deserialization.I would consider choosing between Spray Json and Play Json . I will explain to you how the process works with Play first, and it's very similar to that in Spray. Let's say you have a class, and an object with an instance and a json as string: case class MyClass(id: Int, name: String, description: String)object Data { val obj: MyClass = MyClass(1, "me", "awesome") val str: String = """ |{ | "id": 1, | "name": "me", | "description": "awesome" |} """.stripMargin} For MyClass to be serialized/deserialized, you will need an implicit formatter, specific for this, so you will create an object that contains this formatter using Play . trait MyClassPlayProtocol { implicit val formatAbility = Json.format[Ability]}object MyClassPlayProtocol extends MyClassPlayProtocol The serialization/deserialization will look something like this: object PlayData { import play.api.libs.json.JsValue import play.api.libs.json.Json import MyClassPlayProtocol._ import General._ val str2Json: JsValue = Json.parse(str) val obj2Json: JsValue = Json.toJson(obj) val json2Str: String = Json.stringify(str2Json) val json2Obj: MyClass = obj2Json.as[MyClass]} In Spray , the protocol will look like this: trait MyClassSprayProtocol extends DefaultJsonProtocol { implicit val myClassFormat = jsonFormat3(MyClass)}object MyClassSprayProtocol extends MyClassSprayProtocol and the serialization/deserialization: object SprayData { import spray.json._ import MyClassSprayProtocol._ import General._ val str2Json: JsValue = str.parseJson val obj2Json: JsValue = obj.toJson val json2Str: String = str2Json.compactPrint val json2Obj: MyClass = obj2Json.convertTo[MyClass]} As you can see, it's mostly a matter of choice between this two. Both are still improved and probably will be in the near future. Depending on the benchmark, you will find that one is better than the other by a few miliseconds (usually Spray). I for one am using Spray at work and Play in some personal projects, and I can't say I found something fundamentally different from one to another. EDIT: And to finally answer your question, to go from MyClass to String (serialization), you will do something like this: PLAY: Json.stringify(Json.toJson(myClass))SPRAY: myClass.toJson.compactPrint And the deserialization: PLAY: Json.parse(string).as[MyClass]SPRAY: myClass.parseJson.convertTo[MyClass] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33307413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/388951/']} | jdg_81740 |
Subsets and Splits