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
23641345
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to do some validation on requests coming into my service using the ContainerRequestFilter . Everything is working fine, however there is one problem - every single request gets pass through the filters, even though some of the filters will never apply to them (one filter only validates on ResourceOne, another only on ResourceTwo etc.) Is there a way to set a filter only to be invoked on a request under certain conditions? While it is not a blocker or hindrance, it would be nice to be able to stop this kind of behaviour :) Now provide the response and nothing else.
I assume that You are using Jersey 2.x (implementation for JAX-RS 2.0 API). You have two ways to achieve Your goal. 1. Use Name bindings: 1.1 Create custom annotation annotated with @NameBinding: @NameBinding@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface AnnotationForResourceOne {} 1.2. Create filter with Your annotation: @Provider@AnnotationForResourceOnepublic class ResourceOneFilter implements ContainerRequestFilter {...} 1.3. And bind created filter with selected resource method: @Path("/resources")public class Resources { @GET @Path("/resourceOne") @AnnotationForResourceOne public String getResourceOne() {...}} 2. Use DynamicFeature: 2.1. Create filter: public class ResourceOneFilter implements ContainerRequestFilter {...} 2.2. Implement javax.ws.rs.container.DynamicFeature interface: @Providerpublic class MaxAgeFeature implements DynamicFeature { public void configure(ResourceInfo ri, FeatureContext ctx) { if(resourceShouldBeFiltered(ri)){ ResourceOneFilter filter = new ResourceOneFilter(); ctx.register(filter); } }} In this scenario: filter is not annotated with @Provider annotation; configure(...) method is invoked for every resource method; ctx.register(filter) binds filter with resource method;
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23641345', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1366729/']}
jdg_375641
stackexchange
llm_judgeable_groundtruth_similarity
596632
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: I'm currently studying the textbook Fundamentals of Electric Circuits , 7th edition, by Charles Alexander and Matthew Sadiku. Chapter 1.7 Problem Solving gives the following example: Example 1.10 Solve for the current flowing through the \$8 \ \Omega\$ resistor in Fig. 1.19. Solution: Carefully define the problem . This is only a simple example, but we can already see that we do not know the polarity on the 3-V source. We have the following options. We can ask the professor what the polarity should be. If we cannot ask, then we need to make a decision on what to do next. If we have time to work the problem both ways, we can solve for the current when the 3-V source is plus on top and then plus on the bottom. If we do not have the time to work it both ways, assume a polarity and then carefully document your decision. Let us assume that the professor tells us that the source is plus on the bottom as shown in Fig. 1.20. Notice that the authors have claimed (without justification) that the current is flowing downwards through the \$8 \ \Omega\$ resistor. In SpiRail's answer here , they have also shown that, for the case where the polarity is + on the bottom, the current flows downwards through the \$8 \ \Omega\$ resistor (see the red arrow): How does one know that the current is flowing downwards through the \$8 \ \Omega\$ resistor? This seems to be the immediate assumption, but there's no explanation from the authors as to why this is the case. Now provide the response and nothing else.
No, the authors have not declared that the current \$i_8\$ is flowing downward. They have defined some current named \$i_8\$ that is flowing downward. Once the circuit is solved it may be found that the value of \$i_8\$ is negative. In that case, we know that there is actually a positive current flowing up . We must label some assumed direction for all currents and some assumed polarity for voltages so we can write meaningful and consistent equations for the circuit. If the resulting values come out negative it just means that our assumptions were not correct, but it is a perfectly valid way to start a problem.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/596632', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/207355/']}
jdg_375642
stackexchange
llm_judgeable_groundtruth_similarity
406695
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: There is some development I need to do on some remote box. Fortunately, I have shell access, but I need to go through a gateway that has AllowTcpForwarding set to false. I took a peak at the docs and it says: AllowTcpForwarding Specifies whether TCP forwarding is permitted. The default is ''yes''. Note that disabling TCP forwarding does not improve security unless users are also denied shell access, as they can always install their own forwarders. How would I go about installing (or building) my own forwarder? My goal here is to setup a remote interpreter using Pycharm via SSH and binding it to some local port, that data fed through ssh, that through the gateway, and then to the development box where the code is actually run. I imagine I could somehow utilize nc or some other unix utility that'll help get the job done. I know I can ssh to my remote box by doing: ssh -t user1@gateway ssh user2@devbox But obviously this option isn't available in pycharm. I'll have to be able to open some local port such that ssh -p 12345 localhost(or variant) will connect me to user2@devbox. This will allow me to configure the remote interpreter to use port 12345 on localhost to connect to the remote box. Now provide the response and nothing else.
As long as one can execute socat locally and on gateway (or even just bash and cat on gateway , see last example!) and is allowed to not use a pty to be 8bits clean, it's possible to establish a tunnel through ssh. Here are 4 examples, improving upon the previous: Basic example working once (having it fork would require one ssh connection per tunnel, not good). Having to escape the : for socat to accept the exec command: term1: $ socat tcp-listen:12345,reuseaddr exec:'ssh user1@gateway exec socat - tcp\:devbox\:22',nofork term2: $ ssh -p 12345 user2@localhost term1: user1@gateway's password: term2: user2@localhost's password: Reversing first and second addresses makes the socket immediately available socat has to stay in charge, so no nofork : term1: $ socat exec:'ssh user1@gateway exec socat - tcp\:devbox\:22' tcp-listen:12345,reuseaddr user1@gateway's password: term2: $ ssh -p 12345 user2@localhost user2@localhost's password: Using a ControlMaster ssh allows to fork while using only a single ssh connection to the gateway, thus giving a behaviour similar to the usual port forwarding: term1: $ ssh -N -o ControlMaster=yes -o ControlPath=~/mysshcontrolsocket user1@gateway user1@gateway's password: term2: $ socat tcp-listen:12345,reuseaddr,fork exec:'ssh -o ControlPath=~/mysshcontrolsocket user1@gateway exec socat - tcp\:devbox\:22' term3: $ ssh -p 12345 user2@localhost user2@localhost's password: Having only bash and cat available on gateway By using bash 's built-in tcp redirection , and two half-duplex cat commands (for a full-duplex result) one doesn't even need a remote socat or netcat . Handling of multiple layers of nested and escaped quotes was a bit awkward and can perhaps be done better, or simplified by the use of a remote bash script. Care has to be taken to have the forked cat for output only: term1 (no change): $ ssh -N -o ControlMaster=yes -o ControlPath=~/mysshcontrolsocket user1@gatewayuser1@gateway's password: term2: $ socat tcp-listen:12345,reuseaddr,fork 'exec:ssh -T -o ControlPath=~/mysshcontrolsocket user1@gateway '\''exec bash -c \'\''"exec 2>/dev/null 8<>/dev/tcp/devbox/22; cat <&8 & cat >&8"\'\'\' term3: $ ssh -p 12345 user2@localhostuser2@localhost's password:
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/406695', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/262441/']}
jdg_375643
stackexchange
llm_judgeable_groundtruth_similarity
18404948
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 display a infowindow on a Google Maps. It displays perfect, when you hover over a marker it loads up a infowindow but the map jumps to fit in the window. I don't want the map to move but rather infowindow set its position according to map. Booking.com has something like this. EDIT: Added my code Here is the stripped down version of my code. I'm getting all the info from an AJAX service and this service returns response (which holds some more info too). $.ajax({ url: 'URL', dataType: "json", type: "GET", success: function(response) { // delete all markers clearOverlays(); var infowindow = new google.maps.InfoWindow(); for (var i = 0; i < response.length; i++) { item = response[i]; var marker = new google.maps.Marker({ position: new google.maps.LatLng(item.lat, item.lng), map: map, url: item.detail_url }); markersArray.push(marker); // display infowindow google.maps.event.addListener(marker, "mouseover", (function(marker, item) { return function() { infowindow.setOptions({ content: 'SOME CONTENT HERE FOR INFOWINDOW' }); infowindow.open(map, marker); } })(marker, item)); // remove infowindow google.maps.event.addListener(marker, 'mouseout', function() { infowindow.close(); }); // marker click google.maps.event.addListener(marker, 'click', function() { window.location.href = marker.url; }); } }}); As you can see below, the first image shows the infowindow displayed at bottom of marker while second one shows the infowindow displayed on top of the marker. The map doesn't move but infowindow sets its position within the boundries of the map. Now provide the response and nothing else.
In your declaration for setting the info window options infowindow.setOptions , add the following option to disable the panning of the map when the infowindow is displayed, disableAutoPan : true . However this will also mean you'll need to calculate the real estate you have available to display the infowindow on your map and give it a position using the position option. Otherwise it won't be guaranteed that your infowindow will be completely visible on the map. https://developers.google.com/maps/documentation/javascript/reference#InfoWindowOptions EDIT: How to calculate screen real estate I realize I was pretty vague with my suggestion to calculate the screen real estate available to set the position of your infowindow, when part of your question was to actually set the infowindow's position. So I've provided an update to my answer on how you can calculate the screen real estate and adjust your infowindow's position. The key is to first convert your points from LatLng to pixels, and find out the pixel coordinate of the marker on the map with relation to the pixel coordinate of the map's center. The following snippet demonstrates how this can be done. getPixelFromLatLng: function (latLng) { var projection = this.map.getProjection(); //refer to the google.maps.Projection object in the Maps API reference var point = projection.fromLatLngToPoint(latLng); return point;} Once you've got your pixel coordinates, you'll need to find out which quadrant of the map canvas the marker is currently residing in. This is achieved by comparing the X and Y coordinates of the marker to the map, like so: quadrant += (point.y > center.y) ? "b" : "t";quadrant += (point.x < center.x) ? "l" : "r"; Here, I'm determining if the point is in the bottom right, bottom left, top right or top left quadrant of the map based on it's relative position to the map's center. Keep in mind this is why we use pixels as opposed to LatLng values, because LatLng values will always yield the same result - but reality is the marker can be in any quadrant of the map canvas depending on panning. Once you know which quadrant the marker is in, you can give offset values to the infowindow to position it so it's visible on the map - like so: if (quadrant == "tr") { offset = new google.maps.Size(-70, 185);} else if (quadrant == "tl") { offset = new google.maps.Size(70, 185);} else if (quadrant == "br") { offset = new google.maps.Size(-70, 20);} else if (quadrant == "bl") { offset = new google.maps.Size(70, 20);}//these values are subject to change based on map canvas size, infowindow size Once the offset value is determined you can just adjust the pixelOffset of your infowindow on whatever listener you have invoking the infoWindow.open() method. This is done by using the setOptions() method for infowindows: infowindow.setOptions({pixelOffset : self.getInfowindowOffset(self.map, marker)}); Here is a working JSFiddle example of the solution described above. Note: You will notice the annoying "arrow" on the infowindow displaying desbite the position of your infowindow, this is part of the default Google Map's setting for infowindows and I could not find a proper way of getting rid of it. There was a suggestion here , but I couldn't get it to work. Alternatively you can use the infobox library or the infobubble library - which gives you more styling options.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18404948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49380/']}
jdg_375644
stackexchange
llm_judgeable_groundtruth_similarity
1520132
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have the following html, and no CSS <div> here is some content in this div. it stretches it out <br />and down too!</div> Now I want to get the actual pixel width and height that the browser has rendered this div as. Can that be done with JS? Thank you. Now provide the response and nothing else.
Try getting a reference to your div and reading the offsetWidth and offsetHeight properties: var myDiv = document.getElementById('myDiv');var width = myDiv.offsetWidth; // intvar height = myDiv.offsetHeight; offsetWidth / Height cumulatively measures the element's borders, horizontal padding, vertical scrollbar (if present, if rendered) and CSS width. It's the pixel values of the entire space that the element uses in the document. I think it's what you want. If that is not what you meant, and you'd rather only the element's width and height (i.e. excluding padding, margin, etc) try getComputedStyle : var comStyle = window.getComputedStyle(myDiv, null);var width = parseInt(comStyle.getPropertyValue("width"), 10);var height = parseInt(comStyle.getPropertyValue("height"), 10); The values above will be the final, computed pixel values for the width and height css style properties (including values set by a <style> element or an external stylesheet). Like all helpful things, this won't work in IE. You say you are using jQuery. Well it's trivial now, and works cross-browser: var width = $('div').css('width');var height = $('div').css('height'); With jQuery you don't need the first part of this answer, it's all taken care of for ya ;)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1520132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104361/']}
jdg_375645
stackexchange
llm_judgeable_groundtruth_similarity
22790
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Generally all number systems use addition or multiplication to express numbers like - '12*3 + 6 for 42 in a base 12 system', '2 on the way to 50' or 'even 10+10+10+10+2 in some'. But, are there number systems which use subtraction like 10*5-8 (for an exemplar base 10 system), I know Ainu is close but not what I want to know about. Now provide the response and nothing else.
The Yoruba language has a rather elaborate vigesimal (base-20) numeral system that involves both addition and subtraction and multiplication. There are words for each of the decades; units in 1–4 are created by adding to these, while units in 5–9 are created by subtracting from the next decade. The odd decades are created by subtracting ten from the next even decade: 14=10+4; 15=20-5; 16=20-4; 50=20×3−10, 700=200×4−100; etc. Also, Latin used subtraction in numerals . Among the numbers from 18 to 98, those that ended in 8 or 9 were formed by subtracting 2 and 1 from the following decade: 27: septem et vīgintī ('7 and 20') 28: duodētrīgintā ('2 from 30') 29: ūndētrīgintā ('1 from 30')
{}
{'log_upvote_score': 4, 'links': ['https://linguistics.stackexchange.com/questions/22790', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/14731/']}
jdg_375646
stackexchange
llm_judgeable_groundtruth_similarity
9989785
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I use AutoMapper to map my domain objects to my view models. I have metadata in my domain layer, that I would like to carry over to the view layer and into ModelMetadata. (This metadata is not UI logic, but provides necessary information to my views). Right now, my solution is to use a separate MetadataProvider (independently of ASP.NET MVC), and use conventions to apply the relevant metadata to the ModelMetadata object via an AssociatedMetadataProvider. The problem with this approach is that I have to test for the same conventions when binding the ModelMetadata from the domain as I do with my AutoMapping, and it seems like there should be a way to make this more orthogonal. Can anyone recommend a better way to accomplish this? Now provide the response and nothing else.
I use the approach below to automatically copy data annotations from my entities to my view model. This ensures that things like StringLength and Required values are always the same for entity/viewmodel. It works using the Automapper configuration, so works if the properties are named differently on the viewmodel as long as AutoMapper is setup correctly. You need to create a custom ModelValidatorProvider and custom ModelMetadataProvider to get this to work. My memory on why is a little foggy, but I believe it's so both server and client side validation work, as well as any other formatting you do based on the metadata (eg an asterix next to required fields). Note: I have simplified my code slightly as I added it below, so there may be a few small issues. Metadata Provider public class MetadataProvider : DataAnnotationsModelMetadataProvider{ private IConfigurationProvider _mapper; public MetadataProvider(IConfigurationProvider mapper) { _mapper = mapper; } protected override System.Web.Mvc.ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) { //Grab attributes from the entity columns and copy them to the view model var mappedAttributes = _mapper.GetMappedAttributes(containerType, propertyName, attributes); return base.CreateMetadata(mappedAttributes, containerType, modelAccessor, modelType, propertyName);}} Validator Provivder public class ValidatorProvider : DataAnnotationsModelValidatorProvider{ private IConfigurationProvider _mapper; public ValidatorProvider(IConfigurationProvider mapper) { _mapper = mapper; } protected override System.Collections.Generic.IEnumerable<ModelValidator> GetValidators(System.Web.Mvc.ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) { var mappedAttributes = _mapper.GetMappedAttributes(metadata.ContainerType, metadata.PropertyName, attributes); return base.GetValidators(metadata, context, mappedAttributes); }} Helper Method Referenced in above 2 classes public static IEnumerable<Attribute> GetMappedAttributes(this IConfigurationProvider mapper, Type sourceType, string propertyName, IEnumerable<Attribute> existingAttributes){ if (sourceType != null) { foreach (var typeMap in mapper.GetAllTypeMaps().Where(i => i.SourceType == sourceType)) { foreach (var propertyMap in typeMap.GetPropertyMaps()) { if (propertyMap.IsIgnored() || propertyMap.SourceMember == null) continue; if (propertyMap.SourceMember.Name == propertyName) { foreach (ValidationAttribute attribute in propertyMap.DestinationProperty.GetCustomAttributes(typeof(ValidationAttribute), true)) { if (!existingAttributes.Any(i => i.GetType() == attribute.GetType())) yield return attribute; } } } } } if (existingAttributes != null) { foreach (var attribute in existingAttributes) { yield return attribute; } }} Other Notes If you're using dependency injection, make sure your container isn't already replacing the built in metadata provider or validator provider. In my case I was using the Ninject.MVC3 package which bound one of them after creating the kernel, I then had to rebind it afterwards so my class was actually used. I was getting exceptions about Required only being allowed to be added once, took most of a day to track it down.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9989785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/344211/']}
jdg_375647
stackexchange
llm_judgeable_groundtruth_similarity
158391
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: We know that there are compact manifolds with diffeomorphic interiors but their boundaries are not homeomorphic (see the question Manifolds with homeomorphic interiors ). My question is about a very special case: Assume $D$ is a bounded open set in $R^n$ with smooth boundary.If $D$ is diffeomorphic to the unit ball, is $\bar D$, the closure of $D$, diffeomorphic to the closed unit ball? Now provide the response and nothing else.
The case $n=4$ is open as far as I know. The case $n=3$ follows since $\mathbb R^3$ is irreducible, so it contains no fake 3-disk, i.e. $\bar D$ must be the standard disk. The case $n=5$ is equivalent to the smooth $4$-dimensional Poincare conjecture(which is still open). Here is why: Any homotopy $4$-sphere embeds smoothly into $\mathbb R^5$ (Sketch: homology $4$-sphere bounds a contractible smooth manifold $C$ [Kervaire, "Smooth homology spheres and their fundamental groups", Theorem 3]. In our case $\partial C$ is simply-connected, so attaching a collar on the boundary one gets a contractible $5$-manifold that is simply-connected at infinity, and hence it is diffeomorphic to $\mathbb R^5$ by a result of Stallings). Any embedding of the standard $4$-sphere into $\mathbb R^5$ bounds a standard disk, see [Smale, "Differentiable and Combinatorial Structures on Manifolds", Corollary 1.3]. What Smale actually states is that any embedded $S^{n-1}$ in $\mathbb R^n$ bounds a standard disk unless $n=4$ or $7$. This was before he proved the h-cobodorsm theorem hence he excludes $7$. Finally, as mentioned in comments if $n>5$, then $\bar D$ is diffeomorphic to the standard disk by the h-cobordism theorem (sketch: since by assumption $D$ is simply-connected at infinity, $\partial D$ is a homotopy sphere and $\bar D$ is a contractible smooth manifold, so removing a small ball in its interior results in h-cobordism between then standard sphere and the embedded one. Proving that this is an h-cobordism involves standard excision considerations in homology).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/158391', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4789/']}
jdg_375648
stackexchange
llm_judgeable_groundtruth_similarity
15241124
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 ever a way or some tricks to post an array of data or a single variable string data using redirect() function in codeiginter? Now provide the response and nothing else.
when using redirect you go from one controller or another by this process all post data are destroyed unless you stored them on a session, here is how i do it $data = array('firstname'=>'fname','lastname'=>'lastname');// i store data to flashdata$this->session->set_flashdata('lolwut',$data);// after storing i redirect it to the controllerredirect('controller/method') so on your redirected controller you can access it via $this->session->flashdata('lolwut') note that i am using flashdata not userdata , flashdata destroys itself on the next process. read more flashdata here SESSION CLASS
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15241124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1764442/']}
jdg_375649
stackexchange
llm_judgeable_groundtruth_similarity
4551214
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an NSString that gets assigned a string value. How do I take this NSString and insert @"-thumbnail" between the file's name and its extension? In other words, how do I go from: NSString *fileName = @"myFile.png"; to: NSString *thumbnailName = [NSString someMagicFunction...]NSLog(@"%@", thumbnailName); // Should Output "myFile-thumbnail.png" Now provide the response and nothing else.
The NSString additions for path components can come in handy, specifically: pathExtension and stringByDeletingPathExtension Edit: see also: stringByAppendingPathExtension: (as pointed out by Dave DeLong ) NSString * ext = [fileName pathExtension];NSString * baseName = [fileName stringByDeletingPathExtension];NSString * thumbBase = [baseName stringByAppendingString:@"-thumbnail"];NSString * thumbnailName = [thumbBase stringByAppendingPathExtension:ext]; If you really want that magicFunction to exist, you can add a category method to NSString like so: @interface NSString (MoreMagic)- (NSString *)stringByAddingFileSuffix:(NSString *)suffix;@end@implementation NSString (MoreMagic)- (NSString *)stringByAddingFileSuffix:(NSString *)suffix{ NSString * extension = [self pathExtension]; NSString * baseName = [self stringByDeletingPathExtension]; NSString * thumbBase = [baseName stringByAppendingString:suffix]; return [thumbBase stringByAppendingPathExtension:extension];}@end To be used as follows: NSString * thumbnailName = [fileName stringByAddingFileSuffix:@"-thumbnail"];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4551214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/545352/']}
jdg_375650
stackexchange
llm_judgeable_groundtruth_similarity
822038
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: A module $M$ over a domain $R$ is called uniquely divisible if for every $r \in R \setminus\lbrace 0 \rbrace$ the endomorphism $$\phi_r : M \to M$$ $$m \mapsto r \cdot m$$ is a bijection. Let $K$ be the field of fraction of $R$. I have to prove that for any $R$-module $M$ , $M \otimes_R K$ is uniquely divisible as $R$-module. I have proved that $\phi_r$ is surjective, but how to prove the injectivity ? Now provide the response and nothing else.
Hint $1$: If $R$ is a domain, then $K=\mathrm{Frac}(R)$ is a flat $R$-module. Hint $2$: If $N_r=\{m\in M\mid r\cdot m=0\}$, then $N_r\otimes_{R}K=0$ for $r\ne 0$. Now for any $r\ne 0$, consider the exact sequence of $R$-modules: $$0\to N_r\to M\to rM\to 0$$ Can you finish the argument from here?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/822038', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21024/']}
jdg_375651
stackexchange
llm_judgeable_groundtruth_similarity
189470
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In a Riemannian manifold $(M^n,g)$, is it true that given a point $p$ we can find $n$ vector fields $X_i$ on a neighborhood $U$ of $p$ such that $g(X_i,X_j)(x)=\delta_{ij}$ with $x \in U$?It seems that if I do Gram-Schmidt to the coordinate basis would work, but then the sectional cuvature $K$ will be $0$ and as it is intrinsic, it will imply that the surface (in the case $n=2$) is locally isometric to a plane which obviously is not true in general Now provide the response and nothing else.
Yes, you can do this. Take an orthonormal frame at a fixed central point and extend it in all directions by parallel transport along geodesics leaving the central point. What you cannot also do is say anything about the pairwise Lie brackets of the resulting fields. Chern did most of his calculations in this fashion. EDDIITT: I am not seeing a proof anywhere, so...one of the defining relations of the Levi-Civita connection of a Riemannian metric, with smooth vector fields $U,V,W$ is$$ U \langle V,W \rangle = \langle \nabla_UV, W\rangle + \langle V, \nabla_U W \rangle. $$ If $U$ is the velocity field of a geodesic, we do get (by a little extension trickery that requires a full lesson) $$ \nabla_U U = 0, $$ which is nice. But parallel transport of the two vector fields $V,W$ along the geodesic means precisely that $$ \nabla_U V = 0, \; \; \nabla_U W = 0.$$ In particular, $$ U \langle V,W \rangle = \langle 0, W\rangle + \langle V, 0 \rangle = 0. $$The inner products of the fields remain constant. So, if $V=W = e_i$ at the central point is one of the orthonormal basis vectors, we find that $|V| =1$ always. Next, if $V= e_i$ and $W = e_j$ at the central point with $i \neq j,$ we find that $V,W$ remain orthogonal. Finally, all the transported vector fields are defined on a fairly large ball, up to the injectivity radius actually. Well and good. As I said, no control of the pairwise Lie brackets, as those being $0$ really would require flatness.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/189470', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37986/']}
jdg_375652
stackexchange
llm_judgeable_groundtruth_similarity
1860174
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After reading a question here about what things our computer could do in one second I made a little test I had in mind for a while and I'm very surprised by the results. Look: Simple program to catch a null exception, takes almost one second to do 1900 iterations: for(long c = 0; c < 200000000; c++){ try { test = null; test.x = 1; } catch (Exception ex) { }} Alternatively, checking if test == null before doing the assignation, the same pogram can do aprox 200000000 iterations in one second. for(long c = 0; c < 1900; c++){ test = null; f (!(test == null)) { test.x = 1; }} Anyone has a detailed explanation on why this HUGE diference ? EDIT: Running the test in Release mode, outside Visual studio i'm getting 35000-40000 iterations vs 400000000 iterations (always aprox) Note I'm running this with a crappy PIV 3.06Ghz Now provide the response and nothing else.
There's no way that should take a second for 1900 iterations unless you're running in the debugger. Running performance tests under the debugger is a bad idea. EDIT: Note that this isn't a case of changing to the release build - it's a case of running without the debugger; i.e. hitting Ctrl-F5 instead of F5 . Having said that, provoking exceptions when you can avoid them very easily is also a bad idea. My take on the performance of exceptions: if you're using them appropriately, they shouldn't cause significant performance issues unless you're in some catastrophic situation anyway (e.g. you're trying to make hundreds of thousands of web service calls and the network is down). Exceptions are expensive under debuggers - certainly in Visual Studio, anyway - due to working out whether or not to break into the debugger etc, and probably doing any amount of stack analysis which is unnecessary otherwise. They're still somewhat expensive anyway, but you shouldn't be throwing enough of them to notice. There's still stack unwinding to do, relevant catch handlers to find, etc - but this should only be happening when something's wrong in the first place. EDIT: Sure, throwing an exception is still going to give you fewer iterations per second (although 35000 is still a very low number - I'd expect over 100K) because you're doing almost nothing in the non-exception case. Let's look at the two: Non-exception version of the loop body Assign null to variable Check whether variable is null; it is, so go back to the top of the loop (As mentioned in the comments, it's quite possible that the JIT will optimise this away anyway...) Exception version: Assign null to variable Dereference variable Implicit check for nullity Create an exception object Check for any filtered exception handlers to call Look up the stack for the catch block to jump to Check for any finally blocks Branch appropriately Is it any wonder that you're seeing less performance? Now compare that with the more common situation where you do a whole bunch of work, possibly IO, object creation etc - and maybe an exception is thrown. Then the difference becomes a lot less significant.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1860174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78745/']}
jdg_375653
stackexchange
llm_judgeable_groundtruth_similarity
24044851
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 not yet been able to figure out how to get a substring of a String in Swift: var str = “Hello, playground”func test(str: String) -> String { return str.substringWithRange( /* What goes here? */ )}test (str) I'm not able to create a Range in Swift. Autocomplete in the Playground isn’t super helpful - this is what it suggests: return str.substringWithRange(aRange: Range<String.Index>) I haven't found anything in the Swift Standard Reference Library that helps. Here was another wild guess: return str.substringWithRange(Range(0, 1)) And this: let r:Range<String.Index> = Range<String.Index>(start: 0, end: 2)return str.substringWithRange(r) I've seen other answers ( Finding index of character in Swift String ) that seem to suggest that since String is a bridge type for NSString , the "old" methods should work, but it's not clear how - e.g., this doesn't work either (doesn't appear to be valid syntax): let x = str.substringWithRange(NSMakeRange(0, 3)) Thoughts? Now provide the response and nothing else.
You can use the substringWithRange method. It takes a start and end String.Index. var str = "Hello, playground"str.substringWithRange(Range<String.Index>(start: str.startIndex, end: str.endIndex)) //"Hello, playground" To change the start and end index, use advancedBy(n). var str = "Hello, playground"str.substringWithRange(Range<String.Index>(start: str.startIndex.advancedBy(2), end: str.endIndex.advancedBy(-1))) //"llo, playgroun" You can also still use the NSString method with NSRange, but you have to make sure you are using an NSString like this: let myNSString = str as NSStringmyNSString.substringWithRange(NSRange(location: 0, length: 3)) Note: as JanX2 mentioned, this second method is not safe with unicode strings.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/24044851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18505/']}
jdg_375654
stackexchange
llm_judgeable_groundtruth_similarity
26506275
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code, which should return an offset of 60 (to show that in the UK at present, we are in British Summer Time - ie. 60 minutes ahead of GMT): var info = TimeZoneInfo.FindSystemTimeZoneById("Greenwich Standard Time");DateTimeOffset localServerTime = DateTimeOffset.Now;double off = localServerTime.Offset.TotalMinutes;return off; However, it returns 0. Could anyone please help fix this for me? Now provide the response and nothing else.
Use TimeZoneInfo.IsDaylightSavingTime Method (DateTimeOffset) to find if it is currently Daylight saving for your Timezone. var info = TimeZoneInfo.FindSystemTimeZoneById("Greenwich Standard Time");DateTimeOffset localServerTime = DateTimeOffset.Now;bool isDaylightSaving = info.IsDaylightSavingTime(localServerTime); There are further examples here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26506275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1041617/']}
jdg_375655
stackexchange
llm_judgeable_groundtruth_similarity
27321997
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: At startup, it seems my node.js app uses around 200MB of memory. If I leave it alone for a while, it shrinks to around 9MB. Is it possible from within the app to: Check how much memory the app is using ? Request the garbage collector to run ? The reason I ask is, I load a number of files from disk, which are processed temporarily. This probably causes the memory usage to spike. But I don't want to load more files until the GC runs, otherwise there is the risk that I will run out of memory. Any suggestions ? Now provide the response and nothing else.
If you launch the node process with the --expose-gc flag, you can then call global.gc() to force node to run garbage collection. Keep in mind that all other execution within your node app is paused until GC completes, so don't use it too often or it will affect performance. You might want to include a check when making GC calls from within your code so things don't go bad if node was run without the flag: try { if (global.gc) {global.gc();}} catch (e) { console.log("`node --expose-gc index.js`"); process.exit();}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27321997', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1266109/']}
jdg_375656
stackexchange
llm_judgeable_groundtruth_similarity
1261908
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create a button which has 3 images: a Normal image, a Pressed image and a Disabled image (I will use these for creating up/down arrow buttons). I believe the correct approach would be to derive from Button and use a Template and set triggers to change the image. I have 3 dependency properties, one for each image. The images would be .png and have transparent backgrounds (as they are not rectangular). I am looking for something like CBitmapButton in MFC. Now provide the response and nothing else.
You won't need dependency properties because you are inheriting from Button . You already have the IsPressed and IsEnabled properties. In fact, this is all you need: <Button x:Class="TestWpfApplication.ThreeStateImageButton" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Button.Template> <ControlTemplate TargetType="{x:Type Button}"> <Grid> <Image Name="Normal" Source="Resources/Normal.png"/> <Image Name="Pressed" Source="Resources/Pressed.png" Visibility="Hidden"/> <Image Name="Disabled" Source="Resources/Disabled.png" Visibility="Hidden"/> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsPressed" Value="True"> <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/> <Setter TargetName="Pressed" Property="Visibility" Value="Visible"/> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter TargetName="Normal" Property="Visibility" Value="Hidden"/> <Setter TargetName="Disabled" Property="Visibility" Value="Visible"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Button.Template></Button> With your UserControl code-behind file: public partial class ThreeStateImageButton : Button{ public ThreeStateImageButton() { InitializeComponent(); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1261908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_375657
stackexchange
llm_judgeable_groundtruth_similarity
15304378
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: UPDATE I was doing some maintenance on the server and rebooted... once it came back the code worked just fine... which actually makes me to worry just the same... i think it's a bug on mod_wsgi. Thanks anyway! I'm really new to django (started yesterday). I managed to make a excel parser using xlrd, everything works fine with the data (it loads really really fast), i need to update the file info in the database so i can know how the load is going, this is where i have the problem, the save() method doesn't work, I already used update along with get and filter, but always the same problem. I hope you can point me out where is the mistake models.py class archivo(models.Model): archivo_id = models.AutoField(primary_key=True) fk_cliente = models.IntegerField() fk_usuario = models.IntegerField() archivo_nombre = models.CharField(max_length = 30) archivo_original = models.CharField(max_length = 255) archivo_extension = models.CharField(max_length = 5) archivo_tamano = models.FloatField() archivo_registros = models.IntegerField() archivo_registros_buenos = models.IntegerField() archivo_registros_malos = models.IntegerField() archivo_registros_cargados = models.IntegerField() archivo_fecha_carga = models.DateTimeField() archivo_fecha_envio = models.DateTimeField() def __unicode__(self): return self.archivo_id views.py from procesa.models import *from django.conf import settingsfrom django.shortcuts import render_to_response import xlrdfrom time import strftimefrom symbol import except_clausedef procesa(request, procesar = 0): datos = None infoarchivo = None if(procesar > 0): try: infoarchivo = archivo.objects.get(archivo_id=int(procesar)) except: return render_to_response('error.html') if (infoarchivo is not None): excel_path = settings.FILES_URL+infoarchivo.archivo_original wb = xlrd.open_workbook(str(excel_path)) sh = wb.sheet_by_index(0) ##START UPDATE## infoarchivo2 = archivo.objects.filter(archivo_id = procesar) infoarchivo2.archivo_registros = sh.nrows infoarchivo2.save() ##END UPDATE## for rownum in range(sh.nrows): destino = str(sh.cell(rownum,0).value) destino = destino.replace(".0","") if (int(destino) > 0): mensaje = str(sh.cell(rownum,1).value) ahora = strftime("%Y-%m-%d %H:%M:%S") reg = registro.objects.filter(registro_destino__exact=destino,fk_archivo__exact=procesar) #reg = registro.objects.raw(str(el_query)) if (reg.exists()): exists = True else: r = registro(fk_cliente=1,fk_usuario=1,fk_archivo=int(procesar),registro_destino=destino,registro_mensaje=mensaje,registro_estado='Cargado',registro_fecha_carga=ahora) r.save() datos = {'ID':procesar,'PATH': settings.FILES_URL, 'INFO':infoarchivo, 'el_excel':infoarchivo.archivo_original, 'registros':sh.nrows } return render_to_response('carga.html', {'datos': datos}) in the ##START UPDATE## block i've already tried with infoarchivo.archivo_registros = sh.nrowsinfoarchivo.save() and archivo.objects.filter(archivo_id = procesar).update(archivo_registros=sh.nrows) and archivo.objects.get(archivo_id = procesar).update(archivo_registros=sh.nrows) I can't find any reference to this error or something else to add in the models file, i'm pretty sure it's something really easy to fix, but i just can't find it. The error i'm getting (for all the different codes) is Exception Type: AttributeError at /procesa/4 Exception Value: 'archivo' object has no attribute 'update' The records of the file gets parsed and inserted with no problem. I'm using Django 1.5 with python 2.7 in Apache 2.2 with mod_wsgi and mysql backend installed in EC2 on Amazon UPDATE I was doing some maintenance on the server and rebooted... once it came back the code worked just fine... which actually makes me to worry just the same... i think it's a bug on mod_wsgi. Thanks anyway! Now provide the response and nothing else.
The reason for this error is that .get() returns an individual object and .update() only works on querysets, such as what would be returned with .filter() instead of .get() . If you are using .get() , then .update() will not work. You will need to save the information to the object manually: archivo = archivo.objects.get(archivo_id=procesar)archivo.archivo_registros = sh.nrowsarchivo.save() You can also use update_fields if you only wish to save this particular piece of data: archivo = archivo.objects.get(archivo_id=procesar)archivo.archivo_registros = sh.nrowsarchivo.save(update_fields=['archivo_registros']) This prevents triggering any signals that you may not want to invoke. Your other option is to simply use .filter() . archivo = archivo.objects.filter(archivo_id=procesar).update(archivo_registros=sh.nrows) Note that this will update multiple objects if they exist. If you want to be sure that doesn't happen, you should include the primary key in the filter, or use one of the earlier approaches to make sure you are only modifying a single object.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15304378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2150149/']}
jdg_375658
stackexchange
llm_judgeable_groundtruth_similarity
20941
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: How can I decrypt a message that was encrypted with a one-time pad? Would I need to get that pad, and then reverse the process? I'm confused here. Now provide the response and nothing else.
One-Time Pad is unbreakable, assuming the pad is perfectly random, kept secret, used only once, and no plaintext is known. This is due to the properties of the exclusive-or (xor) operation. Here's its truth table: A xor B = XA | B | X0 | 0 | 00 | 1 | 11 | 0 | 11 | 1 | 0Number of 0s in column A = 2Number of 1s in column A = 2Number of 0s in column B = 2Number of 1s in column B = 2Number of 0s in column X = 2Number of 1s in column X = 2 Note that it introduces no bit-skew - the number of 0s and 1s in the inputs are equal to the number of 0s and 1s in the output, i.e. two of each. Furthermore, if you know only one element from a row, you cannot predict the values of the other two, since they are equally probable. For example, let's say we know that X is 0. There's an equal probability that A = 0 and B = 0, or A = 1 and B = 1. Now let's say we know that X is 1. There's an equal probability that A = 0 and B = 1, or A = 1 and B = 0. It's impossible to predict. So, if you only know one element, you cannot possibly determine any information about A or B. The next interesting property is that it is reversible, i.e. A xor A = 0B xor B = 0A xor 0 = AB xor 0 = BA xor B xor B = A xor 0 = AA xor B xor A = B xor 0 = B So, if we take any value and xor it with itself, the result is cancelled out and it always results in 0. This means that, if we xor a value A with a value B, then later xor that result with either A or B, we get B or A respectively. The operation is reversible. This lends well to cryptography, because: xor introduces no bitskew xor has equally probable inputs for any given output given any two of A, B, X we can compute the third As such, the following is perfectly secure: ciphertext = message xor key but only if message is the same length as key, key is perfectly random, key is only used once, and only one element is known to an attacker. If they know the ciphertext, but not the key or message, it's useless to them. They cannot possibly break it. In order to decrypt the message, you must know the entire key and the ciphertext. Keep in mind that the key must be completely random, i.e. every bit must have an equal probability of being 1 or 0, and be completely independent of all other bits in the key. This actually turns out to be rather impractical, for a few reasons: Generating perfectly random keys is hard. Software generators (and many hardware generators) often have minuscule biases and odd repeating properties. It's almost impossible to gain truly random data in anything but tiny amounts. If the attacker knows the ciphertext and can correctly guess parts of the message (e.g. he knows it's a Windows executable, and therefore must start with MZ ) he can get the corresponding key bits for the known range. These bits are useless for decrypting other parts of the message, but can reveal patterns in the key if it's poorly generated. You must be able to distribute the key, and your key must be equally as long as your message. If you can keep your key 100% secret between those of you who are authorised to read the message, why not just keep your message 100% secret instead? The weak link here is your random number generator. The security of the one time pad is entirely limited by the security of your generator. Since a perfect generator is almost impossible, a perfect one-time pad is almost impossible too. The final problem is that the key can only be used once. If you use it for two different messages, and the attacker knows both ciphertexts, he can xor them together to get the xor of the two plaintexts. This leaks all sorts of information (e.g. which bits are equal) and completely breaks the cipher. So, in conclusion, in a perfect one-time pad you need to know the ciphertext and key in order to decrypt it, but perfect one-time pads are almost impossible.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/20941', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/13659/']}
jdg_375659
stackexchange
llm_judgeable_groundtruth_similarity
45301220
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 wrote a small Spring Boot REST application, which performs a REST request on another REST endpoint. @RequestMapping("/api/v1")@SpringBootApplication@RestController@Slf4jpublic class Application{ @Autowired private WebClient webClient; @RequestMapping(value = "/zyx", method = POST) @ResponseBody XyzApiResponse zyx(@RequestBody XyzApiRequest request, @RequestHeader HttpHeaders headers) { webClient.post() .uri("/api/v1/someapi") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject(request.getData())) .exchange() .subscribeOn(Schedulers.elastic()) .flatMap(response -> response.bodyToMono(XyzServiceResponse.class).map(r -> { if (r != null) { r.setStatus(response.statusCode().value()); } if (!response.statusCode().is2xxSuccessful()) { throw new ProcessResponseException( "Bad status response code " + response.statusCode() + "!"); } return r; })) .subscribe(body -> { // Do various things }, throwable -> { // This section handles request errors }); return XyzApiResponse.OK; }} We are new to Spring and are having trouble writing a Unit Test for this small code snippet. Is there an elegant (reactive) way to mock the webClient itself or to start a mock server that the webClient can use as an endpoint? Now provide the response and nothing else.
We accomplished this by providing a custom ExchangeFunction that simply returns the response we want to the WebClientBuilder : webClient = WebClient.builder() .exchangeFunction(clientRequest -> Mono.just(ClientResponse.create(HttpStatus.OK) .header("content-type", "application/json") .body("{ \"key\" : \"value\"}") .build()) ).build();myHttpService = new MyHttpService(webClient);Map<String, String> result = myHttpService.callService().block();// Do assertions here If we want to use Mokcito to verify if the call was made or reuse the WebClient accross multiple unit tests in the class, we could also mock the exchange function: @Mockprivate ExchangeFunction exchangeFunction;@BeforeEachvoid init() { WebClient webClient = WebClient.builder() .exchangeFunction(exchangeFunction) .build(); myHttpService = new MyHttpService(webClient);}@Testvoid callService() { when(exchangeFunction.exchange(any(ClientRequest.class))) .thenReturn(buildMockResponse()); Map<String, String> result = myHttpService.callService().block(); verify(exchangeFunction).exchange(any()); // Do assertions here} Note: If you get null pointer exceptions related to publishers on the when call, your IDE might have imported Mono.when instead of Mockito.when . Sources: WebClientjavadoc WebClient.Builderjavadoc ExchangeFunctionjavadoc
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45301220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8362787/']}
jdg_375660
stackexchange
llm_judgeable_groundtruth_similarity
52260394
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on some data organization and need to move information into a form. I have a column of IP addresses and some columns have more than one, or even none. I preferably need to be able to go through the column and keep the first 13 characters and remove everything after it, have 581 lines I need it to be able to run through. I think if I could get a VBA that will run through the column and find the first "," and remove that and anything after it will work. I tried this, but it did nothing. Sub cleanup() lastrow = Range("G581").End(xlUp).Row For i = 2 To lastrow If Len(Cells(i, 1)) > 13 Then Cells(i, 1) = Left(Cells(i, 1), 14) End If Next iEnd Sub Now provide the response and nothing else.
As of gitlab 12.9, this can be done using trigger and child pipelines — although a little involved: Quoting the example from the gitlab doc: generate-config: stage: build script: generate-ci-config > generated-config.yml artifacts: paths: - generated-config.ymlchild-pipeline: stage: test trigger: include: - artifact: generated-config.yml job: generate-config In your case, you would put the definition of job_%myParam% in job.yml.in , then have the script generate-ci-config be e.g. sed "s/%myParam%/$PARAM/g" job.yml.in . This is probably a bit much for just changing the names of course, and there will be a cost associated to the additional stage; but it does answer the question, and may be useful to do more, like start with different versions of the parameter in the same pipeline.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52260394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6531198/']}
jdg_375661
stackexchange
llm_judgeable_groundtruth_similarity
9542
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that in a regression situation, if you have a set of highly correlated variables this is usually "bad" because of the instability in the estimated coefficients (variance goes toward infinity as determinant goes towards zero). My question is whether this "badness" persists in a PCA situation. Do the coefficients/loadings/weights/eigenvectors for any particular PC become unstable/arbitrary/non-unique as the covariance matrix becomes singular? I am particularly interested in the case where only the first principal component is retained, and all others are dismissed as "noise" or "something else" or "unimportant". I don't think that it does, because you will just be left with a few principal components which have zero, or close to zero variance. Easy to see this isn't the case in the simple extreme case with 2 variables - suppose they are perfectly correlated. Then the first PC will be the exact linear relationship, and the second PC will be perpindicular to the first PC, with all PC values equal to zero for all observations (i.e. zero variance). Wondering if its more general. Now provide the response and nothing else.
The answer might be given in even simpler terms: the multiple regression has one step more than the pca if seen in terms of linear algebra, and from the second step the instability comes into existence: The first step of pca and mult. regression can be seen as factoring of the correlation-matrix $R$ into two cholesky factors $L \cdot L^t$ , which are triangular -and which is indifferent to low or high correlations. (The pca can then be seen as a rotation of that (triangular) cholesky-factor to pc-position (this is called Jacobi-rotation as far as I remember) The mult. regression procedure is the to apply an inversion of that cholesky factor $L$ minus the row and column of the dependent variable, which is conveniently in the last row of the correlation-matrix. The instability comes into play here: if the independent variables are highly correlated, then the diagonal of the cholesky factor $L$ can degenerate to very small numeric values - and to invert that introduces then the problem of division by nearly-zero.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/9542', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/2392/']}
jdg_375662
stackexchange
llm_judgeable_groundtruth_similarity
118516
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My issue is below but would be interested comments from anyone with experience with xlrd. I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Dow Jones Industrial Average (link: http://www.djindexes.com/mdsidx/?event=showAverages ) When I open the file unmodified I get a nasty BIFF error (binary format not recognized) However you can see in this screenshot that Excel 2008 for Mac thinks it is in 'Excel 1997-2004' format (screenshot: http://skitch.com/alok/ssa3/componentreport-dji.xls-properties ) If I instead open it in Excel manually and save as 'Excel 1997-2004' format explicitly, then open in python usig xlrd, everything is wonderful. Remember, Office thinks the file is already in 'Excel 1997-2004' format. All files are .xls Here is a pastebin of an ipython session replicating the issue: http://pastie.textmate.org/private/jbawdtrvlrruh88mzueqdq Any thoughts on:How to trick xlrd into recognizing the file so I can extract data?How to use python to automate the explicit 'save as' format to one that xlrd will accept?Plan B? Now provide the response and nothing else.
FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points: The file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw raw bytes with Python: >>> open('ComponentReport-DJI.xls', 'rb').read(200)'COMPANY NAME\tPRIMARY EXCHANGE\tTICKER\tSTYLE\tICB SUBSECTOR\tMARKET CAP RANGE\tWEIGHT PCT\tUSD CLOSE\t\r\n3M Co.\tNew York SE\tMMM\tN/A\tDiversified Industrials\tBroad\t5.15676229508\t50.33\t\r\nAlcoa Inc.\tNew York SE\tA' You can read this file using Python's csv module ... just use delimiter="\t" in your call to csv.reader() . xlrd can read any file that pyExcelerator can, and read them better—dates don't come out as floats, and the full story on Excel dates is in the xlrd documentation. pyExcelerator is abandonware—xlrd and xlwt are alive and well. Check out http://groups.google.com/group/python-excel HTHJohn
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/118516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_375663
stackexchange
llm_judgeable_groundtruth_similarity
500730
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: Consider I have equal marginal probabilities as per: $$p_{\theta}(x) = p_{\alpha}(x).$$ Now assume we know there exists another random variable $z$ that is of interest to us. Am I correct in thinking that I can not deduce that: $$p_{\theta}(x, z) = p_{\alpha}(x, z)?$$ I believe this would be the case because you can get the same marginal from different joint distributions, but I am unsure if that applies here. Now provide the response and nothing else.
You are correct. For example, suppose we have two bivariate normals. In the first, both $x$ and $z$ have mean 0 and variance 1, and correlation 0 (i.e. they are independent). In the second, both $x$ and $z$ still have mean 0 and variance 1, but their correlation is 0.5 (they are not independent). In both cases, the marginal distribution of $x$ will be normal with mean 0 and variance 1, but the joint distribution of $(x,z)$ will be different due to the different correlation values.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/500730', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/191333/']}
jdg_375664
stackexchange
llm_judgeable_groundtruth_similarity
8172947
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 newly working with CodeIgniter and PHP. I'm trying to do a simple task that is to show a multilevel menu. Let's say I have a student and status table. I want to show which students are under which status(senior, junior etc.). But I'm getting this error: A PHP Error was encounteredSeverity: NoticeMessage: Trying to get property of non-objectFilename: views/sview.phpLine Number: 31 At line 31 i have <?php echo $status->statusname;?> The controller: // ....$data['status'] = $this->status_model->get_students();$this->load->view('sview', $data); The model: function get_students(){ $s = $this->db->get('status'); foreach ($s->result() as $status){ $students = $this->db->get_where('student', array('status_id'=>$status->id)); $status->students = students->result(); } return $s;} view: <?php foreach($s as $status):?> <h4><?php echo $status->statusname;?></h4> <?php foreach($status->student as $student):?> <?php echo $student->studentname; ?> <?php endforeach;?><?php endforeach;?> Now provide the response and nothing else.
.fig files are .mat files (containing a struct), see http://undocumentedmatlab.com/blog/fig-files-format/ As the reference you give states, structs are only supported up to v7.1: http://www.scipy.org/Cookbook/Reading_mat_files So, in MATLAB I save using -v7: plot([1 2],[3 4])hgsave(gcf,'c','-v7'); Then in Python 2.6.4 I use: >>> from scipy.io import loadmat>>> x = loadmat('c.fig')>>> x{'hgS_070000': array([[<scipy.io.matlab.mio5.mat_struct object at 0x1500e70>]], dtype=object), '__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file, Platform: MACI64, Created on: Fri Nov 18 12:02:31 2011', '__globals__': []}>>> x['hgS_070000'][0,0].__dict__{'handle': array([[1]], dtype=uint8), 'children': array([[<scipy.io.matlab.mio5.mat_struct object at 0x1516030>]], dtype=object), '_fieldnames': ['type', 'handle', 'properties', 'children', 'special'], 'type': array([u'figure'], dtype='<U6'), 'properties': array([[<scipy.io.matlab.mio5.mat_struct object at 0x1500fb0>]], dtype=object), 'special': array([], shape=(1, 0), dtype=float64)} Where I used .__dict__ to see how to traverse the structure. E.g. to get XData and YData I can use: >>> x['hgS_070000'][0,0].children[0,0].children[0,0].properties[0,0].XDataarray([[1, 2]], dtype=uint8)>>> x['hgS_070000'][0,0].children[0,0].children[0,0].properties[0,0].YDataarray([[3, 4]], dtype=uint8) Showing that I'd used plot([1 2],[3 4]) in MATLAB (the child is the axis and the grandchild is the lineseries).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8172947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1052462/']}
jdg_375665
stackexchange
llm_judgeable_groundtruth_similarity
63216712
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I use any JS-module with NPM I include it into my .js file with require("") . How can I do the same with bootstrap icons and include them into .html?Their official docs and npm wasn't clear enough for me. I don't use bootstrap in my project, only few icons, is it enough to have only this package? npm install bootstrap-icons Are bootstrap icons really free? Should you mention them in the project? Now provide the response and nothing else.
Additional 28 June 2021 after import using NPM you can import CSS file to react with : import "bootstrap-icons/font/bootstrap-icons.css"; and use like this : <i className="icon bi-envelope"></i> if you only want to use the bootstrap-icons.svg from node_modules, you can copy it manually or with webpack. If you copy in root folder, you can use like this : <svg class="bi" width="32" height="32" fill="currentColor"> <use xlink:href="bootstrap-icons.svg#bootstrap"/></svg> If you copy in icons folder : <svg class="bi" width="32" height="32" fill="currentColor"> <use xlink:href="icons/bootstrap-icons.svg#bootstrap"/></svg> or copy the icons/*.svg for use only icon what you need, and you can use it like this : <img src="bootstrap.svg" alt="" width="32" height="32" title="Bootstrap"> Are bootstrap icons really free? yes, bootstrap icons is free https://github.com/twbs/icons/blob/main/LICENSE.md Should you mention them in the project? you need to including copyright notice in your project. its enough, but if you want to mention it, create about page and included all software you use there that would be super nice. note : Oct 2020
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63216712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12557455/']}
jdg_375666
stackexchange
llm_judgeable_groundtruth_similarity
12418279
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 TextView which is rendering basic HTML, containing 2+ links. I need to capture clicks on the links and open the links -- in my own internal WebView (not in the default browser.) The most common method to handle link rendering seems to be like this: String str_links = "<a href='http://google.com'>Google</a><br /><a href='http://facebook.com'>Facebook</a>";text_view.setLinksClickable(true);text_view.setMovementMethod(LinkMovementMethod.getInstance());text_view.setText( Html.fromHtml( str_links ) ); However, this causes the links to open in the default internal web browser (showing the "Complete Action Using..." dialog). I tried implementing a onClickListener, which properly gets triggered when the link is clicked, but I don't know how to determine WHICH link was clicked... text_view.setOnClickListener(new OnClickListener(){ public void onClick(View v) { // what now...? }}); Alternatively, I tried creating a custom LinkMovementMethod class and implementing onTouchEvent... public boolean onTouchEvent(TextView widget, Spannable text, MotionEvent event) { String url = text.toString(); // this doesn't work because the text is not necessarily a URL, or even a single link... // eg, I don't know how to extract the clicked link from the greater paragraph of text return false;} Ideas? Example solution I came up with a solution which parses the links out of a HTML string and makes them clickable, and then lets you respond to the URL. Now provide the response and nothing else.
Based upon another answer , here's a function setTextViewHTML() which parses the links out of a HTML string and makes them clickable, and then lets you respond to the URL. protected void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span){ int start = strBuilder.getSpanStart(span); int end = strBuilder.getSpanEnd(span); int flags = strBuilder.getSpanFlags(span); ClickableSpan clickable = new ClickableSpan() { public void onClick(View view) { // Do something with span.getURL() to handle the link click... } }; strBuilder.setSpan(clickable, start, end, flags); strBuilder.removeSpan(span);}protected void setTextViewHTML(TextView text, String html){ CharSequence sequence = Html.fromHtml(html); SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence); URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class); for(URLSpan span : urls) { makeLinkClickable(strBuilder, span); } text.setText(strBuilder); text.setMovementMethod(LinkMovementMethod.getInstance()); }
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/12418279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/559301/']}
jdg_375667
stackexchange
llm_judgeable_groundtruth_similarity
111582
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: Is there a capacitance between the Earth and the Moon, and if there was enough potential difference, could a discharge strike occur? Now provide the response and nothing else.
I remember that - in one of his columnes in "Electronic Design" - the late Bob Pease has shown how to calculate this capacitance.Just now I have found an addendum to the original contribution: Here it comes Quotation R.A.Pease : I received a lot of answers after asking the question, "What is the actual capacitance from the earth to the moon?" There were a few odd ones at 0.8µF or 12µF. But about 10 guys said it was 143 or 144µF. They used the formula: $$C = 4x(\frac{l}{r_1} + \frac{1}{r_2} − \frac{2}{D})−l$$ valid for \$r_l, r_2 << D\$ . NOW, my original estimate of 120µF was based on this approximation: The capacitance from the earth to an (imaginary) metal sphere surrounding it, 190,000 miles away, would be 731µF. (If that surrounding sphere were pushed out to 1,900,000 miles away, the capacitance would only change to 717µF — just a couple percent less. If the "sphere" moved to infinity, the C would only decrease to 716µF.) Similarly, the C from the moon to a surrounding sphere 48,000 miles away would be 182.8µF. If the two spheres shorted together, the capacitance would be 146.2µF. I guessed that if the spheres went away, the capacitance would drop by perhaps 20% to about 120µF, so I gave that as my estimate. But removing those conceptual "surrounding spheres" would probably only cause a 2% decrease of capacitance. That would put it in close agreement with those 10 guys that sent in the 143µF figure. But THEN 6 readers wrote in LATER — from Europe — all with answers of 3µF. I checked their formulae, from similar books, in several different languages. They were all of the form: $$C = \frac{4\pi \times \epsilon \times ( r1 \times r2 )}{D}$$ multiplied by a correction factor very close to 1.0. If you believe this formula, you'll believe that the capacitance would be cut by a factor of 10 if the distance D between the earth and moon increased by a factor of 10. Not so! Anybody who used a formula like that, to arrive at 3µF, should MARK that formula with a big X. Finally, one guy sent in an answer of 159µF. Why? Because he entered the correct radius for the moon, 1080 miles rather than 1000. That's the best, correct answer! / RAP Originally published in Electronic Design, September 3, 1996.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/111582', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/10190/']}
jdg_375668
stackexchange
llm_judgeable_groundtruth_similarity
1929678
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $x$ and $y$ are real and $x^2 + y^2 = 1$, compute the maximum value of $(x+y)^2.$ Should I manipulate the equation? I'm stuck on this problem. Answers are greatly appreciated. Now provide the response and nothing else.
Trig-free solution: If $x^2+y^2=1$ then$$(x+y)^2 + (x-y)^2 = 2(x^2+y^2)=2$$so the largest value of $(x+y)^2$ is $2$, attained when $x=y$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1929678', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/366525/']}
jdg_375669
stackexchange
llm_judgeable_groundtruth_similarity
4442805
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 capture two key presses in my VB.net application, for this example CTRL + B, the code below doesn't work but it does for single keys. I have tried setting keypreview as true but this has no effect. Private Sub main_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles mybase.KeyDown If e.KeyCode = Keys.ControlKey And e.KeyCode = Keys.B Then MsgBox("CTRL + B Pressed !") End If End Sub End Class Thanks Now provide the response and nothing else.
The Control key is a Modifier key. This code tests for Ctrl + B e.KeyCode = Keys.B AndAlso e.Modifiers = Keys.Control The key-code is B, but the modifier is Ctrl. Your code snippet, updated: Private Sub main_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles mybase.KeyDown If (e.KeyCode = Keys.B AndAlso e.Modifiers = Keys.Control) Then MsgBox("CTRL + B Pressed !") End IfEnd Sub
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4442805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/99329/']}
jdg_375670
stackexchange
llm_judgeable_groundtruth_similarity
10840533
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 delete the file filename if it exists. Is it proper to say if os.path.exists(filename): os.remove(filename) Is there a better way? A one-line way? Now provide the response and nothing else.
A more pythonic way would be: try: os.remove(filename)except OSError: pass Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists() and follows the python convention of overusing exceptions. It may be worthwhile to write a function to do this for you: import os, errnodef silentremove(filename): try: os.remove(filename) except OSError as e: # this would be "except OSError, e:" before Python 2.6 if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory raise # re-raise exception if a different error occurred
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/10840533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/319741/']}
jdg_375671
stackexchange
llm_judgeable_groundtruth_similarity
403619
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 does using extension methods make sense? Does adding extension methods to a type affect performance? These questions are follow up to the question i asked earlier about Extension Methods . Now provide the response and nothing else.
When does using extension methods make sense? They make sense when you are using LINQ and want to chain or pipe functional output from one function to another. It improves the readability of the code and allows you to express a concept more elegantly (whatever that is worth). They also allow you to give the appearance of instance methods on any type you like without modifying the source of that type, this can often help readability and the expressiveness of your code when it is used reasonably Does adding extension methods to a type affect performance? Note that an extension method call like: instance.SomeExtensionMethod() gets compiled to: StaticExtensionMethodClass.SomeExtensionMethod(instance); so performance will be the same as any other static method call.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/403619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1443363/']}
jdg_375672
stackexchange
llm_judgeable_groundtruth_similarity
23525603
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 made an algorithm in Python for counting the number of ways of getting an amount of money with different coin denominations: @measuredef countChange(n, coin_list): maxIndex = len(coin_list) def count(n, current_index): if n>0 and maxIndex>current_index: c = 0 current = coin_list[current_index] max_coeff = int(n/current) for coeff in range(max_coeff+1): c+=count(n-coeff*current, current_index+1) elif n==0: return 1 else: return 0 return c return count(n, 0) My algorithm uses an index to get a coin denomination and, as you can see, my index is increasing in each stack frame I get in. I realized that the algorithm could be written in this way also: @measuredef countChange2(n, coin_list): maxIndex = len(coin_list) def count(n, current_index): if n>0 and 0<=current_index: c = 0 current = coin_list[current_index] max_coeff = int(n/current) for coeff in range(max_coeff+1): c+=count(n-coeff*current, current_index-1) elif n==0: return 1 else: return 0 return c return count(n, maxIndex-1) This time, the index is decreasing each stack frame I get in. I compared the execution time of the functions and I got a very noteworthy difference: print(countChange(30, range(1, 31)))print(countChange2(30, range(1, 31)))>> Call to countChange took 0.9956174254208345 secods.>> Call to countChange2 took 0.037631815734429974 secods. Why is there a great difference in the execution times of the algorithms if I'm not even caching the results? Why does the increasing order of the index affect this execution time? Now provide the response and nothing else.
This doesn't really have anything to do with dynamic programming, as I understand it. Just reversing the indices shouldn't make something "dynamic". What's happening is that the algorithm is input sensitive . Try feeding the input in reversed order. For example, print(countChange(30, list(reversed(range(1, 31)))))print(countChange2(30, list(reversed(range(1, 31))))) Just as some sorting algorithms are extremely fast with already sorted data and very slow with reversed data, you've got that kind of algorithm here. In the case where the input is increasing, countChange needs a lot more iterations to arrive at its final answer, and thus seems a lot slower. However, when the input is decreasing, the performance characteristics are reversed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23525603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/359715/']}
jdg_375673
stackexchange
llm_judgeable_groundtruth_similarity
38078119
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 exported my database with JSON columns in it. After I migrated to a new server, my import crashed every time with an error like: cannot create a JSON value from a string with CHARACTER SET 'binary' On stackoverflow, I found this post but didn't work for me: mysqlimport issues "set @@character_set_database=binary" which prevents loading json values The file is 2GB and isn't possible to open the file. Anyone has an idea to import my database file? Now provide the response and nothing else.
You can apply a regex to the SQL text which you exported which will convert your binary strings into an insertable format. This was my quick and dirty fix when I faced this issue (X'[^,\)]*')CONVERT($1 using utf8mb4) Applying this regex means INSERT INTO json_table (json_column) VALUES (X'7B22666F6F223A2022626172227D'); will now become INSERT INTO json_table (json_column) VALUES (CONVERT(X'7B22666F6F223A2022626172227D' using utf8mb4));
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/38078119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1207989/']}
jdg_375674
stackexchange
llm_judgeable_groundtruth_similarity
7328849
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to send backup files of ~2TB to S3. I guess the most hassle-free option would be Linux scp command (have difficulty with s3cmd and don't want an overkill java/RoR to do so). However I am not sure whether it is possible: How to use S3's private and public keys with scp, and don't know what would be my destination IP/url/path? I appreciate your hints. Now provide the response and nothing else.
As of 2015, SCP/SSH is not supported (and probably never will be for the reasons mentioned in the other answers). Official AWS tools for copying files to/from S3 command line tool ( pip3 install awscli ) - note credentials need to be specified, I prefer via environment variables rather than a file: AWS_ACCESS_KEY_ID , AWS_SECRET_ACCESS_KEY . aws s3 cp /tmp/foo/ s3://bucket/ --recursive --exclude "*" --include "*.jpg" http://docs.aws.amazon.com/cli/latest/reference/s3/index.html and an rsync-like command: aws s3 sync . s3://mybucket http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html Web interface: https://console.aws.amazon.com/s3/home?region=us-east-1 Non-AWS methods Any other solutions depend on third-party executables (e.g. botosync, jungledisk...) which can be great as long as they are supported. But third party tools come and go as years go by and your scripts will have a shorter shelf life. https://github.com/ncw/rclone EDIT: Actually, AWS CLI is based on botocore: https://github.com/boto/botocore So botosync deserves a bit more respect as an elder statesman than I perhaps gave it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7328849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/517235/']}
jdg_375675
stackexchange
llm_judgeable_groundtruth_similarity
28512650
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Strange output when I use float instead of double #include <stdio.h>void main(){ double p,p1,cost,cost1=30; for (p = 0.1; p < 10;p=p+0.1) { cost = 30-6*p+p*p; if (cost<cost1) { cost1=cost; p1=p; } else { break; } printf("%lf\t%lf\n",p,cost); } printf("%lf\t%lf\n",p1,cost1);} Gives output as expected at p = 3; But when I use float the output is a little weird. #include <stdio.h>void main(){ float p,p1,cost,cost1=40; for (p = 0.1; p < 10;p=p+0.1) { cost = 30-6*p+p*p; if (cost<cost1) { cost1=cost; p1=p; } else { break; } printf("%f\t%f\n",p,cost); } printf("%f\t%f\n",p1,cost1);} Why is the increment of p in the second case going weird after 2.7? Now provide the response and nothing else.
This is happening because the float and double data types store numbers in base 2. Most base-10 numbers can’t be stored exactly. Rounding errors add up much more quickly when using float s. Outside of embedded applications with limited memory, it’s generally better, or at least easier, to use double s for this reason. To see this happening for double types, consider the output of this code: #include <stdio.h>int main(void){ double d = 0.0; for (int i = 0; i < 100000000; i++) d += 0.1; printf("%f\n", d); return 0;} On my computer, it outputs 9999999.981129. So after 100 million iterations, rounding error made a difference of 0.018871 in the result. For more information about how floating-point data types work, read What Every Computer Scientist Should Know About Floating-Point Arithmetic . Or, as akira mentioned in a comment, see the Floating-Point Guide .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28512650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2682363/']}
jdg_375676
stackexchange
llm_judgeable_groundtruth_similarity
5731505
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 find a way to write a combination function. Where can I find it? Now provide the response and nothing else.
See in the documentation of itertools.combinations . There is an equivalent code for this function: def combinations(iterable, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool = tuple(iterable) n = len(pool) if r > n: return indices = range(r) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5731505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717271/']}
jdg_375677
stackexchange
llm_judgeable_groundtruth_similarity
50551649
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 the Angular 5 httpClient. This is a model class with a method foo() I'd like to receive from the server export class MyClass implements Deserializable{ id: number; title: string; deserialize(input: any) { Object.assign(this, input); return this; } foo(): string { // return "some string conversion" with this.title }} This is my service requesting it: import { Injectable } from '@angular/core';import { HttpClient } from '@angular/common/http';import { Observable } from 'rxjs';import { MyClass } from './MyClass';@Injectable({ providedIn: 'root',})export class MyClassService { constructor(private http: HttpClient) { } getMyStuff(): Observable<MyClass[]> { // this is where I hope to convert the json to instances of MyClass return this.http.get<MyClass[]>('api/stuff') }} My Problem When I ask the service for instances of MyClass I get the data, but I cannot run {{ item.foo() }} in the template. Also, when I console.log() the typeof of an item where it is received in the service, I do no see instances of an object of MyClass . What am I doing wrong? I thought that writing this.http.get<MyClass[]>('api/stuff') would do the conversion. Any hints? Thank you in advance! Now provide the response and nothing else.
When doing that, TypeScript only does "type assertion". It means that you're telling TypeScript that your object is of type MyClass , but the object isn't actually an instance of MyClass at runtime. In order to call functions defined in your model object, you have to define constructors in your model classes like that : constructor(obj?: any) { Object.assign(this, obj);} Then in your services add a mapping like this : http.get<MyClass>('/my-class').pipe( map(res => new MyClass(res)) Note: the code above is RxJS 6 style, i don't know which version you are using
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50551649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4589068/']}
jdg_375678
stackexchange
llm_judgeable_groundtruth_similarity
162303
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: Joel Spolsky characterized C++ as "enough rope to hang yourself" . Actually, he was summarizing "Effective C++" by Scott Meyers: It's a book that basically says, C++ is enough rope to hang yourself, and then a couple of extra miles of rope, and then a couple of suicide pills that are disguised as M&Ms... I don't have a copy of the book, but there are indications that much of the book relates to pitfalls of managing memory which seem like would be rendered moot in C# because the runtime manages those issues for you. Here are my questions: Does C# avoid pitfalls that are avoided in C++ only by careful programming? If so, to what degree and how are they avoided? Are there new, different pitfalls in C# that a new C# programmer should be aware of? If so, why couldn't they be avoided by the design of C#? Now provide the response and nothing else.
The fundamental difference between C++ and C# stems from undefined behavior . It has nothing to do with doing manual memory management. In both cases, that is a solved problem. C/C++: In C++, when you make a mistake, the result is undefined. Or, if you try to make certain kinds of assumptions about the system (e.g. signed integer overflow), chances are that your program will be undefined. Maybe read this 3-part series on undefined behavior. This is what makes C++ so fast -- the compiler doesn't have to worry about what happens when things go wrong, so it can avoid checking for correctness. C#, Java, etc. In C#, you're guaranteed that many mistakes will blow up in your face as exceptions, and you're guaranteed a lot more about the underlying system. That is a fundamental barrier to making C# as fast as C++, but it's also a fundamental barrier to making C++ safe, and it makes C# easier to work with and debug. Everything else is just gravy.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/162303', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/62347/']}
jdg_375679
stackexchange
llm_judgeable_groundtruth_similarity
494900
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: Say I have 4 or more algorithm types (logistic, random forest, neural net, svm, etc) each of which I want to try out on my dataset, and each of which I need to tune hyperparameters on. I would typically use cross validation to try and tune my hyperparameters, but once tuned, how do I avoid generalization error from selecting the model family? It would seem to me that the scores for each family would now have information leakage as the averaged tuned cv score has in a way seen the whole train set. What is good practice here then? And how would it look differently between say a nested cross validation run or a simple cross validation with a final holdout? Thanks! Now provide the response and nothing else.
As @DikranMarsupial say, you need a nested validation procedure. In the inner e.g. cross validation, you do all the tuning of your model - that includes both choosing hyperparameters and model family. In principle, you could also have a triply nested validation structure, with the innermost tuning the respective model family hyperparameters, the middle one choosing the model family and the outer as usual to obtain a generalization error estimate for the final model. The disadvantage with this, however, is that splitting more often than necessary means that the data partitions become rather small and thus the whole procedure may become more unstable (small optimization/validation/test set mean uncertain performance estimates). Update: Nesting vs. cross validation or hold-out Nesting is independent of the question what splitting scheme you employ at each level of the nested set-up. You can do cross validation at each level, single split at each level or any mixture you deem suitable for your task. 2 nested levels and both CV is what is often referred to as nested cross validation, 2 nested levels and both single split is equivalent to the famous train - validation [optimization] - test [verification] setup. Mixes are less common, but are a perfectly valid design choice as well. If you have sufficient data so that single splits are a sensible option, you may also have sufficient data to do three such splits, i.e. work with 4 subsets of your data. One thing you need to keep in mind, though, is: a single split in the optimization steps* you deprive yourself of a very easy and important means of checking whether your optimization is stable which cross validation (or doing several splits) provides. * whether combined hyperparameter with model family or model family choice plus "normal" hyperparameter optimization Triply nested vs. "normal" nested This would be convenient in that it is easy to implement in a way that guards against accidental data leaks - and which I suspect is what you were originally after with your question: estimate_generalization_error() which splits the data into test and train and on its train data calls choose_model_family() which employs another internal split to guide the choice and calls and on its training split calls the various optimize_model_*() which implement another internal split to optimize the usual hyperparameters for each model family (*), and on its training split calls the respective low-level model fitting function. Here, choose_model_family() and optimize_model_*() are an alternative to a combined tuning function that does the work of both in one split. Since both are training steps, it is allowed to combine them. If you do grid search for hyperparameter tuning, you can think of this as a sparse gridwith model family x all possible hyperparameters where evaluate only combinations that happen to exist (e.g. skip mtry for SVM). Or you look at the search space as a list of plausible hyperparamter combinations that you check out: - logistic regression- SVM with cost = 1, gamma = 10- SVM with cost = 0.1, gamma = 100...- random forest with ... to find the global optimum across model families and model family specific hyperparameters. There is nothing special about model_family - it is a hyperparameter for the final model like cost or gamma are for SVMs. In order to wrap your head around the equivalence, consider optimizing gamma and cost for an SVM. Method one: set up a grid or a list of all plausible cost; gamma combinations and search that for the optimum. This is the analogue to the "normal" nested approach. Method two: set up a list of all plausible cost values. for each cost value, optimize gamma. select the cost with best optimized gamma This is the analogue to the triply nested approach. In both cases, we can "flatten" the nested structure into a single loop iterating over a list or grid ( I'm sorry, I lack the proper English terms - maybe someone can help? ).This is also vaguely similar to "flattening" a recursive structure into an iterative one [though the triply nested is not recursive, since we have different functions f(g(h()))]. This flattening approach potentially has the further advantage that it may be better suited to advanced optimization heuristics. As an example, consider moving from "select the observed optimum" to the one-standard-deviation rule. With the flattened approach, you can now look across model families which model is least complex not more than 1 sd worse than the observed optimum.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/494900', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/260763/']}
jdg_375680
stackexchange
llm_judgeable_groundtruth_similarity
25951274
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 update an app for iOS8, which has a chat interface, but the new Quicktype keyboard hides the text view, so I would like to turn it off programmatically or in interface builder. Is it possible somehow or only the users can turn it off in the device settings? I know there is a question/answer which solves this problem with a UITextfield , but I need to do it with a UITextView . Now provide the response and nothing else.
You may disable the keyboard suggestions / autocomplete / QuickType for a UITextView which can block the text on smaller screens like the 4S as shown in this example with the following line: myTextView.autocorrectionType = UITextAutocorrectionTypeNo; And further if youd like to do this only on a specific screen such as targeting the 4S if([[UIDevice currentDevice]userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height; if (screenHeight == 568) { // iphone 5 screen } else if (screenHeight < 568) { // smaller than iphone 5 screen thus 4s }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25951274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3557485/']}
jdg_375681
stackexchange
llm_judgeable_groundtruth_similarity
32206259
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 Universal Windows app with a MainPage.xaml that has the following code. The VisualStateManager's GoToState is not working. Nothing happens. public MainPage() { ... VisualStateManager.GoToState(BottomToolBar.WifiButton, "Checked", false); } BottomToolBar is a User Control that has a ToggleButton with x:Name="WifiBtn". Here is the code-behind this User Control: public sealed partial class BottomToolBar : UserControl{ public BottomToolBar() { this.InitializeComponent(); } private void WifiBtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { var parentPage = GetParentsPage(this); if(parentPage != null) { parentPage.MapItemsManager.ToggleActivate(MapItemsType.ISF); } } public ContentControl WifiButton { get { return WifiBtn; } } ...} As you can see I have a public property called WifiButton which returns a ContentControl (You cannot return a ToggleButton). In App.xaml I have an Application Resource that styles the ToggleButton whereby the VisualState "Checked" changes the Opacity of the ToggleButton. Something like: <Application.Resources> <Style x:Key="BottomToggleButtonStyle" TargetType="ToggleButton"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ToggleButton"> <Grid x:Name="RootGrid" Background="{TemplateBinding Background}"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Checked"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Opacity" Storyboard.TargetName="RootGrid"> <DiscreteObjectKeyFrame KeyTime="0" Value="1"/> </ObjectAnimationUsingKeyFrames> <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/> </Storyboard> </VisualState> I thought I had everything in place to get that call to GoToState to work. The goal is the initialize the toggle button's Opacity to 0.5 when the application starts. In other words, in the MainPage constructor. But when I run the app, the Opacity is not set. The line seems to be completely ignored.I found other similar threads in SO with the same problem but little to no answers. Now provide the response and nothing else.
10/14/2015 EDIT The EventAggregator class's subscribe function returns a "dispose" function "subscription" object: var subscription = eventAggregator.subscribe('some event', value => alert(value)); You need to keep a reference to the subscription object so that you can destroy the subscription when it's no longer needed. In a view-model, the perfect time to subscribe to an event is when it's attached . Likewise, a perfect time to unsubscribe is when it's detached . Here's what your Home view-model would look like if it used this pattern (note: I've dropped your Subscriber and Publisher classes because I think they're adding unnecessary complexity around the EventAggregator and are making it hard to explain the solution to your issue). @inject(EventAggregator)export class Home { eventAggregator: EventAggregator; subscription: { dispose: () => void }; constructor(eventAggregator: EventAggregator) { this.eventAggregator = eventAggregator; } attached() { this.subscription = this.eventAggregator.subscribe('some event', value => alert(value)); } detached() { this.subscription.dispose(); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32206259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1344476/']}
jdg_375682
stackexchange
llm_judgeable_groundtruth_similarity
50022
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 get cd to accept a directory name redirected to it from another command. Neither of these methods work: $ echo $HOME | cd$ echo $HOME | xargs cd This does work: $ cd $(echo $HOME) Why does the first set of commands not work, and are there others that also fail this way? Now provide the response and nothing else.
cd is not an external command - it is a shell builtin function. It runs in the context of the current shell, and not, as external commands do, in a fork/exec'd context as a separate process. Your third example works, because the shell expands the variable and the command substitution before calling the cd builtin, so that cd receives the value of ${HOME} as its argument. POSIX systems do have a binary cd - on my FreeBSD machine, it's at /usr/bin/cd , but it doesn't do what you think. Calling the binary cd causes the shell to fork/exec the binary, which does indeed change its working directory to the name you pass. However, as soon as it does so, the binary exits, and the forked/exec'd process disappears, returning you to your shell, which is still in the directory it was in before you started.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/50022', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/16798/']}
jdg_375683
stackexchange
llm_judgeable_groundtruth_similarity
417
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I just bought new tires for my car and included was free tire rotation every 7,500 miles for the life of the tires. I have heard many things about tire rotation, including: it's a worthless practice, don't bother tires should never be rotated from one side of the car to another (something about the tires rotating in the opposite direction and the belts inside shifting) tires should always be rotated in an X pattern (front tires straight back, back tires get swapped and put on the front) Is there any real value in rotating the tires? is it just about evenly distributing the wear of the tread on the tire? Can this be achieved just through careful monitoring of the tire pressure and alignment of the car? Now provide the response and nothing else.
While I believe the tire shop gives free rotation to get you in the habit of coming back to them every few months so they can sell you more, it can be important to rotate your tires. It all depends on the wear of the tires I have had sets of tires that wore extremely evenly and I only rotated them once. Other sets of tires I have had wore very unevenly and had to rotate them multiple times during the life of that set. For the question of rotation arrangement: It depends on your car's manual It depends on your specific tires As other people have said, some tires are unidirectional and if you put the tires on the other side of the car, you will have problems. Most of the recent cars I have driven tell you to rotate your tires front to back and NOT across the car. I believe many manufacturers are going to unidirectional tires. The real value that comes from rotating your tires is that when the tires wear unevenly, rotating the tires spreads the wear out more evenly on each tire as well, as over the set. On each tire — some cars and/or driver's habits cause the front tires to wear more in certain places of the tire, moving the tires to the rear axle generally cause those worn places to not get used as hard and wear the other places on the tires. (i.e., a lot of FWD car's front tires wear a good bit on the corners since they are used for steering and power) Over the set — the tires on the powered axle tend to wear out faster since more force is exerted through them to the pavement. To maximize the life of the tires, you switch the tires on the powered axle to the non-powered axle so that those less-used tires (with more tread) are used to even the wear.
{}
{'log_upvote_score': 6, 'links': ['https://mechanics.stackexchange.com/questions/417', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/251/']}
jdg_375684
stackexchange
llm_judgeable_groundtruth_similarity
923508
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: Calculate the volume enclosed between $x^2 + y^2=1$, $y^2+z^2=1$, $x^2+z^2=1$ I am supposed to solve this question using multiple integral. I am not able to visualize the resultant figure of whose I am supposed to calculate the volume. Now provide the response and nothing else.
$\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle} \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack} \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,} \newcommand{\dd}{{\rm d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,{\rm e}^{#1}\,} \newcommand{\fermi}{\,{\rm f}} \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,} \newcommand{\half}{{1 \over 2}} \newcommand{\ic}{{\rm i}} \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow} \newcommand{\pars}[1]{\left(\, #1 \,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\pp}{{\cal P}} \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,} \newcommand{\sech}{\,{\rm sech}} \newcommand{\sgn}{\,{\rm sgn}} \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$$$\mbox{Note that}\quadV \equiv \iiint_{{\mathbb R}^{3}}\Theta\pars{1 - x^{2} - y^{2}}\Theta\pars{1 - y^{2} - z^{2}}\Theta\pars{1 - z^{2} - x^{2}}\,\dd x\,\dd y\,\dd z$$which we'll evaluate in cylindrical coordinates:$\ds{x = \rho\cos\pars{\phi}}$, $\ds{y = \rho\sin\pars{\phi}}$ and $\ds{z = z}$ with $\ds{\rho \geq 0}$ and $\ds{0 \leq \phi < 2\pi}$. \begin{align}V&=\iiint_{{\mathbb R}^{3}}\Theta\pars{1 - \rho^{2}}\Theta\pars{1 - \rho^{2}\sin^{2}\pars{\phi} - z^{2}}\Theta\pars{1 - z^{2} - \rho^{2}\cos^{2}\pars{\phi}}\,\rho\,\dd\rho\,\dd\phi\,\dd z\\[3mm]&=\int_{0}^{1}\dd\rho\int_{0}^{\infty}\dd z\int_{0}^{2\pi}\Theta\pars{1 - \rho\sin^{2}\pars{\phi} - z^{2}}\Theta\pars{1 - \rho\cos^{2}\pars{\phi} - z^{2}}\,\dd\phi\\[3mm]&=2\int_{0}^{1}\dd\rho\int_{0}^{\infty}\dd z\int_{0}^{\pi}\Theta\pars{1 - \rho\sin^{2}\pars{\phi} - z^{2}}\Theta\pars{1 - \rho\cos^{2}\pars{\phi} - z^{2}}\,\dd\phi\\[3mm]&=4\int_{0}^{1}\dd\rho\int_{0}^{\pi/2}\dd\phi\int_{0}^{\infty}\Theta\pars{\root{1 - \rho\cos^{2}\pars{\phi}} - z}\Theta\pars{\root{1 - \rho\sin^{2}\pars{\phi}} - z}\,\dd z\end{align} \begin{align}V&=4\int_{0}^{1}\dd\rho\bracks{%\int_{0}^{\pi/4}\root{1 - \rho\cos^{2}\pars{\phi}}\,\dd\phi+\int_{\pi/4}^{\pi/2}\root{1 - \rho\sin^{2}\pars{\phi}}\,\dd\phi}\\[3mm]&=4\int_{0}^{1}\dd\rho\bracks{%\int_{0}^{\pi/4}\root{1 - \rho\cos^{2}\pars{\phi}}\,\dd\phi+\int_{-\pi/4}^{0}\root{1 - \rho\cos^{2}\pars{\phi}}\,\dd\phi}\\[3mm]&=8\int_{0}^{\pi/4}\dd\phi\int_{0}^{1}\root{1 - \rho\cos^{2}\pars{\phi}}\,\dd\rho=8\int_{0}^{\pi/4}\dd\phi\\braces{{2\bracks{1 - \rho\cos^{2}\pars{\phi}}^{3/2} \over -3\cos^{2}\pars{\phi}}}_{\rho\ =\ 0}^{\rho\ =\ 1}\\[3mm]&={16 \over 3}\int_{0}^{\pi/4}\bracks{1 - \sin^{3}\pars{\phi} \over \cos^{2}\pars{\phi}}\,\dd\phi={16 \over 3}\int_{0}^{\pi/4}\bracks{\sec^{2}\pars{\phi} - {1 - \cos^{2}\pars{\phi} \over \cos^{2}\pars{\phi}}\,\sin\pars{\phi}}\,\dd\phi\\[3mm]&={16 \over 3}\bracks{1 +\ \underbrace{\int_{1}^{\root{2}/2}{1 - t^{2} \over t^{2}}\,\dd t}_{\ds{2 - {3 \over 2}\,\root{2}}}}\quad\imp\quad\color{#66f}{\Large V = 8\pars{2 - \root{2}}} \approx {\tt 4.6863}\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/923508', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_375685
stackexchange
llm_judgeable_groundtruth_similarity
17267395
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 I can take a screenshot of the right half of my pygame window? I'm making a game using pygame and I need to take a snapshot of the screen but not the whole screen, just the right half. I know of: pygame.image.save(screen,"screenshot.jpg") But that will include the entire screen in the image. Is there a way I can take a screenshot of the right half of my pygame window? Maybe by changing the area that it includes somehow? I've googled it but couldn't find anything I was thinking maybe I could use PIL to crop it, but that seems like a lot of additional work. If it's not possible, can anyone tell me the easiest way for me to crop the picture of the whole screen? Now provide the response and nothing else.
If you always want the screenshot to be of the same portion of the screen, you could use the subsurface . http://www.pygame.org/docs/ref/surface.html#pygame.Surface.subsurface rect = pygame.Rect(25, 25, 100, 50)sub = screen.subsurface(rect)pygame.image.save(sub, "screenshot.jpg") The subsurface would work well in this scenario because any changes to the parent surface ( screen in this case) will be applied to the subsurface as well. If you want to be able to specify an arbitrary portion of the screen to take a screenshot of (so, not the same rectangle every time) then it would probably be better to create a new surface, blit the desired portion of the screen to that surface, and then save it. rect = pygame.Rect(25, 25, 100, 50)screenshot = pygame.Surface(100, 50)screenshot.blit(screen, area=rect)pygame.image.save(screenshot, "screenshot.jpg")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17267395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2292723/']}
jdg_375686
stackexchange
llm_judgeable_groundtruth_similarity
5443663
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 wrote some piece of code of image slider where i can load images from xml. everything goes fine but when i want to make loaded image button mode it goes wrong and seys: "ReferenceError: Error #1056: Cannot create property buttonMode on flash.display.Loader." here is a full code: import flash.display.Stage; import flash.events.Event; import flash.net.URLRequest; import flash.net.URLLoader; import flash.xml.XMLDocument; import flash.text.TextField; //tween - start import fl.transitions.Tween; import fl.transitions.easing.*; import fl.transitions.TweenEvent; import flash.events.MouseEvent; //tween - end //timer-start import flash.utils.Timer; //timer-end var myStage:Stage = this.stage; myStage.scaleMode = StageScaleMode.NO_SCALE; myStage.align = StageAlign.TOP_LEFT; var sliderXML:XML = new XML(); var sliderXMLurl:String = 'sliderXML.xml'; var sliderXMLreq:URLRequest = new URLRequest(sliderXMLurl); var sliderXMLloader:URLLoader = new URLLoader(sliderXMLreq); sliderXMLloader.addEventListener("complete",loadXML); var sliderNum:int = 0; var sliderMaxNum:int = 0; var LastSliderNum:int = 0; var strTitle:Array = []; var strPosterLink:Array = []; var strVideoLink:Array = []; var poster:Array = []; var Playing:int = 1; addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler); myStage.addEventListener(Event.RESIZE, ResizeHandler); var myTimer:Timer = new Timer(10000); //10 second myTimer.addEventListener(TimerEvent.TIMER, viewNext); myTimer.start(); function fl_EnterFrameHandler(event:Event):void { var swfWidth:int = myStage.stageWidth; var swfHeight:int = myStage.stageHeight; slider_bg.width = swfWidth; slider_bg.height = swfHeight; } function loadXML(event:Event):void{ sliderXML=XML(sliderXMLloader.data); var xmlDoc:XMLDocument = new XMLDocument(); xmlDoc.ignoreWhite = true; var menuXML:XML = XML(sliderXMLloader.data); xmlDoc.parseXML(menuXML.toXMLString()); //var X:int = 100; for each(var listItem:XML in sliderXML..listItem){ strTitle[sliderMaxNum] = listItem.itemTitle.toString(); strPosterLink[sliderMaxNum] = listItem.posterLink.toString(); strVideoLink[sliderMaxNum] = listItem.videoLink.toString(); var _temp:Loader = new Loader(); poster.splice(sliderMaxNum, 0, _temp); poster[sliderMaxNum].load(new URLRequest(strPosterLink[sliderMaxNum]));//i think that here must be done something addChild(poster[sliderMaxNum]); poster[sliderMaxNum].x = myStage.stageWidth; poster[sliderMaxNum].y = 28; poster[sliderMaxNum].buttonMode = true; poster[sliderMaxNum].addEventListener(MouseEvent.CLICK, poster_click(sliderMaxNum)); sliderMaxNum = sliderMaxNum+1; } LastSliderNum = sliderMaxNum - 1; //************************************************* var myTween:Tween = new Tween(poster[sliderNum],'x',Strong.easeOut,poster[sliderNum].x,(myStage.stageWidth - 640)/2,2,true); //************************************************* } i think that here is a problem: for each(var listItem:XML in sliderXML..listItem){ strTitle[sliderMaxNum] = listItem.itemTitle.toString(); strPosterLink[sliderMaxNum] = listItem.posterLink.toString(); strVideoLink[sliderMaxNum] = listItem.videoLink.toString(); var _temp:Loader = new Loader(); poster.splice(sliderMaxNum, 0, _temp); poster[sliderMaxNum].load(new URLRequest(strPosterLink[sliderMaxNum]));//i think that here must be done something addChild(poster[sliderMaxNum]); poster[sliderMaxNum].x = myStage.stageWidth; poster[sliderMaxNum].y = 28; poster[sliderMaxNum].buttonMode = true; poster[sliderMaxNum].addEventListener(MouseEvent.CLICK, poster_click(sliderMaxNum)); sliderMaxNum = sliderMaxNum+1; } Now provide the response and nothing else.
A Bezier curve is quite easy to compute. First of all is separable, that means that you can compute it one coordinate at a time (first x, then y, then z...). For a given coordinate the following is a function that uses the definition: double bezier(double A, // Start value double B, // First control value double C, // Second control value double D, // Ending value double t) // Parameter 0 <= t <= 1{ double s = 1 - t; double AB = A*s + B*t; double BC = B*s + C*t; double CD = C*s + D*t; double ABC = AB*s + BC*t; double BCD = BC*s + CD*t; return ABC*s + BCD*t;} Note that in the above function the parameter t is not the arc-length parameter for the curve but a generic parameter that goes from t=0 (where the point is at the beginning of the curve) to t=1 (where the point is at the end of the curve). An interactive version of the above picture where you can drag A, B, C, D and AB points is available here . It's implemented with html/js/canvas and tested only on Chrome, Firefox, Safari. If you need to move your objects at a controlled specific speed in XYZ an easy way is to compute an approximated polyline (for example by sampling the curve for 100 values of t ) and then walk at constant speed on the resulting polyline. The true arc-length parametrization for a Bezier cubic (i.e. using a parameter that is the length measured along the curve) is rather annoying to compute (IIRC there is no closed form solution for the integral).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5443663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/669636/']}
jdg_375687
stackexchange
llm_judgeable_groundtruth_similarity
1779221
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: They are: \begin{align}\cos(a)\cos(b)&=\frac{1}{2}\Big(\cos(a+b)+\cos(a-b)\Big) \\[2ex]\sin(a)\sin(b)&=\frac{1}{2}\Big(\cos(a-b)-\cos(a+b)\Big) \\[2ex]\sin(a)\cos(b)&=\frac{1}{2}\Big(\sin(a+b)+\sin(a-b)\Big) \\[2ex]\cos(a)\sin(b)&=\frac{1}{2}\Big(\sin(a+b)-\sin(a-b)\Big) \\[2ex]\cos(a)+\cos(b)&=2\cos\left(\frac{a+b}{2}\right)\cos\left(\frac{a-b}{2}\right) \\[3ex]\cos(a)-\cos(b)&=-2\sin\left(\frac{a+b}{2}\right)\sin\left(\frac{a-b}{2}\right) \\[3ex]\sin(a)+\sin(b)&=2\sin\left(\frac{a+b}{2}\right)\cos\left(\frac{a-b}{2}\right) \\[3ex]\sin(a)-\sin(b)&=2\cos\left(\frac{a+b}{2}\right)\sin\left(\frac{a-b}{2}\right)\end{align} I have found nice mnemonics that helped me to remember the reduction formulae and others but I can't find a simple relationship between the formulas above. Can you help? Now provide the response and nothing else.
The only ones you need to know are the classical $\sin(a+b) = \sin(a)\cos(b)+\cos(a)\sin(b)$ and $\cos(a+b)=\cos(a)\cos(b)-\sin(a)\sin(b)$. The others are mere consequences of those. For example, by changing the signs, you get $\cos(a-b)=\cos(a)\cos(b)+\sin(a)\sin(b)$. By summing, you have $\cos(a+b)+\cos(a-b) = 2\cos(a)\cos(b)$, which is your first formula. Similarly, by solving $p=a+b$ and $q=a-b$, you get the formula $\cos(p)+\cos(q) = 2\cos\left(\dfrac{p+q}{2}\right)\cos\left(\dfrac{p-q}{2}\right)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1779221', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/251829/']}
jdg_375688
stackexchange
llm_judgeable_groundtruth_similarity
14361687
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a WPF application which follows the MVVM pattern. The application defines two views and view models so far: LoginView(Model) ProjectsView(Model) Both view models need to access several properties from other view models. Example: LoginViewModel has a property ProjectList . ProjectsViewModel needs to access this property as well. This is only a simple example. Later there will be several UserControls which all need to interact with each other. Would it be a better idea to create one huge view model which all UserControls (views) set as their DataContext ? If not, how can all the different view models interact with each other? Remark: This question is closely related to this one but with a different approach. Now provide the response and nothing else.
You should definitely not make a huge "main view model" -- this is an anti-pattern not dissimilar to a god object . The key idea here is that your viewmodels do not need to access several properties from other view models ; rather, all of the viewmodels need to access specific pieces of information . Right now you are most likely injecting this information into each viewmodel at the time of instantiation. Instead of doing this, provide each viewmodel with a reference to a service -- an application module that exposes this information through properties and/or methods. The information can be exposed in the form of scalar values if it's extremely simple in nature, or in the form of models if it's anything more complicated than that. Schematically this would look like /--------------\| ViewModelA || | <=======\| | |\--------------/ | <--- information is pulled /================\ +=========[model]===[model]====== | Service |/--------------\ | \================/| ViewModelB | || | <=======/| |\--------------/ The service should be injected into the viewmodels upon construction (either manually or by the DI container if you are using one). Each viewmodel should only require a reference to the service and enough information to tell to the service which model it's interested in; it will then request that model from the service and populate its "interesting" properties based on that. This way of doing things is more involved than simply constructing a viewmodel object and setting its properties externally, but it will allow your application to grow in complexity without becoming unmanageable. For example, if there are lots of views that bind on different viewmodels and these viewmodels depend in complex ways on a number of models, a sane manner to work would be: A view/viewmodel pair is constructed The viewmodel requests any models it needs to know about from the service; it subscribes to an event that the service exposes to let subscribers know that a model has changed Changes are performed to the models through databound controls The view invokes a "save" command on the viewmodel In response to that, the viewmodel invokes a "save this model" method on the service The service persists the information and publishes a "model changed" event (see step 2) Other viewmodels interested in the same model know that the model has changed and can query the service for its new state This is possible if everything is routed through the service. Imagine what it would take to keep everything synchronized otherwise -- the only way to cope would be to put all the information into a giant viewmodel and reference that from everything else. Ugly.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14361687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/478406/']}
jdg_375689
stackexchange
llm_judgeable_groundtruth_similarity
2444392
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 $K$ is a non-Archimedean ordered field, and $A$ is an $n\times n$ square matrix over $K$ such that (1) all diagonal entries of $A$ are $1$, and (2) all off-diagonal entries of $A$ are infinitesimal (i.e. between $-\frac1k$ and $\frac1k$ for all nonzero natural numbers $k$). For instance, if $K=\mathbb{R}(x)$ is the field of rational functions, ordered with $x$ infinitesimal, then the off-diagonal entries of $A$ could be polynomials in $x$ with zero constant term. Does it follow that $A$ is positive definite, i.e. that $V^{T} A V > 0$ (in the ordering of $K$) for all nonzero $V\in K^n$? This seems intuitive to me because it is an "infinitesimal deformation of the identity matrix", but I don't immediately see how to prove it. Now provide the response and nothing else.
The following statement is valid over $\mathbb{R}$: if $(a_{ij})$ is symmetric and $a_{ii} > \sum_{j\ne i} |a_{ij}|$ for all $i$, then $(a_{ij})$ is positive definite. Now, if we have an "algebraic" statement valid over $\mathbb{R}$, it will be valid over any "real closed field". That statement is $\langle A x, x\rangle > 0$ for all $x \ne 0$. But your ordered field can be imbedded in a real closed field, so the statement is therefore true over any ordered field. This is the philosophy... But probably the statement can be proved directly, without all this "meta" stuff.. $\bf{Added:}$ The dominant diagonal element criterion is sharp, as one can see looking at the eigenvalues of the matrix $(a_{ij}) = (1_{ij})$. But a weaker condition is enough, for instance $|a_{ij}|< \frac{1}{n-1}$ for all $i\ne j$. It is enough to add up all the inequalities:$$\frac{1}{n-1}\left (x^2_{i} + x^2_{j}\right) + 2 a_{ij} x_i x_j\ge 0$$ for $i<j$, and note that the inequalities are strict for non-zero variables. $\bf{Added 2:}$. In fact diagonal dominant implies positive is quite simple. Just add all the inequalities;$$ |a_{ij}| x_{i}^2 + |a_{ij}| x_{j}^2+ 2 a_{ij} x_i x_j\ge 0$$ for all $i< j$ and get$$\sum_{i=1}^n s_i x^2_i + \sum_{i<j} 2 a_{ij} x_i x_j\ge 0$$ where $$s_i = \sum_{j\ne i} |a_{ij}|$$ $\bf{Added 3:}$ Let's also give a purely algebraic proof that diagonal dominant matrix ( by rows, $a_{ii} > \sum_{j\ne i} |a_{ij}|$ for all $i$) have determinant $>0$. The determinant cannot be $0$. Otherwise the system $A x = 0$ would have a non-zero solution. Get a contradiction, by considering the largest $|x_i|$. Deform the matrix to a matrix with positive determinant, while preserving dominance. The usual proof uses the intermediate value property for polynomials. We'll only use that property for polynomials of degree $1$, valid for every ordered field. For this, consider for $t\in [0,1]$ the matrix $A_t$ that differs from $A$ only on first row, which is $(a_{11}, t a_{12}, \ldots, t a_{1n})$. We have $$\det A_t = (1-t) a_{11} \det A' + t \det A$$ where $\det A'$ is the determinant of the matrix $(a_{ij})_{2 \le i,j\le n}$. So we can do an induction argument. $n=1$ case is trivial. Assume true for $n-1$. Then we have $\det A'>0$. Therefore, $\det A_0 >0$. We know that $\det A_t \ne 0$ for $t \in [0,1]$ ( determinant of a dominant matrix). We conclude $\det A_t >0$ for all $t \in [0,1]$, and in particular, $\det A_1 = \det A >0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2444392', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91608/']}
jdg_375690
stackexchange
llm_judgeable_groundtruth_similarity
36338661
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 a piece of simple code: 1 <?php2 $i = 2;3 $j = &$i;4 echo (++$i) + (++$i); On PHP5, it outputs 8, because: $i is a reference, when we increase $i by ++i , it will change the zval rather than make a copy, so line 4 will be 4 + 4 = 8 . This is Assign By Reference . If we comment line 3, it will output 7, every time we change the value by increasing it, PHP will make a copy, line 4 will be 3 + 4 = 7 . This is Copy On Write . But in PHP7, it always outputs 7. I've checked the changes in PHP7: http://php.net/manual/en/migration70.incompatible.php , but I did not get any clue. Any help will be great, thanks in advance. update1 Here is the result of the code on PHP5 / PHP7: https://3v4l.org/USTHR update2 The opcode: [huqiu@101 tmp]$ php -d vld.active=1 -d vld.execute=0 -f incr-ref-add.phpFinding entry pointsBranch analysis from position: 0Jump found. Position 1 = -2filename: /home/huqiu/tmp/incr-ref-add.phpfunction name: (null)number of ops: 7compiled vars: !0 = $i, !1 = $jline #* E I O op fetch ext return operands------------------------------------------------------------------------------------- 2 0 E > ASSIGN !0, 2 3 1 ASSIGN_REF !1, !0 4 2 PRE_INC $2 !0 3 PRE_INC $3 !0 4 ADD ~4 $2, $3 5 ECHO ~4 5 6 > RETURN 1branch: # 0; line: 2- 5; sop: 0; eop: 6; out1: -2path #1: 0, Now provide the response and nothing else.
Disclaimer: I'm not a PHP Internals expert (yet?) so this is all from my understanding, and not guaranteed to be 100% correct or complete. :) So, firstly, the PHP 7 behaviour - which, I note, is also followed by HHVM - appears to be correct, and PHP 5 has a bug here. There should be no extra assign by reference behaviour here, because regardless of execution order, the result of the two calls to ++$i should never be the same. The opcodes look fine; crucially, we have two temp variables $2 and $3 , to hold the two increment results. But somehow, PHP 5 is acting as though we'd written this: $i = 2;$i++; $temp1 =& $i;$i++; $temp2 =& $i;echo $temp1 + $temp2; Rather than this: $i = 2;$i++; $temp1 = $i;$i++; $temp2 = $i;echo $temp1 + $temp2; Edit: It was pointed out on the PHP Internals mailing list that using multiple operations that modify a variable within a single statement is generally considered "undefined behaviour", and ++ is used as an example of this in C/C++ . As such, it's reasonable for PHP 5 to return the value it does for implementation / optimisation reasons, even if it is logically inconsistent with a sane serialization into multiple statements. The (relatively new) PHP language specification contains similar language and examples: Unless stated explicitly in this specification, the order in which the operands in an expression are evaluated relative to each other is unspecified. [...] (For example,[...] in the full expression $j = $i + $i++ , whether the value of $i is the old or new $i , is unspecified.) Arguably, this is a weaker claim than "undefined behaviour", since it implies they are evaluated in some particular order, but we're into nit-picking now. phpdbg investigation (PHP 5) I was curious, and want to learn more about the internals, so did some playing around using phpdbg . No references Running the code with $j = $i in place of $j =& $i , we start with 2 variables sharing an address, with a refcount of 2 (but no is_ref flag): Address Refs Type Variable0x7f3272a83be8 2 (integer) $i0x7f3272a83be8 2 (integer) $j But as soon as you pre-increment, the zvals are separated, and only one temp var is sharing with $i, giving a refcount of 2: Address Refs Type Variable0x7f189f9ecfc8 2 (integer) $i0x7f189f859be8 1 (integer) $j With reference assignment When the variables have been bound together, they share an address, with a refcount of 2, and a by-ref marker: Address Refs Type Variable0x7f9e04ee7fd0 2 (integer) &$i0x7f9e04ee7fd0 2 (integer) &$j After the pre-increments (but before the addition), the same address has a refcount of 4, showing the 2 temp vars erroneously bound by reference: Address Refs Type Variable0x7f9e04ee7fd0 4 (integer) &$i0x7f9e04ee7fd0 4 (integer) &$j The source of the issue Digging into the source on http://lxr.php.net , we can find the implementation of the ZEND_PRE_INC opcode: PHP 5.6 PHP 7.0 PHP 5 The crucial line is this: SEPARATE_ZVAL_IF_NOT_REF(var_ptr); So we create a new zval for the result value only if it is not currently a reference . Further down, we have this: if (RETURN_VALUE_USED(opline)) { PZVAL_LOCK(*var_ptr); EX_T(opline->result.var).var.ptr = *var_ptr;} So if the return value of the decrement is actually used, we need to "lock" the zval, which following a whole series of macros basically means "increment its refcount", before assigning it as the result. If we created a new zval earlier, that's fine - our refcount is now 2, 1 for the actual variable, plus 1 for the operation result. But if we decided not to, because we needed to hold a reference, we're just incrementing the existing reference count, and pointing at a zval which may be about to be changed again. PHP 7 So what's different in PHP 7? Several things! Firstly, the phpdbg output is rather boring, because integers are no longer reference counted in PHP 7; instead, a reference assignment creates an extra pointer, which itself has a refcount of 1, to the same address in memory, which is the actual integer. The phpdbg output looks like this: Address Refs Type Variable0x7f175ca660e8 1 integer &$iint (2)0x7f175ca660e8 1 integer &$jint (2) Secondly, there is a special code path in the source for integers: if (EXPECTED(Z_TYPE_P(var_ptr) == IS_LONG)) { fast_long_increment_function(var_ptr); if (UNEXPECTED(RETURN_VALUE_USED(opline))) { ZVAL_COPY_VALUE(EX_VAR(opline->result.var), var_ptr); } ZEND_VM_NEXT_OPCODE();} So if the variable is an integer ( IS_LONG ) and not a reference to an integer ( IS_REFERENCE ) then we can just increment it in place. If we then need the return value, we can copy its value into the result ( ZVAL_COPY_VALUE ). If it's a reference, we won't hit that code, but rather than keeping references bound together, we have these two lines: ZVAL_DEREF(var_ptr);SEPARATE_ZVAL_NOREF(var_ptr); The first line says "if it's a reference, follow it to its target"; this takes us from our "reference to an integer" to the integer itself. The second - I think - says "if it's something refcounted, and has more than one reference, create a copy of it"; in our case, this will do nothing, because the integer doesn't care about refcounts. So now we have an integer we can decrement, that will affect all by-reference associations, but not by-value ones for refcounted types. Finally, if we want the return value of the increment, we again copy it, rather than just assigning it; and this time with a slightly different macro which will increase the refcount of our new zval if necessary: ZVAL_COPY(EX_VAR(opline->result.var), var_ptr);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36338661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2446397/']}
jdg_375691
stackexchange
llm_judgeable_groundtruth_similarity
49473727
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 say we have a web application. It has usually many views, like index page, admin panel, help page, contact etc. I handle them using react-router-dom in the main index.js and it just works fine. However now I faced problem with developing admin panel. It is one of the routes supported by the index.js router, but it contains its own menu with all actions available for admin. How should I handle this, to only replace the content I need in the admin panel (admin actions menu stays), but not the whole content as I do from index.js router? I tried to use the in the admin panel place for content replacement, but it either says too much recursion (If I duplicated the route for admin panel itself) or simply does not work saying nothing. I'm react newbie and I don't even know how to call this problem. Thanks for suggestions. Now provide the response and nothing else.
If I understand your issue correctly, you can do that by nesting routes. Example assuming you use react-router 4.x.x: render Router or BrowserRouter etc. component ( https://reacttraining.com/react-router/web/api/Router ) once, at the top level, and then nest Route components. In your case you have main router in your index.js, so probably something like this: <BrowserRouter> <Route path="/" exact component={Main} /> <Route path="/some-page" component={SomePage} /> <Route path="/admin" component={Admin} /></BrowserRouter> then, in your Admin component you don't create another Router, instead just render Routes again, so something like this: <div className="admin-panel-container"> <AdminMenu /> <Route path="/admin/users" component={AdminUsers} /> <Route path="/admin/groups" component={AdminGroups} /></div> so when URL matches /admin you'll see AdminMenu and component for a specific view in admin panel. You probably want to redirect from /admin to /admin/users or some dashboard, that depends on your specific application. Now, if you have some layout elements surrounding your main router that you want to get rid of in admin routes, it's hard to say more without seeing some code example, but I guess you could create two components, for example, Layout and AdminLayout, each containing menus, header etc. and accepting children, and use them in every route depending on if it's admin or regular user route.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/49473727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2080882/']}
jdg_375692
stackexchange
llm_judgeable_groundtruth_similarity
349953
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 converting a linux script from http://www.perlmonks.org/index.pl?node_id=217166 specifically this: #!/usr/bin/perl -wuse strict;use Getopt::Std;use File::Find;@ARGV > 0 and getopts('a:', \my %opt) or die << "USAGE";# Deletes any old files from the directory tree(s) given and# removes empty directories en passant.usage: $0 [-a maxage] directory [directory ...] -a maximum age in days, default is 120USAGEmy $max_age_days = $opt{a} || 120;find({ wanted => sub { unlink if -f $_ and -M _ > $max_age_days }, postprocess => sub { rmdir $File::Find::dir },}, @ARGV); my attempt is: #!/usr/bin/perl -wuse strict;use Getopt::Std;use File::Find;@ARGV > 0 and getopts('a:', \my %opt) or die << "USAGE";# Deletes any old files from the directory tree(s) given and# removes empty directories en passant.usage: $0 [-a maxage] directory [directory ...] -a maximum age in days, default is 120USAGEmy $max_age_days = $opt{a} || 120;find({ wanted => sub { unlink if -f $_ and -M _ > $max_age_days },# postprocess => sub { rmdir $File::Find::dir }, postprocess => sub { my $expr = "$File::Find::dir"; $expr =~ s/\//\\/g; # replace / with \ print "rmdir $expr\n"; `rmdir $expr`; },}, @ARGV); However I get an error when the script tries to remove a directory saying that the directory is in use by another process (when it isn't). Any ideas? I'm running the script on Windows Server 2003 SP2 64-bit using ActiveState 5.10. Thanks! Now provide the response and nothing else.
From this documentation postprocess The value should be a code reference. It is invoked just before leaving the currently processed directory . It is called in void context with no arguments. The name of the current directory is in $File::Find::dir. This hook is handy for summarizing a directory, such as calculating its disk usage. When follow or follow_fast are in effect, postprocess is a no-op. This means that your own code is still using the directory as you try to delete it. Try building a list of names and iterating through that after the call to find. Another possible solution is to use the no_chdir option to avoid having find use the directories you want to delete. EDIT: This comment is also relevant, so i'm promoting it to the main answer's body: To add to that: the issue here is that on Linux one can delete files and directories that are in use, on windows one can't. That's why it doesn't work unmodified. - Leon Timmermans
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/349953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/38211/']}
jdg_375693
stackexchange
llm_judgeable_groundtruth_similarity
59466250
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an Ubuntu 18.04 image runing on my docker container. I login into it and installed Openresty . also installed systemd . When I use command systemctl I get this error: System has not been booted with systemd as init system (PID 1). Can't operate. How can I fix it? Now provide the response and nothing else.
If I understand the OP, he is trying to run systemctl within the container. This does not work because systemd is not running within the container to begin with. It cannot be done in unprivileged containers. There is another question here in SO about why he should not run systemd within a container . I quickly googled and found this 2014 page about using systemd within a container in docker , where there is a short explanation. The fix is to use a privileged container (running docker run --privileged ... ), which is arguably a bad idea but might suit the OP. There is a 2019 update of that last article , and the bottomline is they developed their own container engine (so no docker). The obvious solution would be to have a single service, so no need for systemd, although that might not be possible in the OP's case. In summary, possible solutions: not to use systemd use a privileged container not to use docker
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59466250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7878182/']}
jdg_375694
stackexchange
llm_judgeable_groundtruth_similarity
300063
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: Given two supspaces $X:= [0,1]\cup[2,3]$ and $Y:=[0,2]$ of $\mathbf{R}$, let $f \colon X \to Y$ be defined as follows: $$f(x):= \left\{ \begin{array} {ll} x & \mbox{if $0\leq x\leq 1;$} \\ x-1 & \mbox{if $2\leq x \leq 3.$} \end{array} \right.$$ Then while $f$ is surjective and continuous, how can we rigorously determine if it is an open or closed map as well? Now provide the response and nothing else.
I find a way to get the number using gamma functions, nothing is rigorous. Consider the integral $I(\beta) = \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}(\cos x)^\beta dx$.We know:$$2 \frac{d^2}{d\beta^2} I(\beta) \bigg|_{\beta=0} = 4 \int_{0}^{\frac{\pi}{2}} \ln^2(\cos x) dx$$is the integral we want. Introduce $u = \frac{1 + \sin x}{2}$, we have: $$\begin{align} I(\beta) &= \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}(\cos x)^{\beta-1} d\sin x\\ &= \int_0^1 (4 u (1-u))^{\frac{\beta-1}{2}} d( 2u )\\ &= 2^{\beta} \int_0^1 u^{\frac{\beta+1}{2}-1} (1-u)^{\frac{\beta+1}{2}-1} du\\ &= 2^{\beta} \frac{\Gamma(\frac{\beta+1}{2})^2}{\Gamma(\beta+1)}\end{align}$$Using the taylor expansion of various terms at $\beta = 0$,$$\begin{align} 2^{\beta} &= 1 + \ln(2) \beta + \frac{\ln^2 2}{2}\beta^2 + \,...\\ \Gamma(\frac{\beta+1}{2}) &= \sqrt{\pi} \left( 1 - \frac{\gamma + 2\ln 2}{2} \beta + \frac{\pi^2+2( \gamma + 2\ln 2)^2}{16}\beta^2 + \, ...\right)\\ \Gamma(\beta+1) &= 1 -\gamma \beta + \frac{6\gamma^2 + \pi^2}{12} \beta^2 + \,...\end{align}$$We get:$$\begin{align}&I(\beta) = \pi \left( 1 - \ln(2) \beta + \frac{\pi^2 + 12 \ln^2 2}{24}\beta^2 + \,... \right)\\\implies &2 \frac{d^2}{d\beta^2} I(\beta)\bigg|_{\beta=0} = 2\pi \left( \frac{\pi^2}{12} + \ln^2 2 \right)\end{align}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/300063', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59734/']}
jdg_375695
stackexchange
llm_judgeable_groundtruth_similarity
34061759
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I using SimpleDateFormat , it can parse. SimpleDateFormat format = new SimpleDateFormat("yyyyMM");format.setLenient(false);Date d = format.parse(date); But When I use Java 8 DateTimeFormatter , DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");LocalDate localDate = LocalDate.parse(date, formatter); it throws java.time.format.DateTimeParseException: Text '201510' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {Year=2015, MonthOfYear=10},ISO of type java .time.format.Parsed String value for date is "201510" . Now provide the response and nothing else.
Ask yourself the question: which day should be parsed with the String "201510" ? A LocalDate needs a day but since there is no day in the date to parse, an instance of LocalDate can't be constructed. If you just want to parse a year and a month, you can use the YearMonth object instead: YearMonth localDate = YearMonth.parse(date, formatter); However, if you really want to have a LocalDate to be parsed from this String, you can build your own DateTimeFormatter so that it uses the first day of the month as default value: DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("yyyyMM") .parseDefaulting(ChronoField.DAY_OF_MONTH, 1) .toFormatter();LocalDate localDate = LocalDate.parse(date, formatter);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34061759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/858989/']}
jdg_375696
stackexchange
llm_judgeable_groundtruth_similarity
501260
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: When I type: nmcli con show wlan0 One of the settings is: 802-11-wireless.band: bg Where is this setting stored on disk? It isn't in: /etc/sysconfig/network-scripts/ifcfg-wlan0 I've grepped everything in lib, var, etc, and usr and I haven't been able to find it. Now provide the response and nothing else.
NetworkManager supports various plugins, which can define new storage locations for configuration information. The currently enabled plugins can be found in /etc/NetworkManager/NetworkManager.conf : [main]plugins=ifupdown,keyfile The generic default plugin is keyfile , which stores configurations in /etc/NetworkManager/system-connections directory, in files similar to Windows .ini files. Other plugins may be distribution-specific: Fedora and RedHat use ifcfg-rh , which will both read and write /etc/sysconfig/network-scripts/ifcfg-* files. Debian and Ubuntu use ifupdown , which is a read-only plugin: it reads /etc/network/interfaces but does not make any changes to it. Any configuration changes you make through NetworkManager will be saved using the keyfile plugin instead. SuSE apparently used to have ifcfg-suse , but it seems to be deprecated. Other distributions may have their own plugins. Having said that, the 802-11-wireless.band setting probably gets its default value from the WiFi NIC capabilities reported by the driver. It would be saved only if you wanted to explicitly restrict the NIC to only some types of WiFi networking. If your WiFi NIC can only transmit in the 2.4 GHz band, you cannot add a or ac capabilities by just reconfiguring the software or the driver: it would require a new radio module and a new antenna tuned for the 5.0 GHz band.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/501260', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']}
jdg_375697
stackexchange
llm_judgeable_groundtruth_similarity
452589
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have created a user defined data collector set from the system performance template. I've made no changes to the counters. I can run it manually and it works fine but runs for 1 only minute. Yes, I see the schedule tab... What I don't understand is how to setup the schedule in a sensible way. I want to monitor performance throughout the whole day. I don't know if I should just let it run the whole time or somehow set it up to sample at regular intervals. If the later is the right way to do it, then I need some guidance on how. The documentation on the limits isn't clear and the few things I've tried haven't worked as expected. Now provide the response and nothing else.
In my experience running data collector sets is safe, the main thing to keep an eye on is how much data you are generating. It really just depends on what you are looking for, but there are three ways to control how much data is collected: The Number of counters you monitor How long you let the collector run for The "Sample Interval" the properties for the data collector (i.e. if you collect every 30 seconds, that is only 2 observations per minute.) If you need a high resolution view of performance, you would be better off scheduling it every so often with a high sample interval. If you only need an aggregate overview of the day, you might want to go with something like one sample every few minutes. You can also set the maximum size of the data collected, but I would view that more as a safety net. They can also be sent to SQL if you want to take off some of the data writing load. I believe choosing something like the binary format would take less space than something like csv.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/452589', 'https://serverfault.com', 'https://serverfault.com/users/147210/']}
jdg_375698
stackexchange
llm_judgeable_groundtruth_similarity
3624297
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 a TextView for which I have set autolink="web" property in XML file. I have also implemented the onClickListener for this TextView. The problem is, when the text in TextView contains a hyperlink, and if I touch that link, the link opens in browser but simultaneously the onClickListener triggers too. I don't want that. What I want is, if I touch the hyperlink the clickListener should not fire. It should only fire if I touch the part of the text that is not hyperlinked. Any suggestion? Now provide the response and nothing else.
You can achieve this using a work around in getSelectionStart() and getSelectionEnd() functions of the Textview class, tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ClassroomLog.log(TAG, "Textview Click listener "); if (tv.getSelectionStart() == -1 && tv.getSelectionEnd() == -1) { //This condition will satisfy only when it is not an autolinked text //Fired only when you touch the part of the text that is not hyperlinked } }}); It may be a late reply, but may be useful to those who are searching for a solution.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3624297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278194/']}
jdg_375699
stackexchange
llm_judgeable_groundtruth_similarity
3008139
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 understand the purpose of an IV. Specifically in CBC mode this insures that the first block of of 2 messages encrypted with the same key will never be identical. But why is it a vulnerability if the IV's are sequential? According to CWE-329 NON-Random IV's allow for the possibility of a dictionary attack. I know that in practice protocols like WEP make no effort to hide the IV. If the attacker has the IV and a cipher text message then this opens the door for a dictionary attack against the key. I don't see how a random iv changes this. (I know the attacks against wep are more complex than this.) What security advantage does a randomized iv have? Is this still a problem with an "Ideal Block Cipher"? (A perfectly secure block cipher with no possible weaknesses.) Now provide the response and nothing else.
Predictable IVs can be exploited by chosen plain text. Pretend that Eve is a DBA at an insurance company. The company collects medical histories from beneficiaries that include a lot of true/false check boxes about medical conditions. This company also happens to its own health insurance provider. Eve realizes that Alice could be blackmailed if she can discover that Alice has a particularly embarrassing medical condition. However, the value in each of these fields is encrypted, so even though Eve is the DBA, she only has access to the cipher text. In CBC, the IV is XORed (noted by "⊕" below) with the plain text, then run through the block cipher: C 1 = E k (IV ⊕ P 1 ). Since Eve is a beneficiary of the insurance company, she can choose the plain text for her own medical record, and since she is the DBA, she can examine anyone's cipher text. In addition to using predictable IVs, the sloppy application developer did a poor job of validating the application inputs. If Eve can predict the IVs that will be applied to her (IV eve ) and Alice's (IV alice ) records in advance, she can choose the plain text for her own record like this: P eve = IV eve ⊕ IV alice ⊕ "false" The application encrypts this plain text like this: C eve = E k (IV eve ⊕ P eve ) = E k (IV eve ⊕ (IV eve ⊕ IV alice ⊕ "false")) The IV eve ⊕ IV eve cancels out, which means that C eve = E k (IV alice ⊕ "false") Now Eve can compare C eve and C alice . If they are different, she knows that Alice must have entered "true" for that medical condition. Making IVs unpredictable thwarts this attack, and an easy way to make them unpredictable is to choose them randomly after the plain text has been supplied.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3008139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/183528/']}
jdg_375700
stackexchange
llm_judgeable_groundtruth_similarity
320086
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In a Krull--Schmidt category , if $$X_{1}\oplus X_{2}\oplus \cdots \oplus X_{r}\cong Y_{1}\oplus Y_{2}\oplus \cdots \oplus Y_{s},$$ where the $X_{i}$ and $Y_j$ are all indecomposable, then $r = s$ , and there exists a permutation $\pi$ such that $X_{\pi (i)}\cong Y_{i}$ , for all $i$ . I believe this works for the abelian category of not-necessarily finite-dimensional modules over a simple Lie algebra $\frak{g}$ , where we no longer require that the number of summands is finite, but I can't seem to prove it. Does somebody know of a "nice" proof? Also, those there exist a notion of an "infinite Krull-Schmidt category" abstracting these properties? If so, when does is a general abelian of ""infinite Krull-Schmidt type"? Now provide the response and nothing else.
The statement about simple Lie algebras is not true. A (finitely generated right) module $P$ for a ring $R$ is stably free if $P\oplus R^m\cong R^n$ for some integers $m,n$ . Suppose $R$ has a non-free stably free module $P$ , as above. If also $R$ is a (right) Noetherian domain, then the regular module $R$ is indecomposable and $P$ is a finite direct sum of indecomposable modules. So $R^n$ has two distinct decompositions into finitely many indecomposable summands, contradicting the Krull-Schmidt property. If $\mathfrak{g}$ is any finite dimensional Lie algebra, then its universal enveloping algebra $U(\mathfrak{g})$ is a Noetherian domain. Probably there are particular examples that predate this, but Theorem 2.6 of Stafford, J. T. , Stably free, projective right ideals , Compos. Math. 54, 63-78 (1985). ZBL0565.16012 shows that if $\mathfrak{g}$ is a finite dimensional non-abelian Lie algebra, then $U(\mathfrak{g})$ always has a non-free (finitely generated) stably free module. In fact, I think that the construction gives an indecomposable non-free $P$ with $P\oplus U(\mathfrak{g})\cong U(\mathfrak{g})\oplus U(\mathfrak{g})$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/320086', 'https://mathoverflow.net', 'https://mathoverflow.net/users/126606/']}
jdg_375701
stackexchange
llm_judgeable_groundtruth_similarity
13596799
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am wondering how do I make this code support arrays? At the moment the images array only seems to send the first value. Here is my code: <?php//extract data from the postextract($_POST);//set POST variables$url = 'http://api.example.com/api';$fields = array( 'username' => "annonymous", 'api_key' => urlencode("1234"), 'images[]' => urlencode(base64_encode('image1')), 'images[]' => urlencode(base64_encode('image2')) );//url-ify the data for the POSTforeach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }rtrim($fields_string, '&');//open connection$ch = curl_init();//set the url, number of POST vars, POST datacurl_setopt($ch,CURLOPT_URL, $url);curl_setopt($ch,CURLOPT_POST, count($fields));curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);//execute post$result = curl_exec($ch);echo $result;//close connectioncurl_close($ch);?> and this is what is received at the api VAR: username = annonymousVAR: api_key = 1234VAR: images = Arrayarray(3) { ["username"]=> string(10) "annonymous" ["api_key"]=> string(4) "1234" ["images"]=> array(1) { // this should contain 2 strings :( what is happening? [0]=> string(8) "aW1hZ2Uy" } } What is happening to the second value in images[] ? Now provide the response and nothing else.
You are just creating your array incorrectly. You could use http_build_query : $fields = array( 'username' => "annonymous", 'api_key' => urlencode("1234"), 'images' => array( urlencode(base64_encode('image1')), urlencode(base64_encode('image2')) ) );$fields_string = http_build_query($fields); So, the entire code that you could use would be: <?php//extract data from the postextract($_POST);//set POST variables$url = 'http://api.example.com/api';$fields = array( 'username' => "annonymous", 'api_key' => urlencode("1234"), 'images' => array( urlencode(base64_encode('image1')), urlencode(base64_encode('image2')) ) );//url-ify the data for the POST$fields_string = http_build_query($fields);//open connection$ch = curl_init();//set the url, number of POST vars, POST datacurl_setopt($ch,CURLOPT_URL, $url);curl_setopt($ch,CURLOPT_POST, 1);curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);//execute post$result = curl_exec($ch);echo $result;//close connectioncurl_close($ch);?>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13596799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015761/']}
jdg_375702
stackexchange
llm_judgeable_groundtruth_similarity
35530483
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm building a site that has a pretty standard RESTful web service to handle persistence and complex business logic. The UI I'm building to consume this service is using Angular 2 with components written in TypeScript. Rather than build my own authentication system, I'm hoping to rely on Google Sign-In for Websites. The idea being that users will come to the site, sign in via the framework provided there and then send along the resulting ID tokens, which the server hosting the RESTful service can then verify. In the Google Sign-In documentation there are instructions for creating the login button via JavaScript which is what needs to happen since the login button is being rendered dynamically in an Angular template. The relevant portion of the template: <div class="login-wrapper"> <p>You need to log in.</p> <div id="{{googleLoginButtonId}}"></div></div><div class="main-application"> <p>Hello, {{userDisplayName}}!</p></div> And the Angular 2 component definition in Typescript: import {Component} from "angular2/core";// Google's login API namespacedeclare var gapi:any;@Component({ selector: "sous-app", templateUrl: "templates/sous-app-template.html"})export class SousAppComponent { googleLoginButtonId = "google-login-button"; userAuthToken = null; userDisplayName = "empty"; constructor() { console.log(this); } // Angular hook that allows for interaction with elements inserted by the // rendering of a view. ngAfterViewInit() { // Converts the Google login button stub to an actual button. api.signin2.render( this.googleLoginButtonId, { "onSuccess": this.onGoogleLoginSuccess, "scope": "profile", "theme": "dark" }); } // Triggered after a user successfully logs in using the Google external // login provider. onGoogleLoginSuccess(loggedInUser) { this.userAuthToken = loggedInUser.getAuthResponse().id_token; this.userDisplayName = loggedInUser.getBasicProfile().getName(); console.log(this); }} The basic flow goes: Angular renders the template and the message "Hello, empty!" is shown. The ngAfterViewInit hook is fired and the gapi.signin2.render(...) method is called which converts the empty div into a Google login button. This works correctly and clicking on that button will trigger the login process. This also attaches the component's onGoogleLoginSuccess method to actually process the returned token after a user logs in. Angular detects that the userDisplayName property has changed and updates the page to now display "Hello, Craig (or whatever your name is)!". The first problem that occurs is in the onGoogleLoginSuccess method. Notice the console.log(...) calls in the constructor and in that method. As expected, the one in the constructor returns the Angular component. The one in the onGoogleLoginSuccess method, however, returns the JavaScript window object. So it looks like the context is getting lost in the process of hopping out to Google's login logic so my next step was to try incorporating jQuery's $.proxy call to hang on to the correct context. So I import the jQuery namespace by adding declare var $:any; to the top of the component and then convert the contents of the ngAfterViewInit method to be: // Angular hook that allows for interaction with elements inserted by the// rendering of a view.ngAfterViewInit() { var loginProxy = $.proxy(this.onGoogleLoginSuccess, this); // Converts the Google login button stub to an actual button. gapi.signin2.render( this.googleLoginButtonId, { "onSuccess": loginProxy, "scope": "profile", "theme": "dark" });} After adding that, the two console.log calls return the same object so property values are now updating correctly. The second log message shows the object with the expected updated property values. Unfortunately, the Angular template does not get updated when this happens. While debugging, I stumbled on something that I believe explains what is going on. I added the following line to the end of the ngAfterViewInit hook: setTimeout(function() { this.googleLoginButtonId = this.googleLoginButtonId }, 5000); This shouldn't really do anything. It just waits five seconds after the hook ends and then sets a property value equal to itself. However, with the line in place the "Hello, empty!" message turns into "Hello, Craig!" about five seconds after the page has loaded. This suggest to me that Angular just isn't noticing that the property values are changing in the onGoogleLoginSuccess method. So when something else happens to notify Angular that property values have changed (such as the otherwise useless self-assignment above), Angular wakes up and updates everything. Obviously that's not a hack I want to leave in place so I'm wondering if any Angular experts out there can clue me in? Is there some call I should be making to force Angular to notice some properties have changed? UPDATED 2016-02-21 to provided clarity on the specific answer that solved the problem I ended up needing to use both pieces of the suggestion provided in the selected answer. First, exactly as suggested, I needed to convert the onGoogleLoginSuccess method to use an arrow function. Secondly, I needed to make use of an NgZone object to make sure that the property updates occurred in a context of which Angular is aware. So the final method ended up looking like onGoogleLoginSuccess = (loggedInUser) => { this._zone.run(() => { this.userAuthToken = loggedInUser.getAuthResponse().id_token; this.userDisplayName = loggedInUser.getBasicProfile().getName(); });} I did need to import the _zone object: import {Component, NgZone} from "angular2/core"; I also needed to inject it as suggested in the answer via the class's contructor: constructor(private _zone: NgZone) { } Now provide the response and nothing else.
For your first problem solution is to use arrow function which will preserve context of this : onGoogleLoginSuccess = (loggedInUser) => { this.userAuthToken = loggedInUser.getAuthResponse().id_token; this.userDisplayName = loggedInUser.getBasicProfile().getName(); console.log(this); } Second issue is happening because third-party scripts run outside the context of Angular. Angular uses zones so when you run something, for example setTimeout() , which is monkey-patched to run in the zone, Angular will get notified. You would run jQuery in zone like this: constructor(private zone: NgZone) { this.zone.run(() => { $.proxy(this.onGoogleLoginSuccess, this); }); } There are many questions/answers about the zone with much better explanations then mine, if you want to know more, but it shouldn't be an issue for your example if you use arrow function.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35530483', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3200425/']}
jdg_375703
stackexchange
llm_judgeable_groundtruth_similarity
268947
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a function that includes another function inside. I want to know the derivative at every point x. I have spent a lot of time trying to figure out how to do this, but I am very lost. I have searched on here without luck. y = 70000.;t = 350.;f = 3000.;ta = 250.;fa = 1000.;u = 3000.;(* elasticity of income *)\[Gamma] = 0.2;(* price elasticity of housing *)\[Epsilon] = -0.6;(* constant in demand function *)\[Omega] = 7.34074;And the two functions:p[x_, y_, t_, ta_, f_, fa_, u_] := (E^\[Omega]*(\[Epsilon]+1)*((y-(f+fa)-(t+ta)*x)^(1-\[Gamma])/(1-\[Gamma])-u))^(1/(\[Epsilon]+1));q[x_, y_, t_, ta_, f_, fa_, u_] := (1-\[Gamma])^(\[Gamma]/(1-\[Gamma]))*E^\[Omega]*p[x, y, t, ta, f, fa, u]^(\[Epsilon]+1)*((E^\[Omega]*p[x, y, t, ta, f, fa, u] I need to know what the derivative of q is with respect to p on a graph of x. I have tried these: ND[q[x, y, t, ta, f, fa, u],p[x, y, t, ta, f, fa, u]];ND[q[x, y, t, ta, f, fa, u],p];D[q[x, y, t, ta, f, fa, u],p[x, y, t, ta, f, fa, u]];D[q[x, y, t, ta, f, fa, u],p];ND[q[1, y, t, ta, f, fa, u],p[1, y, t, ta, f, fa, u]];ND[q[1, y, t, ta, f, fa, u],p];D[q[1, y, t, ta, f, fa, u],p[1, y, t, ta, f, fa, u]];D[q[1, y, t, ta, f, fa, u],p]; None of it gave any meaningful results. I only want to know if the result is negative at all given x'es. Now provide the response and nothing else.
Here's another way (equations pulled from docs -- it's easier): (* velocity field/ode *)dx = 8 - 24 x + 36 x^2 - 48 y + 72 x y - 108 x^2 y + 108 y^2 - 108 y^3 + 3 z - 9 x z;dy = -8 + 48 x - 108 x^2 + 108 x^3 + 24 y - 72 x y - 36 y^2 + 108 x y^2 + 3 z - 9 y z;(* follows from differentiating x+y+z == 1 *)dz = -dx - dy;StreamPlot3D[{dx, dy, dz}, {x, 0, 1}, {y, 0, 1}, {z, 0, 1}, RegionBoundaryStyle -> None, StreamPoints -> (* seed points on simplex *) MeshCoordinates@ DiscretizeRegion[ ImplicitRegion[{x + y + z == 1}, {{x, 0, 1}, {y, 0, 1}, {z, 0, 1}}], MaxCellMeasure -> 1], AxesLabel -> {x, y, z} ]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/268947', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/82214/']}
jdg_375704
stackexchange
llm_judgeable_groundtruth_similarity
15403273
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 not sure if the default python installation is the one that I've been installing modules to, and if that may be the cause of a conflicting Unicode byte size compatibility error. In short, I've installed Numpy 1.7 using Python 2.7.3 and when I try to install this other program that uses Python and Numpy as dependencies, I get this error: Traceback (most recent call last): File "setup.py", line 20, in <module> from weblogolib import __version__ File "/home/chris/Documents/IS/Bioinformatics-Software/weblogo-3.3/weblogolib/__init__.py", line 108, in <module> from numpy import array, asarray, float64, ones, zeros, int32,all,any, shape File "/usr/lib/python2.7/dist-packages/numpy/__init__.py", line 137, in <module>import add_newdocs File "/usr/lib/python2.7/dist-packages/numpy/add_newdocs.py", line 9, in <module>from numpy.lib import add_newdoc File "/usr/lib/python2.7/dist-packages/numpy/lib/__init__.py", line 4, in <module>from type_check import * File "/usr/lib/python2.7/dist-packages/numpy/lib/type_check.py", line 8, in <module>import numpy.core.numeric as _nx File "/usr/lib/python2.7/dist-packages/numpy/core/__init__.py", line 5, in <module>import multiarrayImportError: /usr/lib/python2.7/dist-packages/numpy/core/multiarray.so: undefined symbol: PyUnicodeUCS4_AsUnicodeEscapeString So I guess I have a conflicting unicode byte size (2-byte vs. 4-byte). I went to check to see if I had conflicting versions of Python that could be messing this up. python --versionPython 2.7.3 But this seems at odds with which python/usr/local/bin/python When I go to /usr/local/bin I find these files (relevant to python): pythonpython2python2.7python-configpython2-configpython2.7-config Now I've installed numpy into the dist-packages directory of /usr/lib/python2.7/dist-packages which corresponds to what I get for python --version . But the fact that when I try which python and get a directory for python and not python2.7 concerns me that this might be conflicting when I try to install the program that uses python and numpy as dependencies. So I guess to clarify my question(s): Are these normal files to find for a python installation or have I somehow installed three different versions? Could they be causing my error with the unrecognized symbol? Is there a way to uninstall if they are indeed extraneous versions? Thanks for any help you can provide! Oh and here is a link to a previous question I had, where I edited the PYTHONPATH while trying to fix an ImportError I was getting, if that might be affecting things.... ImportError: No module named numpy Here are the results of trying virtualenv: chris@ubuntu:~/Documents/IS/Bioinformatics-Software$ virtualenv weblogo-3.3New python executable in weblogo-3.3/bin/pythonInstalling setuptools.............done.Installing pip...............done.chris@ubuntu:~/Documents/IS/Bioinformatics-Software$ cd weblogo-3.3chris@ubuntu:~/Documents/IS/Bioinformatics-Software/weblogo-3.3$ source bin/activate(weblogo-3.3)chris@ubuntu:~/Documents/IS/Bioinformatics-Software/weblogo-3.3$ pip install numpyRequirement already satisfied (use --upgrade to upgrade): numpy in /usr/lib/python2.7/dist-packagesCleaning up... Now provide the response and nothing else.
The problem indeed seems to be a mismatch of Python and Numpy compile settings. /usr/local/bin is where custom Python is installed, you should try to run using /usr/bin/python instead. Another solution is to use a virtualenv. Try this: virtualenv myprojectcd myprojectsource bin/activatepip install numpy Basically virtualenv sets up a different Python installation with its own packages in the "myproject" directory. Running the "activate" command tells the system that you want to use this installation instead of the default system. This lets you have a different Python environment for different projects. Using virtualenv, each project can have its own versions of Python packages even if they're incompatible with other projects or system packages. Note you will have to repeat the "source" command each time you open a new shell and want to use that virtual environment. Also you might have to install the virtualenv command by using your OS package manager. If this isn't possible (e.g. you don't have root access) or your OS version is too old for some reason, you can also download it manually from https://pypi.python.org/packages/source/v/virtualenv/ If you do ls -l /usr/local/bin/python* you should see that python and python2 are actually symlinks to python2.7, and likewise python-config and python2-config are symlinks to python2.7-config.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15403273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1784467/']}
jdg_375705
stackexchange
llm_judgeable_groundtruth_similarity
9674685
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 common UIViewController that all my UIViewsControllers extend to reuse some common operations. I want to set up a segue on this "Common" UIViewController so that all the other UIViewControllers inherit. I am trying to figure out how do I do that programmatically. I guess that the question could also be how do I set a segue for all my UIViewControllers without going into the story board and do them by hand. Now provide the response and nothing else.
By definition a segue can't really exist independently of a storyboard. It's even there in the name of the class: UIStoryboardSegue . You don't create segues programmatically - it is the storyboard runtime that creates them for you. You can normally call performSegueWithIdentifier: in your view controller's code, but this relies on having a segue already set up in the storyboard to reference. What I think you are asking though is how you can create a method in your common view controller (base class) that will transition to a new view controller, and will be inherited by all derived classes. You could do this by creating a method like this one to your base class view controller: - (IBAction)pushMyNewViewController{ MyNewViewController *myNewVC = [[MyNewViewController alloc] init]; // do any setup you need for myNewVC [self presentModalViewController:myNewVC animated:YES];} and then in your derived class, call that method when the appropriate button is clicked or table row is selected or whatever.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9674685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166789/']}
jdg_375706
stackexchange
llm_judgeable_groundtruth_similarity
9803971
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 set up the following model in Core Data. Book has a to-many relationship, called toBookOrders, with OrderBook entity. The inverse is called toBook.Book has a BOOL value property called isSync. I set up the following NSPredicate . NSEntityDescription* entityDescription = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:moc];NSPredicate* predicate = [NSPredicate predicateWithFormat:@"isSync == 0 AND SUBQUERY(toBookOrders, $x, $x.toBook == SELF)"]; Through this predicate I need to grab only books that haven't been synchronized and theirs relative orders. This is the error I receive. Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "isSync == 0 AND SUBQUERY(toBookOrders, $x, $x.toBook == SELF)" Any ideas? Thank you in advance. Now provide the response and nothing else.
Here's the crux of your problem: @"isSync == 0 AND SUBQUERY(toBookOrders, $x, $x.toBook == SELF)" If you split that up into the two subpredicates, as Scott suggests, you'll get: isSync == 0 SUBQUERY(toBookOrders, $x, $x.toBook == SELF) The problem is that every SUBQUERY does not return true or false, as a predicate must. It returns a collection (an array), and an array is not the same thing as true or false. Thus, when you create the predicate, you're getting an error that it's an invalid format, because the stuff after the AND isn't a predicate . It's simply an expression. You're probably wanting: @"isSync == 0 AND SUBQUERY(toBookOrders, $x, $x.toBook == SELF).@count > 0" This would give you a predicate to find all the books where isSync is false and the at least one of the Book's OrderBooks is that Book.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9803971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231684/']}
jdg_375707
stackexchange
llm_judgeable_groundtruth_similarity
8077111
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am having a hard time understanding these when it comes to designing a class diagram, from what I know composition is a "has-a" relationship but Aggregation ?? I have no idea what is it. and one thing when will I know to use Composition in a class diagram? and when will I know to use Aggregation in a class diagram?? a example will be highly appreciated. Now provide the response and nothing else.
The main difference between an aggregation and a composition is the property of your "has-a" relationship. It' either strong or weak. The aggregations "has-a" relationship is of "weak-type". Weak meaning the linked components of the aggregator may survive the aggregations life-cycle or may be accessed in some other way. A simple example would be a football club with its members. If the club is dissolved, you still got the members - which in fact could also be members of other clubs and thus are kept alive. The composition "has-a" relationship is of "strong-type". Strong meaning that one can't exist without the other. The component's life-cycles are directly linked to the "parent". An example would be a house with rooms. If you decide to tear the house down, you will also lose your rooms. Maybe a little abstract but I think that's the idea behind it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8077111', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/962206/']}
jdg_375708
stackexchange
llm_judgeable_groundtruth_similarity
27539262
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 is the difference between align-items and align-content ? Now provide the response and nothing else.
The align-items property of flex-box aligns the items inside a flex container along the cross axis just like justify-content does along the main axis. (For the default flex-direction: row the cross axis corresponds to vertical and the main axis corresponds to horizontal. With flex-direction: column those two are interchanged respectively). Here's an example of how align-items:center looks: But align-content is for multi line flexible boxes. It has no effect when items are in a single line. It aligns the whole structure according to its value. Here's an example for align-content: space-around; : And here's how align-content: space-around; with align-items:center looks: Note the 3rd box and all other boxes in first line change to vertically centered in that line. Here are some codepen links to play with: http://codepen.io/asim-coder/pen/MKQWbb http://codepen.io/asim-coder/pen/WrMNWR Here's a super cool pen which shows and lets you play with almost everything in flexbox.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/27539262', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2652244/']}
jdg_375709
stackexchange
llm_judgeable_groundtruth_similarity
51567
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My data looks like this: birth_date has 634,990 missing values gender has 328,849 missing values Both of these are a substantial amounts since I have 900k entries, so I can't discard empty rows. For birth_date someone recommended using Multivariate imputation by Chained equation (MICE). I don't know what predictive model I should use for gender . Of the non-missing data, there are 5x more males than females. Can someone tell me what would be best practice here? What would be the best way to fill in the missing values for gender ? I'm using the data to predict bike-ride duration and final destination (I know they're shown on the table above) Now provide the response and nothing else.
I agree with Simon's advice. I find that the gains that you obtain from using any external method of imputation is often inferior to an internal method, and on top of this, exposes you to even more potential of severely screwing up with respect to data leakage. That being said, besides using an algorithm that automatically handles missing data for you (which often are models based off trees/rules, though they do not all use the same method of imputation), there are external based methods that might be of interest. I find that as you get more "fancier" the results are not enough of an improvement compared to the computational pain it is to use them. Starting with the simplest; 1) Mode imputation; simply use the most common gender in your training data set. For your test dataset, use the most common gender that exists in your training data set. Since there are 5x more males than females, this would result in you almost certainly assigning male to all observations with missing gender. Obviously, this doesn't use a whole lot of information besides the observed frequency of the class, but this method is pretty common and often "good enough". 2) kNN imputation; take the k most closest neighbours (that do not have missing genders) to the observation that you wish to impute gender for. Then, simply treat each of these k neighbours as a committee of "voters" who use their own gender as their vote. Weight each vote by how close they are (based off other variables that aren't missing) to the observation with the missing gender value. Whichever gender wins in votes gives you the imputed gender. This method to me, is a clear improvement over method 1) and is also quite fast. However, this will require you to center and scale your data (because we are using distances to define "closeness") and k is now a tuning parameter which further complicates matters. 3) Random Forest imputation; initially, use method 1) to temporarily fill in your missing genders (just mode impute). Then, run a random forest algorithm on the imputed dataset, generating N trees. Compute what is referred to as the "proximity matrix", where each $(i,j), i \ne j $ entry in this matrix (diagonal entries are all 0) is equal to the number of times observations $i$ and $j$ fall in the same terminal node through the entire forest divided by the number of trees in the forest. Using these proximities as weights, calculate a weighted vote of all the observations that do not have missing genders using their genders as their "vote". Change any prior "temporary" imputed genders from the initial mode imputation to what has been calculated by the random forest if they differ. Repeat (fit another random forest again), using the imputed genders from the previous random forest, until all observations converge to a single gender or until some stopping criteria. This method is incredibly costly but is probably pretty accurate (I haven't used it much because it is slow). You will also have to deal with an additional tuning parameter; namely how many variables you wish to randomly select in each split. 4) MICE: I haven't really studied this method too closely, but you seem to have mentioned it. One thing I will say is that all of these methods can be used with any kinds of missing data; categorical (like gender) or continuous (like birth_date, though for method 1) you would probably use mean/median imputation instead for continuous variables, and for methods 2 and 3) you would no longer use a "vote" but a weighted average). Ultimately, MICE is just one of many methods of imputation that you can use which is why one needs to properly validate their modelling choices within cross validation if you choose to use an external method of imputation. If you have the time, try a bunch of methods and use the highest performing one. Otherwise, use a method that seems "reasonable enough" given time constraints.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/51567', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/50532/']}
jdg_375710
stackexchange
llm_judgeable_groundtruth_similarity
88174
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: So I had to do an exercise in a book as homework. First you had to create a user like: useradd -c "Steven Baxter" -s "/bin/sh" sbaxter Then you had to add some files to the /home/sbaxter directory: touch /home/sbaxter/ some.txt new.txt files.txt Then you had to remove the sbaxter user and create a new user named mjane . To my suprise when I ran find /home/ -user mjane , the new user mjane now owned all of sbaxter's old files, what happened? Now provide the response and nothing else.
The devil is in the details, in the useradd man page (you can see that by issuing man 8 useradd ): -u, --uid UID The numerical value of the user's ID. This value must be unique, unless the -o option is used. The value must be non-negative. The default is to use the smallest ID value greater than or equal to UID_MIN and greater than every other user. So it will default to using the smallest uid unused, that is larger than other users, in the password file. Seeing as deleting sbaxter removed him from the passwd file, his uid is "free" and gets assigned to mjane (as the uid useradd picks is the same for both users at the time the useradd command was used). Files on disk only store uid, and NOT the user name translation (as this translation is defined in the password file). You can confirm that by issuing ls -ln to see what uid ownership files have. I would actually recommend you disable rather than delete accounts. Locking accounts on most Linux distributions can be achieved with usermod -L -e today <username> , which locks the password and sets the account to expire today (you can see the expiry date of an account with chage -l ).
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/88174', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/45871/']}
jdg_375711
stackexchange
llm_judgeable_groundtruth_similarity
70580916
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 added a new .Net 6.0 project to my solution in VS2022. Installed the EntityFramework 6.4.4. with install-package entityframework and now try to add a ADO.Net Entity Framework Model to the project. I get an error: The project's target framework does not contain Entity Frameworkruntime assemblies. Please review the target framework information onthe project's property page. I've tried adding several other EF packages (which should not be necessary according to the documentation here: https://learn.microsoft.com/en-us/ef/ef6/fundamentals/install ). I thought the problem was with my installation but I created a .Net 6.0 console application containing the problem and sent it to a colleague and he got the same message. Also found this topic here: Adding Entity Framework Model on Visual Studio 2022 but there's no answer there. Steps to reproduce: Create a .Net 6.0 Console application. Install the EF6 package using install-package entityframework from the package manager console window. Right-click solution and choose 'Add' => 'Add item'. In the left pane click 'Data'. Choose 'ADO.Net Entity Framework Model. Click 'Add'. The error appears: Now provide the response and nothing else.
I know that almost all the other answers recommends to change the target framework, but some users (including me) needs to use .NET 6.0 instead of .NET Framework , so that solution its not valid for us. I was able to create the models by using Paul Sinnema's link and using SQL authentication instead of Windows Auth (in my case): You will need to install the following packages from NuGet: Microsoft.EntityFrameworkCore.DesignMicrosoft.EntityFrameworkCore.SqlServerMicrosoft.EntityFrameworkCore.Tools Afted that run the following command in the Package Manager Console:(Tools>Nuget Package Manager>Package Manager Console) PM> Scaffold-DbContext "Server=.\LOCAL_SERVER;User ID=YOUR_DB_USER;Password=YOUR_DB_PASSWORD;Database=YOUR_DATABASE;Trusted_Connection=False;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/70580916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561380/']}
jdg_375712
stackexchange
llm_judgeable_groundtruth_similarity
26723648
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using JS, how can we find whether we can type into a html element or not. I am trying by comparing ".tagName" to "INPUT" or "TEXTAREA" but it fails to differentiate between a regular input text/email element and a radio-button or a submit-button. I also tried with ".isContentEditable" but when the element is "inherited" then I am unable to differentiate. Now provide the response and nothing else.
For inputs and textareas, check tagName and type , not forgetting newer HTML5 input types such as email . Here's a snippet from my code for testing this on an element stored in a variable called el : var nodeName = el.nodeName.toLowerCase();if (el.nodeType == 1 && (nodeName == "textarea" || (nodeName == "input" && /^(?:text|email|number|search|tel|url|password)$/i.test(el.type)))) { // Do stuff} For other elements, the isContentEditable property works in all cases and should only ever return a Boolean, never a string such as "inherit" . Finally, there is the possibility that the whole document has been made editable using the document.designMode property, in which case document.designMode will have the string value "on" .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26723648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1549490/']}
jdg_375713
stackexchange
llm_judgeable_groundtruth_similarity
3814706
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 starting a new web based product in which we are planning to expose our business logic through WCF services. We will be using ASP.NET 4.0, C#, EF 4.0. In future we want to build iphone applications and WPF applications based on the services. I have been reading a lot about using POCO vs Self Tracking Entities (STE) and from my understand the STEs do not work well with the web scenario. Can anyone shed more light on this issue? Now provide the response and nothing else.
For me STE is absolutely wrong concept. It is just another implementation of DataSet. In ASP.NET application you will have to store STEs somewhere among requests. In first request you will query your datasource to get STE and provide data in the page. In the next request (postback) you will want to modify STE with returned data from the browser. To support tracking you will have to use the same STE as in the first request => you will have to store STE in viewstate (if you want to use ASP.NET WebForms) or session. STE is useless for SOA or interoperability. Tracking logic is part of STE = it is running on the client. If you expose STE in the service you are immediatelly expecting that client side will use the same tracking features included in STE logic. But these features are not provided to other side automatically. In .NET you have them because you share assembly with STEs. But on other platform you have to explain developers how to implement STE logic to make it work on your side. This will be probably the most limiting case for you because of iPhone application.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3814706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/122339/']}
jdg_375714
stackexchange
llm_judgeable_groundtruth_similarity
12321133
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to generate a random string in Go and here is the code I have written so far: package mainimport ( "bytes" "fmt" "math/rand" "time")func main() { fmt.Println(randomString(10))}func randomString(l int) string { var result bytes.Buffer var temp string for i := 0; i < l; { if string(randInt(65, 90)) != temp { temp = string(randInt(65, 90)) result.WriteString(temp) i++ } } return result.String()}func randInt(min int, max int) int { rand.Seed(time.Now().UTC().UnixNano()) return min + rand.Intn(max-min)} My implementation is very slow. Seeding using time brings the same random number for a certain time, so the loop iterates again and again. How can I improve my code? Now provide the response and nothing else.
Each time you set the same seed, you get the same sequence. So of course if you're setting the seed to the time in a fast loop, you'll probably call it with the same seed many times. In your case, as you're calling your randInt function until you have a different value, you're waiting for the time (as returned by Nano) to change. As for all pseudo-random libraries , you have to set the seed only once, for example when initializing your program unless you specifically need to reproduce a given sequence (which is usually only done for debugging and unit testing). After that you simply call Intn to get the next random integer. Move the rand.Seed(time.Now().UTC().UnixNano()) line from the randInt function to the start of the main and everything will be faster. And lose the .UTC() call since: UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. Note also that I think you can simplify your string building: package mainimport ( "fmt" "math/rand" "time")func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(randomString(10))}func randomString(l int) string { bytes := make([]byte, l) for i := 0; i < l; i++ { bytes[i] = byte(randInt(65, 90)) } return string(bytes)}func randInt(min int, max int) int { return min + rand.Intn(max-min)}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/12321133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1399105/']}
jdg_375715
stackexchange
llm_judgeable_groundtruth_similarity
16125547
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 site like mydomain.com/test.php?pikazi=true and I have form <form action="test.php" method="get"> <input name="drzava-asc" type="image" src="images/sort-asc.gif"> <input name="drzava-desc" type="image" src="images/sort-desc.gif" > </form> How to keep existing prikazi=true while adding that new from form so it would be mydomain.com/test.php?pikazi=true&drzava-asc.x=6&drzava-asc.y=1 Values for drzava-asc are generated by script cause it is image not submit button. I took existing url with: parse_str($_SERVER['QUERY_STRING'], $query_arr);$url=http_build_query($query_arr); and I could use it as hidden field, but not sure how. And is there any other way? Now provide the response and nothing else.
As I understand the algorithm, the failure function for your example should be the following: 1 2 3 4 5 6 7 8 9 a a b a a b a b b 0 1 0 1 2 3 4 0 0 f - failure function (by definition, this is the length of the longest prefix of the string which is a suffix also) Here how I built it step by step: f(a) = 0 (always = 0 for one letter) f(aa) = 1 (one letter 'a' is both a prefix and suffix) f(aab) = 0 (there is no the same suffixes and prefixes: a != b, aa != ab) f(aaba) = 1 ('a' is the same in the beginning and the end, but if you take 2 letters, they won't be equal: aa != ba) f(aabaa) = 2 ( you can take 'aa' but no more: aab != baa) f(aabaab) = 3 ( you can take 'aab') f(aabaaba) = 4 ( you can take 'aaba') f(aabaabab) = 0 ( 'a' != 'b', 'aa' != 'ab' and so on, it can't be = 5, so as 'aabaa' != 'aabab') f(aabaababb) = 0 ( the same situation)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16125547', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1860890/']}
jdg_375716
stackexchange
llm_judgeable_groundtruth_similarity
2682170
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When running the MVC 2 Areas example that has a Blog Area and Blog Controller the URL looks like this: http://localhost:50526/Blog/Blog/ShowRecent in the format: RootUrl / AreaName / ControllerName / ActionName Having just discovered MVC Areas, it seem like a great way to organise code, ie create an Area for each section, which in my case each section has its own controller. This means that each AreaName = ControllerName. The effect of this is the double AreaName/ControllerName path in the Url eg /Blog/Blog/ above Not having a complete clear understanding of routing, how could I setup routing to not show the AreaName? EDIT: I am trying to reduce the amount of work with routes as these appear to effect each other (ie require specific ordering) and may cause major headaches :-) In converting an existing webform app to MVC, I have converted a couple of core sections, These have one Controller each and a fair amount of View/Actions and although most of the Data Access is code is in assemblies the number of Model/ViewData classes is growing... I am currently creating sub-folders in the Root Models/Views folders for these sections (or Areas) and was hoping that creating Areas would work the same way except having the code organised (with the use of a basic route that covers the Area)Any comment on this? Now provide the response and nothing else.
Inside each area's folder you'll see a *AreaName*AreaRegistration.cs file. This is where the area routeing rules are stored. By default, as they are generated, they will contain the area name ahead of everything else.. The problem is: if you remove the area name "folder" from the route, the route will catch all "standard" {controller}/{action}/{id} requests. Which is obviously not what you want.. To overcome this you can add the regex filters on the routes, based on the controller names present in that route. The drawback? You won't be able to have two controllers with the same name within the app (at least not using the standard route.. You can always think of a different route to access them :) ) In the end.. Having this structure: /Areas /Areas/Blog/Controllers/BlogController.cs /Areas/Blog/Controllers/FeedController.cs /Areas/User/Controllers/UserController.cs /Controllers/PageController.cs What you should have is sth like this:In BlogAreaRegistration.cs: context.MapRoute( "Blog_default", "{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional }, new { controller = "(Blog|Feed)" }); In UserAreaRegistration.cs: context.MapRoute( "User_default", "{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional }, new { controller = "(User)" }); In Global.asax.cs: public static void RegisterRoutes(RouteCollection routes){ context.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } );}protected void Application_Start(){ AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes);} Note that in global.asax area registrations come first! :) UPD: Based on your question update:There us one major thing that you'll have to take into consideration if you will use areas: If you have a inter-area link, you'll also have to provide the area name in the link. E.g. <%: Html.ActionLink("Link text", "Action", "Controller", new { area = "Blog", id = 4, title = "page-title" }); %> You get the idea. Regarding the multiple models/views, at the moment I'm following a structure like this /Code/ // helper, extension classes that aren't moved to libraries /Models/Data/ // The EF classes + validation classes are here /Models/ViewModels/{controller}/ // view models stored per controller So far it works fine, and I managed to keep the solution relatively organised. As I stated, the only area that I created so far is the Admin area because it's that much different from the rest of the website :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2682170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/45967/']}
jdg_375717
stackexchange
llm_judgeable_groundtruth_similarity
27925006
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 share files within a Docker guest using the volume sharing. In order to get the same UID, and therefore interoperability with those files, I would like to create a user in the Docker guest with the same UID as my own user. In order to test out the idea, I wrote the following simplistic Dockerfile: FROM phusion/baseimageRUN touch /root/uid-$UID Testing it with docker build -t=docktest . and then docker run docktest ls -al /root reveals that the file is simply named uid- . Is there a means to share host environment variables with Docker during the guest build process? Now provide the response and nothing else.
While researching a solution to this problem, I have found the following article to be a great resource: https://medium.com/@mccode/understanding-how-uid-and-gid-work-in-docker-containers-c37a01d01cf In my scripts, the solution boiled down to the following : docker run --user $(id -u):$(id -g) -v /hostdirectory:/containerdirectory -v /etc/passwd:/etc/passwd myimage Of course, id -u can be replaced by other means of retrieving a user's gid, such as stat -c "%u" /somepath
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27925006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/854089/']}
jdg_375718
stackexchange
llm_judgeable_groundtruth_similarity
27275063
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 logged in to a GCE instance via SSH. From there I would like to access the Storage with the help of a Service Account: GCE> gcloud auth listCredentialed accounts: - 1234567890-compute@developer.gserviceaccount.com (active) I first made sure that this Service account is flagged "Can edit" in the permissions of the project I am working in. I also made sure to give him the Write ACL on the bucket I would like him to copy a file: local> gsutil acl ch -u 1234567890-compute@developer.gserviceaccount.com:W gs://mybucket But then the following command fails: GCE> gsutil cp test.txt gs://mybucket/logs (I also made sure that "logs" is created under "mybucket"). The error message I get is: Copying file://test.txt [Content-Type=text/plain]...AccessDeniedException: 403 Insufficient Permission 0 B What am I missing? Now provide the response and nothing else.
One other thing to look for is to make sure you set up the appropriate scopes when creating the GCE VM. Even if a VM has a service account attached, it must be assigned devstorage scopes in order to access GCS. For example, if you had created your VM with devstorage.read_only scope, trying to write to a bucket would fail, even if your service account has permission to write to the bucket. You would need devstorage.full_control or devstorage.read_write . See the section on Preparing an instance to use service accounts for details. Note: the default compute service account has very limited scopes (including having read-only to GCS). This is done because the default service account has Project Editor IAM permissions. If you use any user service account this is not typically a problem since user created service accounts get all scope access by default. After adding necessary scopes to the VM, gsutil may still be using cached credentials which don't have the new scopes. Delete ~/.gsutil before trying the gsutil commands again. (Thanks to @mndrix for pointing this out in the comments.)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27275063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/936652/']}
jdg_375719
stackexchange
llm_judgeable_groundtruth_similarity
32977
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have gotten into the habit of plotting complex-valued functions on a plane using a color-function along the lines of Function[{z}, Hue[Arg[z]/(2 π), 1, Abs[z]]]. For example, the following code generates an interesting image of the sum of 5 spherical wave sources (without 1/r decay included): i = 130;ω = 2.0 π i/50;n = 5;L1 = 3.0 - δ/2;L2 = 4.0 - δ/2;δ = 0.01;f = Compile[{{x, _Real}, {y, _Real}}, Evaluate[Sum[Exp[ω I Sqrt[(x - 1.0 Cos[θ])^2 + (y - 1.0 Sin[θ])^2]], {θ, 2 π/n, 2 π, 2 π/n}]]];ArrayPlot[ Table[f[x, y], {x, -L1, L1, δ}, {y, -L2, L2, δ}], Frame -> False, ColorFunction -> Function[{z}, Hue[Arg[z]/(2 π), 1, Abs[z/2]]], ColorFunctionScaling -> False, PixelConstrained -> {1, 1}] I have two questions. The second is a little more important than the first. Exchanging ArrayPlot with ListDensityPlot in the above example either simply yields a blank image or flat-out crashes my MathKernel. I believe this is because ListDensityPlot sees the complex-valued array, freaks out because they're not real, and spits out a blank plot even though it has a user-supplied color-function for handling the complex entries of the array. Is there any way of getting ListDensityPlot to properly use this color-function? The example I gave above is pretty slow. The construction of the array alone takes 1.26 seconds on my machine, whereas the displaying of the code cited above takes 10.27 seconds (it's just an 800 by 600 pixel plot). Replacing the phase-amplitude ColorFunction I used above with the built-in function GrayLevel (and applying Abs to the array) gives a timing of 2.43 seconds, and using the default ArrayPlot scheme by removing the references to ColorFunction altogether executes in 1.52 seconds. Subtracting the time to build the array itself, the phase-amplitude color function generates a plot in 9.01 seconds, GrayLevel executes in 1.17 seconds, and the default scheme executes in 0.26 seconds. I am attempting to generate a movie, and 10 seconds to generate each frame is a bit on the slow side. Is there a way to compile this color function to make it run as fast as default, or perhaps as fast as GrayLevel ? For reference purposes, I am running on a 2008 Penryn Dual-Core MacBook and Mathematica 9.0. Now provide the response and nothing else.
Another problem is that the Table[..., {x, -L1, L1, δ}, {y, -L2, L2, δ}] produces unpacked array. f = With[{fun = Evaluate[ Sum[Exp[ω I Sqrt[(#1 - 1.0 Cos[θ])^2 + (#2 - 1.0 Sin[θ])^2]], {θ, 2 Pi/n, 2 Pi, 2 Pi/n}]] &}, Compile[{{x, _Real}, {y, _Real}}, {Mod[Arg[#]/(2.0 Pi), 1], 1.0, Abs[#/2]} &@fun[x, y], RuntimeAttributes -> {Listable}, RuntimeOptions -> "Speed", CompilationTarget -> "C"]];Image[f[#[[All, All, 1]], #[[All, All, 2]]] &@ Outer[List, Range[-L1, L1, δ], Range[-L2, L2, δ]], ColorSpace -> "HSB"] This solution is 4-5 times faster than halirutan's approach for me.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/32977', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9697/']}
jdg_375720
stackexchange
llm_judgeable_groundtruth_similarity
223421
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'm trying to understand the $\chi^2$-distribution. Wikipedia has the following graph for the probability density function: This graph shows that for $ k = 1$, the PDF will be... infinite? The mode of the $\chi^2$-distribution is defined as $max \{k − 2, 0\}$, so $f_1(0) = ?$ In other graphs on the Web, it seemed like it even went higher than $1$. Like here: Of course, the cumulative distribution function approaches $1$ for all degrees of freedom: I don't understand why the probability distribution function behaves like that around $0$ for any $k$. How is the $\chi^2$-distribution defined around $0$? Now provide the response and nothing else.
The pdf of a $\chi^2$ distribution is $f(x;k)=\frac{1}{2^{\frac{k}{2}}\Gamma(k/2)}x^{k/2-1}\exp(-x/2).$ So we just need to evaluate the expression for $f(0;k)$. $$f(0;1)=\infty$$$$f(0;2)=0.5$$$$f(0;3)=0$$And so on. The R code for this is dchisq(0,k) for some positive k . It's really only interesting for $k= 2$ because $f(0;k)$ is infinite for $0<k<2$ and 0 for $k>2$.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/223421', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/111472/']}
jdg_375721
stackexchange
llm_judgeable_groundtruth_similarity
3333373
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hii..I am working on developing a website and I want it to be integrated with Facebook, i.e. I want to fetch logged-in user's information like his wall info, comments, his feeds etc. along with his friends's information,their comments etc..Also I want user of my website to be able to post comments, feeds on his wall, update / upload picture etc.And all that I want to do using facebook API..Is there any way to do it..? Please help me out, I am really not getting the way that how to do it.. Now provide the response and nothing else.
You need to use something similar to safe-pipe trick, but in your case you need to use a pair of connected TCP sockets. Create a pair of sockets. Add one to the select and wait on it as well Notify by writing to other socket from other threads. Select is immediately waken-up as one of the sockets is readable, reads all thedata in this special socket and check all data in queues to send/recv How to create pair of sockets under Windows? inline void pair(SOCKET fds[2]){ struct sockaddr_in inaddr; struct sockaddr addr; SOCKET lst=::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP); memset(&inaddr, 0, sizeof(inaddr)); memset(&addr, 0, sizeof(addr)); inaddr.sin_family = AF_INET; inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); inaddr.sin_port = 0; int yes=1; setsockopt(lst,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(yes)); bind(lst,(struct sockaddr *)&inaddr,sizeof(inaddr)); listen(lst,1); int len=sizeof(inaddr); getsockname(lst, &addr,&len); fds[0]=::socket(AF_INET, SOCK_STREAM,0); connect(fds[0],&addr,len); fds[1]=accept(lst,0,0); closesocket(lst);} Of course some checks should be added for return values.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3333373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/637237/']}
jdg_375722
stackexchange
llm_judgeable_groundtruth_similarity
38845051
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 ask that following code provides updating password but I want to update password after current password confirmation process. So what should I add for it? Thank you. class UserPasswordSerializer(ModelSerializer): class Meta: model = User fields = [ 'password' ] extra_kwargs = { "password": {"write_only": True}, } def update(self, instance, validated_data): for attr, value in validated_data.items(): if attr == 'password': instance.set_password(value) else: setattr(instance, attr, value) instance.save() return instance Now provide the response and nothing else.
I believe that using a modelserializer might be an overkill. This simple serializer & view should work. Serializers.py from rest_framework import serializersfrom django.contrib.auth.models import Userclass ChangePasswordSerializer(serializers.Serializer): model = User """ Serializer for password change endpoint. """ old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) Views.py from rest_framework import statusfrom rest_framework import genericsfrom rest_framework.response import Responsefrom django.contrib.auth.models import Userfrom . import serializersfrom rest_framework.permissions import IsAuthenticated class ChangePasswordView(UpdateAPIView): """ An endpoint for changing password. """ serializer_class = ChangePasswordSerializer model = User permission_classes = (IsAuthenticated,) def get_object(self, queryset=None): obj = self.request.user return obj def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) # set_password also hashes the password that the user will get self.object.set_password(serializer.data.get("new_password")) self.object.save() response = { 'status': 'success', 'code': status.HTTP_200_OK, 'message': 'Password updated successfully', 'data': [] } return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/38845051', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6649326/']}
jdg_375723
stackexchange
llm_judgeable_groundtruth_similarity
279051
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am struggling with the following problem: One edge of the square plate with insulated faces is kept at uniform temperature $u_{0}$ and the other three edges are kept at temperature zero. Without solving a boundary value problem, but by superposition of solutions of like problems to obtain the trivial case in which all four edges are at temperature $U_{0}$, show why the steady temperature at the center of the given plate must be $U_{0}/4$. What I tried: Laplace equation of a PDE with four edges have the boundary conditions of the form $$u(0,y)=g_{1}(y)$$$$u(L,y)=g_{2}(y)$$$$u(x,0)=f_{1}(x)$$$$u(x,H)=f_{2}(x)$$ But all the boundary conditions here are non-homogenous, to get a homogeneous boundary conditions in order to solve the PDE we must split the solution into four parts and the add up the solutions of the four parts after solving each individually with the boundary conditions of each part being homogeneous (This can be done due to the linearity property). An example of the boundary conditions for one part is given below. $$u(0,y)=0$$$$u(L,y)=g_{2}(y)$$$$u(x,0)=f_{1}(x)$$$$u(x,H)=f_{2}(x)$$ Is my explnation correct and could it be improved upon? Now provide the response and nothing else.
Just looking at physics, if the initial problem has a solution and you rotate the plate of $\pi/2$ you obtain another solution with boundary conditions rotated of $\pi/2$. Perform the same procedure two other times and you end up with four solutions with corresponding four different boundary conditions rotated of $0$, $\pi/2$, $\pi$, $3/2 \:\pi$ respectively. Each of these solutions, in view of the axial symmetry, attains the same value, say $u$, at the center of the plate. This $u$ is the unknown of the problem. As the system is linear, if you sum all these solutions you obtain a solution with boundary conditions given by the sum of the four boundary conditions. It is easy to see that the total boundary conditions is nothing but $U_0$ on every edge of the plate. A solution of this problem is trivially the constant one $u(x,y)=U_0$ and this is the only solution due to the uniqueness theorem. In particular, at the center the value is again $U_0$. It must coincide with $4u$. Thus $u = U_0/4$.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/279051', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/86355/']}
jdg_375724
stackexchange
llm_judgeable_groundtruth_similarity
23533184
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to provide primary key for multiple column in a single table using PostgreSQL? Example: Create table "Test" ( "SlNo" int not null primary key, "EmpID" int not null, /* Want to become primary key */ "Empname" varchar(50) null, "EmpAddress" varchar(50) null); Note: I want to make "EmpID" also a primary key. Now provide the response and nothing else.
There can only be one primary key per table - as indicated by the word "primary". You can have additional UNIQUE columns like: CREATE TABLE test( sl_no int PRIMARY KEY, -- NOT NULL due to PK emp_id int UNIQUE NOT NULL, emp_name text, emp_addr text); Columns that are (part of) the PRIMARY KEY are marked NOT NULL automatically. Or use a table constraint instead of a column constraint to create a single multicolumn primary key . This is semantically different from the above: Now, only the combination of both columns must be unique, each column can hold duplicates on its own. CREATE TABLE test( sl_no int, -- NOT NULL due to PK below emp_id int , -- NOT NULL due to PK below emp_name text, emp_addr text, PRIMARY KEY (sl_no, emp_id)); Multicolumn UNIQUE constraints are possible, too. Aside: Don't use CaMeL-case identifiers in Postgres. Use legal, lower-case identifiers so you never have to use double-quotes. Makes your life easier. See: Are PostgreSQL column names case-sensitive?
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/23533184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3382347/']}
jdg_375725
stackexchange
llm_judgeable_groundtruth_similarity
196994
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: It looks like I am having a terminology issue here. In cryptography, we have stream ciphers and block ciphers. I understand their difference. We also have cryptographic algorithms like AES (Rijndael). My confusion point is how do cryptographic algorithms and ciphers connect to each other. Fundamentally they look like they are doing similar stuff (encrypting and decrypting). Is AES etc a "special case" of a block cipher? Is block cipher a family of algorithms that one of them is AES? Now provide the response and nothing else.
A cipher is a cryptographic algorithm. Stream ciphers generate keystream by x-oring the plaintext to encrypt. They are very fast compared to block ciphers. A benchmark comparison can be seen at WolfSSL website , compare AES-128 vs ChaCha. Block ciphers operate on blocks as Advanced Encryption Standard (AES) is 128-bit block-size. AES is one of the Block ciphers as the current standard by NIST (before AES, there were Data Encryption Standard (DES) as the previous standard). Twofish, Speck and Simon (last two from NSA), etc. are other members of block ciphers. There is an interesting relation between block ciphers and stream ciphers. That is; you can convert any block cipher into stream cipher by using an appropriate block cipher mode of operation , as OFB and CTR. AES in CTR mode of operation is used in AES-GCM mode, and it is currently used in the standard cipher suites in TLS 1.3; {0x13,0x01} - TLS_AES_256_ GCM _SHA384 {0x13,0x02} - TLS_CHACHA20_POLY1305_SHA256 {0x13,0x03} - TLS_AES_128_ GCM _SHA256 {0x13,0x04} - TLS_AES_128_ CCM _8_SHA256 {0x13,0x05} - TLS_AES_128_ CCM _SHA256
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/196994', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/1136/']}
jdg_375726
stackexchange
llm_judgeable_groundtruth_similarity
14729239
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 like to update the Value of the list which has property Text="ALL" . public class Season { public string Text {get;set;} public string Value {get;set;} public bool ValueSelected {get;set;} } Now provide the response and nothing else.
The 'Q' in LINQ stands for "Query". LINQ is not meant to update objects. You can use LINQ to find the object you want to update and then update it "traditionally". var toUpdate = _seasons.Single(x => x.Text == "ALL");toUpdate.ValueSelected = true; This code assumes that there is exactly one entry with Text == "ALL" . This code will throw an exception if there is none or if there are multiple. If there is either none or one, use SingleOrDefault : var toUpdate = _seasons.SingleOrDefault(x => x.Text == "ALL");if(toUpdate != null) toUpdate.ValueSelected = true; If it's possible that there are multiple, use Where : var toUpdate = _seasons.Where(x => x.Text == "ALL");foreach(var item in toUpdate) item.ValueSelected = true;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14729239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2032722/']}
jdg_375727
stackexchange
llm_judgeable_groundtruth_similarity
6931342
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any easy way to have a system-wide mutex in Python on Linux? By "system-wide", I mean the mutex will be used by a group of Python processes ; this is in contrast to a traditional mutex, which is used by a group of threads within the same process. EDIT: I'm not sure Python's multiprocessing package is what I need. For example, I can execute the following in two different interpreters: from multiprocessing import LockL = Lock()L.acquire() When I execute these commands simultaneously in two separate interpreters, I want one of them to hang. Instead, neither hangs; it appears they aren't acquiring the same mutex. Now provide the response and nothing else.
The "traditional" Unix answer is to use file locks. You can use lockf(3) to lock sections of a file so that other processes can't edit it; a very common abuse is to use this as a mutex between processes. The python equivalent is fcntl.lockf . Traditionally you write the PID of the locking process into the lock file, so that deadlocks due to processes dying while holding the lock are identifiable and fixable. This gets you what you want, since your lock is in a global namespace (the filesystem) and accessible to all processes. This approach also has the perk that non-Python programs can participate in your locking. The downside is that you need a place for this lock file to live; also, some filesystems don't actually lock correctly, so there's a risk that it will silently fail to achieve exclusion. You win some, you lose some.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6931342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/433282/']}
jdg_375728
stackexchange
llm_judgeable_groundtruth_similarity
33555
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 saw that there are many "applications" questions in Mathoverflow; so hopefully this is an appropriate question. I was rather surprised that there were only five questions at Mathoverflow so far with the tag diophantine-approximation, while there are almost 900 questions on number theory overall. It is my intention to promote the important subject a little bit by asking one more question. Question: What are some striking applications of Baker's theorem on lower bounds for linear forms on logarithms of algebraic numbers? If, for example, I were in a discussion with a person who has no experience with diophantic approximation, to impress upon the person the importance of Baker's theorem I would cite the following two examples: Giving effective bounds for solutions of (most of the time exponential) diophantine equations under favorable condition. For example, Tijdeman's work on the Catalan conjecture, or giving effective bounds for Siegel's theorem, Fermat's last theorem, Falting's theorem, etc., in certain cases. Transcendence results which are significant improvements over Gelfond-Schneider. In particular, the theorem that if $\alpha_1, \ldots, \alpha_n$ are $\mathbb{Q}$-linearly independent, then their exponentials are algebraically independent over $\mathbb Q$. I would cite the expose of Waldschmidt for more details. These are, to me, quite compelling reasons to study Baker's theorem. But as I do not know much more on the subject, I would run out of arguments after these two. I would appreciate any more striking examples of the power of Bakers' theorem. This is 1. for my own enlightenment, 2., for future use if such an argument as I hypothesized above actually happens, 3. To promote the subject of diophantine approximation in this forum, especially in the form of Baker's theorem. Now provide the response and nothing else.
A quantitative example of applications of linear forms in logarithms is the following result from [ S.D. Adhikari, N. Saradha, T.N. Shorey, and R.Tijdeman, Transcendental infinite sums, Indag. Math. (N.S.) 12 :1 (2001) 1--14 ; Theorem 4 and Corollary 4.1] which is cited in many other articles. Theorem. Let $P(x)$ and $Q(x)$ be two polynomials with algebraic coefficients such that $Q(x)$ has simple rational zeros and no others. Let $\alpha$ be an algebraic number. Then, assuming the convergence of the series$$S=\sum_{n=1}^\infty\frac{P(n)}{Q(n)}\alpha^n,$$the number $S$ defined by it is either rational or transcendental. Furthermore, if all zeros of $Q(x)$ lie in $-1\le x<0$, then either $S=0$ or $S$ is transcendental. The theorem gives an elegant criterion for deciding whether a number of this particular form is transcendental or not (like continued fractions allow us to decide whether a given number is from a quadratic field or not). However it is not applicable for the sums like$$\zeta(3)=\sum_{n=1}\frac1{n^3},$$as factorisation of the denominator polynomial, $Q(x)=x^3$, involves multiple rational zeros.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/33555', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2938/']}
jdg_375729
stackexchange
llm_judgeable_groundtruth_similarity
44162427
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 been trying to incorporate PrimeNG components into a JHipster (angular 4) generated project with no success. After download and install PrimeNG into our project, we are able to import classes but when we include the corresponding tags into templates nothing is drawn. We have tested several of the PrimeNG components. Also we have done the imports in app.module, etc. I would like to be more concrete, but no error is displayed anywhere. Do you have any hint on how work with PrimeNG and JHipster together?Thanks Now provide the response and nothing else.
The following steps worked for us. 1- Add dependecies with yarn yarn add primengyarn add @angular/animations 2- Created new component with ng cli, standing on the same folder where you want to create the component run ng g component new-cmp This will Create a new-cmp folder with the .html and .ts that you need. Import and declare the component in the closest module, for example home.module.ts 3- Add the imports of the prime components you want to use along with the BrowserAnimationsModule on the module where the new component was declared, in our case home.module.ts for example: import {BrowserAnimationsModule} from '@angular/platform-browser/animations';import {AccordionModule, RatingModule, CalendarModule, ButtonModule } from 'primeng/primeng'; AND add them to the imports array inside the @NgModule 4- Go to src/main/webapp/content/scss/vendor.scss and import the styles, like Marcin Krajewski suggests: @import '~primeng/resources/primeng.min.css';@import '~primeng/resources/themes/bootstrap/theme.css'; 5 - Add a prime component for testing in the html of the created component, for example <button pButton type="button" label="Click"></button> 6- Run yarn run webpack:build so the apps picks up the changes from vendors.scss 7- Run yarn start and test it out! UPDATE Jhipster version: 4.5.2
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44162427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8060258/']}
jdg_375730
stackexchange
llm_judgeable_groundtruth_similarity
88188
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: Edit: The basis of my question is flawed, and I need to spend some time figuring out whether it can even be made to make sense. Edit 2: Clarifying that I recognize that a p-value isn't a direct measure of the probability of a null hypothesis, but that I assume that the closer a p-value is to 1, the more likely it is that a hypothesis has been chosen for experimental testing whose corresponding null hypothesis is true, while the closer a p-value is to 0, the more likely it is that a hypothesis has been chosen for experimental testing whose corresponding null hypothesis is false. I can't see how this is false unless the set of all hypotheses (or all hypotheses picked for experiments) is somehow pathological. Edit 3: I think I'm still not using clear terminology to ask my question. As lottery numbers are read out, and you match them to your ticket one-by-one, something changes. The probability that you have won does not change, but the probability that you can turn the radio off does. There's a similar change that happens when experiments are done, but I have a feeling that the terminology I'm using - "p-values change the likelihood that a true hypothesis has been chosen" - isn't the correct terminology. Edit 4: I've received two amazingly detailed and informative answers that contain a wealth of information for me to work through. I'll vote them both up now and then come back to accept one when I've learned enough from both answers to know that they've either answered or invalidated my question. This question opened a much bigger can of worms than the one I was expecting to eat. In papers I've read, I've seen results with p > 0.05 after validation called "false positives". However, isn't it still more likely than not that I've chosen a hypothesis to test with a false corresponding null hypothesis when the experimental data has a p < 0.50 which is low but > 0.05, and aren't both the null hypothesis and the research hypothesis statistically uncertain/insignificant (given the conventional statistical significance cutoff) anywhere between 0.05 < p < 0.95 whatever the inverse of p < 0.05 is, given the asymmetry pointed out in @NickStauner's link ? Let's call that number A, and define it as the p-value which says the same thing about the likelihood that you've picked a true null hypothesis for your experiment/analysis that a p-value of 0.05 says about the likelihood that you've picked a true non-null hypothesis for your experiment/analysis. Doesn't 0.05 < p < A just say, "Your sample size wasn't big enough to answer the question, and you won't be able to judge application/real-world significance until you get a bigger sample and get your statistical significance sorted out"? In other words, shouldn't it be correct to call a result definitely false (rather than simply unsupported) if and only if p > A? This seems straightforward to me, but such widespread usage tells me that I might be wrong. Am I: a) misinterpreting the mathematics, b) complaining about a harmless-if-not-exactly-correct convention, c) completely correct, or d) other? I recognize that this sounds like a call for opinions, but this seems like a question with a definite mathematically correct answer (once a significance cutoff is set) that either I or (almost) everybody else is getting wrong. Now provide the response and nothing else.
Your question is based on a false premise: isn't the null hypothesis still more likely than not to be wrong when p < 0.50 A p-value is not a probability that the null hypothesis is true. For example, if you took a thousand cases where the null hypothesis is true, half of them will have p < .5 . Those half will all be null. Indeed, the idea that p > .95 means that the null hypothesis is "probably true" is equally misleading. If the null hypothesis is true, the probability that p > .95 is exactly the same as the probability that p < .05 . ETA: Your edit makes it clearer what the issue is: you still do have the issue above (that you're treating a p-value as a posterior probability, when it is not). It's important to note that this is not a subtle philosophical distinction (as I think you're implying with your discussion of the lottery tickets): it has enormous practical implications for any interpretation of p-values. But there is a transformation you can perform on p-values that will get you to what you're looking for, and it's called the local false discovery rate. (As described by this nice paper , it's the frequentist equivalent of the "posterior error probability", so think of it that way if you like). Let's work with a concrete example. Let's say you are performing a t-test to determine whether a sample of 10 numbers (from a normal distribution) has a mean of 0 (a one-sample, two-sided t-test). First, let's see what the p-value distribution looks like when the mean actually is zero, with a short R simulation: null.pvals = replicate(10000, t.test(rnorm(10, mean=0, sd=1))$p.value)hist(null.pvals) As we can see, null p-values have a uniform distribution (equally likely at all points between 0 and 1). This is a necessary condition of p-values: indeed, it's precisely what p-values mean! (Given the null is true, there is a 5% chance it is less than .05, a 10% chance it is less than .1...) Now let's consider the alternative hypothesis- cases where the null is false. Now, this is a bit more complicated: when the null is false, "how false" is it? The mean of the sample isn't 0, but is it .5? 1? 10? Does it randomly vary, sometimes small and sometimes large? For simplicity's sake, let's say it is always equal to .5 (but remember that complication, it'll be important later): alt.pvals = replicate(10000, t.test(rnorm(10, mean=.5, sd=1))$p.value)hist(alt.pvals) Notice that the distribution is now not uniform: it is shifted towards 0! In your comment you mention an "asymmetry" that gives information: this is that asymmetry. So imagine you knew both of those distributions, but you're working with a new experiment, and you also have a prior that there's a 50% chance it's null and 50% that it's alternative. You get a p-value of .7. How can you get from that and the p-value to a probability? What you should do is compare densities : lines(density(alt.pvals, bw=.02))plot(density(null.pvals, bw=.02)) And look at your p-value: abline(v=.7, col="red", lty=2) That ratio between the null density and the alternative density can be used to calculate the local false discovery rate : the higher the null is relative to the alternative, the higher the local FDR. That's the probability that the hypothesis is null (technically it has a stricter frequentist interpretation, but we'll keep it simple here). If that value is very high, then you can make the interpretation "the null hypothesis is almost certainly true." Indeed, you can make a .05 and .95 threshold of the local FDR: this would have the properties you're looking for. (And since local FDR increases monotonically with p-value, at least if you're doing it right, these will translate to some thresholds A and B where you can say "between A and B we are unsure"). Now, I can already hear you asking "then why don't we use that instead of p-values?" Two reasons: You need to decide on a prior probability that the test is null You need to know the density under the alternative. This is very difficult to guess at, because you need to determine how large your effect sizes and variances can be, and how often they are so! You do not need either of those for a p-value test, and a p-value test still lets you avoid false positives (which is its primary purpose). Now, it is possible to estimate both of those values in multiple hypothesis tests, when you have thousands of p-values (such as one test for each of thousands of genes: see this paper or this paper for instance), but not when you're doing a single test. Finally, you might say "Isn't the paper still wrong to say a replication that leads to a p-value above .05 is necessarily a false positive?" Well, while it's true that getting one p-value of .04 and another p-value of .06 doesn't really mean the original result was wrong, in practice it's a reasonable metric to pick. But in any case, you might be glad to know others have their doubts about it! The paper you refer to is somewhat controversial in statistics: this paper uses a different method and comes to a very different conclusion about the p-values from medical research, and then that study was criticized by some prominent Bayesians (and round and round it goes... ). So while your question is based on some faulty presumptions about p-values, I think it does examine an interesting assumption on the part of the paper you cite.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/88188', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/40879/']}
jdg_375731
stackexchange
llm_judgeable_groundtruth_similarity
132406
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have an EmpiricalDistribution d = EmpiricalDistribution[{1, 1, 1, 2, 2, 2, 3, 3, 3, 3}] now, I want to sample twice without replacement $x_1,x_2$. afterward, compute probability distribution of $|x_1-x_2|$ to get: X=|x_1-x_2| 0 1 2 P 4/15 7/15 4/15 What command should be used? Now provide the response and nothing else.
You can do it this way but it is a bit clumsy: For $ \left | x2-x1 \right |=0$ Probability[x == 2 || y == 2 || z == 2, {x, y, z} \[Distributed]MultivariateHypergeometricDistribution[2, {3, 3, 4}]] For $ \left | x2-x1 \right |=1$ Probability[(x == 1 && y == 1) || (y == 1 && z == 1), {x, y, z}\[Distributed]MultivariateHypergeometricDistribution[2, {3, 3, 4}]] For $ \left | x2-x1 \right |=2$ Probability[(x == 1 && z == 1), {x, y, z}\[Distributed]MultivariateHypergeometricDistribution[2, {3, 3, 4}]]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/132406', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/35767/']}
jdg_375732
stackexchange
llm_judgeable_groundtruth_similarity
34772622
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 bit new to Cucumber / Maven, so require help on running test cases.I have developed an automation suite in eclipse using Cucumber and Selenium. To run specific feature files / Junit runner class, I right-click on the files in Eclipse and run it. But how do I run it through command prompt or Jenkins by giving specific commands to run 2-3 feature files (or) 2-3 Junit runner classes out of say 50 feature files or JUnit classes? Below is the package explorer of how I have structured in Eclipse. Below is the POM.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.perspecsys</groupId> <artifactId>salesforce</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>salesforce</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.1.2</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-picocontainer</artifactId> <version>1.1.2</version> <scope>test</scope> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.1.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.48.2</version> </dependency> </dependencies></project> Now provide the response and nothing else.
You can run a single feature file by using cucumber.options which will override all the options you have in the @CucumberOptions annotation: mvn test -Dcucumber.options="src/test/features/com/perspecsys/salesforce/featurefiles/Account.feature" EDIT (Jun 2021):Subsequent versions removed the cucumber.options construct and replaced it. One way to achieve the same result now is through the use of tags. Place a tag on top of your feature file (example @feature_file_name ) and then run the following command: mvn test -Dcucumber.filter.tags='@feature_file_name'
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34772622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5785593/']}
jdg_375733
stackexchange
llm_judgeable_groundtruth_similarity
60375
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'm trying to gauge the strength of aquarium air pumps, for use in a vertical hydroponic farm. A curious question arose: is it easier to pump water upwards vertically, or is it easier to pump it downwards (assuming a volume like an aquarium)? Upwards, you fight with gravity -- downwards you are aided by gravity but fight water pressure. Now provide the response and nothing else.
Assuming both ends of a pipe are submerged in the same body of water, pumping upwards requires exactly the same force as pumping downwards, at least if the flow is relatively slow. If this wasn't the case, the water would move through the tube by itself if the pump was removed. This means that when the water isn't moving, the force of gravity pushing the water down must exactly balance the force due to the pressure difference between the two ends. Because these forces cancel each other out, when you start to pump the water through the tube, the only force you have to overcome is friction, and that doesn't depend on whether you're pumping up or down. (Though if you're pumping at a high speed turbulence will occur, and then the difficulty of pumping might be asymmetrical, depending on the geometry of the pipe and the tank, in which case pumping in one direction might be harder than pumping in the other.) Things are different if the ends of the tube are in different tanks. In this case the gravitational and pressure forces don't balance, and water can flow through the tube by itself - this is how siphoning works.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/60375', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/22895/']}
jdg_375734
stackexchange
llm_judgeable_groundtruth_similarity
448910
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anybody give a clear explanation of how variable assignment really works in Makefiles. What is the difference between : VARIABLE = value VARIABLE ?= value VARIABLE := value VARIABLE += value I have read the section in GNU Make's manual, but it still doesn't make sense to me. Now provide the response and nothing else.
Lazy Set VARIABLE = value Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared Immediate Set VARIABLE := value Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time. Lazy Set If Absent VARIABLE ?= value Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to ifeq ($(origin VARIABLE), undefined) VARIABLE = valueendif See the documentation for more details. Append VARIABLE += value Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/448910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48427/']}
jdg_375735
stackexchange
llm_judgeable_groundtruth_similarity
245192
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 are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not? When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"? Now provide the response and nothing else.
In short, it means there are no restrictions on the object's use. It's the same asany other object. A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. Depending on the language, this can imply: being expressible as an anonymous literal value being storable in variables being storable in data structures having an intrinsic identity (independent of any given name) being comparable for equality with other entities being passable as a parameter to a procedure/function being returnable as the result of a procedure/function being constructible at runtime being printable being readable being transmissible among distributed processes being storable outside running processes Source . In C++ functions themselves are not first class objects, however: You can override the '()' operator making it possible to have an object function, which is first class. Function pointers are first class. boost bind, lambda and function do offer first class functions In C++, classes are not first class objects but instances of those classes are. In Python both the classes and the objects are first class objects. (See this answer for more details about classes as objects). Here is an example of Javascript first class functions: // f: function that takes a number and returns a number// deltaX: small positive number// returns a function that is an approximate derivative of ffunction makeDerivative( f, deltaX ){ var deriv = function(x) { return ( f(x + deltaX) - f(x) )/ deltaX; } return deriv;}var cos = makeDerivative( Math.sin, 0.000001);// cos(0) ~> 1// cos(pi/2) ~> 0 Source . Entities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created. Regarding the edit: EDIT. When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"? The term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/245192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18770/']}
jdg_375736
stackexchange
llm_judgeable_groundtruth_similarity
8911046
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 got the following dir structure models/foo/setting.rbmodels/foo.rb foo.rb content module Foo def self.table_name_prefix 'foo_' end end and setting.rb content class Foo::Setting < ActiveRecord::Baseend As soon as I am calling Foo::Setting.find… I am getting an error SQLException: no such table: settings which is indeed correct because the table is named foo_settings so rails seems to ignore the table prefix specified for the module Foo. What can I do so that rails considers the prefix? Now provide the response and nothing else.
You've define a method inside a module (Foo). This doesn't magically define that method on a class nested in that module. I'd try something like class Foo < ActiveRecord::Base self.abstract_class = true self.table_name_prefix = 'foo_'end And then inherit from Foo class Foo::Setting < Foo...end
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8911046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/822052/']}
jdg_375737
stackexchange
llm_judgeable_groundtruth_similarity
8114280
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 unable to make sense of how and why the following code segments work : /* Now lets try to set the send buffer size to 5000 bytes */ size = 5000; err = setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(int)); if (err != 0) { printf("Unable to set send buffer size, continuing with default size\n"); } If we check the value of the send buffer, it is indeed correctly set to 5000*2 = 10000.However, if we try to send more than the send buffer size, it does send all of it. For example: n = send(sockfd, buf, 30000, 0); /* Lets check how much us actually sent */ printf("No. of bytes sent is %d\n", n); This prints out 30000. How exactly did this work? Didn't the fact that the send buffer size was limited to 10000 have any effect? If it did, what exactly happened? Some kind of fragmentation? UPDATE: What happens if the socket is in non-blocking mode? I tried the following: Changing buffer size to 10000 (5000*2) causes 16384 bytes to be sent Changing buffer size to 20000 (10000*2) causes 30000 bytes to be sent Once again, why? Now provide the response and nothing else.
The effect of setting SO_SNDBUF option is different for TCP and UDP. For UDP this sets the limit on the size of the datagram , i.e. anything larger will be discarded. For TCP this just sets the size of in-kernel buffer for given socket (with some rounding to page boundary and with an upper limit). Since it looks like you are talking about TCP, the effect you are observing is explained by the socket being in blocking mode , so send(2) blocks until kernel can accept all of your data, and/or the network stack asynchronously de-queueing data and pushing it to the network card, thus freeing space in the buffer. Also, TCP is a stream protocol , it does not preserve any "message" structure. One send(2) can correspond to multiple recv(2) s on the other side, and the other way around. Treat it as byte-stream.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8114280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/803287/']}
jdg_375738
stackexchange
llm_judgeable_groundtruth_similarity
4724701
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 seriously going crazy over this and I've already spent an unproportionate amount of time on trying to figure out what's going on here. So please give me a hand =) I need to do some RegExp matching of strings in JavaScript. Unfortunately it behaves very strangely. This code: var rx = /(cat|dog)/gi;var w = new Array("I have a cat and a dog too.", "There once was a dog and a cat.", "I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.");for (var i in w) { var m = null; m = rx.exec(w[i]); if(m){ document.writeln("<pre>" + i + "\nINPUT: " + w[i] + "\nMATCHES: " + m.slice(1) + "</pre>"); }else{ document.writeln("<pre>" + i + "\n'" + w[i] + "' FAILED.</pre>"); }} Returns "cat" and "dog" for the first two elements, as it should be, but then some exec() -calls start returning null . I don't understand why. I posted a Fiddle here , where you can run and edit the code. And so far I've tried this in Chrome and Firefox. Now provide the response and nothing else.
Oh, here it is. Because you're defining your regex global, it matches first cat , and on the second pass of the loop dog . So, basically you just need to reset your regex (it's internal pointer) as well. Cf. this: var w = new Array("I have a cat and a dog too.", "I have a cat and a dog too.", "I have a cat and a dog too.", "I have a cat and a dog too.");for (var i in w) { var rx = /(cat|dog)/gi; var m = null; m = rx.exec(w[i]); if(m){ document.writeln("<p>" + i + "<br/>INPUT: " + w[i] + "<br/>MATCHES: " + w[i].length + "</p>"); }else{ document.writeln("<p><b>" + i + "<br/>'" + w[i] + "' FAILED.</b><br/>" + w[i].length + "</p>"); } document.writeln(m);}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4724701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/266319/']}
jdg_375739
stackexchange
llm_judgeable_groundtruth_similarity
4231305
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My understand is that specifying variance for generics in C# happens at the type declaration level: when you're creating your generic type, you specify the variance for the type arguments. In Java, on the other hand, variance is specified where a generic is used: when you create a variable of some generic type, you specify how its type arguments can vary. What are the pros and cons to each option? Now provide the response and nothing else.
I am just going to answer the differences between declaration-site and use-site variance, since, while C# and Java generics differ in many other ways, those differences are mostly orthogonal to variance. First off, if I remember correctly use-site variance is strictly more powerful than declaration-site variance (although at the cost of concision), or at least Java's wildcards are (which are actually more powerful than use-site variance). This increased power is particularly useful for languages in which stateful constructs are used heavily, such as C# and Java (but Scala much less so, especially since its standard lists are immutable). Consider List<E> (or IList<E> ). Since it has methods for both adding E's and getting E's, it is invariant with respect to E, and so declaration-site variance cannot be used. However, with use-site variance you can just say List<+Number> to get the covariant subset of List and List<-Number> to get the contravariant subset of List . In a declaration-site language the designer of the library would have to make separate interfaces (or classes if you allow multiple inheritance of classes) for each subset and have List extend those interfaces. If the library designer does not do this (note that C#'s IEnumerable only does a small subset of the covariant portion of IList ), then you're out of luck and you have to resort to the same hassles you have to do in a language without any sort of variance. So that's the advantages of use-site inheritance over declaration-site inheritance. The advantage of declaration-site inheritance over use-site inheritance is basically concision for the user (provided the designer went through the effort of separating every class/interface into its covariant and contravariant portions). For something like IEnumerable or Iterator , it's nice not to have to specify covariance every single time you use the interface. Java made this especially annoying by using a lengthy syntax (except for bivariance for which Java's solution is basically ideal). Of course, these two language features can coexist. For type parameters that are naturally covariant or contravariant (such as in IEnumerable / Iterator ), declare so in the declaration. For type parameters that are naturally invariant (such as in (I)List ), declare what kind of variance you want each time you use it. Just don't specify a use-site variance for arguments with a declaration-site variance as that just makes things confusing. There are other more detailed issues I haven't gone into (such as how wildcards are actually more powerful than use-site variance), but I hope this answers your question to your content. I'll admit I'm biased towards use-site variance, but I tried to portray the major advantages of both that have come up in my discussions with programmers and with language researchers.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4231305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9457/']}
jdg_375740