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
|
6119153
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Getting an error when trying to install the gem devise, the installation is stopping onthe gem bcrypt-ruby: $ gem install bcrypt-rubyError installing bcrypt-ruby:ERROR: Failed to build gem native extension. I'm running OSX 10.6.7 with Ruby under RVM.I reinstalled the lastest version of xcode & reinstalled Ruby 64bit, Rails and all the gems.
Now provide the response and nothing else.
|
I had the same problem installing under OSX 10.7.3. When installing the gem, my error message was: Building native extensions. This could take a while...ERROR: Error installing bcrypt-ruby:ERROR: Failed to build gem native extension.creating Makefilemakecompiling bcrypt_ext.cmake: /usr/bin/gcc-4.2: No such file or directorymake: *** [bcrypt_ext.o] Error 1 Looks like the gem is looking for gcc-4.2 but I only had a file called gcc. Now since I had just installed the latest Xcode (4.3), I knew that my C compiler was compliant but the gem had gcc-4.2 hardcoded into it. So my solution was: sudo ln -s /usr/bin/gcc /usr/bin/gcc-4.2 The linking worked like a charm.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6119153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/728439/']}
|
jdg_375141
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48226268
|
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 reset React state variables (to default values) in a container using setState() method. But getting the following error Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`. And finally: Maximum call stack size exceeded. My code below: resetMsg=()=> { const company = this.state.company;company.id = 0;company.messages = []; this.setState({company: company}); } I am calling resetMsg() when variable in Redux state is true. Code where I call resetMsg (The value of resetMessages is false initially and I need to reset React-state, when its true ): render() { if(this.props.resetMessages){ this.resetMsg(); }
Now provide the response and nothing else.
|
You might want to look into componentWillReceiveProps(nextProps) function. As per the official docs: componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method. This is where you want to do the resets. So something like: componentWillReceiveProps(nextProps) { if(nextProps.resetMessages) { const company = Object.assign({}, this.state.company); company.id = 0; company.messages = []; this.setState({company: company}); }} The snippet above will run every time props are sent down to the component. It first checks if the resetMessages prop is truthy. If it is, it will create a temporary copy of the company state, change the id and messages property values, and then update company with the new one. I want to highlight the issues you had with your code: Calling setState() inside render() is a no-no. Whenever you call setState() in general the render() will be run afterwards. Doing so inside render() itself will cause that function to be called again, and again, and again... Mutating the state and/or props directly. This line const company = this.state.company; does not create a copy of the state variable. It only store the reference to it. So once you do this, and then do company.id = ... you are essentially doing this.state.company.id = ... , which is anti-pattern in React. We only ever change state through setState() . To create a copy, use Object.assign({}, this.state.yourObject) for objects and this.state.yourArray.slice() for arrays.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48226268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8125765/']}
|
jdg_375142
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3934583
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
public class ClassA{ public string MyString {get; set;}}public class ClassB{ public List<ClassA> MyObjects {get; set;}}List<ClassB> classBList = new List<ClassB>();var results = (from i in classBList select i.MyObjects).Distinct(); I want a distinct list of all the ClassA objects in the classBList . How do I go about this using LINQ ? I'm thinking about a nested query, but couldn't quite figure it out. Any help is very appreciated.
Now provide the response and nothing else.
|
You're trying to select multiple result objects for each ClassB object in the original list. Therefore, you're looking for the SelectMany extension method : var results = classBList.SelectMany(b => b.MyObjects).Distinct(); If you want to use query expressions, you'll need to use two from clauses : var results = (from b in classBList from a in b.MyObjects select a).Distinct();
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3934583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109028/']}
|
jdg_375143
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12055005
|
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 a regular expression for a password. The password has to contain at least 8 characters. At least one character must be a number or a special character (not a letter). [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)][RegularExpression(@"(?=.*\W)?(?=.*\d)", ErrorMessage = "Error message")][DataType(DataType.Password)][Display(Name = "Password")]public string Password { get; set; } I have a length validation, but I need help with a regular expression that checks if the password contains at least one number or special character. Examples of valid passwords: testtest85*testtes*testtes1test1234*+ Examples of not valid passwords: testtesttestabc
Now provide the response and nothing else.
|
Use regex pattern ^(?=.{8})(?=.*[^a-zA-Z]) Explanation: ^(?=.{8})(?=.*[^a-zA-Z])│└──┬───┘└──────┬──────┘│ │ ││ │ └ string contains some non-letter character│ ││ └ string contains at least 8 characters│└ begining of line/string If you want to limit also maximum length (let's say 16) , then use regex pattern: ^(?=.{8,16}$)(?=.*[^a-zA-Z])
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12055005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/362194/']}
|
jdg_375144
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15610994
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been debugging this for 2 hours now, and it boils down to this. If I call QString::toStdString QString s = "testtesttesttesttesttest";const std::string &temp = s.toStdString(); the program later crashes on std::string destructor __CLR_OR_THIS_CALL ~basic_string() { // destroy the string _Tidy(true); // <---- It crashes on this line. } I thought it was memory corruption at first, but this happens even if main() contains only those 2 lines. Does anyone know why this happens, and also how can I fix it? My Qt version is 4.8.1 .
Now provide the response and nothing else.
|
Your Qt DLLs need to be compiled with STL support and exactly the same C-Runtime Library as your code. It looks as though you are using two different CRTs at the same time, which would destroy the objects created on one heap by Qt into the heap used by your program. Check the DLL Usage with the Dependency Walker!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15610994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492336/']}
|
jdg_375145
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15036007
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
GMSReverseGeocodeResponse contains - (GMSReverseGeocodeResult *)firstResult; whose definition is like: @interface GMSReverseGeocodeResult : NSObject<NSCopying>/** Returns the first line of the address. */- (NSString *)addressLine1;/** Returns the second line of the address. */- (NSString *)addressLine2;@end Is there any way to obtain the country, ISO country code, state (administrative_area_1 or corresponding one) from those two strings (valid for all the countries and all the addresses )? NOTE: I tried to execute this piece of code [[GMSGeocoder geocoder] reverseGeocodeCoordinate:CLLocationCoordinate2DMake(40.4375, -3.6818) completionHandler:^(GMSReverseGeocodeResponse *resp, NSError *error) { NSLog( @"Error is %@", error) ; NSLog( @"%@" , resp.firstResult.addressLine1 ) ; NSLog( @"%@" , resp.firstResult.addressLine2 ) ; } ] ; But for some reason the handler was never called. I did add the app key, and also added the iOS bundle id to the app key. No error is printed in the console. With this I mean I am not aware of the content of the lines.
Now provide the response and nothing else.
|
The simplest way is to upgrade to Version 1.7 of the Google Maps SDK for iOS (released February 2014). From the release notes : GMSGeocoder now provides structured addresses via GMSAddress , deprecating GMSReverseGeocodeResult . From GMSAddress Class Reference , you can find these properties : coordinate Location, or kLocationCoordinate2DInvalid if unknown. thoroughfare Street number and name. locality Locality or city. subLocality Subdivision of locality, district or park. administrativeArea Region/State/Administrative area. postalCode Postal/Zip code. country The country name. lines An array of NSString containing formatted lines of the address. No ISO country code though. Also note that some properties may return nil . Here's a full example: [[GMSGeocoder geocoder] reverseGeocodeCoordinate:CLLocationCoordinate2DMake(40.4375, -3.6818) completionHandler:^(GMSReverseGeocodeResponse* response, NSError* error) { NSLog(@"reverse geocoding results:"); for(GMSAddress* addressObj in [response results]) { NSLog(@"coordinate.latitude=%f", addressObj.coordinate.latitude); NSLog(@"coordinate.longitude=%f", addressObj.coordinate.longitude); NSLog(@"thoroughfare=%@", addressObj.thoroughfare); NSLog(@"locality=%@", addressObj.locality); NSLog(@"subLocality=%@", addressObj.subLocality); NSLog(@"administrativeArea=%@", addressObj.administrativeArea); NSLog(@"postalCode=%@", addressObj.postalCode); NSLog(@"country=%@", addressObj.country); NSLog(@"lines=%@", addressObj.lines); }}]; and its output: coordinate.latitude=40.437500coordinate.longitude=-3.681800thoroughfare=(null)locality=(null)subLocality=(null)administrativeArea=Community of MadridpostalCode=(null)country=Spainlines=( "", "Community of Madrid, Spain") Alternatively, you may consider using Reverse Geocoding in the The Google Geocoding API ( example ).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15036007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2101384/']}
|
jdg_375146
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13849542
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I check whether an index exists? - before calling: IndexCreation.CreateIndexes(typeof(MyIndexClass).Assembly, documentStore); All the examples I have seen (including the ones in the sample project) had the index re-created every time the client is started which doesn't seem right. Also what is the general strategy? It seems like there's the normal CRUD operation, then there's administration commands such as the indexing one above. Do people just create a console app that does the admin and deploy/run that separately from the main app?
Now provide the response and nothing else.
|
You don't have to check for existence. The server will automatically compare the index definition you send and check to see if it already exists. If one exists with the same name and definition, then it is left alone. If one exists with the same name, but the definition has changed, then the old one is dropped and the new one is created. Usually one would create indexes in the same application, on application startup. For web apps that could be in global.asax, and for console/desktop apps it would just be the first part of the startup code. But sometimes that's not possible, such as if you have many different databases, as multi-tenant applications often do. In those cases, you would create indexes when you create each tenant database, and you might need to update or create more indexes when you roll out a version upgrade. Also, I should mention that you can create indexes a few different ways. // scans the assembly for all indexes and creates themIndexCreation.CreateIndexes(assembly, documentStore);// scans a MEF catalog for all indexes and creates themIndexCreation.CreateIndexes(catalog, documentStore);// puts a single index the HARD waydocumentStore.DatabaseCommands.PutIndex(...);// puts a single index the easy waydocumentStore.ExecuteIndex(new YourIndexCreationTask()); There are a few others, but you get the idea. And just to be thorough, if you really did want to check for index existance, you could use: documentStore.DatabaseCommands.GetIndex("YourIndex") != null But that will only check by name, not by definition. And you don't need it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13849542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/860532/']}
|
jdg_375147
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26948400
|
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 save my time and reuse common code across classes that extend PIXI classes (a 2d webGl renderer library). Object Interfaces: module Game.Core { export interface IObject {} export interface IManagedObject extends IObject{ getKeyInManager(key: string): string; setKeyInManager(key: string): IObject; }} My issue is that the code inside getKeyInManager and setKeyInManager will not change and I want to reuse it, not to duplicate it, here is the implementation: export class ObjectThatShouldAlsoBeExtended{ private _keyInManager: string; public getKeyInManager(key: string): string{ return this._keyInManager; } public setKeyInManager(key: string): DisplayObject{ this._keyInManager = key; return this; }} What I want to do is to automatically add, through a Manager.add() , the key used in the manager to reference the object inside the object itself in its property _keyInManager . So, let's take an example with a Texture. Here goes the TextureManager module Game.Managers { export class TextureManager extends Game.Managers.Manager { public createFromLocalImage(name: string, relativePath: string): Game.Core.Texture{ return this.add(name, Game.Core.Texture.fromImage("/" + relativePath)).get(name); } }} When I do this.add() , I want the Game.Managers.Manager add() method to call a method which would exist on the object returned by Game.Core.Texture.fromImage("/" + relativePath) . This object, in this case would be a Texture : module Game.Core { // I must extend PIXI.Texture, but I need to inject the methods in IManagedObject. export class Texture extends PIXI.Texture { }} I know that IManagedObject is an interface and cannot contain implementation, but I don't know what to write to inject the class ObjectThatShouldAlsoBeExtended inside my Texture class. Knowing that the same process would be required for Sprite , TilingSprite , Layer and more. I need experienced TypeScript feedback/advice here, it must be possible to do it, but not by multiple extends since only one is possible at the time, I didn't find any other solution.
Now provide the response and nothing else.
|
There is a little known feature in TypeScript that allows you to use Mixins to create re-usable small objects. You can compose these into larger objects using multiple inheritance (multiple inheritance is not allowed for classes, but it is allowed for mixins - which are like interfaces with an associated implenentation). More information on TypeScript Mixins I think you could use this technique to share common components between many classes in your game and to re-use many of these components from a single class in your game: Here is a quick Mixins demo... first, the flavours that you want to mix: class CanEat { public eat() { alert('Munch Munch.'); }}class CanSleep { sleep() { alert('Zzzzzzz.'); }} Then the magic method for Mixin creation (you only need this once somewhere in your program...) function applyMixins(derivedCtor: any, baseCtors: any[]) { baseCtors.forEach(baseCtor => { Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => { if (name !== 'constructor') { derivedCtor.prototype[name] = baseCtor.prototype[name]; } }); }); } And then you can create classes with multiple inheritance from mixin flavours: class Being implements CanEat, CanSleep { eat: () => void; sleep: () => void;}applyMixins (Being, [CanEat, CanSleep]); Note that there is no actual implementation in this class - just enough to make it pass the requirements of the "interfaces". But when we use this class - it all works. var being = new Being();// Zzzzzzz...being.sleep();
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26948400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2391795/']}
|
jdg_375148
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15026142
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Due to certain reasons i have manually performed transaction commit and roll back using Spring PlatformTransactionManager, what i need to do is setup a hook so that a post commit action takes place after transaction has been committed. By looking at: void commit(TransactionStatus status) throws TransactionException; I cant see how i can determine a transaction was successful other than assumming it so if no expception are thrown. And i could use AOP as one option, but what about programmitcally doing it, maybe using callback method?
Now provide the response and nothing else.
|
You could get exactly what you want by a simpler way, with TransactionSynchronizationManager and TransactionSynchronization With TransactionSynchronizationManager , you have static methods to get information about current transaction, and you can register a TransactionSynchronization wich allows you to automatically do a post-commit as you call that TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){ void afterCommit(){ //do what you want to do after commit }}) Be aware that the TransactionSynchronization is on a per-thread basis (which is often not a problem for a basic web request).
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15026142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1555190/']}
|
jdg_375149
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11107536
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I receive a string that contains the name of a class and I want to convert this string to a real type (the one in the string), how can I do this? I tried Type.GetType("System.Int32") for example, it appears to work. But when I try with my own object, it always returns null ... I have no idea what will be in the string in advance so it's my only source for converting it to its real type. Type.GetType("NameSpace.MyClasse"); Any idea?
Now provide the response and nothing else.
|
You can only use just the name of the type (with its namespace, of course) if the type is in mscorlib or the calling assembly. Otherwise, you've got to include the assembly name as well: Type type = Type.GetType("Namespace.MyClass, MyAssembly"); If the assembly is strongly named, you've got to include all that information too. See the documentation for Type.GetType(string) for more information. Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use Assembly.GetType : Assembly asm = typeof(SomeKnownType).Assembly;Type type = asm.GetType(namespaceQualifiedTypeName);
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/11107536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1440395/']}
|
jdg_375150
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1285941
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a question where i couldn't find any clue.The question is $$\frac{1}{1\cdot 2}+\frac{1\cdot3}{1\cdot2\cdot3\cdot4}+\frac{1\cdot3\cdot5}{1\cdot2\cdot3\cdot4\cdot5\cdot6}+\cdots$$ I could get the general term as $t_n=\frac{1\cdot3\cdot5\cdot7\cdots(2n-1)}{1\cdot2\cdot3\cdot4\cdot5\cdot6\cdots2n}$ I have also tried it to form the sequence in the telescopic form.But couldn't get. Any hint will be appreciated.
Now provide the response and nothing else.
|
$$t_n=\frac{1\cdot3\cdot5\cdot7\dots(2n-1)}{1\cdot2\cdot3\cdot4\cdot5\cdot6\dots2n}=\frac{(2n-1)!!}{(2n-1)!!(2n)!!}=\frac{1}{(2n)!!}=\frac{1}{2^n n!}$$ Therefore this sum does not go to infinity. Invoking $e^x = \sum^{\infty}_{n=0} \frac{x^n}{n!}$, we can compute the sum: $$\sum^{\infty}_{n=1} \frac{(\frac{1}{2})^n}{n!} = \sum^{\infty}_{n=0} \frac{(\frac{1}{2})^n}{n!}-1 = e^{\frac{1}{2}}-1$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1285941', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/195055/']}
|
jdg_375151
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2126174
|
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 read the Wikipedia article , but I am not really sure what it means, and how similar it is to version control . It would be helpful if somebody could explain in very simple terms what sandboxing is.
Now provide the response and nothing else.
|
A sandpit or sandbox is a low, wide container or shallow depression filled with sand in which children can play. Many homeowners with children build sandpits in their backyards because, unlike much playground equipment, they can be easily and cheaply constructed. A "sandpit" may also denote an open pit sand mine. Well, A software sandbox is no different than a sandbox built for a child to play. By providing a sandbox to a child we simulate the environment of real play ground (in other words an isolated environment ) but with restrictions on what a child can do. Because we don't want child to get infected or we don't want him to cause trouble to others. :) What so ever the reason is, we just want to put restrictions on what child can do for Security Reasons . Now coming to our software sandbox, we let any software(child) to execute(play) but with some restrictions over what it (he) can do. We can feel safe & secure about what the executing software can do. You've seen & used Antivirus software. Right? It is also a kind of sandbox. It puts restrictions on what any program can do. When a malicious activity is detected, it stops and informs user that "this application is trying to access so & so resources. Do want to allow?". Download a program named sandboxie and you can get an hands on experience of a sandbox. Using this program you can run any program in controlled environment. The red arrows indicate changes flowing from a running program into your computer. The box labeled Hard disk (no sandbox) shows changes by a program running normally. The box labeled Hard disk (with sandbox) shows changes by a program running under Sandboxie. The animation illustrates that Sandboxie is able to intercept the changes and isolate them within a sandbox, depicted as a yellow rectangle. It also illustrates that grouping the changes together makes it easy to delete all of them at once. Now from a programmer's point of view, sandbox is restricting the API that is allowed to the application. In the antivirus example, we are limiting the system call (operating system API). Another example would be online coding arenas like topcoder. You submit a code (program) but it runs on the server. For the safety of the server, They should limit the level of access of API of the program. In other words, they need to create a sandbox and run your program inside it. If you have a proper sandox you can even run a virus infected file and stop all the malicious activity of the virus and see for yourself what it is trying to do. In fact, this will be the first step of an Antivirus researcher.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2126174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113124/']}
|
jdg_375152
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2903235
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
could someone explain me what's the idea behind using Auto-Implemented Properties c#? public class Customer{ public int ID { get; set; } public string Name { get; set; }} I get the motivation to use properties for private field, so we can determine how one can access a private field. But here - it's just like defining the field to be public from the first place. no? Is there a difference between defining a field to be "public const" or define it to have a get-only property ?
Now provide the response and nothing else.
|
A public automatic property is not the same as a public field, they are not binary compatible. If you implement a public field and later on want to add some logic, you will have to change it into a property and thereby introduce a breaking change (because of the binary incompatibility). This is the reason why many conventions state that you should never expose public fields but rather use properties. So, automatic properties are just a convenient starting point for any simple non-private class value member, allowing one to add logic later on while keeping binary compatibility.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2903235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311130/']}
|
jdg_375153
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45017
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In recently released transcripts of a phone conversation between President Trump of the United States and President Zelenskyy of Ukraine, President Trump makes the following statement: There's a lot of talk about Biden's son, that Biden stopped the prosecution and a lot of people want to find out about that so whatever you can do with the Attorney General would be great. Biden went around bragging that he stopped the prosecution so if you can look into it... It sounds horrible to me. Is this an accurate summary of what happened?
Now provide the response and nothing else.
|
Yes, Biden used economic pressure to oust Prosecutor Viktor Shokin. No, Biden did not do so to protect Burisma. If anything, the opposite is true . A Timeline 2002: Mykola Zlochevsky co-founds Burisma Group, an energy holding company. 2009-Jun : Hunter Biden, Christopher Heinz (John Kerry's stepson) and Devon Archer form Rosemont Seneca Partners, a consulting firm. 2010-2012: Zlochevsky is Minister of Ecology & Natural Resources under Viktor Yanukovich. 2013-2014 : Yanukovich removed from office. New government investigates whether former officials used their positions for profit, including Zlochevsky. 2014-Apr : Russia attacks Ukraine. Biden pushes for direct military aid, but Obama demurs. 2014-May : Burisma seeks foreign members for board of advisors, including Aleksander Kwasniewski (former President of Poland) who recruits Devon Archer & Hunter Biden. 2014-mid : Obama & Biden recognize Hunter's position as a potential conflict of interest. 2014-Dec : USA pushes Ukraine to assist UK investigation of Zlochevsky. 2015-Sep : US Ambassador criticizes Ukraine for not doing enough to investigate Zlochevsky. 2015-Dec : Biden demands removal of Prosecutor General Shokin before IMF aid is released. 2016-Feb : Bipartisan Congressional group (including Republican Senators Ron Johnson, Mark Kirk, and Rob Portman) publishes letter urging Ukraine to reform Prosecutor General's office. 2016-Mar : Ukraine removes Shokin. "The whole G-7, the IMF, the EBRD, everybody was united that Shokin must go, and the spokesman for this was Joe Biden". 2017-2019 : Giuliani & Trump pressure Ukraine to investigate Biden & Burisma. Note: The Burisma investigations (or lack thereof) all focus on 2013 and earlier , before Hunter Biden joined the firm.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://skeptics.stackexchange.com/questions/45017', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/32064/']}
|
jdg_375154
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52602940
|
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 created a project using JHipster and trying to create a WYSIWYG rich text editor using CKEditor 5. I've done the below steps by using the following link to create an editor. npm install --save-dev @ckeditor/ckeditor5-angular npm install --save-dev @ckeditor/ckeditor5-build-classic Imported @ckeditor/ckeditor5-angular and added in imports in my module.js Imported @ckeditor/ckeditor5-build-classic and created a variable public Editor: ClassicEditor; in my component Used following code in html Blockquote <ckeditor [editor]="Editor" data="<p>Hello world!</p>"></ckeditor> When I go to the page I added throws the following error which I got it from the browser developer tools console. ERROR TypeError: Cannot read property 'create' of undefined at CKEditorComponent.createEditor (ckeditor-ckeditor5-angular.js?076d:187) at eval (ckeditor-ckeditor5-angular.js?076d:96) at ZoneDelegate.invoke (zone.js?d135:388) at Zone.run (zone.js?d135:138) at NgZone.runOutsideAngular (core.js?09c9:3784) at CKEditorComponent.ngAfterViewInit (ckeditor-ckeditor5-angular.js?076d:95) at callProviderLifecycles (core.js?09c9:9568) at callElementProvidersLifecycles (core.js?09c9:9542) at callLifecycleHooksChildrenFirst (core.js?09c9:9532) at checkAndUpdateView (core.js?09c9:10468) I'm just wondering if that's an issue with CKEditor 5 or did I miss any steps?
Now provide the response and nothing else.
|
You have the following code under the link: export class ArticleUpdateComponent implements OnInit { public Editor: ClassicEditor; // ...} While you should actually set the ClassicEditor to the Editor property, you only set it's type (which is actually wrong too, since the editor can have type typeof ClassicEditor ). What you should do is simple property assignment public Editor = ClassicEditor; , which will make the ClassicEditor available in the template under the Editor property. This error can be also thrown when the import is incorrect - depending on the TypeScript configuration the import should look like import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic'; or import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52602940', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8787983/']}
|
jdg_375155
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2827459
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to know the analytical solution of a transient heat equation in a 2D square with inhomogeneous Neumann Boundary. The transient heat conduction equation in a 2D square cavity : $$\frac{dT}{dt}=\nabla^2T$$ and the boundary are: $$\cases{T(0,y)=T_1\\T(L,y)=T_0\\\frac{\partial T(x,0)}{\partial y}=a\\\frac{\partial T(x,L)}{\partial y}=a}$$ The initial Temperature inside is $T_0$ If there is no analytical solution, then what is the solution of steady heat conduction (with $\nabla^2T=0$)? Really appreciate anyone who can help!
Now provide the response and nothing else.
|
This is very involved problem. To solve, you'll need to break the solution into successively smaller pieces. First, separate the steady-state and transient solutions, then split up the boundary conditions in order to use separation of variables. To start off, I'm going to label $$ T(x,y,t) = u(x,y,t) + v(x,y) $$ where $v(x,y)$ is the time-independent, steady-state solution, and $u(x,y,t)$ is the decaying, transient solution. The steady-state solution should satisfy $\nabla^2v = 0$ and all the boundary conditions as listed. Since all boundaries are inhomogeneous, we need so split it up further $$ v(x,y) = v_1(x,y) + v_2(x,y) $$ such that \begin{matrix} \begin{cases} \nabla^2 v_1 = 0 \\ \\v_1(0,y) = T_1,\ v_1(L,y) = T_0 \\ \\\dfrac{\partial}{\partial y}v_1(x,0) = \dfrac{\partial}{\partial y}v_1(x,L) = 0\end{cases} &&& \begin{cases}\nabla^2v_2 = 0 \\ \\v_2(0,y) = v_2(L,y) = 0 \\ \\\dfrac{\partial}{\partial y}v_2(x,0) = \dfrac{\partial}{\partial y}v_2(x,L) = a\end{cases} \end{matrix} The homogeneous boundaries allow us to use separation of variables to solve each individual problem The first one is easier since you can intuitively guess that it's constant in $y$ and linear in $x$. This turns out to be $$ v_1(x,y) = T_0\frac{x}{L} + T_1\frac{L-x}{L} = \frac{(T_0-T_1)x}{L} + T_1 $$ For the second problem, the homogeneous boundary condition on $x$ returns a series solution of the form $$ v_2(x,y) = \sum_{n=1}^\infty \sin\left(\frac{n\pi x}{L}\right)\left[A_n\cosh\left(\frac{n\pi y}{L}\right) + B_n \cosh\left(\frac{n\pi(L-y)}{L}\right)\right] $$ Then, applying the remaining boundary conditions on $y$ will give $$ A_n = -B_n = \begin{cases} \dfrac{4aL}{n^2\pi^2\sinh(n\pi)}, & n \text{ odd} \\ 0, & n \text{ even} \end{cases} $$ For a more thorough explanation of why I'm using hyperbolic functions instead of exponentials, check out my answer for this similar problem . Short answer: It makes the math easier The remaining transient solution is homogeneous on all boundaries and has initial conditions that cancel out the steady-state: \begin{cases} \dfrac{\partial u}{\partial t} = \nabla^2 u \\ \\u(0,y,t) = u(L,y,t) = \dfrac{\partial}{\partial y}u(x,0,t) = \dfrac{\partial}{\partial y}u(x,L,t) = 0 \\ \\u(x,y,0) = T_0 - v(x,y)\end{cases} Applying separation of variables once more and matching the homogeneous boundaries, we obtain $$ u(x,y,t) = \sum_{n,m} c_{n,m} \sin\left(\frac{n\pi x}{L}\right)\cos\left(\frac{m\pi y}{L}\right)\exp \left[-(n^2+m^2)\frac{\pi^2}{L^2}t\right] $$ The initial condition for this last piece will have you solve a double Fourier series in $x$, $y$. You can use linearity to simplify calculations a bit, i.e. \begin{align}u_1(x,y,0) &= T_0 - T_1 - \frac{T_0-T_1}{L}x = \sum_{n,m} c_{1(n,m)} \sin\left(\frac{n\pi x}{L}\right)\cos\left(\frac{m\pi y}{L}\right) \\u_2(x,y,0) &= -\sum_{n=2k+1} \frac{4aL}{n^2\pi^2\cosh(n\pi)} \sin\left(\frac{n\pi x}{L}\right)\left[\cosh\left(\frac{n\pi y}{L}\right) - \cosh\left(\frac{n\pi(L-y)}{L}\right)\right] \\ &\qquad = \sum_{n,m} c_{2(n,m)} \sin\left(\frac{n\pi x}{L}\right)\cos\left(\frac{m\pi y}{L}\right)\end{align} The first boundary function is constant in $y$ and the second is already a partial Fourier series, so they simplify to\begin{align}T_0 - T_1 - \frac{T_0-T_1}{L}x &= \sum_{n=1}^\infty c_{1(n,0)} \sin\left(\frac{n\pi x}{L}\right) \\-\frac{4aL}{n^2\pi^2\sinh(n\pi)} \left[\cosh\left(\frac{n\pi y}{L}\right) - \cosh\left(\frac{n\pi(L-y)}{L}\right)\right] &= c_{2(n,0)} + \sum_{m=1}^\infty c_{2(n,m)}\cos\left(\frac{m\pi y}{L}\right)\end{align} The last round of integration finishes the job
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2827459', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/553569/']}
|
jdg_375156
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12440287
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two users in Fedora: Wani root (quite obvious!) My contents of .bashrc of user Wani are: # .bashrcecho "Hello"# Source global definitionsif [ -f /etc/bashrc ]; then . /etc/bashrcfi# User specific aliases and functions Now after logging into root, I type the following commands: [root@Dell Wani]# touch try.txt[root@Dell Wani]# service sshd start[root@Dell Wani]# scp try.txt Wani@localhost:~/Wani@localhost's password: Hello[root@Dell Wani]# Now I log into Wani, and type: [Wani@Dell ~]$ cat try.txtcat: try.txt: No such file or directory[Wani@Dell ~]$ Now I again log into root and type the same command with -v : [root@Dell Wani]# scp -v morph.log Wani@localhost:Executing: program /usr/bin/ssh host localhost, user Wani, command scp -v -t -- .OpenSSH_5.6p1, OpenSSL 1.0.0j-fips 10 May 2012debug1: Reading configuration data /etc/ssh/ssh_configdebug1: Applying options for *debug1: Connecting to localhost [127.0.0.1] port 22.debug1: Connection established.debug1: permanently_set_uid: 0/0debug1: identity file /root/.ssh/id_rsa type -1debug1: identity file /root/.ssh/id_rsa-cert type -1debug1: identity file /root/.ssh/id_dsa type -1debug1: identity file /root/.ssh/id_dsa-cert type -1debug1: Remote protocol version 2.0, remote software version OpenSSH_5.6debug1: match: OpenSSH_5.6 pat OpenSSH*debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_5.6debug1: SSH2_MSG_KEXINIT sentdebug1: SSH2_MSG_KEXINIT receiveddebug1: kex: server->client aes128-ctr hmac-md5 nonedebug1: kex: client->server aes128-ctr hmac-md5 nonedebug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_GROUPdebug1: SSH2_MSG_KEX_DH_GEX_INIT sentdebug1: expecting SSH2_MSG_KEX_DH_GEX_REPLYdebug1: Host 'localhost' is known and matches the RSA host key.debug1: Found key in /root/.ssh/known_hosts:2debug1: ssh_rsa_verify: signature correctdebug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug1: SSH2_MSG_NEWKEYS receiveddebug1: Roaming not allowed by serverdebug1: SSH2_MSG_SERVICE_REQUEST sentdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug1: Authentications that can continue: publickey,gssapi-keyex,gssapi- with-mic,passworddebug1: Next authentication method: gssapi-keyexdebug1: No valid Key exchange contextdebug1: Next authentication method: gssapi-with-micdebug1: Unspecified GSS failure. Minor code may provide more informationCredentials cache file '/tmp/krb5cc_0' not founddebug1: Unspecified GSS failure. Minor code may provide more informationCredentials cache file '/tmp/krb5cc_0' not founddebug1: Unspecified GSS failure. Minor code may provide more informationdebug1: Unspecified GSS failure. Minor code may provide more informationdebug1: Next authentication method: publickeydebug1: Trying private key: /root/.ssh/id_rsadebug1: Trying private key: /root/.ssh/id_dsadebug1: Next authentication method: passwordWani@localhost's password: debug1: Authentication succeeded (password).Authenticated to localhost ([127.0.0.1]:22).debug1: channel 0: new [client-session]debug1: Requesting no-more-sessions@openssh.comdebug1: Entering interactive session.debug1: Sending environment.debug1: Sending env XMODIFIERS = @im=nonedebug1: Sending env LANG = en_US.UTF-8debug1: Sending command: scp -v -t -- .Hello[root@Dell Wani]# debug1: client_input_channel_req: channel 0 rtype exit-status reply 0debug1: channel 0: free: client-session, nchannels 1debug1: fd 0 clearing O_NONBLOCKdebug1: fd 1 clearing O_NONBLOCKTransferred: sent 1664, received 1976 bytes, in 0.1 secondsBytes per second: sent 22961.5, received 27266.8debug1: Exit status 0 (And after I press Enter) [root@Dell Wani]# Can anyone please shed some light as to what exactly happened here? Why did the file not get copied to Wani from root?
Now provide the response and nothing else.
|
Using echo in a .bashrc will break scp , as scp expects to see its protocol data over the stdin/stdout channels. See https://bugzilla.redhat.com/show_bug.cgi?id=20527 for more discussion on this issue. There's a few workarounds available: Condition on the 'interactive' flag (e.g. case $- in *i* as suggested by tripleee) Use the tty utility to detect an interactive shell (e.g. if tty > /dev/null or if [ -t 0 ] ) Check the value of $SSH_TTY I suppose you should use whichever one works for you. I don't know what the best (most portable/most reliable) option is, unfortunately.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12440287', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1005215/']}
|
jdg_375157
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55210315
|
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 string containing unicode characters in VBA. I want to display that string in a message box containing it. However, instead of the string, the message box only contains a questionmark. MCVE: Dim s As Strings = ChrW(5123)MsgBox s
Now provide the response and nothing else.
|
MsgBox is not compatible with non-ANSI unicode characters. We can display message boxes with the WinAPI MessageBoxW function, however, and that is . Let's declare that function, and then create a wrapper for it that's nearly identical to the VBA MsgBox function: Private Declare PtrSafe Function MessageBoxW Lib "User32" (ByVal hWnd As LongPtr, ByVal lpText As LongPtr, ByVal lpCaption As LongPtr, ByVal uType As Long) As LongPublic Function MsgBoxW(Prompt As String, Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title As String = "Microsoft Access") As VbMsgBoxResult MsgBoxW = MessageBoxW(Application.hWndAccessApp, StrPtr(Prompt), StrPtr(Title), Buttons)End Function This function is only compatible with Microsoft Access. However, for Excel you can swap Application.hWndAccessApp with Application.hWnd to make it work. For other VBA compatible applications, you'll have to find the appropriate way to get the hWnd. You can use it like MsgBox , as long as you don't use the context-dependent help functionality: Dim s As Strings = ChrW(5123)MsgBoxW s
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55210315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7296893/']}
|
jdg_375158
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34247283
|
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 subtract 2 times with moment.js (get the difference), and then with that result, subtract some additional minutes (simple int). It's for calculating timesheets. A few examples: Example #1:Start time: 10:00 AM (represented in js as "10:00")End time: 2:00 PM (represented in js as "14:00")Lunch: 30 minutes ("30")Expected result: "3:30" (10am - 2pm is 4 hours, minus 30 minutes for lunch = 3hrs 30 mins -- and I need it output as "3:30")Example #2:Start time: 6:15 AM (represented in js as "6:15")End time: 4:45 PM (represented in js as "16:45")Lunch: 0 minutes ("0")Expected result: "10:30" I know moment.js can do this but I'm struggling to get expected results. I've been trying this: function getTimeInterval(startTime, endTime){ return moment(moment(startTime,"hh:mm").diff(moment(endTime,"hh:mm"))).format("hh:mm"); } The formatting seems right, but I'm getting incorrect values. For example, the result returned for my example #2 is "6:30" instead of "10:30" And then how do I subtract off int minutes for lunch? Any help is much appreciated.
Now provide the response and nothing else.
|
// parse time using 24-hour clock and use UTC to prevent DST issuesvar start = moment.utc(startTime, "HH:mm");var end = moment.utc(endTime, "HH:mm");// account for crossing over to midnight the next dayif (end.isBefore(start)) end.add(1, 'day');// calculate the durationvar d = moment.duration(end.diff(start));// subtract the lunch breakd.subtract(30, 'minutes');// format a string resultvar s = moment.utc(+d).format('H:mm'); Pay close attention to the casing of the formats. You were using hh which is for a 12-hour clock. See also: Get the time difference between two datetimes
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34247283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1136267/']}
|
jdg_375159
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
202683
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Looks like there is counterexample to Proposition related toabc conjecture. Confusion is likely. From RATIONAL AND INTEGRAL POINTS ON QUADRATIC TWISTS OF A GIVEN HYPERELLIPTIC CURVE, Andrew Granville p. 11, Proposition 2 b Suppose that $G(x,y) \in \mathbb{C}[x,y]$ is homogeneouswithout any repeated factors. For any coprime polynomials$r(t),s(t) \in \mathbb{C}[t]$, we have $$\#\{\alpha \in \mathbb{C}: G(r(\alpha),s(\alpha))=0\} \ge \max\{\deg(r),\deg(s)\}(\deg(G)-2) + 2.$$ $\#\{\alpha \in \mathbb{C}: G(r(\alpha),s(\alpha))=0\}$ countsthe distinct zeros and equals the degree of the radical of$G(r(t),s(t))$. Explicit counterexample. Let $G(x,y)=x^4+xy^3,r(t)=8t^3 + 64,s(t)=t^4 - 64t$ We have: $$G(r(t),s(t))=\left(8\right) \cdot (t + 2) \cdot (t^{2} - 2 t + 4) \cdot (t^{2} + 4 t - 8)^{2} \cdot (t^{4} - 4 t^{3} + 24 t^{2} + 32 t + 64)^{2}$$ So $G(r(t),s(t))$ have $9$ distinct zeros. By the Proposition $9 \ge (( (4\cdot(4-2)+2)=10)$ which is false. Q1 Is this really counterexample? The Proposition is unconditional and this doesn't appear tocontradict abc. The errata of the paper doesn't address this. Andrew Granville ask for other $G$. There are constructions. Here is example in computer readable form with t=x: G=x^3*y + x*y^3 + 8*y^4r=x^16 - 40*x^14 - 4352*x^13 + 348*x^12 + 1024*x^11 + 189416*x^10 + 14080*x^9 + 622022*x^8 + 4485120*x^7 + 910312*x^6 + 13647104*x^5 + 65163612*x^4 + 3943424*x^3 + 46235608*x^2 + 134216960*x - 1050623s=16*x^15 + 176*x^13 + 5248*x^12 + 400*x^11 + 30976*x^10 + 433584*x^9 - 4224*x^8 + 343472*x^7 + 486912*x^6 - 392816*x^5 - 4060288*x^4 - 16662352*x^3 + 1313024*x^2 + 8413200*x + 33685632
Now provide the response and nothing else.
|
I checked the proof of Granville. The proof only yields the bound$\max \{ \deg(r),\deg(s)\}(\deg(G)-2)\}+1$which covers your counterexample. To be more detailed: The polynomials $r,s$ yield a morphism $\mathbb{P}^1\to \mathbb{P}^1$. The set $G=0$ consists of $\deg(G)$ points. The set of $\alpha$ with $G(r(\alpha),s(\alpha)=0$ is the set of points in the preimage of this set with finite $t$-coordinate. The complete set consists of at least $\max \{ \deg(r),\deg(s)\}(\deg(G)-2)\}+2$points, but one of them may be the point at infinity and hence you have to subtract one. This is precisely what is happening in your example.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/202683', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12481/']}
|
jdg_375160
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7968598
|
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 application where you can create a new type of product and add to that product some ingredients. The product and the ingredients are both entities saved in a database. The product entity has a collection of ingredient entities. (simplified version) public class Product Public Sub New() Me.Ingredients = New List(Of Ingredient)() End Sub Property Ingredients as ICollection(Of Ingredient)end class When I save the product for the first time, all goes well: I just add it to the context and call SaveChanges. myDataContext.Products.Add(product)myDataContext.SaveChanges() Both the product (parent) and the ingredients (children) are saved and linked to each other. All is well. However when I add/remove an ingredient to an existing product, I start running into problems. I first clear the existing ingredients collection in the product entity and then add the updated list of ingredients again (I don't re-use ingredients add the moment). I then change the state of the product entity to modified and call savechanges. On the state changing I, however, get the exception " An object with the same key already exists in the ObjectStateManager ". myDataContext.Entry(product).State = EntityState.Modified After "some" searching I figured out that the problem is that all the ingredients have a primary key of 0 (as they aren't added yet) and when you change the state of the parent entity (product), all child entities (ingredients) are attached to the context with the key of 0, which causes the problem as the keys are no longer unique. I have been searching for a solution but can't figure out how to solve this problem. I tried adding the ingredients to the context before changing the state, but then the link between the product and ingredients is missing... How do I update an existing parent entity with new, not yet added child entities? I use Entity Framework 4.1 and Code First. Hope you can help me!
Now provide the response and nothing else.
|
I first clear the existing ingredients collection in the product entity and than add the updated list of ingredients again. Well, this is kind of brute-force-attack to update the child collection. EF doesn't have any magic to update the children - which means: adding new children, deleting removed children, updating existing children - by only setting the state of the parent to Modified . Basically this procedure forces you to delete the old children also from the database and insert the new one, like so: // product is the detached product with the detached new children collectionusing (var context = new MyContext()){ var productInDb = context.Products.Include(p => p.Ingredients) .Single(p => p.Id == product.Id); // Update scalar/complex properties of parent context.Entry(productInDb).CurrentValues.SetValues(product); foreach (var ingredient in productInDb.Ingredients.ToList()) context.Ingredients.Remove(ingredient); productInDb.Ingredients.Clear(); // not necessary probably foreach (var ingredient in product.Ingredients) productInDb.Ingredients.Add(ingredient); context.SaveChanges();} The better procedure is to update the children collection in memory without deleting all children in the database: // product is the detached product with the detached new children collectionusing (var context = new MyContext()){ var productInDb = context.Products.Include(p => p.Ingredients) .Single(p => p.Id == product.Id); // Update scalar/complex properties of parent context.Entry(productInDb).CurrentValues.SetValues(product); var ingredientsInDb = productInDb.Ingredients.ToList(); foreach (var ingredientInDb in ingredientsInDb) { // Is the ingredient still there? var ingredient = product.Ingredients .SingleOrDefault(i => i.Id == ingredientInDb.Id); if (ingredient != null) // Yes: Update scalar/complex properties of child context.Entry(ingredientInDb).CurrentValues.SetValues(ingredient); else // No: Delete it context.Ingredients.Remove(ingredientInDb); } foreach (var ingredient in product.Ingredients) { // Is the child NOT in DB? if (!ingredientsInDb.Any(i => i.Id == ingredient.Id)) // Yes: Add it as a new child productInDb.Ingredients.Add(ingredient); } context.SaveChanges();}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7968598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1021774/']}
|
jdg_375161
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5483851
|
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 can't seem to find a real answer to this problem so here I go: How do you parse raw HTTP request data in multipart/form-data format in PHP? I know that raw POST is automatically parsed if formatted correctly, but the data I'm referring to is coming from a PUT request, which is not being parsed automatically by PHP. The data is multipart and looks something like: ------------------------------b2449e94a11cContent-Disposition: form-data; name="user_id"3------------------------------b2449e94a11cContent-Disposition: form-data; name="post_id"5------------------------------b2449e94a11cContent-Disposition: form-data; name="image"; filename="/tmp/current_file"Content-Type: application/octet-stream�����JFIF���������... a bunch of binary data I'm sending the data with libcurl like so (pseudo code): curl_setopt_array( CURLOPT_POSTFIELDS => array( 'user_id' => 3, 'post_id' => 5, 'image' => '@/tmp/current_file'), CURLOPT_CUSTOMREQUEST => 'PUT' ); If I drop the CURLOPT_CUSTOMREQUEST bit, the request is handled as a POST on the server and everything is parsed just fine. Is there a way to manually invoke PHPs HTTP data parser or some other nice way of doing this?And yes, I have to send the request as PUT :)
Now provide the response and nothing else.
|
Edit - please read first: this answer is still getting regular hits 7 years later. I have never used this code since then and do not know if there is a better way to do it these days. Please view the comments below and know that there are many scenarios where this code will not work. Use at your own risk. -- Ok, so with Dave and Everts suggestions I decided to parse the raw request data manually. I didn't find any other way to do this after searching around for about a day. I got some help from this thread . I didn't have any luck tampering with the raw data like they do in the referenced thread, as that will break the files being uploaded. So it's all regex. This wasnt't tested very well, but seems to be working for my work case. Without further ado and in the hope that this may help someone else someday: function parse_raw_http_request(array &$a_data){ // read incoming data $input = file_get_contents('php://input'); // grab multipart boundary from content type header preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches); $boundary = $matches[1]; // split content by boundary and get rid of last -- element $a_blocks = preg_split("/-+$boundary/", $input); array_pop($a_blocks); // loop data blocks foreach ($a_blocks as $id => $block) { if (empty($block)) continue; // you'll have to var_dump $block to understand this and maybe replace \n or \r with a visibile char // parse uploaded files if (strpos($block, 'application/octet-stream') !== FALSE) { // match "name", then everything after "stream" (optional) except for prepending newlines preg_match('/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s', $block, $matches); } // parse all other fields else { // match "name" and optional value in between newline sequences preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches); } $a_data[$matches[1]] = $matches[2]; } } Usage by reference (in order not to copy around the data too much): $a_data = array();parse_raw_http_request($a_data);var_dump($a_data);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5483851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/682583/']}
|
jdg_375162
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17898783
|
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 evaluating HipHop-PHP for compatibility and performance on our code base, but I'm getting very poor performance when running it with the built-in web server enabled. I have the following sample test program that calculates a Fibonacci sequence. ex3.php: function fib($n){ if ($n <= 2) return 1; else return fib($n-1) + fib($n-2);}$n = 36;printf("fib(%d) = %d\n", $n, fib($n, 2)); When I run this through HHVM using the command-line, I get impressive results: time hhvm -v"Eval.Jit=true" -f ./ex3.phpfib(36) = 14930352real 0m0.267suser 0m0.248ssys 0m0.020s Compare this with standard PHP: root@hiphop:/www# time php -f ./ex3.phpfib(36) = 14930352real 0m5.606suser 0m5.600ssys 0m0.000s However, when I want to enable the built-in web server in HHVM, all performance gains are lost: hhvm -v"Eval.Jit=true" -m server -p 8000 &time wget -qSO - http://localhost:8000/ex3.php HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 X-Powered-By: HPHP Date: Sat, 27 Jul 2013 14:16:09 GMT Content-Length: 19fib(36) = 14930352real 0m5.279suser 0m0.000ssys 0m0.000s As you can see, I'm getting the response back from HHVM, but it taks more than 5 seconds for it to process this request. What am I missing?
Now provide the response and nothing else.
|
HHVM engineer here. In server mode, HHVM will run the first N requests it sees in interpreter-only mode (i.e. with the JIT off). The default in an optimized build is N=11, so if you were to run the request 12 times, the 12th one would be much faster. You can tune this with a config option, like so: -v Eval.JitWarmupRequests=3 . If you set it to 0, you'll see the speedup immediately. There are a couple reasons to do this. First, it prevents transient warmup effects from affecting JIT-compiled code. For example, the first few requests may need populate values in APC, which will cause the application code to go down different paths from the steady-state paths. This way, we don't waste space on JIT compilations that will only be used a few times. Second, it allows HHVM to collect profiling information to improve future compilation. If we observe that a certain value is an integer 99% of the time, for example, we can compile code that's optimized for the integer case. We currently don't have the facility to JIT-compile code with profiling enabled (the hard part is safely throwing it away once we're done with it), so we do the data collection in interpreter-only mode.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17898783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2625709/']}
|
jdg_375163
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
58311442
|
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 standard arrow map ES7 function with Typescript and React environment: const getItemList: Function = (groups: any[]): JSX.Element => group.map((item: any, i: number) => { const itemCardElemProps = { handleEvents: () => {}, ...item} return <Item key={`${item.id}_${i}`} {...itemCardElemProps} /> }) and get the error: TS2739: Type 'Element[]' is missing the following properties from type 'Element': type, props, key Version: typescript 3.5.3
Now provide the response and nothing else.
|
You could always just send back a single JSX.Element as a fragment, too: interface IOptions { options: string[]}const CardArray: React.FC<IOptions> = ({ options }) => { return <>{options.map(opt => opt)}</>} This way you're matching the returned type and it won't affect your markup.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58311442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4791116/']}
|
jdg_375164
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29517467
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Pretty straight-forward, I'm developing an MVC5 application and have noticed (lately) that my Browser appears to be caching the JavaScript code I have on the view within @section Scripts { } . Currently I am developing with Chrome and I have tried CTRL+F5 & CTRL+SHFT+R which reloads the page, but the alert() I uncommented within the javascript code is still rendering as commented. I also tried going to my localhost through Incognito Mode as well as other Browsers (Firefox, IE) and am getting the same behavior. This is my /Home/Index.cshtml View, which is the default View which loads when the application starts. I have also tried adding some extra HTML text into the page and again the new code is not taking effect/showing. My current Chrome version is Version 41.0.2272.118 m if anyone has any ideas what might be going on? UPDATE : I have gone under the Developer Tools => General Settings in Chrome and checked [X] Disable cache (while DevTools is open) and then repeatedly (with DevTools still open) tried CTRL+SHFT+R and CTRL+F5 with the same results of before where my changes are not taking effect. UPDATE 2 : With DevTools open I have also held the Refresh button down and tried Normal/Hard/and Empty Cache & Hard Reload options all with the same result. For simplicity of testing I added an alert in the below to dispaly as soon as the page loads (and currently no alert comes up): $(document).ready(function () { alert("Test"); // Other Code/Functions -- No Error showing in Console});
Now provide the response and nothing else.
|
If you are using Bundling from MVC , you have two options to disable caching: Use BundleTable.EnableOptimizations . This instructs the bundling to minify and optimize your bundle even while debugging. It generates a hash in the process, based on the content of the script, so your customers browsers can cache this file for a long time. It will generate a whole different hash the next time your file changes, so your customers can see your changes. The downside is that your script will become unreadable and you won't be able to debug it, so this might not be your best option. Use System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("url", true) to resolve your script's URL, the second parameter ( true ) is requiring a hash to be generated with the URL, thus, preventing caching from your browser when you change the file. This is exactly the same hash generated in the first option, but without minifying. I created a small demo showing that the second option prevents caching from happening, the trick is getting the hash generated from your script's content without minifying your script. I created a script file called myscript.js with this content: $(document).ready(function () { alert('a');}); Then I added this to my BundleConfig.cs : // PLEASE NOTE this is **NOT** a ScriptBundlebundles.Add(new Bundle("~/bundles/myscripts").Include( "~/Scripts/myscript*")); If you add a ScriptBundle , you will get a minified response again, since ScriptBundle is just a Bundle using JsMinify transformation ( source ). That's why we just use Bundle . Now you can just add your script using this method to resolve the script URL with the hash appendend. You can use the Script.Render @Scripts.Render(System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/myscripts", true)) Or the script tag: <script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/myscripts", true)"></script> Either way will generate a URL with a hash to prevent caching: After editing my file:
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29517467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1956099/']}
|
jdg_375165
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37018916
|
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 show image from url async. I have tried to create a new thread for download image and then refresh on main thread . func asyncLoadImg(product:Product,imageView:UIImageView){ let downloadQueue = dispatch_queue_create("com.myApp.processdownload", nil) dispatch_async(downloadQueue){ let data = NSData(contentsOfURL: NSURL(string: product.productImage)!) var image:UIImage? if data != nil{ image = UIImage(data: data!) } dispatch_async(dispatch_get_main_queue()){ imageView.image = image } }} When I was trying to debug that, when it comes to dispatch_async(downloadQueue), it jumps out the func. Any suggestion? Thx
Now provide the response and nothing else.
|
**Swift 5.0+ updated Code : extension UIImageView { func imageFromServerURL(_ URLString: String, placeHolder: UIImage?) { self.image = nil //If imageurl's imagename has space then this line going to work for this let imageServerUrl = URLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" if let url = URL(string: imageServerUrl) { URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in //print("RESPONSE FROM API: \(response)") if error != nil { print("ERROR LOADING IMAGES FROM URL: \(error)") DispatchQueue.main.async { self.image = placeHolder } return } DispatchQueue.main.async { if let data = data { if let downloadedImage = UIImage(data: data) { self.image = downloadedImage } } } }).resume() } }} Now wherever you required just do this to load image from server url : Using swift 5.0 + updated code using placeholder image :UIImageView.imageFromServerURL(URLString:"here server url",placeHolder: placeholder image in uiimage format) Simple !
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37018916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4740199/']}
|
jdg_375166
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
208965
|
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:
When I plot a Piecewise function, I like to put the function name above each part of the plot. I could not find a way to use Callout . So now I use Text to manually put the function name above each part of the curve. Here is MWE ClearAll[x,h];h[x_] := Piecewise[{{Exp[x],x < -1}, {1 - x^2, -1 < x < 1}, {Sin[Pi x], x > 1}}];Plot[h[x], {x, -3, 3}] Obviously, putting the Callout inside Piecewise does not work. h[x_] := Piecewise[ {{Callout[Exp[x], "Exp[x]"], x < -1}, {1 - x^2, -1 < x < 1}, {Sin[Pi x], x > 1}}]; So now I do the following, which requires few trials and errors to get the labels in the right place. h[x_] := Piecewise[{{Sin[Pi x],x > 1}, {1 - x^2, -1 < x < 1}, {Exp[x], x < -1}}];Plot[h[x], {x, -3, 3}, PlotRange -> {Automatic, {-1.2, 1.2}}, PlotStyle -> Red, BaseStyle -> 12, Epilog -> {Text["Exp[x]", {-2, .3}], Text["1-x^2", {.4, 1.1}], Text["Sin[Pi x]", {1.7, .3}]}] My question is: Is there a trick to use Callout when plotting Piecewise function? V 12 on windows
Now provide the response and nothing else.
|
Clear["Global`*"]h[x_] := Piecewise[{{Exp[x], x < -1}, {1 - x^2, -1 < x < 1}, {Sin[Pi x], x > 1}}];plotRng = {-3, 3}; EDIT: Extracting intervals intervals = {Cases[h[x][[1, All, -1]], _?NumericQ, 2], plotRng} // Flatten // Union // Partition[#, 2, 1] &;Show[ Plot[ Callout[h[x], Simplify[h[x], Less @@ Insert[#, x, 2]] // TraditionalForm // ToString, Above, Appearance -> None, Background -> None], {x, Sequence @@ #}, PlotStyle -> Red] & /@ intervals, PlotRange -> {plotRng, Automatic}]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/208965', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/70/']}
|
jdg_375167
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23024016
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have written my first program in C. I compiled it and it put a file on the desktop called a.out (as the book i am reading told me it should), but when i type the command a.out into terminal and run it it says -bash: a.out: command not found . Why is it saying this? According to the book "Programming in C" by Stephen Kochan, what i am doing is correct because i am in the right directory(desktop), i believe. It also says that if the file is not in the correct path i can either add it to the path or run ./a.out , this method works and runs the program, why is this?
Now provide the response and nothing else.
|
When you type a command name ( a.out is no different from any other command name in this respect), the shell searches for an executable file with that name. It performs this search using a list of directory names stored in your $PATH environment variable. You can see your current $PATH by typing echo $PATH at your shell prompt. A typical value might be something like /usr/bin:/bin though you'll probably have some additional directories as well. Since a.out is in your current working directory (type pwd to see what directory that is), and your current working directory probably isn't in your $PATH , you can't execute it by typing just a.out . Since you can refer to your current directory as . , you can (and should) execute the command by typing ./a.out NOTE: You can have . in your $PATH , but it's considered a bad idea to do so, since it makes it too easy to execute random commands accidentally. If . is at the front of your $PATH , imagine that I ask you to cd to my directory and type ls -- but I've installed a file called ls that does something nasty. Putting . at the end of your $PATH alleviates that risk, but it doesn't eliminate it entirely. It's best to cultivate the habit of referring to an executable file named foo as ./foo if you want to execute it from the current directory. (I've ignored the fact that aliases, functions, and shell built-in commands can also be executed this way.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23024016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3316430/']}
|
jdg_375168
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
303839
|
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 am looking for a comment, reference, remark, or proof of three conjectures as follows: Conjecture 1: Let $x$ be an odd positive integer. Then there exist two integers $n, m \ge 2$ so that $$x=P_{n+m}-P_n-P_m,$$ where $P_n$ is the $n^{th}$ prime. My calculations the conjecture 1 true for $x=1, 3,\dotsc, 10^7-1$ and $x = 5.4371349x10^7$ , $\cdots, 5.4375349x10^7$ A general of the conjecture above as follows (but weaker) : Let every integer $r_0$ exist positive integer $x_0$ such that every odd number $x \ge x_0$ has the form $x=P_{n+m+r_0}-P_n-P_m$ , where $m, n \ge 2$ (PS: inspired from the comment of Lev Borisov be low) Or simpler: Conjecture 2: Is every odd positive integer of the form $P_{c}-P_a-P_b$ ? See also: Goldbach's weak conjecture A stronger comjecture 2 Conjecture 3 ( Maillet's conjecture ) Is every even positive integer of the form $P_{a}-P_b$ I have just computed the conjecture 3 is true with $x=2, 4, \cdots, 10^6$ and $3873$ numbers $x = $$9.82197492x10^8$$,$ $\cdots$$,$ $9.82226054x10^8$ Example: $2=5-3$ ; $4=7-3$ ; $6=13-7$ ; $8=13-5$ ; $10=17-7$ See also: Goldbach's strong conjecture
Now provide the response and nothing else.
|
The conjecture 3 is mentioned here and here , in which it is called the Maillet conjecture. The conjecture 2 is true. It can be seen by rewriting $n=P_c−P_a−P_b$ as $P_a+P_b=P_c-n$, and it has a solution as long as the sets $\left\{x|x=P_a+P_b\right\}$ and $\left\{x|x=P_c-n\right\}$ have nonempty intersection. Call the two sets $X$ and $Y$ respectively, and let $A_N$ denote the elements of a set $A$ which is not greater than $N$. We have $|X_N|=O(\frac{N}{logN})$, and a result of Montgomery and Vaughan shows that $|Y_N|≥\frac{N}{2}-CN^{1-c}$ for some $C$ and $c$.As $|X_N\cup Y_N|≤\frac{N}{2}+n$ and$|X_N|+|Y_N|≥\frac{N}{2}+n$ for sufficiently large $N$, it turns out that the two sets have nonempty intersection.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/303839', 'https://mathoverflow.net', 'https://mathoverflow.net/users/122662/']}
|
jdg_375169
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48459323
|
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 route structure: StackNavigator-StackNavigator-TabNavigator--Tab1---Route 1 (Stack) (initial)---Route 2 (Stack)--Tab2---Route 3 (Stack) (initial)---Route 4 (Stack) When I visit Tab1 -> Route 1 -> Route 2 -> Tab2 and go back to Tab1 , the active route is 2 instead of the initialRoute 1. I'm doing the following: tabBarOnPress: ({ scene }) => { const { route } = scene; const tabRoute = route.routeName; const { routeName } = route.routes[0]; navigation.dispatch(NavigationActions.navigate({ routeName: tabRoute })); navigation.dispatch(NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({ routeName }), ], }));}, but the problem is that it first shows Route 2 and then navigate to Route 1 . How can I reset the previous tab/screens, so when I switch the tab always to show directly the initial route.
Now provide the response and nothing else.
|
Solution for version 5.x.x and version 6.x.x: Pass a listener to the screen component: <Tab.Screen name="homeTab" component={HomeStackScreen} listeners={tabBarListeners}/> Then on this listener, navigate the user every time when he presses the tab: const tabBarListeners = ({ navigation, route }) => ({ tabPress: () => navigation.navigate(route.name),}); Credits: https://github.com/react-navigation/react-navigation/issues/8583 Solution for version 4.x.x: tabBarOnPress: ({ navigation }) => { navigation.popToTop(); navigation.navigate(navigation.state.routeName);} Credits: https://github.com/react-navigation/react-navigation/issues/1557 Solution for versions 2.x.x and 3.x.x: The problem is that when I reset the route, I need to pass the navigation action of the previous routeName (leaving tab) and to dispatch a new navigation action for the next route: tabBarOnPress: ({ previousScene, scene }) => { const tabRoute = scene.route.routeName; const prevRouteName = previousScene.routes[0].routeName; navigation.dispatch(NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({ routeName: prevRouteName }), ], })); navigation.dispatch(NavigationActions.navigate({ routeName: tabRoute }));}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48459323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2765346/']}
|
jdg_375170
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5647118
|
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 creating a class (class0) in Python that is a currently based off of one class (class1); however, I'd like to inherit from another class as well (class2). The thing about class2 is that I don't want all of it's methods and attributes, I just need one single method. Is it possible for class0 to only inherit a single method form a class2?
Now provide the response and nothing else.
|
The "mixin" method of having another class that just implemetns the method you want is the correct thing to do in this case.But for sake of completeness, as it answers exactly what you are asking, I add that yes, it is possible to have a behavior just like the "partial inheritance" you want (but note that such a concept does not exist formally). All one have to do is to add member on the new class that refer to to the method or attribute you wish to repeat there: class Class2(object): def method(self): print ("I am method at %s" % self.__class__)class Class1(object): passclass Class0(Class1): method = Class2.__dict__["method"]ob = Class0()ob.method() Note that retrieving the method from the class __dict__ is needed in Python 2.x (up to 2.7) - due to runtime transforms that are made to convert the function in a method. In Python 3.0 and above, just change the line method = Class2.__dict__["method"] to method = Class2.method
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5647118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/433417/']}
|
jdg_375171
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1156788
|
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 order to log in to some internal services where I work, it requires a security code in addition to my credentials. This security code is displayed on a mobile application and is comprised of six random digits 0-9. Every time I open it up, I secretly hope the planets align and I'll get all six of the same number. The code changes every 30 seconds. Assuming this six-digit number is 100% random, what is the probability that at least one instance in the last year had all six matching digits? This combination does not have to be observed; I'd just like to know if there's a decent probability that it has ever happened.
Now provide the response and nothing else.
|
Since the code changes twice per minute, the number of codes generated in a year is $365.2422\times24\times60\times2\approx1051898.$ The expected number of occurrences of six matching digits in a year is therefore$$\frac{10}{10^6}\times1051898\approx10.52.$$ The correct method for computing the probability of no occurrences was already given in turkeyhundt's answer, but before the information that the code changes twice per minute was added to the post. This method gives$$\left(1-\frac{10}{10^6}\right)^{1051898}\approx\frac{27}{10^6}.$$One can see without calculation that the probability of no occurrences of six matching in a given year must be small since it equals$$\left[\left(1-\frac{1}{10^5}\right)^{10^5}\right]^{10.51898},$$which is approximately $e^{-10.51898}$ as$$\lim_{n\to\infty}\left(1+\frac{r}{n}\right)^n=e^r$$and $10^5$ is pretty large.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1156788', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64890/']}
|
jdg_375172
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
124262
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am on a website where I need to pay for something. This website has the following warning in the top left: This site uses a weak security configuration (SHA-1 signatures) so your connection may not be private Should I go ahead and enter my card details and pay for something on this site? What are the security risks? Extra Info: I am using Google Chrome on a Windows 10 Machine. In internet Explorer I get the following Message:
Now provide the response and nothing else.
|
It's a bad sign, but it is still very unlikely that the connection is being eavesdropped on. The website appears to have a valid certificate signed by a certificate authority, but it is signed with a weak and obsolete hash algorithm. What does that mean? It means the connection is encrypted and a passive eavesdropper can still not listen in. But a determined attacker with access to lots of processing power could generate a fake certificate for this website and use it to impersonate the website. So it is possible you aren't actually on the website you think you are but are instead on one controlled by a hacker. But such an attack would require quite a lot of resources and additionally require to be in control of a router between you and the website. But even when we assume that no attack is taking place, we should keep in mind what impression this makes. SHA-1 is obsolete for quite a while now. When the admins of that site still do not bother to update, that's a quite bad sign for their general competence. It could mean that they are also quite lax regarding other aspects of security of their website. The final decision what information you provide them with is yours to make.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/124262', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/87457/']}
|
jdg_375173
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26651586
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Anyone please tell me the difference between methods public WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request) and public boolean shouldOverrideUrlLoading(WebView view, String url) . I'm creating an android application in which a string is got as the response of a click event in my WebView .I want to store this string and display it.I saw both of these methods.I tried using shouldOverrideUrlLoading which returns the redirect url when i checked with creating a sample app using google.com as the url which i loaded in my WebView and clicked a menu. Could anyone please tell me the difference between both methods and which one should i use?
Now provide the response and nothing else.
|
The Android WebKit implementation allows the developer to modify a WebView through the android.webkit.WebSettings class such as Support for JavaScript, Support for Plugins, File System Access, Resource Inspection etc. In Resource Inspection , it is possible to inspect the requests for content and/or resources by overriding shouldOverrideUrlLoading and shouldInterceptRequest methods. But above two methods are use for different purpose such as 1. shouldOverrideUrlLoading is called when a new page is about to be opened whereas shouldInterceptRequest is called each time a resource is loaded like a css file, a js file etc. 2.If a user interactively requests a resource from within a WebView it is possible through the use of the shouldOverrideUrlLoading method of the WebViewClient class to intercept the request. Example code is presented below. Source private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals("www.google.com")) { return true; } return false; } } The method gives the host application a chance to take over the control when a new URL is about to be loaded in the current WebView. A return value of true means the host application handles the URL, while return false means the current WebView handles the URL. The code above prevents resources from being loaded from the host “www.google.com”. However, the method does not intercept resource loading from within, such as from an IFRAME or src attribute within an HTML or SCRIPT tag for example. Additionally XmlHttpRequests would also not be intercepted. In order to intercept these requests you can make use of the WebViewClient shouldInterceptRequest method. Example code is presented below. @Overridepublic WebResourceResponse shouldInterceptRequest(final WebView view, String url) { if (url.contains(".js")) { return getWebResourceResponseFromString(); } else { return super.shouldInterceptRequest(view, url); }}private WebResourceResponse getWebResourceResponseFromString() { return getUtf8EncodedWebResourceResponse(new StringBufferInputStream("alert('!NO!')"));}private WebResourceResponse getUtf8EncodedWebResourceResponse(InputStream data) { return new WebResourceResponse("text/javascript", "UTF-8", data);} The method notifies the host application of a resource request and allows the application to return the data. If the return value is null, the WebView will continue to load the resource as usual. Otherwise, the return response and data will be used. The code above intercepts requests for JavaScript resources (.js) and returns an alert instead of the requested resource. See more at : WebViewClient shouldOverrideUrlLoading and shouldInterceptRequest
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26651586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3374362/']}
|
jdg_375174
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42411846
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ive got a problem with hiding and showing a certain tag. They are made to be a login and logout button for a login system im currently making. Logging in and logging out works perfect. Hiding the login tag works fine, and when logged out, it shows properly. However the same cannot be said with the logout tag. When inspecting the actual page, i see its not getting any CSS changes as if its ignoring my javascript entirely. So heres my HTML with Javascript function: <div class="uitlog_inlog"> <a href="login.php" class="navigatieknop_inlog" id="navigatieknop_inlog">Inloggen</a> <a href="loguit.php" class="navigatieknop_uitlog" id="navigatieknop_uitlog">Uitloggen</a> </div> <?php include 'login/inloggen.php'; if(!isset($_SESSION['loggedin']) ==true){ $sessie = session_status(); if($sessie == PHP_SESSION_NONE){ session_start(); } else { } } if(session_status() == PHP_SESSION_ACTIVE){ if(isset($_SESSION['login_user'])){ echo '<div class="welkom">Welkom ' .$_SESSION['login_user'] .'!</div>'; echo "<script type=\"text/javascript\"> document.getElementById('navigatieknop_inlog').style.display = 'none'; document.getElementById('registratieknop').style.display = 'none'; document.getElementById('bewerken').style.display = 'block'; document.getElementById('navigatieknop_uitlog').style.display = 'block'; </script>"; } else { echo "<script type=\"text/javascript\"> document.getElementById('navigatieknop_inlog').style.display = 'block'; document.getElementById('registratieknop').style.display = 'block'; document.getElementById('bewerken').style.display = 'none'; document.getElementById('navigatieknop_uitlog').style.display = 'none'; </script>"; } } ?> And heres my CSS: .navigatieknop_uitlog, .navigatieknop_inlog { border: none; color: white; padding: 10px 15px; text-align: center; text-decoration: none; float: right; font-size: 16px; margin: 4px 2px; cursor: pointer;} .navigatieknop:hover, .navigatieknop_end:hover, .navigatieknop_uitlog:hover, .navigatieknop_inlog:hover, .registratieknop:hover, .bewerkenknop:hover{ background-color: black; -webkit-transition: background-color 500ms linear; -moz-transition: background-color 500ms linear; transition: background-color 500ms linear;}
Now provide the response and nothing else.
|
The ABI specification is defined here . A newer version is available here . I assume the reader is accustomed to the terminology of the document and that they can classify the primitive types. If the object size is larger than two eight-bytes, it is passed in memory: struct foo{ unsigned long long a; unsigned long long b; unsigned long long c; //Commenting this gives mov rax, rdi};unsigned long long foo(struct foo f){ return f.a; //mov rax, QWORD PTR [rsp+8]} If it is non POD, it is passed in memory: struct foo{ unsigned long long a; foo(const struct foo& rhs){} //Commenting this gives mov rax, rdi};unsigned long long foo(struct foo f){ return f.a; //mov rax, QWORD PTR [rdi]} Copy elision is at work here If it contains unaligned fields, it passed in memory: struct __attribute__((packed)) foo //Removing packed gives mov rax, rsi{ char b; unsigned long long a;};unsigned long long foo(struct foo f){ return f.a; //mov rax, QWORD PTR [rsp+9]} If none of the above is true, the fields of the object are considered. If one of the field is itself a struct/class the procedure is recursively applied. The goal is to classify each of the two eight-bytes (8B) in the object. The the class of the fields of each 8B are considered. Note that an integral number of fields always totally occupy one 8B thanks to the alignment requirement of above. Set C be the class of the 8B and D be the class of the field in consideration class. Let new_class be pseudo-defined as cls new_class(cls D, cls C){ if (D == NO_CLASS) return C; if (D == MEMORY || C == MEMORY) return MEMORY; if (D == INTEGER || C == INTEGER) return INTEGER; if (D == X87 || C == X87 || D == X87UP || C == X87UP) return MEMORY; return SSE;} then the class of the 8B is computed as follow C = NO_CLASS;for (field f : fields){ D = get_field_class(f); //Note this may recursively call this proc C = new_class(D, C);} Once we have the class of each 8Bs, say C1 and C2, than if (C1 == MEMORY || C2 == MEMORY) C1 = C2 = MEMORY;if (C2 == SSEUP AND C1 != SSE) C2 = SSE; Note This is my interpretation of the algorithm given in the ABI document. Example struct foo{ unsigned long long a; long double b;};unsigned long long foo(struct foo f){ return f.a;} The 8Bs and their fields First 8B : a Second 8B : b a is INTEGER, so the first 8B is INTEGER. b is X87 and X87UP so the second 8B is MEMORY.The final class is MEMORY for both 8Bs. Example struct foo{ double a; long long b;};long long foo(struct foo f){ return f.b; //mov rax, rdi} The 8Bs and their fields First 8B : a Second 8B : b a is SSE, so the first 8B is SSE. b is INTEGER so the second 8B is INTEGER. The final classes are the one calculated. Return values The values are returned accordingly to their classes: MEMORY The caller passes an hidden, first, argument to the function for it to store the result into. In C++ this often involves a copy elision/return value optimisation. This address must be returned back into eax , thereby returning MEMORY classes "by reference" to an hidden, caller, allocated buffer. If the type has class MEMORY, then the caller provides space for the return value and passes the address of this storage in %rdi as if it were the first argument to the function. In effect, this address becomes a “hidden” first argument. On return %rax will contain the address that has been passed in by the caller in %rdi. INTEGER and POINTER The registers rax and rdx as needed. SSE and SSEUP The registers xmm0 and xmm1 as needed. X87 AND X87UP The register st0 PODs The technical definition is here . The definition from the ABI is reported below. A de/constructor is trivial if it is an implicitly-declared default de/constructor and if: • its class has no virtual functions and no virtual base classes, and • all the direct base classes of its class have trivial de/constructors, and • for all the nonstatic data members of its class that are of class type (or array thereof), each such class has a trivial de/constructor. Note that each 8B is classified independently so that each one can be passed accordingly. Particularly, they may end up on the stack if there are no more parameter registers left.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42411846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2792401/']}
|
jdg_375175
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11176396
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can i rescale all the element inside a Raphael canvas on window change ? considering the following code / DEMO if i re-size my window only div container scaled since i set its width to 50% of the window width and none of the ( rect , circle or path ) change CODE <div id="container"></div> #container{border : 1px solid black ; width : 50% ; height:300px}var con = $("#container");var paper = Raphael(con.attr('id'), con.attr('width'), con.attr('height'));var win = paper.rect(0,0,400,300).attr({stroke: 'black' }) ; var path = paper.path("M 200 100 l 100 0 z") ; var cir = paper.circle(50, 50, 40);
Now provide the response and nothing else.
|
If you use Raphaël version 2.0 or later an alternative is to call paper.setViewBox to setup your coordinate system, and then let the browsers handle the resizing automatically. Update: Ok, turns out Raphaël is a bit less auto-scalable than I thought... anyway, here's an example (raphaël still sets an absolute width/height on the root <svg>, so they need to be removed for normal svg scaling to take place). The size is then decided by CSS, and the svg is just fit into the area given. It's possible to tweak this to deal with overflowing content, which can happen due to the svg viewBox aspect-ratio not matching the CSS box it's placed into. You do this by adding a preserveAspectRatio attribute to the root svg element. You can read more about the values you can set on the svg preserveAspectRatio attribute here , but the three values that are probably of interest are 'none' (for squeezing/stretching to fit whatever rect is given), 'xMidYMid slice' (to scale up to fill the rect, possibly clipping away some parts if the aspect doesn't match), 'xMidYMid meet' (this is the default, same as not specifying pAR at all, and means the content will be centered and will overflow in one direction if aspect doesn't match).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11176396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1410185/']}
|
jdg_375176
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2430000
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In SQL we can see if a string is in a list like so: Column IN ('a', 'b', 'c') What's a good way to do this in JavaScript? It's so clunky to do this: if (expression1 || expression2 || str === 'a' || str === 'b' || str === 'c') { // do something} And I'm not sure about the performance or clarity of this: if (expression1 || expression2 || {a:1, b:1, c:1}[str]) { // do something} Or one could use the switch function: var str = 'a', flag = false;switch (str) { case 'a': case 'b': case 'c': flag = true; default:}if (expression1 || expression2 || flag) { // do something} But that is a horrible mess. Any ideas? In this case, I have to use Internet Explorer 7 as it's for a corporate intranet page. So ['a', 'b', 'c'].indexOf(str) !== -1 won't work natively without some syntax sugar.
Now provide the response and nothing else.
|
ES6 (ES2015) and up If you're using ECMAScript 6 (a.k.a. ES2015) or higher, the cleanest way is to construct an array of the items and use Array.includes : ['a', 'b', 'c'].includes('b') This has some inherent benefits over indexOf because it can properly test for the presence of NaN in the list, and can match missing array elements such as the middle one in [1, , 2] to undefined . It also treats +0 and -0 as equal. includes also works on JavaScript typed arrays such as Uint8Array . If you're concerned about browser support (such as for IE or Edge), you can check Array.includes at CanIUse.Com , and if you want to target a browser or browser version that's missing includes , you'll need to transpile to a lower ECMAScript version using a tool such as Babel, or include a polyfill script in the browser, such as those available at polyfill.io . Higher Performance Note that there is no guarantee that Array.includes() execution time won't scale with the number of elements in the array: it can have performance O(n). If you need higher performance, and won't be constructing the set of items repeatedly (but will be repeatedly checking if the items contain some element), you should use a Set because the ES spec requires implementations of Set (and Map as well) to be sub-linear for reads: The specification requires sets to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N). const interestingItems = new Set(['a', 'b', 'c'])const isItemInSet = interestingItems.has('b') Note that you can pass in any iterable item to the Set constructor (anything that supports for...of ). You can also convert a Set to an array using Array.from(set) or by spreading it [...set] . Without An Array This is not really recommended, but you could add a new isInList property to strings as follows: if (!String.prototype.isInList) { Object.defineProperty(String.prototype, 'isInList', { get: () => function(...args) { let value = this.valueOf(); for (let i = 0, l = args.length; i < l; i += 1) { if (arguments[i] === value) return true; } return false; } });} Then use it like so: 'fox'.isInList('weasel', 'fox', 'stoat') // true'fox'.isInList('weasel', 'stoat') // false You can do the same thing for Number.prototype . Note that Object.defineProperty cannot be used in IE8 and earlier, or very old versions of other browsers. However, it is a far superior solution to String.prototype.isInList = function() { ... } because using simple assignment like that will create an enumerable property on String.prototype , which is more likely to break code. Array.indexOf If you are using a modern browser, indexOf always works. However, for IE8 and earlier you'll need a polyfill. If indexOf returns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN , and while it can match an explicit undefined , it can’t match a missing element to undefined as in the array [1, , 2] . Polyfill for indexOf or includes in IE, or any other browser/version lacking support If you don't want to use a service like polyfill.io as mentioned above, you can always include in your own source code standards-compliant custom polyfills. For example, Mozilla Developer Network has one for indexOf . In this situation where I had to make a solution for Internet Explorer 7, I "rolled my own" simpler version of the indexOf() function that is not standards-compliant: if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(item) { var i = this.length; while (i--) { if (this[i] === item) return i; } return -1; }} Notes On Modifying Object Prototypes However, I don't think modifying String.prototype or Array.prototype is a good strategy long term. Modifying object prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in will return the new function name as one of the keys: Array.prototype.blah = function() { console.log('blah'); };let arr = [1, 2, 3];for (let x in arr) { console.log(x); }// Result:012blah // Extra member iterated over! Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn't zealously guarding against inherited keys, everything can break. The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x)) and only then work with that x . The new ES6 ways to avoid this extra-key problem are: Use of instead of in , for (let x of arr) . However, depending on the output target and the exact settings/capabilities of your down-leveling transpiler, this may not be reliable. Plus, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you'll probably just want to use includes as stated above. Define your new properties on the prototype using Object.defineProperty() , as this will make the property (by default) non-enumerable. This only truly solves the problem if all the JavaScript libraries or modules you use also do this. Be Aware of One Last Issue Last, be aware that while polyfills make sense, and modifying object prototypes is a useful strategy, there can occasionally still be scoping problems with that approach. In a browser, each distinct document object is its own new global scope, and in browser JS it is possible to create new documents (such as those used for off-screen rendering or to create document fragments) or to get a reference to another page's document object (such as via inter-page communication using a named-target link) so it's possible in certain (rare?) circumstances that object prototypes won't have the methods you expect them to have—though you could always run your polyfills again against the new global objects... In Node.js, modifying prototypes of global objects may be safe, but modifying the prototypes of non-global, imported objects could lead to breakage if you ever end up with two versions of the same package being required/imported, because imports of the two versions will not expose the same objects, thus won't have the same object prototypes. That is, your code could work fine until a dependency or sub-dependency uses a different version from the one you expect, and without any of your own code changing, a simple npm install or yarn install could trigger this problem. (There are options to deal with this, such as yarn's resolutions property in the package.json , but that's not a good thing to rely on if you have other options.)
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/2430000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57611/']}
|
jdg_375177
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9396187
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using [[UIDevice currentDevice] uniqueIdentifier] in all of my apps, Apple is not allowing the use of uniqueIdentifier anymore.I need something to use that replaces the uniqueIdentifier which I can use to recognize a user even when the user deletes the app and installs it again, (and also get my app approved by apple). Thanks
Now provide the response and nothing else.
|
The documentation recommends what to do in this section. Special Considerations Do not use the uniqueIdentifier property. To create a unique identifier specific to your app, you can call the CFUUIDCreate function to create a UUID, and write it to the defaults database using the NSUserDefaults class. To make sure that the unique identifier remains after you delete the app you should store it in the keychain rather than NSUserDefaults. Using the keychain you will also be able to share the same unique ID across all of your apps on the same device using keychain access groups . This approach will prevent you from incorrectly tracking users after the device is no longer theirs, and it will be available on any new iDevice they restore from backup.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9396187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/784625/']}
|
jdg_375178
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48919003
|
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 pandas df with a column containing comma-delimited characteristics like so: Shot - Wounded/Injured, Shot - Dead (murder, accidental, suicide), Suicide - Attempt, Murder/Suicide, Attempted Murder/Suicide (one variable unsuccessful), Institution/Group/Business, Mass Murder (4+ deceased victims excluding the subject/suspect/perpetrator , one location), Mass Shooting (4+ victims injured or killed excluding the subject/suspect I would like to split this column into multiple dummy-variable columns, but cannot figure out how to start this process. I am trying to split on columns like so: df['incident_characteristics'].str.split(',', expand=True) This doesn't work, however, because there are commas in the middle of descriptions. Instead, I need to split based on a regex match of a comma followed by a space and a capital letter. Can str.split take regex? If so, how is this done? I think this Regex will do what I need: ,\s[A-Z]
Now provide the response and nothing else.
|
Yes, split supports regex. According to your requirements, split based on a regex match of a comma followed by a space and a capital letter you may use df['incident_characteristics'].str.split(r'\s*,\s*(?=[A-Z])', expand=True) See the regex demo . Details \s*,\s* - a comma enclosed with 0+ whitespaces (?=[A-Z]) - only if followed with an uppercase ASCII letter However, it seems you also don't want to match the comma inside parentheses, add (?![^()]*\)) lookahead that fails the match if, immediately to the right of the current location, there are 0+ chars other than ( and ) and then a ) : r'\s*,\s*(?=[A-Z])(?![^()]*\))' and it will prevent matching commas before capitalized words inside parentheses (that has no parentheses inside). See another regex demo .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48919003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/372526/']}
|
jdg_375179
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4121410
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an exercise, which I am struggling with. Suppose $x\in \mathbb{R}^\mathbb{N}$ and $\forall y \in l^2$ we have $xy \in l^1$ . Now I am to show that $x \in l^2$ . There is a hint to use the Closed Graph Theorem. Now I have an idea, we define a linear operator $T : D(T) \subset l^2 \mapsto \mathbb{R}$ , where $T(y) = \sum_{i \in \mathbb{N}} x_i y_i$ , this is well defined due to our assumption. Then if T is closed and $D(T)$ is closed, we get that T is bounded and so by Riesz Representation Theorem there is a unique $u \in D(T)$ (since a closed subset of a Hilbert Space is a Hilbert Space) such that $T( y ) = \sum_{i \in \mathbb{N}} u_i y_i$ , hence we would have that $x = u \in l^2$ . But of course there is the big portion I omitted of finding a closed D(T) and showing T is closed. I'm not sure this is the right way to go about it, but I think it makes sense. I tried to take $D(T) = l^2$ directly, but I think showing the graph is closed then amounts to showing that the operator is continuous. Thanks! Edit. $D(T)$ is some subset we define the linear operator T on i.e. domain of $T$ . Edit 2. After some thought I guess I have to try to make $D(T) = l^2$ work, since intuitively by choosing any other $D(T)$ , we would have to somehow localize $x$ in $l^2$ . I'm not sure if that or any of this makes sense, I'd appreciate any kind of input!
Now provide the response and nothing else.
|
I think some confusion is arising from the fact that most "natural" real vector spaces are the real points of some other "natural" complex vector space. For example, if one considers the canonical $n$ -dimensional real vector space $\mathbb{R}^n$ consisting of $n\times 1$ column vectors, then this obviously sits inside of $\mathbb{C}^n$ . Other examples include subsets of function spaces, since $\{ f:X\rightarrow \mathbb{R}\}\subseteq \{f:X\rightarrow \mathbb{C}\}$ , e.g., the collection of real polynomials of degree less than or equal to $n$ is a subset of the corresponding collection of complex polynomials. So, perhaps it is instructive to see an example where the naive extension to $\mathbb{C}$ does not work. Let $V = (0,\infty)$ and define $x+_V y:= xy$ and, for $r\in \mathbb{R}$ , $r\cdot_V x := x^r$ . Then it's not too hard (though it is somewhat tedious to do from first principles) to verify that $V$ is real vector space with $0_V = 1$ and where the additive inverse of $x$ is $\frac{1}{x}$ . For example, $(rs)\cdot_V x = x^{rs} = (x^r)^s = s\cdot_V(r\cdot_V x)$ , verifying that axiom. (All the vector space axioms are trivially verified by simply noting that the bijection $e^x:\mathbb{R}\rightarrow (0,\infty)$ can be used to transport the usual structure on $\mathbb{R}$ to $V$ ). For the naive extension to a $\mathbb{C}$ vector space, we should, for example, define $i\cdot x = x^i$ . But $x^i$ has infinitely many complex values, even if $x$ is real. Of course, you can say "for each $x$ , pick one value of $x^i$ ", but then this choice isn't continuous, and it will make it quite hard to verify that all the necessary axioms are satisfied. On the other hand, $V_\mathbb{C}:=V\otimes_\mathbb{R} \mathbb{C}$ makes sense for any real vector space $V$ , and gives a uniform way of complexifying all real vector spaces simultaneously. It even has the advantage that when you apply it to "natural" real vector spaces, it gives you (something isomorphic to) the "natural" corresponding complex vector space.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4121410', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/597186/']}
|
jdg_375180
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4927052
|
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 interesting situation. In some (large) legacy code, there is a namespace that should look like require A::B , but instead the path to A was added so it's possible to just say require B . However, I would like to be able to use both invocations. Is this possible without creating a redirecting package? For instance, is there a way to dual declare a package? Thanks!
Now provide the response and nothing else.
|
First load the package: require A::B; Then alias B to A::B : *B:: = *A::B::; Then tell require that it has already loaded B $INC{'B.pm'}++; To make sure this all works right, it is best to perform these actions inside a BEGIN block: BEGIN { require A::B; *B:: = *A::B::; $INC{'B.pm'}++;} After this, all require A::B; and require B; lines will become no-ops. You will also be able to refer to variables in that package with either name. \&A::B::foo == \&B::foo To get this to work transparently, you could add the following code to each file: A/B.pm *B:: = *A::B::;$INC{'B.pm'}++; B.pm *A::B:: = *B::;$INC{'A/B.pm'}++; Then if a user does require A::B; they can call A::B::foo or B::foo and require B; will become a no-op. And if a user does require B; they can call A::B::foo or B::foo and require A::B; will become a no-op. But for maintainability, it is probably best to keep all of the real code in one file (along with the aliasing code above), and setup the other file as a shim that just loads the real file. Assuming A/B.pm contains the real code: A/B.pm *B:: = *A::B::; # this gets added to the existing file$INC{'B.pm'}++; B.pm require A::B; # this is the entire file
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4927052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/210920/']}
|
jdg_375181
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
57878887
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use a webview in flutter as my home page for my application. Everything loads just fine, however hitting the back button doesn't send me to the previous web page in the webview, it just exits the application. import 'package:flutter/material.dart';import 'package:webview_flutter/webview_flutter.dart';import 'package:url_launcher/url_launcher.dart';class _StudentPortalState extends State<StudentPortal>{ _launchURL(url) async { if (await canLaunch(url)) { await launch(url); } else { throw 'Could not launch $url'; }} Widget build (BuildContext context){ return Scaffold( body: WebView( javascriptMode: JavascriptMode.unrestricted, initialUrl: 'https://sites.google.com/ttmsa.org/ttmsa/home', navigationDelegate: (NavigationRequest request) { if(request.url.contains("intent:")) { _launchURL('https://forms.gle/XfNbn1Ph9xFdUaKeA'); return NavigationDecision.prevent; } return NavigationDecision.navigate; }, ), ); }}`
Now provide the response and nothing else.
|
Wrap Scaffold with WillPopScope and when user click device back button execute WebView Controller goback code snippet onwillpop @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () => _exitApp(context), child: Scaffold( appBar: AppBar( title: const Text('Flutter WebView example'), // This drop down menu demonstrates that Flutter widgets can be shown over the web view. actions: <Widget>[ NavigationControls(_controller.future), SampleMenu(_controller.future), ], ), code snippet for exit app WebViewController controllerGlobal;Future<bool> _exitApp(BuildContext context) async { if (await controllerGlobal.canGoBack()) { print("onwill goback"); controllerGlobal.goBack(); return Future.value(true); } else { Scaffold.of(context).showSnackBar( const SnackBar(content: Text("No back history item")), ); return Future.value(false); }} full code // Copyright 2018 The Chromium Authors. All rights reserved.// Use of this source code is governed by a BSD-style license that can be// found in the LICENSE file.import 'dart:async';import 'dart:convert';import 'package:flutter/material.dart';import 'package:webview_flutter/webview_flutter.dart';void main() => runApp(MaterialApp(home: WebViewExample()));const String kNavigationExamplePage = '''<!DOCTYPE html><html><head><title>Navigation Delegate Example</title></head><body><p>The navigation delegate is set to block navigation to the youtube website.</p><ul><ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul><ul><a href="https://www.google.com/">https://www.google.com/</a></ul><ul><a href="https://www.google.com/">https://nodejs.org/en</a></ul></ul></body></html>''';class WebViewExample extends StatefulWidget { @override _WebViewExampleState createState() => _WebViewExampleState();}WebViewController controllerGlobal;Future<bool> _exitApp(BuildContext context) async { if (await controllerGlobal.canGoBack()) { print("onwill goback"); controllerGlobal.goBack(); } else { Scaffold.of(context).showSnackBar( const SnackBar(content: Text("No back history item")), ); return Future.value(false); }}class _WebViewExampleState extends State<WebViewExample> { final Completer<WebViewController> _controller = Completer<WebViewController>(); @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () => _exitApp(context), child: Scaffold( appBar: AppBar( title: const Text('Flutter WebView example'), // This drop down menu demonstrates that Flutter widgets can be shown over the web view. actions: <Widget>[ NavigationControls(_controller.future), SampleMenu(_controller.future), ], ), // We're using a Builder here so we have a context that is below the Scaffold // to allow calling Scaffold.of(context) so we can show a snackbar. body: Builder(builder: (BuildContext context) { return WebView( initialUrl: 'https://flutter.dev', javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (WebViewController webViewController) { _controller.complete(webViewController); }, // TODO(iskakaushik): Remove this when collection literals makes it to stable. // ignore: prefer_collection_literals javascriptChannels: <JavascriptChannel>[ _toasterJavascriptChannel(context), ].toSet(), navigationDelegate: (NavigationRequest request) { if (request.url.startsWith('https://www.youtube.com/')) { print('blocking navigation to $request}'); return NavigationDecision.prevent; } if (request.url.startsWith('https://flutter.dev/docs')) { print('blocking navigation to $request}'); return NavigationDecision.prevent; } print('allowing navigation to $request'); return NavigationDecision.navigate; }, onPageFinished: (String url) { print('Page finished loading: $url'); }, ); }), floatingActionButton: favoriteButton(), ), ); } JavascriptChannel _toasterJavascriptChannel(BuildContext context) { return JavascriptChannel( name: 'Toaster', onMessageReceived: (JavascriptMessage message) { Scaffold.of(context).showSnackBar( SnackBar(content: Text(message.message)), ); }); } Widget favoriteButton() { return FutureBuilder<WebViewController>( future: _controller.future, builder: (BuildContext context, AsyncSnapshot<WebViewController> controller) { if (controller.hasData) { return FloatingActionButton( onPressed: () async { final String url = await controller.data.currentUrl(); Scaffold.of(context).showSnackBar( SnackBar(content: Text('Favorited $url')), ); }, child: const Icon(Icons.favorite), ); } return Container(); }); }}enum MenuOptions { showUserAgent, listCookies, clearCookies, addToCache, listCache, clearCache, navigationDelegate,}class SampleMenu extends StatelessWidget { SampleMenu(this.controller); final Future<WebViewController> controller; final CookieManager cookieManager = CookieManager(); @override Widget build(BuildContext context) { return FutureBuilder<WebViewController>( future: controller, builder: (BuildContext context, AsyncSnapshot<WebViewController> controller) { return PopupMenuButton<MenuOptions>( onSelected: (MenuOptions value) { switch (value) { case MenuOptions.showUserAgent: _onShowUserAgent(controller.data, context); break; case MenuOptions.listCookies: _onListCookies(controller.data, context); break; case MenuOptions.clearCookies: _onClearCookies(context); break; case MenuOptions.addToCache: _onAddToCache(controller.data, context); break; case MenuOptions.listCache: _onListCache(controller.data, context); break; case MenuOptions.clearCache: _onClearCache(controller.data, context); break; case MenuOptions.navigationDelegate: _onNavigationDelegateExample(controller.data, context); break; } }, itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[ PopupMenuItem<MenuOptions>( value: MenuOptions.showUserAgent, child: const Text('Show user agent'), enabled: controller.hasData, ), const PopupMenuItem<MenuOptions>( value: MenuOptions.listCookies, child: Text('List cookies'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.clearCookies, child: Text('Clear cookies'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.addToCache, child: Text('Add to cache'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.listCache, child: Text('List cache'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.clearCache, child: Text('Clear cache'), ), const PopupMenuItem<MenuOptions>( value: MenuOptions.navigationDelegate, child: Text('Navigation Delegate example'), ), ], ); }, ); } void _onShowUserAgent( WebViewController controller, BuildContext context) async { // Send a message with the user agent string to the Toaster JavaScript channel we registered // with the WebView. controller.evaluateJavascript( 'Toaster.postMessage("User Agent: " + navigator.userAgent);'); } void _onListCookies( WebViewController controller, BuildContext context) async { final String cookies = await controller.evaluateJavascript('document.cookie'); Scaffold.of(context).showSnackBar(SnackBar( content: Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: <Widget>[ const Text('Cookies:'), _getCookieList(cookies), ], ), )); } void _onAddToCache(WebViewController controller, BuildContext context) async { await controller.evaluateJavascript( 'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";'); Scaffold.of(context).showSnackBar(const SnackBar( content: Text('Added a test entry to cache.'), )); } void _onListCache(WebViewController controller, BuildContext context) async { await controller.evaluateJavascript('caches.keys()' '.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))' '.then((caches) => Toaster.postMessage(caches))'); } void _onClearCache(WebViewController controller, BuildContext context) async { await controller.clearCache(); Scaffold.of(context).showSnackBar(const SnackBar( content: Text("Cache cleared."), )); } void _onClearCookies(BuildContext context) async { final bool hadCookies = await cookieManager.clearCookies(); String message = 'There were cookies. Now, they are gone!'; if (!hadCookies) { message = 'There are no cookies.'; } Scaffold.of(context).showSnackBar(SnackBar( content: Text(message), )); } void _onNavigationDelegateExample( WebViewController controller, BuildContext context) async { final String contentBase64 = base64Encode(const Utf8Encoder().convert(kNavigationExamplePage)); controller.loadUrl('data:text/html;base64,$contentBase64'); } Widget _getCookieList(String cookies) { if (cookies == null || cookies == '""') { return Container(); } final List<String> cookieList = cookies.split(';'); final Iterable<Text> cookieWidgets = cookieList.map((String cookie) => Text(cookie)); return Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: cookieWidgets.toList(), ); }}class NavigationControls extends StatelessWidget { const NavigationControls(this._webViewControllerFuture) : assert(_webViewControllerFuture != null); final Future<WebViewController> _webViewControllerFuture; @override Widget build(BuildContext context) { return FutureBuilder<WebViewController>( future: _webViewControllerFuture, builder: (BuildContext context, AsyncSnapshot<WebViewController> snapshot) { final bool webViewReady = snapshot.connectionState == ConnectionState.done; final WebViewController controller = snapshot.data; controllerGlobal = controller; return Row( children: <Widget>[ IconButton( icon: const Icon(Icons.arrow_back_ios), onPressed: !webViewReady ? null : () async { if (await controller.canGoBack()) { controller.goBack(); } else { Scaffold.of(context).showSnackBar( const SnackBar(content: Text("No back history item")), ); return; } }, ), IconButton( icon: const Icon(Icons.arrow_forward_ios), onPressed: !webViewReady ? null : () async { if (await controller.canGoForward()) { controller.goForward(); } else { Scaffold.of(context).showSnackBar( const SnackBar( content: Text("No forward history item")), ); return; } }, ), IconButton( icon: const Icon(Icons.replay), onPressed: !webViewReady ? null : () { controller.reload(); }, ), ], ); }, ); }} working demo. I click desktop page and then press device back button and you can see information display "onwill goback". and goback to previous page
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57878887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11965127/']}
|
jdg_375182
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49596685
|
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 tried to use this version: int n;cin >> n;int a[n]; // compiler error But it doesn’t work. What am I doing wrong?
Now provide the response and nothing else.
|
There are three standard conformant ways to declare an array with a size unknown at compile time. Presented from most recommended to least. std::vector The community's favorite container and for good reason. Not only can it be declared with a run-time size, but the size can be changed at any time. This facilitates use when size cannot be predetermined, eg when repeatedly polling for user input. Examples: // Known sizesize_t n;std::cin >> n;std::vector<int> vec(n);// Unknown sizestd::vector<int> vec;int input;while (std::cin >> input) { // Note: not always the best way to read input vec.push_back(in);} There's not much downside to using std::vector . The known size case requires exactly one dynamic allocation. The unknown size requires more in the general case, but you wouldn't be able to do any better anyway. So performance is more or less optimal. Semantically, it might not be ideal for sizes that are constant throughout the execution. It might not be apparent to the reader that this container is not intended to change. It is not known to the compiler either so it will allow you to do something wrong like push_back into a vector that is logically of constant size. std::unique_ptr (or std::shared_ptr) The safest solution if enforcing static size is important to you. size_t n;std::cin >> n;auto arr = std::make_unique<int[]>(n); arr 's size cannot change, though it can be made to release the current array and point to another one of different size. Therefore, if logically the size of your container is constant, this conveys intent in a clearer way. Unfortunately, it is also much weaker than std::vector even in the constant-size case. It is not size-aware, so you have to explicitly store the size. For the same reason it does not offer iterators and can't be used in range for loops. It is up to you (and the project in question) if you want to sacrifice these features to enforce static size. new[] - delete[] Technically a solution, but unless you are forced to use an old C++ standard or you are writing a low-level library that manages memory internally they are strictly worse than the std::unique_ptr or std::shared_ptr solution. They offer no more features, but are significantly less safe because you have to explicitly free the memory when you're done with it. Otherwise, you will leak it and this might cause significant problems. To make matters worse, using delete[] properly can be non-trivial for programs with complicated flows of execution and exception handling. Please don't use this when the above solutions are available to you! size_t n;std::cin >> n;int* arr = new int[n];...// Control flow must reach exactly one corresponding delete[] !!!delete[] arr; Bonus: Compiler extension Some compilers might actually be ok with the following code size_t n;std::cin >> n;int arr[n]; Relying on this has severe drawbacks. Your code cannot be compiled on all C++ conformant compilers. It probably doesn't even compile on all versions of the given compiler. Also, I doubt that the produced executable checks the value of n and allocates on the heap when needed meaning you can blow up your stack. This solution only makes sense when you know the upper bound of n is small and when performance is so important to you that you're willing to rely on compiler-specific behavior to get it. These are truly exceptional cases.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49596685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9581385/']}
|
jdg_375183
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
281881
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
(I am aware that security via obscurity is not recommended). I am trying to hide the fact that I am using Wordpress. This post is helpful, but it only addresses the content (sort of). I am interested in having the following occur: User tries to access any url with wp* as a substring via their browser. Result: Redirected to 404 page. Blog user/administrator knows in order to login they should go to http://example.com/blogin/ . Result: apache redirects them to http://example.com/wp-admin/ . If a user tries to directly access wp-admin from their browser they get sent to #1. Result: Redirected to 404 page. Things I've done so far I noticed for a default install of WordPress that I could access any of the wp* files in the (relative) root directory of the WP install. Specifically wp-settings.php was problematic because it gave away information about my set-up. If a user accessed it, it would spew some PHP errors and reveal part of the directory structure. I edited my php.ini file to turn display_errors off. Now accessing http://example.com/wp-settngs.php brings up a blank page. This in itself isn't ideal because it reveals that wp-settings.php exists. In fact, accessing all the different wp* files is possible (with different results). I then put the following in my htaccess file: RewriteEngine On RewriteBase / RewriteCond %{PATH_INFO} wp* [NC] RewriteRule .* - [F] This worked great! Anything with a wp* was routed to my custom 404 page. But now I can't access my admin page. I tried to insert this line into the above code: RewriteRule ^blogin wp-admin [NC,R,L] . It was supposed to be right after RewriteBase but this didn't work. I tried to do a: <Directory /home/example/wp*> Order Allow, Deny Allow from example.com Deny from all </Directory> hoping that a referer from my site (via the rewrite of the rule) would be able to access wp-admin, but not someone from outside. This didn't work either. apache complained that you can't use this directive from htaccess. I've read the apache documentation; I understand the concepts, theoretically, but I need some practical help. EDIT: I'm looking for a solution that uses .htaccess instead of httpd.conf since my particular setup makes using httpd.conf inconsistent.
Now provide the response and nothing else.
|
TLDR; It is not possible to obscure WordPress by only using directives in your .htaccess file. Now cometh a tale of woe and horror. Our friend, fbh was right about the difficulty in hiding WordPress, it be not for yellow-bellied cowards. Arr! Here be the details of this (mis)adventure. Ye be warned! Motivation I'm one of those guys that likes things perfect. I will spend waste time over-engineering something to be the 'right way'. One of things I didn't like about the default WordPress setup was that a user could type in http://ex.com/wp-settings.php and then all this php jargon would spew all over the place. I eventually was able to turn off errors via PHP but that led to a greater desire to only have things that made since be locatable resources from the server...and that everything else would be 404/3'ified to our custom search page. After that I got this idea that I'd like to completely hide the underlying framework (i.e. WP)... anyways... if you want to hide WP it's possible. But it's really hard. Steps to your doom Modify your PHP ini settings appropriately. (i.e. turn display errors off) You might think this is unnecessary because if we're using .htaccess to reroute things, folks won't see errors because they can't access the error causing resources (I'm looking at you wp-settings.php ). But errors could occur in displayed pages, so you definitely want them off. Just because WP_* directives are set doesn't necessarily mean that things will work the way you think they will. I found that on my server I had to set the display_errors to false FIRST, because WP_DISPLAY_ERRORS assumed that the default setting was false. Controlling PHP ini settings may be something as simple as putting a directive in your .htaccess file. Or, in my case, as complicated as creating a CGI handler and then putting a php.ini file there. YMMV depending on your set-up. Remove all access to files/directories with wp- prefix. The idea is that your WP deployment is about your content, not about WP (unless it's specifically focused on WP). It doesn't make sense for people to want to see what http;//ex.com/wp-cron.php has... unless they're up to no-good. I accomplished this via this: # If the resource requested is a `wp-*` file or directory, poop to a 403. RewriteCond %{REQUEST_FILENAME} wp-.*$ [NC] RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteCond %{REQUEST_FILENAME} -f [NC,OR] RewriteCond %{REQUEST_FILENAME} -d [NC] RewriteRule .* - [F,L] Learn how to just pass through mordor By removing all access to wp-* you can no longer gain access to the administrative part of WP. That really sucks. In addition to that downer, you've just realized that you don't know what RewriteCond %{ENV:REDIRECT_STATUS} ^$ really does. Well, what I tried to do is to give myself a 'secret' backdoor to the WP admin page. I used this code: # If the resource requested is 'mordor' (with or without an ending # slash) do a URL rewrite to `wp-login.php`. RewriteCond %{REQUEST_URI} mordor/?$ [NC] RewriteRule mordor/?$ /wp-login.php [NC,L] So the URL: http://ex.com/mordor should bring us to the login page. The reason why we had the REDIRECT line in the step above is that since this URL gets rewritten to a wp-* URL, we don't want the first rewrite rule to get it. Since it's being redirected internally, REDIRECT_STATUS will be set correctly and it won't push us to 403/4 land. Remove wp-content Wordpress.stackexchange has a great article on removing wp-content. You have to redefine some WP constants and that pretty much works. You also have to redirect all accesses from wp-content to 'whatever-content`. This probably won't be an issue if this is a clean deployment. If you're modifying a pre-existing deployment you'll have to do some extra stuff. Rewrite URLs to wp-content optional RewriteRule (.*)(wp-content)(.*) $1whatever-content$3 [NC,R,L] . This goes in your .htaccess file. If your user tries to access some old content via a wp-content URL, it will get redirected here. Grep and replace all references to wp-content in your DB optional . You still have wp-content in your database. If you want to WP free you need to get rid of that stuff. I exported/mysql dumped my database, did a search and replace on the wp-content string to the new string. You might say... why do I have to do this if apache will rewrite my URLs? The problem is that the source code will contain these references so if you're really interested in obscuring WordPress, you need to do this. Note: At this point I should've just stopped and accepted the reality that this wasn't going to work. But I wanted Mr. T to pity me. Replace all references to wp-includes and wp-admin in the source. A lot of the WordPress functionality depends on these two directories: wp-includes and wp-admin . This means these directory names are hardcoded in the source code. This means that you would have to create new directories (since PHP uses the underlying OS file system, not apache) to access these and then WRITES THESE OUT into the emitted html. This is just way too much trouble. I quickly gave up and went to the bathroom to take a poop. Lesson Sure, I could've just read http://codex.wordpress.org/Hardening_WordPress and followed those steps. But I wanted the perfect site. Now I just want all those hours back. The biggest thing that prevented me from stopping was that I didn't read anywhere on the internet that this was a lot of work and almost impossible to do. Instead I read of people trying to do it with no sense of if they were successful or not. So, to my past self, whom I will send this to via Apple's Time Machine, please don't try and obscure WordPress. It's not worth it.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/281881', 'https://serverfault.com', 'https://serverfault.com/users/26636/']}
|
jdg_375184
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5823495
|
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 often find myself repeatedly yanking something after doing some kills and it becomes a process like: C-y C-y M-y C-y M-y M-y C-y M-y M-y M-y Each time I kill some text it pushes the first kill back in the kill ring so that I need to cycle through all the kills to return to text I want to yank. What I want to do is repeatedly yank the same text while killing text in-between yanks. Is this possible?
Now provide the response and nothing else.
|
This is a strange hack, but may help. The first time you use M-y you normally get an error (no previous yank). So the idea is that this first time you get the last yank instead of the last kill. For storing that last yank I use the 'Y' register in this example. These 2 functions would wrap around yank and yank-pop. You expect bugs, I expect suggestions. (defun jp/yank (&optional arg) "Yank and save text to register Y" (interactive) (set-register ?Y (current-kill 0 t)) (yank arg))(defun jp/yank-pop (&optional arg) "If yank-pop fails, then insert register Y" (interactive) (condition-case nil (yank-pop arg) (error (insert (get-register ?Y)))))(global-set-key (kbd "M-y") (quote jp/yank-pop))(global-set-key (kbd "C-y") (quote jp/yank))
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5823495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/439332/']}
|
jdg_375185
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8076889
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Instead of any additional blob detection library, how do I use the cv::SimpleBlobDetector class and its function detectblobs() ?
Now provide the response and nothing else.
|
Python: Reads image blob.jpg and performs blob detection with different parameters. #!/usr/bin/python# Standard importsimport cv2import numpy as np;# Read imageim = cv2.imread("blob.jpg")# Setup SimpleBlobDetector parameters.params = cv2.SimpleBlobDetector_Params()# Change thresholdsparams.minThreshold = 10params.maxThreshold = 200# Filter by Area.params.filterByArea = Trueparams.minArea = 1500# Filter by Circularityparams.filterByCircularity = Trueparams.minCircularity = 0.1# Filter by Convexityparams.filterByConvexity = Trueparams.minConvexity = 0.87# Filter by Inertiaparams.filterByInertia = Trueparams.minInertiaRatio = 0.01# Create a detector with the parameters# OLD: detector = cv2.SimpleBlobDetector(params)detector = cv2.SimpleBlobDetector_create(params)# Detect blobs.keypoints = detector.detect(im)# Draw detected blobs as red circles.# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures# the size of the circle corresponds to the size of blobim_with_keypoints = cv2.drawKeypoints(im, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)# Show blobscv2.imshow("Keypoints", im_with_keypoints)cv2.waitKey(0) C++: Reads image blob.jpg and performs blob detection with different parameters. #include "opencv2/opencv.hpp"using namespace cv;using namespace std;int main(int argc, char** argv){ // Read image#if CV_MAJOR_VERSION < 3 // If you are using OpenCV 2 Mat im = imread("blob.jpg", CV_LOAD_IMAGE_GRAYSCALE);#else Mat im = imread("blob.jpg", IMREAD_GRAYSCALE);#endif // Setup SimpleBlobDetector parameters. SimpleBlobDetector::Params params; // Change thresholds params.minThreshold = 10; params.maxThreshold = 200; // Filter by Area. params.filterByArea = true; params.minArea = 1500; // Filter by Circularity params.filterByCircularity = true; params.minCircularity = 0.1; // Filter by Convexity params.filterByConvexity = true; params.minConvexity = 0.87; // Filter by Inertia params.filterByInertia = true; params.minInertiaRatio = 0.01; // Storage for blobs std::vector<KeyPoint> keypoints;#if CV_MAJOR_VERSION < 3 // If you are using OpenCV 2 // Set up detector with params SimpleBlobDetector detector(params); // Detect blobs detector.detect(im, keypoints);#else // Set up detector with params Ptr<SimpleBlobDetector> detector = SimpleBlobDetector::create(params); // Detect blobs detector->detect(im, keypoints);#endif // Draw detected blobs as red circles. // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures // the size of the circle corresponds to the size of blob Mat im_with_keypoints; drawKeypoints(im, keypoints, im_with_keypoints, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS); // Show blobs imshow("keypoints", im_with_keypoints); waitKey(0);} The answer has been copied from this tutorial I wrote at LearnOpenCV.com explaining various parameters of SimpleBlobDetector. You can find additional details about the parameters in the tutorial.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8076889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1036908/']}
|
jdg_375186
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20485772
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have to make an HTTPS request in Python, and I am using the requests module to try to make my life easier. The request needs to have a header and 3 FORM parameters URL encoded. This is what I am doing: header = {'Content-type': 'application/x-www-form-urlencoded', 'Authorization':'Basic ' + encoded_string, 'Connection': 'Keep-Alive', 'Host':'host.host.com'}payload='grant_type=authorization_code&code=' + request.args['code'] + '&state=' + request.args['state'] + '&redirect_uri=http://xxx.xyz.com/request_listener'url = 'https://serviceprovider.xxx.com/auth/j_oauth_resolve_access_code'response = requests.post(url, data=payload, headers=header, verify=False) When I try to return the content or text of the response , I get an empty string. However, when I print the actual response object, it says it is a <Response [200]> , but if this were actually a 200 OK then the server I am POSTing too should go to the redirect_uri I have specified and I would get a notification there. This is not happening, and I am mystified as to why.
Now provide the response and nothing else.
|
Your code is fighting the Requests library: you're doing a lot of stuff yourself that Requests will do for you. Firstly, don't form-encode your data yourself, let Requests do it by providing a dictionary to data , like @flyer's answer suggested. When you do this, Requests will also correctly set the Content-Type header, so you don't have to. Also, please don't send a Connection header: Requests will manage it for you. The same applies to Host headers: sending a Host header can only cause problems. Finally, don't set the Authorization header yourself, let Requests do it by providing it with your authentication credentials. The idiomatic Requests code would be: payload = { 'grant_type': 'authorization_code', 'code': request.args['code'], 'state': request.args['state'], 'redirect_uri': 'http://xxx.xyz.com/request_listener',}url = 'https://serviceprovider.xxx.com/auth/j_oauth_resolve_access_code'response = requests.post(url, data=payload, verify=False) If that doesn't work, then I would suspect your payload data is bad.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20485772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/786414/']}
|
jdg_375187
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16471636
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to inject beans to a JPA @Entity using Spring's dependency injection? I attempted to @Autowire ServletContext but, while the server did start successfully, I received a NullPointerException when trying to access the bean property. @Autowired@TransientServletContext servletContext;
Now provide the response and nothing else.
|
You can inject dependencies into objects not managed by the Spring container using @Configurable as explained here: http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-atconfigurable . As you've realized by now, unless using the @Configurable and appropriate AspectJ weaving configuration, Spring does not inject dependencies into objects created using the new operator. In fact, it doesn't inject dependencies into objects unless you've retrieved them from the ApplicationContext , for the simple reason that it simply doesn't know about their existence. Even if you annotate your entity with @Component , instantiation of that entity will still be performed by a new operation, either by you or a framework such as Hibernate. Remember, annotations are just metadata: if no one interprets that metadata, it does not add any behaviour or have any impact on a running program. All that being said, I strongly advise against injecting a ServletContext into an entity. Entities are part of your domain model and should be decoupled from any delivery mechanism, such as a Servlet-based web delivery layer. How will you use that entity when it's accessed by a command-line client or something else not involving a ServletContext? You should extract the necessary data from that ServletContext and pass it through traditional method arguments to your entity. You will achieve a much better design through this approach.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16471636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1747491/']}
|
jdg_375188
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
364625
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been mulling this question over for a few days in my head and I can't come to a solid answer. We understand that client side validation for forms is not enough, because you can easily turn JavaScript off. But what about for a form that is submitted purely through AJAX (I have a register form that I want to be submitted through AJAX). If you turn JavaScript off, you won't be able to submit the form anyways, so wouldn't it be alright to do all of your validation on the frontend?
Now provide the response and nothing else.
|
The answer is 'no' as others point out but it's really important to understand why . The best way, I think is take web browser (the following assumes Chrome), point it to your web page and right click->inspect element . Select the 'network' tab. Now do your submit. One or more entries will appear in the view. You'll see that there's a POST call with headers and a payload etc. in it. That POST call is all your server will ever see. Everything it knows about the request is shown in that networking. Now right click->Copy->Copy as cURL (cmd or bash as you wish). Open a text editor and paste. What you will see is a command-line instruction cURL installed. If you have cURL (you should probably get it if you don't) you can run this command. If you look on your server logs, it will look pretty much exactly like the one that came from the browser. Now go to the text file and change some of the payload data to something invalid. Run that command and look at your server logs. It should now be readily apparent why you must do server side validation. It's the client-side validation that is optional.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/364625', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/281809/']}
|
jdg_375189
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55223592
|
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 some booleans that are used throughout my grails project (services & controllers, etc) so they are declared in my domain class but I do not want them appearing in the table in the database. Instead of declearing them Boolean I tried Def but this isn't working. Is there a way to do this?
Now provide the response and nothing else.
|
By default, docker will attach your new container to a bridged network. This means that addresses such as: localhost and 127.0.0.1 only refers to the container itself. Not the host machine. The easy was to solve this, is to wrap the MySQL database in a container of it's own. This way your containers can address eachother without issues. Connect to MySQL database on the host If you really want to connect the service in the container with a service on the host, you will need to connect the container to the appropriate network. First, you will need to create a network. Assuming that your local machine has a fixed IP of 192.168.0.1 , you should be able to do this with: docker network create -d bridge --subnet 192.168.0.0/24 --gateway 192.168.0.1 dockernet You can then: docker run --name test-wordpress --net=dockernet -p 8081:80 -d wordpress And you should then be able to refer to the host from inside the container by the IP: 192.168.0.1 . Create stack with wordpress and MySQL The better alternative here though, is to create an application stack definition with docker-compose, that includes both the database and the wordpress application. You can create a docker-compose.yml file like this: docker-compose.yml version: '3.3'services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpressvolumes: db_data: {} And the start the stack with this: docker-compose up Then visit: http://localhost:8000 Notice that the database data will be stored in the docker managed volume called db_data . Details on installing docker-compose can be found here: https://docs.docker.com/compose/install/ Start both containers with just docker run The same can be achieved with just docker run , like this: docker volume create db_datadocker network create mysqlnetdocker run --name test-mysql -e MYSQL_ROOT_PASSWORD=somewordpress -e MYSQL_DATABASE=wordpress -e MYSQL_USER=wordpress -e MYSQL_PASSWORD=wordpress -v db_data:/var/lib/mysql --net=mysqlnet -d mysql:5.7docker run --name test-wordpress -e WORDPRESS_DB_HOST=test-mysql:3306 -e WORDPRESS_DB_USER=wordpress -e WORDPRESS_DB_PASSWORD=wordpress -e WORDPRESS_DB_NAME=wordpress --net=mysqlnet -p 8081:80 -d wordpress:latest You can change the mapping of the mysql datafiles to a local directory instead, and just ommit the docker volume create statement.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55223592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6495551/']}
|
jdg_375190
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
177546
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I use Visual Studio 2012 and he have cases where we added templates parameters to a class "just" in order to introduce a "seam point" so that in unit-test we can replace those parts with mock objects. How do you usually introduce seam points in C++: using interfaces and/or mixing based on some criteria with implicit interfaces by using templates parameters also ? One reason to ask this is also because when compiling sometimes a single C++ file (that includes templates files, that could also include other templates) results in an object file being generated that takes in the order of around 5-10 seconds on a developer machine. VS compiler is also not particularly fast on compiling templates as far as I understand, and because of the templates inclusion model (you practically include the definition of the template in every file that uses it indirectly and possibly re-instantiate that template every time you modify something that has nothing to do with that template) you could have problems with compile times (when doing incremental compiling). What are your ways of handling incremental(and not only) compile time when working with templates (besides a better/faster compiler :-)).
Now provide the response and nothing else.
|
If your templates parameters can only assume a finite (and small) set of values, you could move their definition in a source file, and use explicit instantiation . For instance, in aaa.h you only declare the template functions f and g : template <int n>int f();template <class T>void g(int a); Assume n template parameter can only be 1, 3, 6, and T template parameter can only be int , long and void * . Then you define them in aaa.cpp like this: template <int n>int f(){ ...}template <class T>void g(int a){ ...}template int f<1>();template int f<3>();template int f<6>();template void g<int>(int a);template void g<long>(int a);template void g<void *>(int a); In this way the compiler instantiates the template for the given parameters when compiling aaa.cpp . When compiling client code, it assumes that the definitions exist somewhere, and the linker will take care of that. #include "aaa.h"int main(){ f<1>(); f<3>(); f<6>(); g<int>(5); g<long>(5); g<void *>(5);} You can explicitly instantiate template classes too. The drawback is that you can not use f or g with other template parameters. #include "aaa.h"int main(){ f<5>();} results in undefined reference to `int f<5>()' I used this technique in a project where few complex classes depended on a small (< 10) set of integer template parameters, and it significantly reduced compilation time (since the compiler did not have to parse the complex template definitions when compiling the client code). Of course you may get lesser improvements, depending on the actual code.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/177546', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/35709/']}
|
jdg_375191
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19053827
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I detect the CSV separator from a string in Javascript/NodeJS? Which is the standard algorithm? Note that the separator is not a comma always. The most common separators being ; , , and \t (tab).
Now provide the response and nothing else.
|
A possible algorithm for getting the likely separator(s) is pretty simple, and assumes the data is well-formed: For every delimiter, For every line, Split the line by the delimiter, check the length . If its length is not equal to the last line's length, this is not a valid delimiter. Proof of concept (doesn't handle quoted fields): function guessDelimiters (text, possibleDelimiters) { return possibleDelimiters.filter(weedOut); function weedOut (delimiter) { var cache = -1; return text.split('\n').every(checkLength); function checkLength (line) { if (!line) { return true; } var length = line.split(delimiter).length; if (cache < 0) { cache = length; } return cache === length && length > 1; } }} The length > 1 check is to make sure the split didn't just return the whole line. Note that this returns an array of possible delimiters - if there's more than one item, you have an ambiguity problem.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19053827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1420197/']}
|
jdg_375192
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
138321
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $p(n)$ denote the number of partitions of a positive integer $n$. It seems to me that we have for all $n>25$$$p(n)^2>p(n-1)p(n+1).$$In other words, the sequence $(p(n))_{n\in \mathbb{N}}$ is log-concave, or satisfies $PF_2$, with$$\det \begin{pmatrix} p(n) & p(n+1) \cr p(n-1) & p(n) \end{pmatrix}>0$$for $n>25$. Is this true ? I could not find a reference in the literature so far. On the other hand, the partition function is really studied a lot.So it seems likely that this is known. Similarly, property $PF_3$, with the corresponding $3\times 3$ determinant, seems to hold for all $n>221$, too, and also$PF_4$ for all $n>657$. The question is also motivated from the study of Betti numbers for nilpotent Lie algebras, in particular filiform nilpotent Lie algebras.
Now provide the response and nothing else.
|
The first two terms of the Hardy-Ramanujan formula give$$p(n) = \frac{1}{4 \sqrt{3} n} \exp(\pi \sqrt{2n/3}) + O \left(\exp(\pi \sqrt{n/6} ) \right)$$so$$\log p(n) = \pi \sqrt{2/3} \sqrt{n} - \log n - \log (4 \sqrt{3}) + O(\exp(-\pi \sqrt{n/6} ) ).$$So$$\log p(n+2) - 2 \log p(n+1) + \log p(n) = $$$$ \pi \sqrt{2/3} \left( \sqrt{n+2} - 2\sqrt{n+1} + \sqrt{n} \right) - \left( \log(n+2) - 2 \log(n+1) + \log n \right) + O(\exp(-\pi \sqrt{n/6} ) )$$$$= \left[ \left( \frac{- \pi \sqrt{2/3}}{4} \right) n^{-3/2} + O(n^{-5/2}) \right] + O(n^{-2}) + O(\exp(-\pi \sqrt{n/6} ) ).$$So this quantity is negative for $n$ sufficiently large. The larger determinants seem harder; there is probably a smarter way to do this. With the help of Mathematica, I set $q(n) = a \exp(c \sqrt{n})/n$ and computed that$$\det \begin{pmatrix} q(n) & q(n+1) & q(n+2) \\ q(n-1) & q(n) & q(n+1) \\ q(n-2) & q(n-1) & q(n) \end{pmatrix} = q(n)^3 \left( \frac{c^3}{32 n^{9/2}} + O(n^{-10/2}) \right).$$The error in approximating $p(n)$ by $q(n)$ (for $a = 1/(4 \sqrt{3})$ and $c = \pi \sqrt{2/3}$) will be exponentially smaller than $n^{-9/2}$, so the $3 \times 3$ determinant is positive for $n$ large. The $4 \times 4$ determinant vanishes to order at least $n^{-12/2}$, and I gave up waiting for the computation to finish when I asked for more terms.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/138321', 'https://mathoverflow.net', 'https://mathoverflow.net/users/32332/']}
|
jdg_375193
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
63331430
|
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 three environments - Development, Test and Production. I believe I have two options on how to set them up in AWS: Create a VPC per environment, so three VPCs in total. Then within each VPC add subnets in different availibility zones for availibility/redundancy. Create a fourth 'shared services' VPC that contains the services that all the different environments require. Create a single VPC with multiple subnets. I would create the subnets in different availability zones and spread the different environment resoures evenly across the subnets, so that should one zone go down I don't lose an environment Which one of these approaches is considered best practice? What are the advantages or disadvantages of each, if any? I'm new to AWS and so far have been unable to find a definitive answer for which is best
Now provide the response and nothing else.
|
The good practice is to have production fully separated from test or development environments, which is best achieved by having separate accounts for them: Accounts in the SDLC OU host non-production workloads and therefore should not have production dependencies from other accounts. Since you are not using different account, the closest you can get (if you want to follow the good practice) is to have different VPCs (option 1). What's more, to further separate the environments, the VPCs could be in different regions . Also I would encourage you to re-think why do you need any common resources (i.e. forth VPC). If you share something (e.g. RDS) between prod and devel through the forth VPC, it is a disaster waiting to happen.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63331430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7717158/']}
|
jdg_375194
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2278426
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the following Python (runs in 2.x or 3.x): class Outer(object): pass class Inner(object): def __init__(self): print("Inner.self", self)o = Outer()i = o.Inner() I want to get my hands on o while inside Inner.__init__() . But: I don't want o to be an explicit parameter to Inner . I want O.Inner and o.Inner to be a class object, not something weird like a closure. Can you suggest how I might achieve this? Right now my best idea is to use thread local storage. In my use case, whenever I construct an o.Inner() , I'm already inside a method on o somewhere, and it wouldn't be a big deal to add threading.local()["my o object"] = o to my code. This gives you an idea of the level of depravity I'm willing to consider.
Now provide the response and nothing else.
|
In Python 2.6, a class decorator that's also a custom descriptor matches the specs you give: class InnerClassDescriptor(object): def __init__(self, cls): self.cls = cls def __get__(self, instance, outerclass): class Wrapper(self.cls): outer = instance Wrapper.__name__ = self.cls.__name__ return Wrapperclass Outer(object): @InnerClassDescriptor class Inner(object): def __init__(self): print self.outero = Outer()i = o.Inner()print 'Outer is a', type(Outer)print 'Inner is a', type(o.Inner) This emits: <__main__.Outer object at 0x82f90>Outer is a <type 'type'>Inner is a <type 'type'> just to confirm that o.Inner [[is]] a class object, not something weird like a closure as per your peculiar specs. Of course it needs to be a different class each time for reentrancy -- even in a single-threaded world, the following: o1 = Outer()o2 = Outer()i1 = o1.Inneri2 = o2.Innerprint i1(), i2(), i1(), i2() should work cleanly, and stashing o1 vs o2 anywhere else than in the classes returned by o1.Inner vs o2.Inner (e.g., in TLS) would mean horrible results for this use. But then you didn't specify " o.Inner has to be exactly the same class object for every possible o that's an instance of Outer ", so this code fully meets the specs you did give;-).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2278426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/208607/']}
|
jdg_375195
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
656757
|
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:
EDIT : Instead of expressing the integral as the imaginary part of another integral, I instead expanded $\sin^{3}(x)$ in terms of complex exponentials and I don't run into problems anymore. \begin{align} \int_{0}^{\infty} \frac{x^{3}-\sin^{3}(x)}{x^{5}} \ dx &= \frac{1}{2} \int_{-\infty}^{\infty} \frac{x^{3}-\sin^{3}(x)}{x^{5}} \ dx \\ &= \frac{1}{2} \ \int_{-\infty}^{\infty} \frac{x^{3}+\frac{1}{8i}(e^{3ix}-3e^{ix}+3e^{-ix}-e^{-3ix})}{x^{5}} \ dx \\ &= \frac{1}{2} \lim_{\epsilon \to 0^{+}} \ \int_{-\infty}^{\infty} \frac{x^{3}+\frac{1}{8i}(e^{3ix}-3e^{ix}+3e^{-ix}-e^{-3ix})}{(x-i \epsilon)^{5}} \ dx \\ &= \frac{1}{2} \lim_{\epsilon \to 0^{+}} \int_{-\infty}^{\infty} \frac{x^{3}+\frac{1}{8i} (e^{3ix}-3e^{ix})}{(x-i \epsilon)^{5}} + \frac{1}{16i} \lim_{\epsilon \to 0^{+}} \int_{-\infty}^{\infty} \frac{3e^{-ix}-e^{-3ix}}{(x-i \epsilon)^{5}} \ dx \end{align} Then I integrated $ f(z) = \frac{z^{3}+ \frac{1}{8i}(e^{3iz}-3e^{iz})}{(z-i \epsilon)^{5}}$ around the upper half of $|z|=R$ and $ g(z) = \frac{3e^{-iz}-e^{-3iz}}{(z-i \epsilon)^{5}}$ around the lower half of $|z|=R$ and applied Jordan's lemma. \begin{align} \int_{0}^{\infty} \frac{x^{3}-\sin^{3}x}{x^{5}} \ dx &= \frac{1}{2} \lim_{\epsilon \to 0^{+}}2 \pi i \ \text{Res}[f(z),i \epsilon] + \frac{1}{16i} \lim_{\epsilon \to 0^{+}} 2 \pi i (0) \\ &= \frac{1}{2} \lim_{\epsilon \to 0^{+}} \frac{2 \pi i}{4!} \lim_{z \to i \epsilon} \frac{d^{4}}{dz^{4}} \Big(z^{3}+\frac{1}{8i}e^{3iz}-\frac{3}{8i}e^{iz} \Big) \\ &= \frac{\pi i}{24} \lim_{\epsilon \to 0^{+}} \ \lim_{z \to i \epsilon}\Big( \frac{1}{8i}(3i)^{4}e^{3iz}- \frac{3}{8i} (i)^{4} e^{iz} \Big) \\ &= \frac{\pi i}{24} \lim_{\epsilon \to 0^{+}} \Big( \frac{81}{8i}e^{- 3\epsilon} - \frac{3}{8i}e^{- \epsilon} \Big) \\ &= \frac{\pi i}{24} \Big(\frac{81}{8i}-\frac{3}{8i} \Big) \\ &= \frac{13 \pi}{32} \end{align}
Now provide the response and nothing else.
|
I like to calculate this integral as follows: Let us note that $$\frac{1}{x^5}=\frac{1}{4!}\int_0^\infty t^4e^{-xt}dt$$ So $$I=\frac{1}{4!}\int_{0}^{\infty}(x^{3}-\sin^{3}x)\int_0^\infty t^4e^{-xt}\;dt\;dx$$ $$=\frac{1}{4!}\int_{0}^{\infty}t^4\int_{0}^{\infty}(x^{3}-\sin^{3}x)e^{-xt}\;dx\;dt$$ $$=\frac{1}{4!} \int_{0}^{\infty}t^4\left [\frac{6}{t^4}-\frac{6}{(t^2+1)(t^2+9)}\right ]dt$$ $$=\frac{1}{4}\int_{0}^{\infty}\frac{10t^2+9}{(t^2+1)(t^2+9)}dt=\frac{13\pi}{32}$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/656757', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16033/']}
|
jdg_375196
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3861772
|
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 Rails application which need to run under SSL. I tried ssl_requirement but seems I have to type in all the actions in every controllers. Is there any method that I can add a before_filter in application controller with ssl_requirement, so that the apps will redirect to https automatically when user request is in http? Thanks all. :)
Now provide the response and nothing else.
|
Use a Rack Middleware . # lib/force_ssl.rbclass ForceSSL def initialize(app) @app = app end def call(env) if env['HTTPS'] == 'on' || env['HTTP_X_FORWARDED_PROTO'] == 'https' @app.call(env) else req = Rack::Request.new(env) [301, { "Location" => req.url.gsub(/^http:/, "https:") }, []] end endend# config/environment.rbconfig.middleware.use "ForceSSL"
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3861772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314325/']}
|
jdg_375197
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47417152
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I just started an Angular app so I want to add multiple components on same page. How does this work in Angular? Let's assume each div will be a separate component as well as the view. The components must be in separate .ts files. Would the following work? app.component.html: <div>APP Component1</div><div>App Component2</div> app.component.ts: import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent1 { title = 'app works!';}export class AppComponent2 { title = 'app works!';}
Now provide the response and nothing else.
|
In order to do that, you actually need 3 components. The main component of the Angular application, and the two components you want to display. That would give the following file structure. The main component app.component.html : <div>{{title}}</div><app-comp1></app-comp1><app-comp2></app-comp2> app.component.ts : import { Component } from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html'})export class AppComponent { title = 'App works!';} Component n°1 comp1.component.html : <div>{{title}}</div> comp1.component.ts : import { Component } from '@angular/core';@Component({ selector: 'app-comp1', templateUrl: './comp1.component.html', styleUrls: ['./comp1.component.css']})export class AppComponent1 { title = 'AppComponent1 works!';} Component n°2 comp2.component.html : <div>{{title}}</div> comp2.component.ts : import { Component } from '@angular/core';@Component({ selector: 'app-comp2', templateUrl: './comp2.component.html', styleUrls: ['./comp2.component.css']})export class AppComponent2 { title = 'AppComponent2 works!';}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47417152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6014098/']}
|
jdg_375198
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22682308
|
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 write a value say 65 in hbase. I have to run the following command on hbase shell for that: put 'table','key','cf:qual','A' But is there a way to write it directly something like: put 'table','key','cf:qual',65 (this is not allowed though) Let me know if you understand the question else I will explain more. Update: By 65 I meant to put 'A' but directly the ascii value of 'A'. The real issue for me is I want to put values which fall in the range of 128-255 from the shell.
Now provide the response and nothing else.
|
Since Hbase Shell is implemented using ruby, you can insert byte values by representing them in hexadecimal format. For example if you want to insert a byte value 255 hex representation of 255 is FF.In Hbase shell we should give it as stringBinary which is "\xFF" The "\x" is a special escape character to encode an arbitrary byte from hex, so "\xFF" means byte 0xFF. so put 'table', 'rowkey', 'cf:qual', "\xFF" will insert the byte 255 Note : The value has to be with in " " (double quotes) not ' ' (single quotes). Useful links: How Does Ruby handle bytes/binary Hexadecimal Digits (Hex-Codes) Cheatsheet
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22682308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2369455/']}
|
jdg_375199
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
513745
|
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:
Simple cloud chamber construction is described in various places and all seem to use 90% - 99% isopropyl alcohol as a start. What property does this have that makes it an essential component for these devices?
Now provide the response and nothing else.
|
There is no particular property of alcohols; Wilson’s original cloud chamber used water and worked fine. The essential point of a cloud chamber is to create a supersaturated vapor. Vapors in air have a dew point at which they will condense onto dust and nearby surfaces (like dew condensing onto grass) and they are supersaturated when the dew point is above the temperature of the gas. These supersaturated vapors are then able to spontaneously condense around the wreckage of high-energy particles. Wilson created this high dew point with water by suddenly lowering pressure in a container filled with water vapor; homebrew setups typically use a warm surface evaporating the alcohol into a clear container that is cooled by dry ice, which drops the air temperature below the dew point of the alcohol—although thermoelectric coolers and perhaps even ice water might be able to generate similar temperatures. Probably the relevant physical fact about isopropyl alcohol is that its freezing point is beneath the freezing point of dry ice, so a layer of liquid alcohol might build up on the cold surface, but it does not start to crystallize at those temperatures. If the liquid crystallizes then it is possible that there is a steady current of vapor out of the air which does not allow it to remain supersaturated, while maybe if the layer deposited remains a liquid, it builds up an equilibrium with the supersaturated air and once this happens the air can remain supersaturated without losing more vapor to the surface. Possibly the lower boiling point of alcohol also helps (just as certainly the high purity of 99% helps) in evaporating more of it from the warm side of the homebrew cloud chamber into the air inside, raising the dew point therein and making for a somewhat larger cloud inside. But it is possible that in typical homebrew setups this effect is negligible.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/513745', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/231113/']}
|
jdg_375200
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3697984
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I reboot in c++? Is there any provision in WinSDK? What kind of rights should my program(process) have to do so?
Now provide the response and nothing else.
|
There is the ExitWindowsEx Function that can do this. You need to pass the EWX_REBOOT (0x00000002) flag to restart the system. Important note here (quote from MSDN ): The ExitWindowsEx function returns as soon as it has initiated the shutdown process. The shutdown or logoff then proceeds asynchronously. The function is designed to stop all processes in the caller's logon session. Therefore, if you are not the interactive user, the function can succeed without actually shutting down the computer. If you are not the interactive user, use the InitiateSystemShutdown or InitiateSystemShutdownEx function. You can choose between the appropriate function depending on your situation.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3697984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432622/']}
|
jdg_375201
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16261717
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Actually arrival is pretty simple, tag gets into a range of receivers antenna, but the departure is what is causing the problems. First some information about the setup we have.Tags:They work at 433Mhz, every 1.5 seconds they transmit a "heartbeat", on movement they go into a transmission burst mode which lasts for as long as they are moving. They transmit their ID, transmission sequence number(1 to 255, repeating over and over), for how long they have been in use, and input from motion sensor, if any. We have no control over them whatsoever. They will continue doing what they do until their battery dies. And they are sealed shut. Receiver forwards all that data + signal strength of a tag to our software. Software can work with several receivers. Currently we are using omnidirectional antennas. How can we be sure that the tag has departed from premises? Problems: Sometimes two or more tags transmit "heartbeat" at the same time and no signal is received. With number of tags increasing these collisions happen more often, this problem is solved by tags randomly changing their heartbeat rate (in several milliseconds) to avoid collisions. Problem is I can't rely on tags not "checking in" for a certain period of time as sign of departure. It could be timeout because of collisions. Because of these collisions we cannot rely that every "heartbeat" will be received. Tag manufacturer advised that we use two receivers and set them up as a gate for tags to pass through. Based on the order of tags passing through "gates" we can tell in which direction they are going. The problem with our omnidirectional antennas is that sometimes tag signal bounces of building and then arrives to receiver. So based on signal strength it looks like its farther away then it is. Does anybody have a solution of what we can do to have a reliable way of determining if tags are coming or leaving? Also we can setup antennas in different way as well. I wrote the software that interprets data from receivers, so that part can be manipulated in any way. But I'm out of ideas of how to interpret information to get reliability we need. Right now the only idea is to try out with directional antennas? But I would like to tryout all the options with the current equipment we have. Also any literature suggestion that deals with active RFID tags is more than welcome, most of books I've found deal with passive tag solutions.
Now provide the response and nothing else.
|
As a top level statement, if you need to track items leaving your site, your RFID technology is probably the wrong one. The technology you have is better suited to the positional tracking tags within a large area - eg a factory floor. Notwithstanding the above, here is my take: A good approach to active RFID is to break your area down into zones that are tied to your business processes, for example: Warehouse Loading bay Packing Entry of a tag into a zone represents the start of a new process or perhaps the end of a process the tag is currently in. For example, moving from warehouse to the packing represents assembling a shipment, and movement into the loading bay initiates a shipment. The crux of many RFID implementations is the installation and configuration of the RFID intrastructure to: Map tag -> asset (which you have done) Map tag read -> zone (and by inference asset -> zone) Map movements between zones to steps in a business processes (and therefore understand when an asset leaves the site, your goal) There are a number of considerations: the physical characteristics of 433MHz signals, position of antennae, sensitivity of antennae and some tricks that some vendors have. After an optimal site configuration, then you may need to have some processing tricks on the tag reads that will pour in. Dirty data Always keep in mind that tag read data is dirty - that RF interference (from unshielded motors, electric wiring, etc), weather conditions and physical manipulation of tags (eg covering with metal) happen all the time. RSSI's are like stock tickers - there is a lot of random/microeconomic noise on top of broad macroeconomic trends. To interpret movement, compute the linear regression of groups of reads rather then rely on a specific read's RSSI. If you do see a tag broadcasting with a high RSSI, which then falls to medium then low and then disappears, you really can interpret that as the tag is leaving the range of the receiver. Is that off-site? Well, you need to consider the site's layout (the zones) and the positioning of receivers within the zones. Triangulation Trilateration EDIT I had incorrectly used the term 'triangulation'. This refers to determining the position of something by known the angle it subtends from two or three known locations. In RFID, you use the distance and as such it is called 'trilateration' . In my experience, vendors selling the tag technology you describe have server software that determines the absolute position of the tags using the received RSSI. You should be able to obtain the position of the tag within 1-10m using such software. Determining if the tag is moving off-site is then easy. To code this yourself: First, each tag is pinging away when moving. These pings hit the receivers at almost the same time and sent to the server. However the messages can sometimes arrive out of order or interleaved with earlier and later reads from other receivers. To help correlate pings, the ping contains a sequence number. You are looking for tag reads from the same tag, with the same sequence number, received by three (or more) receivers. If more than three, pick the three with the largest RSSI. The distance is approximated from RSSI. This is not linear and subject to non-trivial random variation. A quick google turns up: Given three approximate distances from three known points (the receivers' locations), you can then resolve the approximate position of the tag using Trilateration using 3 latitude and longitude points, and 3 distances . Now you have the absolute position of the tag. You can use these positions to track the absolute movement of the tag. To make this useful, you should position receivers so that you can reliably detect tags right up to the physical site boundaries. You should then determine a 'geofence' around your site, within receiver range. I would write a business rule that states: If the last known position of a tag was outside the geofence, and A tag read from the tag has not been detected in (say) 10s, then Declare the tag has left the site. By using the trilateration and geofence, you can focus the business logic on only those tags close to going awol. If you fail to receive your 1.5s ping only a few times from such a tag, it's highly likely that the tag has gone outside your receiver's range, and therefore off-site. You're already aware that tag reads can sometimes come from reflections. If you have a lot of these, then your trilateration will be pretty poor. So this method works best when there are fairly large open spaces and minimal reflectors. Some RFID vendors have all this built into their servers - processing this by writing your own code is (clearly) non-trivial. Zone design using wide-area receivers Logical design of zones can help the business logic layer. For example, suppose you have two zones (A and B) with two receivers (1 and 2): A B+----------+----------+| | || 1 | 2 || | |+----------+----------+ If you get tag reads from the tag at receiver 1, then one at receiver 2, how do you interpret that? Did tag T move into zone B, or just get a read at the extreme range of 2? If you get a later read at 1, did the tag move back, or did it never move? A better physical solution is: A B+----------+----------+| | || 1 2 3 || | |+----------+----------+ In this approach, a tag moving from A to B would get reads from the following receivers: 1 1 1 2 1 2 2 3 2 2 3 2 3 3 3 3 3 -------> time From a programming logic point of view, a movement from A -> B has to traverse reads 1 -> 2 -> 3 (even though there is a lot of jitter). It gets even easier to interpret when you combine with RSSI. Portal design with directional receivers You can create quite a good portal using two directional receivers (you will need to spend some time configuring the antenna and sensitivity carefully). Mount a receiver well above the door on both sides. Below is a schematic from the side. R1 and R2 are the receivers (and the rough read field is shown), and on the left is a worker pushing an asset through the door: ----> direction of motion -------------------+---------------- R1 | R2 / \ | / \ o / \ / \ |-++ / \ / \ |\++ / \ / \ ------------------------------------------ You should get a pattern of reads like this: <nothing> 1 1 1 1 1 12 1 21 2 12 2 1 2 2 2 2 2 <nothing> -------> time This indicates a movement from receiver 1 to receiver 2. "Signposts" Savi implementations often use "sign posts" to assist with location. The sign post emits beam that illuminates a small area (like a doorway) in a 123KHz beam. The signpost also transmits a unique number identifying itself (left door might be 1, while the right door might be 2). When the tag passes through the beam, it wakes up and re-broadcasts the number. The reader now knows which door the tag passed through. Watch out for any metal in the surrounding area. 123KHz travels extremely well down rebar in concrete walls, metal fences and rail tracks. We once had tags reporting themselves hundreds of meters from a signpost due to such effects. With this approach you can implement a portal much like you would for passive. Simulating signposts If you don't have the ability to use signposts, then there is a dirty hack: Stick a passive RFID tag to your active RFID tag Install a passive RFID reader on each doorway Passive RFID is actually very good in restricted spaces, so this implementation can work very well. This solution may be the same cost (or cheaper) than with your active RFID vendor. If you're clever, you can use the EPC GIAI namespace for the passive tag ID and so burn it with the active tag ID. Both active and passive tags would then be identically named. Physical considerations 433MHz tags have some interesting characteristics. Well-constructed receivers can get a read of tags within about 100m, which is a long way for RFID. In addition, 433MHz wraps itself around obstacles very well, especially metal ones. We could even read tags in the boot (trunk) of a car travelling at 50km/h - the signal propagates from the rubber seal. When installing a reader to monitor a zone, you need to adjust its location and sensitivity very carefully to maximize the reads from tags within your zone, but also to minimize reads from outside your zone. This might be done in HW or in SW configuration (like dropping all reads below a particular RSSI). One idea might be to move the receiver away from the area where your tags are exiting as in the layout below (R is the reader): +-------------------------+-----------+| Warehouse | Exit || . || . | R . R --->| . | . || | |+-------------------------+-----------+ It pays to do a RF site survey and spend enough time to properly understand how tags and readers work in an area. Getting the physical installation right is critical. Other thing to do is to consider physical constrictions such as corridors and doorways and treat them as choke-points - map logical zones to them. Put a reader (with directional receiver tuned to cover the constriction) and lower sensitivity in to cover the constriction. What no tag-reads actually means If my experience of RFID has taught me anything, it is that you can get spurious reads at any time, and you need to treat everything with a degree of suspicion. For example, you might have a few seconds of missing reads from a given tag - this can mean anything: A user accidentally putting a metal tin over the tag A fork lift truck getting between tag and reader An RF collision A momentary network congestion The battery dying or fading out (remember to check the low-battery flag in tag reads and ensure the business has a process to replace old tags). Tag destroyed by a pallet being pushed into it Stollen by someone wanting to resell it for scrap (Not a joke - this actually happened) Oh yeah, it may be that the tag moved off-site. If the tag has not been heard of in, say, 5 minutes, odds are that it's off site. In most business processes that you would use this active tag technology for, a short delay before the system decides the tag is off-site is acceptable. Conclusions Site survey: spend time experimenting with readers in different locations. Walk around the site with a tag and see what reads you are actually getting. Use this to: Logically segment your site into zones and locate receivers to most accurately position tags in zones It's easier to determine movement between zones using several receivers; if possible, instrument physical constrictions such as doors and corridors as portals. As part of your RFID implementation, you might even want to install new walls or fences to create such constrictions. Consider a passive RFID for portals. Beware of metal, especially large expanses of it. You have dirty data. You need to compute linear regressions on the RSSIs to spot trends over short periods; you need to be able to forgive a small number of missing tag reads Make sure that there are business processes to handle dying batteries and sudden disappearances of tags. Above all, this problem is best solved by getting the receivers installed in the best locations and configuring them carefully, then getting the software right. Trying to solve a bad site installation with software can cause premature ageing. Disclosure: I worked 8 years for a major active RFID vendor.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16261717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/870903/']}
|
jdg_375202
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15978370
|
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 working on some custom UIView-based input controls, and I'm trying to ascertain proper practice for setting up the view. When working with a UIViewController, it's fairly simple to use the loadView and related viewWill , viewDid methods, but when subclassing a UIView, the closest methosds I have are `awakeFromNib , drawRect , and layoutSubviews . (I'm thinking in terms of setup and teardown callbacks.) In my case, I'm setting up my frame and internal views in layoutSubviews , but I'm not seeing anything onscreen. What is the best way to ensure that my view has the correct height and width that I want it to have? (My question applies regardless of if I'm using autolayout, although there might be two answers.) What's the proper "best practice"?
Now provide the response and nothing else.
|
Apple defined pretty clearly how to subclass UIView in the doc. Check out the list below, especially take a look at initWithFrame: and layoutSubviews . The former is intended to setup the frame of your UIView whereas the latter is intended to setup the frame and the layout of its subviews. Also remember that initWithFrame: is called only if you are instantiating your UIView programmatically. If you are loading it from a nib file (or a storyboard), initWithCoder: will be used. And in initWithCoder: the frame hasn't been calculated yet, so you cannot modify the frame you set up in Interface Builder. As suggested in this answer you may think of calling initWithFrame: from initWithCoder: in order to setup the frame. Finally, if you load your UIView from a nib (or a storyboard), you also have the awakeFromNib opportunity to perform custom frame and layout initializations, since when awakeFromNib is called it's guaranteed that every view in the hierarchy has been unarchived and initialized. From the doc of NSNibAwaking (now superseded by the doc of awakeFromNib ): Messages to other objects can be sent safely from within awakeFromNib—by which time it’s assured that all the objects are unarchived and initialized (though not necessarily awakened, of course) It's also worth noting that with autolayout you shouldn't explicitly set the frame of your view. Instead you are supposed to specify a set of sufficient constraints, so that the frame is automatically calculated by the layout engine. Straight from the documentation : Methods to Override Initialization initWithFrame: It is recommended that you implement this method. You can also implement custom initialization methods in addition to, or instead of, this method. initWithCoder: Implement this method if you load your view from an Interface Builder nib file and your view requires custom initialization. layerClass Implement this method only if you want your view to use a different Core Animation layer for its backing store. For example, if you are using OpenGL ES to do your drawing, you would want to override this method and return the CAEAGLLayer class. Drawing and printing drawRect: Implement this method if your view draws custom content. If your view does not do any custom drawing, avoid overriding this method. drawRect:forViewPrintFormatter: Implement this method only if you want to draw your view’s content differently during printing. Constraints requiresConstraintBasedLayout Implement this class method if your view class requires constraints to work properly. updateConstraints Implement this method if your view needs to create custom constraints between your subviews. alignmentRectForFrame: , frameForAlignmentRect: Implement these methods to override how your views are aligned to other views. Layout sizeThatFits: Implement this method if you want your view to have a different default size than it normally would during resizing operations. For example, you might use this method to prevent your view from shrinking to the point where subviews cannot be displayed correctly. layoutSubviews Implement this method if you need more precise control over the layout of your subviews than either the constraint or autoresizing behaviors provide. didAddSubview: , willRemoveSubview: Implement these methods as needed to track the additions and removals of subviews. willMoveToSuperview: , didMoveToSuperview Implement these methods as needed to track the movement of the current view in your view hierarchy. willMoveToWindow: , didMoveToWindow Implement these methods as needed to track the movement of your view to a different window. Event Handling: touchesBegan:withEvent: , touchesMoved:withEvent: , touchesEnded:withEvent: , touchesCancelled:withEvent: Implement these methods if you need to handle touch events directly. (For gesture-based input, use gesture recognizers.) gestureRecognizerShouldBegin: Implement this method if your view handles touch events directly and might want to prevent attached gesture recognizers from triggering additional actions.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/15978370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/224988/']}
|
jdg_375203
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10898699
|
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 using PHP, I find myself writing code like this a lot: $target = $_SESSION[AFTER_LOGIN_TARGET];unset($_SESSION[AFTER_LOGIN_TARGET]);return $target; In Python, there is a dict.pop method that would let me do something similar in one statement, without a temporary variable: return session.pop(AFTER_LOGIN_TARGET) Is there a similar function or trick in PHP?
Now provide the response and nothing else.
|
I don't see a built-in function for this, but you can easily create your own. /** * Removes an item from the array and returns its value. * * @param array $arr The input array * @param $key The key pointing to the desired value * @return The value mapped to $key or null if none */function array_remove(array &$arr, $key) { if (array_key_exists($key, $arr)) { $val = $arr[$key]; unset($arr[$key]); return $val; } return null;} You can use it with any array, e.g. $_SESSION : return array_remove($_SESSION, 'AFTER_LOGIN_TARGET'); Short and Sweet With PHP 7+ you can use the null coalescing operator to shorten this function greatly. You don't even need isset() ! function array_remove(array &$arr, $key) { $val = $arr[$key] ?? null; unset($arr[$key]); return $val;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10898699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244407/']}
|
jdg_375204
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39823648
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Amplitude Analytics does provide Javascript SDK for Amplitude but how do I implement analytics in a React App where I don't have access to the DOM directly? The GitHub page suggests to use amplitude.getInstance().logEvent('EVENT_IDENTIFIER_HERE') but in React I don't have an unique identifier of a component or a event.
Now provide the response and nothing else.
|
This is what I did and works perfectly: yarn add amplitude-js utilities/amplitude.js import amplitude from 'amplitude-js';export const initAmplitude = () => { amplitude.getInstance().init(process.env.REACT_APP_AMPLITUDE);};export const setAmplitudeUserDevice = installationToken => { amplitude.getInstance().setDeviceId(installationToken);};export const setAmplitudeUserId = userId => { amplitude.getInstance().setUserId(userId);};export const setAmplitudeUserProperties = properties => { amplitude.getInstance().setUserProperties(properties);};export const sendAmplitudeData = (eventType, eventProperties) => { amplitude.getInstance().logEvent(eventType, eventProperties);}; index.js ...import { initAmplitude } from './utilities/amplitude';initAmplitude();ReactDOM.render( <ThemeProvider theme={theme}> <Provider store={store}> <Routes store={store} /> </Provider> </ThemeProvider>, document.getElementById('root')); And then you're good to go. Call the other methods when you need it, like setAmplitudeUserDevice : import { setAmplitudeUserDevice } from 'utilities/amplitude';export function installationInitializationSuccess(id, token) { setAmplitudeUserDevice(token); return { type: INSTALLATION_INITIALIZATION_SUCCESS, id, token };} Hope it helps!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39823648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3818829/']}
|
jdg_375205
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3546801
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have often heard (both online and in person) people say that " $\mathbb{R}^2$ can't be totally ordered." I would like to understand this statement. Of course, on the face of it, this is false: Pick your favorite bijection $f:\mathbb{R}^2 \to \mathbb{R}$ and define $x \leq y$ iff $f(x) \leq f(y)$ . When I bring this up, people usually dismiss it, saying it isn't "nice" enough. This is fair, but now leaves me with the question of what a "nice" ordering would look like. Other questions on this site (like this ) show that there is no ordering which makes $\mathbb{C}$ an ordered field. I find this answer somewhat unsatisfying. I don't need to appeal to the algebraic structure of $\mathbb{R}$ to give it a "nice" ordering. Furthermore, I would like to be able to extend this notion of a "nice ordering" to other topological spaces that don't admit field structures: does $\mathbb{R}^3$ have a "nice" ordering? how about $S^1$ ? Here's a definition I came up with: a total ordering on a topological space $X$ is "nice" if for every $x < y$ , there are neighborhoods $U_x \ni x$ and $U_y \ni y$ so that for all $a \in U_x$ and $b \in U_y$ , we have $a < b$ . So the usual ordering on $\mathbb{R}$ is "nice," but (for all $f$ I can think of) the ordering of $\mathbb{R}^2$ given above isn't. I've tried proving that $\mathbb{R}^2$ and $S^1$ can't be given a nice total ordering under this definition, but have had some difficulty. Questions: Is there an established notion of a "nice" ordering on a topological space? How can you prove that $\mathbb{R}^2$ (or $S^1$ ) can't be totally ordered nicely? (either with my definition or someone else's, if it exists)
Now provide the response and nothing else.
|
I have not seen a standard definition of a nice total ordering, but I like the one you provided. Neither $\mathbb{R}^2$ nor $S^1$ admit a nice ordering by your definition. The proof is straightforward: Claim 1: In a topological space $X$ with a nice total ordering $<$ , for all $x\in X$ the sets $\{y \mid y<x\}$ and $\{y \mid y> x\}$ are open. Claim 2: For $X = \mathbb{R}^2$ or $X=S^1$ , there is no way to write $X=A\cup B\cup\{x\}$ for disjoint nonempty open sets $A,B$ . The proof of each claim is straightforward: For the first, note that the set $\{y\mid y<x\}$ can be written as a union of open balls around all points inside itself, and similarly for $\{y \mid y>x\}$ . For the second, observe that the compliment of a singleton set in $\mathbb{R}^2$ or in $S^1$ is connected.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3546801', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/581608/']}
|
jdg_375206
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1839422
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
float f = 0.7;if( f == 0.7 ) printf("equal");else printf("not equal"); Why is the output not equal ? Why does this happen?
Now provide the response and nothing else.
|
This happens because in your statement if(f == 0.7) the 0.7 is treated as a double. Try 0.7f to ensure the value is treated as a float: if(f == 0.7f) But as Michael suggested in the comments below you should never test for exact equality of floating-point values.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1839422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/303986/']}
|
jdg_375207
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
160790
|
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 an URL of this type: http://www.example.com/?param1=val1¶m2=¶m3=val3¶m4=val4¶m5=val5 And I want to redirect it to this one: http://www.example.com/newparam/val3/val4 So I have tried this rewrite rule with no success: rewrite "/?param1=val1¶m2=¶m3=(.+)¶m4=(.+)¶m5=(.+)" http://www.example.com/newparam/$1/$2 redirect; Is nginx not able to deal with query parameters? EDIT: I don't want to rewrite all petitions. I only need to rewrite that URL, without affecting the others.
Now provide the response and nothing else.
|
Ok, thanks to the initial help of rzab, I have redefined his rule to this working solution: location / { if ($args ~* "/?param1=val1¶m2=¶m3=[0-9]+¶m4=.+¶m5=[0-9]+") { rewrite ^ http://www.example.com/newparam/$arg_param3/$arg_param4? last; }} I just added a condition to avoid infinite recursion, and a ? at the end of the rule to get rid of the initial params . It works perfectly :)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/160790', 'https://serverfault.com', 'https://serverfault.com/users/34741/']}
|
jdg_375208
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1582384
|
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:
Q: Prove that $e>2$ geometrically. Attempt: I only know one formal definition of $e$ that is $\lim_\limits{n\to\infty} (1+\frac{1}{n})^n=e$. I could somehow understand that this is somehow related to rotation in the complex plane.$$e^{i\theta}=\cos \theta + i \sin \theta$$Hence we have $$e^{i\pi}=-1$$But how can I bring out the value of $e$ when I am showing this rotation in a geometrical figure? Any hints are appreciated. EDIT: As per the comments, I am making a small addition to the question which will not affect the existing answers. It is that, as a definition of $e$, one can use any definition which does not use the fact $2<e<3$.
Now provide the response and nothing else.
|
In this image we see that$$\color{#00A000}{1}+\color{#C000C0}{x}\le\left(1+\frac x2\right)^2$$Therefore,$$\begin{align}1+1&\le\left(1+\frac12\right)^2\\&\le\left(1+\frac14\right)^4\\&\le\left(1+\frac18\right)^8\\&\dots\\&\le\lim_{n\to\infty}\left(1+\frac1{2^n}\right)^{\large2^n}\\[9pt]&=e\end{align}$$
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1582384', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/278967/']}
|
jdg_375209
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10511
|
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've found in many exercises where I'm asked to show that $f(n)=\Theta(g(n))$ where the two functions are of the same order of magnitude I have difficulty finding a constant $c$ and a value $n_0$ for the lower bound. I'm using Corman's definition of $\Theta$: $$\exists c_1,c_2>0\in\mathbb{R}:\forall n\geq n_0: 0 \leq c_1 g(n)\leq f(n)\leq c_2 g(n)$$ Showing the upper bound usually doesn't give me too much trouble, but for the lower bound I allot of times find myself using limits. And even though I'm getting the right answers, I'm a bit worried that my method isn't very rigorous and that maybe I'm doing a bit of hand waving in the process. For example, problem 2.17 from Skiena's Algorithm Design Manual: Show that for any $a,b\in \mathbb{R}: b>0$ that $(n+a)^b = \Theta(n^b)$ In this case I used limits to help find both constants. For the upper limit I decided to look for some $c$ such that $(n+a)^b \leq c^bn^b$. So taking the $b$th root of each side and dividing by $n$ I have $\frac{n+a}{n}\leq c$ which gives me $1 + \frac{a}{n} \leq c$. For any $a\in\mathbb{R}$, $\lim_{n\to\infty }1+\frac{a}{n}=1$. If I pick $n_0>|a|$, then for $a<0$ the expression approaches 1 from the left starting arbitrarily close to $0$. If $a>0$ then the expression approaches 1 from the right starting arbitrarily close to 2. So choosing $c=2$ will satisfy the inequality and we have $c_2=2^b$. Now for the lower bound. I'm looking at the same expression except with the inequality pointing the other way. In this case I'm trying to find $n_0$ and $c$ such that $c\leq 1+\frac{a}{n}$. The value of $n_0$ has to be greater than $|a|$ because otherwise we would have $c\leq 0$ which isn't allowed. This puts us in the same range of values between $0$ and $2$ approaching 1 from each side. So I choose any $c,n_0$ such that $n_0>|a|$ and $0 < c\leq 1-|\frac{a}{n_0}|$. So I could choose $n_0=3|a|$ and $c=\frac{2}{3}$. Thus we have $0 < (\frac{2}{3})^bn^b \leq (n+a)^b \leq 2^bn^b$ for any $n \geq 3|a|$. Is there an easier way to do this? Normally when looking for upper limit constants where the two functions are of the same magnitude I simply eliminate negative lower order terms and change positive ones into multiples of the highest order term such as : $$3n^2+15n-5\leq 3n^2+15n^2=18n^2$$ But when looking for the constant for the lower bound I find myself typically resorting to looking at limits. Is there any kind of short cut to finding the lower bound constant like there is for the upper bound constant?
Now provide the response and nothing else.
|
You can codify your method in the following lemma. Lemma. If $f(n)/g(n) \rightarrow C$, where $C > 0$, then $f(n) = \Theta(g(n))$. The proof is the same as the one you gave. After you prove this lemma once and for all, you can use it forever. That's actually a good way of verifying $f(n) = \Theta(g(n))$. Note that the converse to the lemma isn't true. For example, let $f(n) = n$ and let $g(n) = \exp\lfloor\log n\rfloor$. The ratio $f(n)/g(n)$ moves inside the interval $[1,e)$, and in particular does not tend to a constant limit.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/10511', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/6728/']}
|
jdg_375210
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
136466
|
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The basic steps involved in the conversion of $\ce{FeCr2O4 -> Cr}$ involves, $$\ce{FeCr2O4 ->[NaOH / air, \Delta] Na_2CrO4 ->[C, \Delta] CrO3 ->[Al, \Delta] Cr}$$ Basically, I'm having problems in learning so large amount of inorganic reactions, so I thought it would be easy to learn the mechanism behind these reactions, just like we do in organic chemistry. Therefore, I'm keen to know the mechanism behind first conversion (i.e., from $\ce{FeCr2O4 -> Na_2CrO4}$ ). I've already tried to search for this, but found nothing related. My attempt I know some basic sets of inorganic mechanisms, as follows Ion-exchange Decomposition Water-addition Redox Complex reaction From the above listed, I don't think it would be ion-exchange (bcoz, $\ce{FeCr2O4 -> FeCr+ + CrO4-}$ is very unlikely to happen), water-addition or complex reaction. I guess it could be decomposition or redox, but I'm not sure on the "bond-movement" mechanism part.
Now provide the response and nothing else.
|
The first reaction is a double oxidation. Both Fe and Cr are oxidized by O2 from the air. The reaction is made of two half-reactions. The first half-reaction is not easy to establish, because two elements (Fe, Cr) are oxidized simultaneously, Fe from +II to +III, and Cr from +III to +VI. Sorry to say it : It is one of the most difficult half-equations I ever had to state. It is : $$\ce{FeCr_2O_4 + 11 OH^- -> Fe(OH)_3 + 2 CrO_4^{2-} + 4 H_2O + 7 e-}$$ The second half-equation is easier to write. $$\ce{O_2 + 2H_2O + 4 e- -> 4 OH^-}$$ The overall equation is obtained by multiplying the first equation by $4$ and the second by $7$ and adding the whole. After simplification, it yields : $$\ce{4 FeCr_2O_4 + 16 OH^- + 7 O_2 -> 4 Fe(OH)_3 + 8 CrO_4^{2-} + 2 H_2O}$$ or, without ions : $$\ce{4 FeCr_2O_4 + 16 NaOH + 7 O_2 -> 4 Fe(OH)_3 + 8 Na_2CrO_4 + 2 H_2O}$$ This was the first step, defining how to pass from the mineral $\ce{FeCr_2O_4}$ to $\ce{Na_2CrO_4}$ , at high temperature, and in the presence of air and $\ce{NaOH}$ . The final mixture can be washed with water, which dissolves easily $\ce{Na_2CrO_4}$ , as $\ce{Fe(OH)_3}$ is insoluble in water. Then $\ce{Na_2CrO_4}$ is transformed in $\ce{CrO_3}$ by adding moderately concentrated sulfuric acid : $$\ce{Na_2CrO_4 + H_2SO_4 -> CrO_3 + Na_2SO_4 + H_2O}$$ $\ce{CrO_3}$ is not soluble and can be separated by filtration. Then it is mixed with aluminum powder to get a exothermic reaction when engaged by a match : $$\ce{2 Al + CrO_3 -> Al2O3 + Cr}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/136466', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/63955/']}
|
jdg_375211
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35525588
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
QPair is nice, but what if I need 3 items? Should I just make a struct, or does Qt have me covered?
Now provide the response and nothing else.
|
As QTBUG-22441 indicates, the developers have no intention of adding a Qt analog of std::tuple . (Even though QTBUG-3283 gives us hope that it could be done, it's dated Dec'09, while the newer report, with a WONTFIX, is dated May'15). Thus, you need to fall back to std::tuple or come up with your own data structure. Quote from Marc Mutz: A hypothetical QTuple wouldn't do anything differently, anyway, except drain Qt developer resources. Moreover, the docs for Qt 5 Algorithms module state the following explicitly: Historically, Qt used to provide functions which were direct equivalents of many STL algorithmic functions. Starting with Qt 5.0, you are instead encouraged to use directly the implementations available in the STL; most of the Qt ones have been deprecated (although they are still available to keep the old code compiling). So using STL when programming with Qt 5 is officially encouraged, should it become a necessity.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35525588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2158002/']}
|
jdg_375212
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
194985
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How does one show that $$\lim_{n \rightarrow \infty}\int_{0}^{1}\frac{x^{n}}{1 + x^{n}}\, dx = 0?$$ My idea is to evaluate the inner integral, but I can't seem to be able to do that.
Now provide the response and nothing else.
|
For all $x\in [0,1]$ you have $$ \frac{x^n}{1+x^n} \leq x^n $$ and hence $$ 0\leq\int_{0}^{1}\frac{x^{n}}{1 + x^{n}}\, dx \leq \int_{0}^{1}x^{n}\, dx = \frac{1}{n+1}\rightarrow 0 \quad (n\rightarrow \infty).$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/194985', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11990/']}
|
jdg_375213
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3220670
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Normally, I code as follows for getting a particular item in a variable as follows try: config = ConfigParser.ConfigParser() config.read(self.iniPathName)except ConfigParser.MissingSectionHeaderError, e: raise WrongIniFormatError(`e`)try: self.makeDB = config.get("DB","makeDB")except ConfigParser.NoOptionError: self.makeDB = 0 Is there any way to read all the contents in a python dictionary? For example [A]x=1y=2z=3[B]x=1y=2z=3 is written into val["A"]["x"] = 1...val["B"]["z"] = 3
Now provide the response and nothing else.
|
I suggest subclassing ConfigParser.ConfigParser (or SafeConfigParser , &c) to safely access the "protected" attributes (names starting with single underscore -- "private" would be names starting with two underscores, not to be accessed even in subclasses...): import ConfigParserclass MyParser(ConfigParser.ConfigParser): def as_dict(self): d = dict(self._sections) for k in d: d[k] = dict(self._defaults, **d[k]) d[k].pop('__name__', None) return d This emulates the usual logic of config parsers, and is guaranteed to work in all versions of Python where there's a ConfigParser.py module (up to 2.7, which is the last of the 2.* series -- knowing that there will be no future Python 2.any versions is how compatibility can be guaranteed ;-). If you need to support future Python 3.* versions (up to 3.1 and probably the soon forthcoming 3.2 it should be fine, just renaming the module to all-lowercase configparser instead of course) it may need some attention/tweaks a few years down the road, but I wouldn't expect anything major.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3220670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260127/']}
|
jdg_375214
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3078569
|
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:
On my exam I had to solve the following differential equation. \begin{equation}(\ln(x)-1)y'' - \frac{1}{x}y' + \frac{1}{x^2}y = \frac{(\ln(x) - 1)^2}{x^2}\end{equation} Which is a differential equation of the form: \begin{equation}y'' + a(x)y' + b(x)y = R(x)\end{equation} The only method we've seen to solve this kind of differential equations is: If the differential equation is of the form: \begin{equation}y'' + a(x)y' + b(x)y = 0\end{equation} First find a solution of the characteristic equation, being $\varphi_1$ . Then: \begin{equation}\varphi_2(x) = \varphi_1(x)\int\frac{dx}{A(x)(\varphi_1(x))^2}\end{equation} With $A(x) = e^{\int a(x) dx}$ Then the homogenous solution is given by: \begin{equation}y(x) = c_1\varphi_1(x) + c_2\varphi_2(x)\end{equation} The first problem is that this doesn't satisfy the requirements for this method since the differential equation is not homogenous, but since this is the only fitting method, I'd still try to use it. My guess would be to start with the characteristic equation which gives: \begin{equation}(\ln(x)-1)x^2 - 1 + \frac{1}{x^2}y = 0\end{equation} or \begin{equation}x^2 - \frac{1}{(\ln(x)-1)} + \frac{1}{x^2(\ln(x)-1)} = 0\end{equation} but i wouldn't even know how to start solving this equation to find the roots of the equation. Does anyone have an idea as to how to tackle this problem. Note the only other ways of solving linear differential equations that we have seen are ways to solve first order differential equation or ways to solve second order differential equations in the form: \begin{equation}y'' + py' + qy = R(x)\;\;\;\text{with}\;\; p,q\in\mathbb{R}\end{equation}
Now provide the response and nothing else.
|
Replace $$\begin{align}z&=\ln x -1\\w(z)&=y(x)\text{.}\end{align}$$ Then the differential equation is $$z w'' -(z+1)w'+w=z^2\mathrm{e}^{z+1}\text{.}$$ The linear differential operator on the left side factors, so the solution to this equation can be found by solving in turn the first-order equations $$\begin{align}zv'-v&=z^2\mathrm{e}^{z+1} \\w'-w&=v\text{.}\end{align}$$ Another form for these equations is $$\begin{align}\left(\tfrac{v}{z}\right)'&=\mathrm{e}^{z+1} \\(\mathrm{e}^{-z}w)'&=\mathrm{e}^{-z}v\text{.}\end{align}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3078569', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/628839/']}
|
jdg_375215
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
172498
|
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:
Questions : Can we talk about: variance of a deterministic variable?; covariance between a deterministic variable and a stochastic variable?; covariance between two deterministic variables? Are these concepts well defined in sample?; in population? Motivation Take a simple regression $$y = \beta_0 + \beta_1 x + \varepsilon.$$ Suppose the regressor $x$ is stochastic. The OLS estimate of $\beta_1$ will be $$\hat{\beta}_1=\frac{\widehat{\text{Cov}}(x,y)}{\widehat{Var}(x)}$$ where hats denote sample counterparts of the population concepts. No problem here. Now suppose $x$ is deterministic. I am not sure if I can use terms like variance and covariance in this context. Should I exchange $\hat{\beta}_1=\frac{\widehat{\text{Cov}}(x,y)}{\widehat{Var}(x)}$ for something like $$\hat{\beta}_1=\frac{\frac{1}{n-1}\sum(x_i-\bar{x})(y_i-\bar{y})}{\frac{1}{n-1}\sum(x_i-\bar{x})^2}$$ to be correct? But then again, how meaningful is $\bar{x}$ when $x$ is deterministic? So should I go all the way to $$\hat{\beta}_1=\frac{\frac{1}{n-1}\sum_{i=1}^n(x_i-\frac{1}{n}\sum_{j=1}^n x_j)(y_i-\frac{1}{n}\sum_{j=1}^n y_j)}{\frac{1}{n-1}\sum(x_i-\frac{1}{n}\sum_{j=1}^n x_j)^2}?$$ I am picking on details here and this may not be too important; my main questions are listed at the top of the post.
Now provide the response and nothing else.
|
All five questions have "yes" answers --but we have to be careful about what they mean. "Variance of a deterministic variable." Let's understand a "deterministic variable" to be a univariate dataset. It's just a bunch of values $X=x_1, x_2, \ldots, x_n$, with no probability model. By definition its variance is $$\text{Var}(X) = \frac{1}{n}\sum_{i=1}^n \left(x_i - \bar X\right)^2$$ where $$\bar X = \frac{1}{n}\sum_{i=1}^n x_i$$ is its mean. There is no justification whatsoever to use $n-1$ instead of $n$ in any of these fractions--and this is never legitimately done--because no estimates are being made. We may always think of $X$ as defining a "population." This is the definition of a population variance. "Covariance between a deterministic variable and a stochastic variable." One way to understand this is to assume it refers to a sequence of the form $(x_1, Y_1), (x_2,Y_2), \ldots, (x_n,Y_n)$ where the $x_i$ are numbers and the $Y_i$ are random variables. Then we may define the random variable $$\bar Y = \frac{1}{n}\sum_{i=1}^n Y_i,$$ via which the covariance of $x$ and $Y$ is defined as $$\text{Cov}(x,Y) = \frac{1}{n}\sum_{i=1}^n (x_i - \bar x)(Y_i - \bar Y).$$ It is a linear combination of the $Y_i$ and consequently is itself a random variable. This notation is frequently used as a shorthand in linear regression calculations. "Covariance between two deterministic variables." "Two deterministic variables" can be considered a dataset of ordered pairs $(x_1, y_1), (x_2,y_2), \ldots, (x_n,y_n)$. The covariance can be defined exactly as in (2) and interpreted similarly. In fact, this is a direct consequence of (1): after all, covariances are variances . "Are these concepts well defined in samples?" Because they are well-defined for any dataset, they are well-defined for a sample. Note that similar expressions with $n-1$ in the (outer) denominator are estimators : they are not the sample variance or sample covariance. "Are these concepts well defined in populations?" Because they are well-defined for any dataset, and a population can be considered a dataset (when fully enumerated), they are well-defined for a population.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/172498', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/53690/']}
|
jdg_375216
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
307666
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing a daemon to manage my Java app on a headless Ubuntu 16.04 box using jsvc and this (probably pre-systemd) tutorial , and got as far as running update-rc.d mydaemon enable , receiving the error update-rc.d: error: mydaemon Default-Start contains no runlevels, aborting Having Googled around a bit this appears to have something to do with the (fairly?) recent move to systemd , which I have confirmed is running with pidof systemd . How do I achieve the same starting-at-boot behaviour as update-rc.d (and more importantly stopping the service via /etc/init.d/mydaemon stop rather than just killing the process as the Java app needs to clean up). And are systemd and update-rc.d different systems, or does systemd just change how the latter works?
Now provide the response and nothing else.
|
I don't have a Ubuntu 16.04 to test this on, or provide you with many details, but systemd has a compatibility feature to allow older /etc/init.d scripts to continue working. Instead of using update-rc.d to enable your daemon, use the systemd native command equivalent: sudo systemctl enable mydaemon If this still produces the same error, add the missing lines to the starting set of comments in your script: # Default-Start: 2 3 4 5# Default-Stop: 0 1 6 between the ### BEGIN INIT INFO and ### END INIT INFO lines, and try again.See the LSB core description for these lines. You can also explicitly start the daemon with sudo systemctl start mydaemon and ask for its status with sudo systemctl status -l mydaemon See man systemd-sysv-generator for the compatibility feature. See this wiki for converting System V or upstart scripts like yours to native systemd Units.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/307666', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/188049/']}
|
jdg_375217
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
124919
|
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 am helping a friend with his thesis and we would like to do the following: We would like to show the construction of Barnsley's fern fractal by starting on the zeroth step with a big ellipse, then on the first step drawing two smaller ellipses, rotated and placed on the sides of the first one plus one more ellipse of the same size, placed on the bottom etc.We are actually trying to show each iteration as a sequence of pictures in order for it to be understood by the reader. So far, I have only found the Barnsley's ftern to be constructed in way similar to the Chaos game sierpinski triangle, but none in the way I mention above. Is it possible to do so? Thank you.
Now provide the response and nothing else.
|
After playing with the variables in a Manipulate I came up with these numbers for the arguments of the AffineMap functions. They aren't perfect. I recommend tuning them yourself: (* Activate Roman Maeder's Code first!* ) (fract2[x_, n_] := Show[Graphics[Nest[IFS[{ AffineMap[0 °, 0 °, 0, 0, 0.18, 0], AffineMap[-2.5 °, -2.5 °, 0.90, 0.90, 0, 1.7], AffineMap[49 °, 49 °, 0.33, 0.33, 0, 1.7], AffineMap[120 °, -50 °, 0.33, 0.33, 0.0, 0.33]}], x, n]], Axes -> False, AspectRatio -> Automatic, AxesOrigin -> {0, 0}]; Table[fract2[Circle[{1, 1}, {1, 2}], c], {c, 8}]) You set the initial conditions: AffineMap provides the fractal Step This is Roman Maeder's AffineMap function and IFS $CirclePoints = 24Format[m_map] := "-map-"AffineMap[phi_, psi_, r_, s_, e_, f_] := map[{{r Cos[phi], -s Sin[psi], e}, {r Sin[phi], s Cos[psi], f}}]AffineMap[params : {_Symbol, _Symbol}, expr : {_, _}] := map[Function[params, expr]]AffineMap[mat_?MatrixQ] /; Dimensions[mat] == {2, 3} := map[mat]map[mat_?MatrixQ][{x_, y_}] := mat.{x, y, 1}map[f_Function][{x_, y_}] := f[x, y]map /: Composition[map[mat1_?MatrixQ], map[mat2_?MatrixQ]] := map[mat1.Append[mat2, {0, 0, 1}]]map /: Composition[map[f_Function], map[g_Function]] := Module[{x, y}, AffineMap[{x, y}, f @@ g[x, y]]] AverageContraction[map[mat_?MatrixQ]] := Abs[Det[Drop[#, -1] & /@ mat]]AverageContraction[map[f_Function]] := Module[{x, y}, Abs[Det[Outer[D, f[x, y], {x, y}]]]](m_map)[Point[xy_]] := Point[m[xy]](m_map)[Line[points_]] := Line[m /@ points](m_map)[Polygon[points_]] := Polygon[m /@ points](m_map)[Rectangle[{xmin_, ymin_}, {xmax_, ymax_}]] := m[Polygon[{{xmin, ymin}, {xmax, ymin}, {xmax, ymax}, {xmin, ymax}}]](m_map)[Circle[xy_, {rx_, ry_}]] := With[{dp = N[2 Pi/$CirclePoints]}, m[Line[Table[xy + {rx Cos[phi], ry Sin[phi]}, {phi, 0, 2 Pi, dp}]]]](m_map)[Circle[xy_, r_]] := m[Circle[xy, {r, r}]](m_map)[Disk[xy_, {rx_, ry_}]] := With[{dp = N[2 Pi/$CirclePoints]}, m[Polygon[ Table[xy + {rx Cos[phi], ry Sin[phi]}, {phi, 0, 2 Pi - dp, dp}]]]] (m_map)[Disk[xy_, r_]] := m[Disk[xy, {r, r}]] (m_map)[(Circle | Disk)[xy_, r_, args__]] := Sequence[] (m_map)[Text[text_, pos : {_, _}, args___]] := Text[text, m[pos], args] (m_map)[(h : PointSize | AbsolutePointSize | Thickness | AbsoluteThickness) [r_]] := h[r Sqrt[AverageContraction[m]]] (m_map)[Graphics[objs_List, opts___]] := Graphics[Function[g, m[g], Listable] /@ objs, opts](m_map)[unknown_] := unknownrotation[alpha_] := AffineMap[alpha, alpha, 1, 1, 0, 0]scale[s_, t_] := AffineMap[0, 0, s, t, 0, 0]scale[r_] := scale[r, r]translation[{x_, y_}] := AffineMap[0, 0, 1, 1, x, y]Options[IFS] = {Probabilities -> Automatic};Format[_ifs] := "-ifs-"optnames = First /@ Options[IFS]IFS[ms : {_map ...}, opts___?OptionQ] := Module[{optvals}, optvals = optnames /. Flatten[{opts}] /. Options[IFS];ifs[ms, Thread[optnames -> optvals]]] ifs[ms_List, _][gr : Graphics[_, opts___]] := Graphics[First /@ Through[ms[gr]], opts] (i_ifs)[objs_List] := i /@ objs ifs[ms_List, _][obj_] := Through[ms[obj]] The examples below are from the book and they use points. collage1[x_, n_] := Graphics[Nest[IFS[{ AffineMap[-2 °, -2 °, 0.02, 0.6, -0.14, -0.8], AffineMap[0, 0, 0.6, 0.4, 0, 1.2], AffineMap[-30 °, -30 °, 0.4, 0.7, 0.6, -0.35], AffineMap[30 °, 30 °, 0.4, 0.65, -0.7, -0.5]}], x, n], Axes -> False, AspectRatio -> Automatic, AxesOrigin -> {0, 0}, ColorOutput -> (RGBColor[0.316411, 0.699229, 0.0585946] &)];Show[collage1[Point[{0, 0}], 8]] collage2[x_, n_] := Graphics[Nest[IFS[{ AffineMap[0 °, 0 °, 0, 0, 0.16, 0], AffineMap[-2.5 °, -2.5 °, 0.85, 0.85, 0, 1.6], AffineMap[49 °, 49 °, 0.3, 0.34, 0, 1.6], AffineMap[120 °, -50 °, 0.3, 0.37, 0.0, 0.37]}], x, n], Axes -> False, AspectRatio -> Automatic, AxesOrigin -> {0, 0}, ColorOutput -> (RGBColor[0.316411, 0.699229, 0.0585946] &)]; Show[collage2[Point[{0, 0}], 8]] I took this from
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/124919', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/37326/']}
|
jdg_375218
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2038040
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi All, I have 2 questions regarding a ListView in Android: How can I get the color of the listview's focused row ?I tried to use the ListView.getSelector() method, which according to its documentation should give me what I'm looking for, but it's giving me a Drawable object which I don't know how to retrieve the color from (if possible...). How can I set the color of the listview's focused row ?Here I tried to use the setSelector() method on the listview, passing it a ColorDrawable object, but the result of doing it is that the whole background of the list view is painted in that color... and this is not what I wanted of course... Thanks!
Now provide the response and nothing else.
|
The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled... While you can retrieve the drawable using getSelector() , I don't believe you can retrieve a specific Drawable from a StateListDrawable , nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway. As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this: <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="false" android:state_focused="true" android:drawable="@drawable/item_disabled" /> <item android:state_pressed="true" android:drawable="@drawable/item_pressed" /> <item android:state_focused="true" android:drawable="@drawable/item_focused" /></selector>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2038040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239193/']}
|
jdg_375219
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8191891
|
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 chain async rest service calls and have single callback when they finished. Is it possible to do it with guava?
Now provide the response and nothing else.
|
You can use Futures.chain for chaining ListenableFuture s: final ListeningExecutorService service1 = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(16));final ListeningExecutorService service2 = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(16));ListenableFuture<String> service1result = service1.submit(new Callable<String>() { @Override public String call() throws Exception { return "service1result"; }});ListenableFuture<String> service2result = Futures.chain(service1result, new Function<String, ListenableFuture<String>>() { @Override public ListenableFuture<String> apply(final @Nullable String input) { return service2.submit(new Callable<String>() { @Override public String call() throws Exception { return Joiner.on(" -> ").join(input, "service2result"); } }); }});System.out.format("Result: %s\r\n", service2result.get()); Output of at the code above in the terminal: > run-main training.Training[info] Compiling 1 Java source to /home/remeniuk/projects/guava-training/target/scala-2.9.1/classes...[info] Running training.Training Result: service1result -> service2result
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8191891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/161287/']}
|
jdg_375220
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18474497
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking to replace text in a webpage (any webpage I want to run it on) using JavaScript. I'm not an expert in JavaScript, so I am sort of lost. If I can help it I would like to avoid jQuery. Through Google, I've found this stackoverflow question. But when I inject document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi'); into a webpage it sort of messes the page up. It seems to make the page revert to basic text and formatting. Also, I'm wondering if the regex code from here , could be used. Again, I really am not sure how to use it. What it would do is replace only webpage text - not links or filenames. I'm using Google Chrome incase that matters.
Now provide the response and nothing else.
|
You could perform your repleacements on all the just the text nodes in the DOM: function replaceTextOnPage(from, to){ getAllTextNodes().forEach(function(node){ node.nodeValue = node.nodeValue.replace(new RegExp(quote(from), 'g'), to); }); function getAllTextNodes(){ var result = []; (function scanSubTree(node){ if(node.childNodes.length) for(var i = 0; i < node.childNodes.length; i++) scanSubTree(node.childNodes[i]); else if(node.nodeType == Node.TEXT_NODE) result.push(node); })(document); return result; } function quote(str){ return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); }} Quote function borrowed from this answer. Usage: replaceTextOnPage('hello', 'hi'); Note that you will need to SHIM forEach in older browsers or replace that code with a loop like so: var nodes = getAllTextNodes();for(var i = 0; i < nodes.length; i++){ nodes[i].nodeValue = nodes[i].nodeValue.replace(new RegExp(quote(from), 'g'), to);}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18474497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2577654/']}
|
jdg_375221
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11332111
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is my code: <CheckBox android:id="@+id/sprint_checkbox" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/sprint_game" /> <CheckBox android:id="@+id/marathon_checkbox" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/marathon" /> <CheckBox android:id="@+id/never_ending_checkbox" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/never_ending" /> What i want to do is "detect" when one of these is checked and then set the other two to "disable", so the user can select only one at time.I tried to use the ".setOnCheckedChangeListener", but i can't do that, can someone help me with some code?Thanks a lot guys!
Now provide the response and nothing else.
|
This is the way you are notified about checked changes: CheckBox check = findViewById(R.id.sprint_checkbox);check.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { //do stuff } }); You can also let your activity implements the OnCheckedChangeListener interface and then: CheckBox check1 = findViewById(R.id.sprint_checkbox);CheckBox check2 = findViewById(R.id.marathon_checkbox); CheckBox check3 = findViewById(R.id.never_ending_checkbox);check1.setOnCheckedChangeListener(this);check2.setOnCheckedChangeListener(this);check3.setOnCheckedChangeListener(this); Overriding the interface method: @Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { switch(buttonView.getId()){ case R.id.sprint_checkbox: //do stuff break; case R.id.marathon_checkbox: //do stuff break; case R.id.never_ending_checkbox: //do stuff break; }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11332111', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1501963/']}
|
jdg_375222
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30754
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have 2 choices in sending data between 2 web applications. I encode the data in Base64 and append to the URL and retrieve these parameters at my destination application and decode the parameters. For eg., http:/myDomain/someCode/pages/somePage.jsf?pin=MzAwMDY3MDI2OQ Send the parameters as hidden values from application1 to application2. String res=(String)request.getAttribute("paramValue");document.myForm.action='myDestinationURL';document.myForm.method="POST";document.myForm.submit();<form name="myForm" method="post"><input type="hidden" name="paramValue" value="<%=res%>" /> In Choice 1, one can know the parameters that am sending and my Encoding technique. In choice 2, one can view the data that am sending by doing a view source easily. Apart from above things, what possible ways exist for an intruder to know my system better? And which option is more suitable in general for a developer? Choice 1 or Choice 2?
Now provide the response and nothing else.
|
Option 1 may introduce a number of non-security related issues anyway: The resulting URL may be cached by the browser, or bookmarked, causing users to resubmit. The resulting URL may be shared by users, causing third parties to submit. The URL may be sent to your browser vendor , who may hit the site. But this is about security, and it introduces a few risks not present in option 2: The URL with its parameter may end up in the proxy logs of everything along the way, revealing your data. Your decode function is now an additional attack vector. (Does it handle unicode correctly? Does it have length restrictions?) You may be tempted to think of your encoded string as somehow secure, when it's just security through obscurity (and not very much obscurity), or perhaps more appropriately, security theatre . That said though; they are otherwise largely equivalent in the security they offer . They both submit plain text data in the HTTP header, and base64 isn't exactly rocket science (and you can base64 encode your POST version). Neither offers any meaningful protection for your data. If it's information you don't want the user to see; why are you sending it to the user to begin with? Consider the architecture you're using and see if there's a way to simply remove the risk entirely by not handling that information on the client side. So, to answer the question: with regards to sending data - both reveal the same information to an attacker; choose whichever option is more appropriate for the situation ( this Treehouse blog post may help with that ), but you should not rely on either method to actually protect anything.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/30754', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/15520/']}
|
jdg_375223
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4484002
|
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 difference between If Assigned(Foo) and If (Foo <> nil) ? If So, when should they each be used?
Now provide the response and nothing else.
|
TL;DR The official documentation states Assigned(P) corresponds to the test P <> nil for a pointer variable, and @P <> nil for a procedural variable. Hence, for a non-procedural pointer variable (such as a variable of type PInteger , PMyRec , TBitmap , TList<integer> , or TFormClass ), Assigned(P) is the same thing as P <> nil . However, for a procedural variable, Assigned(P) is the same thing as @P <> nil , while P <> nil would try to execute the procedure or function that P points to (with an empty list of parameters). Explanation The documentation excerpt above summarizes it pretty well. Assigned(X) returns True if and only if the X variable, which has to be a pointer under the hood (with some exception), has a non- nil value. Assigned can be used for "old-school" pointer variables: var i: Integer; p: PInteger;begin i := 5; p := @i; { Assigned(p) True } { p <> nil True } p := nil; { Assigned(p) False } { p <> nil False } Assigned can also be used for object (and metaclass) variables. Indeed, in Delphi, an object (or metaclass) variable is simply a pointer under the hood: L := TList<integer>.Create;try { Assigned(L) True } { L <> nil True }finally FreeAndNil(L);end;{ Assigned(L) False }{ L <> nil False } (And, for completeness, an example with a metaclass variable: var FC: TFormClass;begin FC := TForm; { Assigned(FC) True } { FC <> nil True } FC := nil; { Assigned(FC) False } { FC <> nil False } ) In all these examples, Assigned(X) is exactly the same thing as X <> nil . However, for procedural types, things are slightly different. First, let's warm up: type TStringProc = procedure(const AText: string);procedure MyStrProc(const AText: string);begin ShowMessage(AText);end;procedure TForm1.FormCreate(Sender: TObject);var SP: TStringProc;begin SP := MyStrProc; SP('test');end; Notice in particular that SP is used to actually invoke the procedure it currently points to. Now, you might try procedure TForm1.FormCreate(Sender: TObject);var SP: TStringProc;begin SP := MyStrProc; ShowMessage(BoolToStr(Assigned(SP), True)); { True } ShowMessage(BoolToStr(SP <> nil, True)); { will not compile } SP := nil; ShowMessage(BoolToStr(Assigned(SP), True)); { False } ShowMessage(BoolToStr(SP <> nil, True)); { will not compile }end; but that will not even compile. The compiler says, "Not enough actual parameters". The reason is that the above code will try to execute the procedure that SP points to, and then indeed the required AText parameter is missing. (Of course, at compile time, the compiler doesn't know if SP will point to a compatible procedure or not, but it does know the signature of such a valid procedure.) And even if the procedural type had an empty parameter list, it wouldn't compile, since a procedure doesn't return a value (much less a value that can be compared against nil ). But beware! The following code will compile: type TGetPtrFunc = function: pointer;function MyPtrFunc: pointer;begin Result := nil;end;procedure TForm1.FormCreate(Sender: TObject);var PF: TGetPtrFunc;begin PF := MyPtrFunc; ShowMessage(BoolToStr(Assigned(PF), True)); { True } ShowMessage(BoolToStr(PF <> nil, True)); { False (!) } PF := nil; ShowMessage(BoolToStr(Assigned(PF), True)); { False } ShowMessage(BoolToStr(PF <> nil, True)); { will cause access violation at runtime }end; The first PF <> nil will compare the MyPtrFunc function result value against nil ; it will not tell you whether the PF function pointer is assigned or not (it is!). The second PF <> nil will try to invoke a nil function pointer; that's a bug (access violation exception). To test if a procedural variable is assigned, you have to test @PF <> nil : procedure TForm1.FormCreate(Sender: TObject);var SP: TStringProc;begin SP := MyStrProc; ShowMessage(BoolToStr(Assigned(SP), True)); { True } ShowMessage(BoolToStr(@SP <> nil, True)); { True } SP := nil; ShowMessage(BoolToStr(Assigned(SP), True)); { False } ShowMessage(BoolToStr(@SP <> nil, True)); { False }end;procedure TForm1.FormCreate(Sender: TObject);var PF: TGetPtrFunc;begin PF := MyPtrFunc; ShowMessage(BoolToStr(Assigned(PF), True)); { True } ShowMessage(BoolToStr(@PF <> nil, True)); { True } PF := nil; ShowMessage(BoolToStr(Assigned(PF), True)); { False } ShowMessage(BoolToStr(@PF <> nil, True)); { False }end; For procedural variables, Assigned(X) is the same thing as @X <> nil , as stated by the documentation. Methods Methods work as regular procedures as far as this topic is concerned. For instance, for a method variable M , Assigned(M) is equivalent to @M <> nil and is True iff the method pointer is not nil . (Under the hood, I believe @M yields the Code member of TMethod .) procedure TForm1.FormCreate(Sender: TObject);var M: TNotifyEvent;begin M := Self.FormClick; ShowMessage(BoolToStr(Assigned(M), True)); { True } ShowMessage(BoolToStr(@M <> nil, True)); { True } M := nil; ShowMessage(BoolToStr(Assigned(M), True)); { False } ShowMessage(BoolToStr(@M <> nil, True)); { False }end; What to use? So, should you use Assigned(X) or X <> nil for non-procedural pointers? And should you use Assigned(X) or @X <> nil for procedural pointers? It is entirely a matter of taste. Personally , I tend to use Assigned(X) when I want to test if the variable is assigned, and X = nil (or @X = nil ) when I want to test if the variable is not assigned, simply because not Assigned(X) is less compact. A related warning Of course, both Assigned(X) and X <> nil (or @X <> nil ) only test if the pointer is nil or not; if non- nil , the pointer might still point to garbage. For instance, since local non-managed variables are not initialized in Delphi, they might well be non- nil before they are assigned a value, but in that case they point to garbage: procedure TForm1.FormCreate(Sender: TObject);var L: TList<integer>; { local non-managed variable: not initialized }begin Assigned(L) { True or False (chance). If True, it points to garbage data. } { Bad things will happen if you try to use L as a list here } { (especially if L is not nil). } Another example: L := TList<integer>.Create; try { Do things with L } finally L.Free; end; Assigned(L); { True, but L points to garbage -- don't use it as a list! }
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4484002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174534/']}
|
jdg_375224
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
61073032
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using a data table from Vuetify: <v-data-table :ref="`sortableTable${index}`" class="items-table-container" :headers="headers" :items="category.items" hide-default-footer> ...custom rows</v-data-table> I noticed that when adding a new item to the table, it wasn't appearing. I verified that the items I'm passing it have 11 items, however the table is only displaying 10 max. When I looked at the wrapper surrounding the table, I noticed that it had: overflow-x: auto;overflow-y: hidden; however, I'm unable to override it for some reason. I've tried adding the height prop but nothing seems to work. How can I give the table an auto height, so that it expands no matter how many rows are in the table?
Now provide the response and nothing else.
|
This issue is happening because you have removed default footer using hide-default-footer , but the pagination is still enabled. Pagination is by default set to show only 10 items per row. You can easily fix this by simply adding disable-pagination options, which disables pagination completely and then you can see all items after 10th index also. <v-data-table :ref="`sortableTable${index}`" class="items-table-container" :headers="headers" :items="category.items" hide-default-footer disable-pagination> DEMO: new Vue({ el: '#app', vuetify: new Vuetify(), data() { return { headers: [{text:"Dessert (100g serving)",align:"start",sortable:!1,value:"name"},{text:"Calories",value:"calories"},{text:"Fat (g)",value:"fat"},{text:"Carbs (g)",value:"carbs"},{text:"Protein (g)",value:"protein"},{text:"Iron (%)",value:"iron"}], desserts: headers=[{name:"Frozen Yogurt",calories:159,fat:6,carbs:24,protein:4,iron:"1%"},{name:"Ice cream sandwich",calories:237,fat:9,carbs:37,protein:4.3,iron:"1%"},{name:"Eclair",calories:262,fat:16,carbs:23,protein:6,iron:"7%"},{name:"Cupcake",calories:305,fat:3.7,carbs:67,protein:4.3,iron:"8%"},{name:"Gingerbread",calories:356,fat:16,carbs:49,protein:3.9,iron:"16%"},{name:"Jelly bean",calories:375,fat:0,carbs:94,protein:0,iron:"0%"},{name:"Lollipop",calories:392,fat:.2,carbs:98,protein:0,iron:"2%"},{name:"Honeycomb",calories:408,fat:3.2,carbs:87,protein:6.5,iron:"45%"},{name:"Donut",calories:452,fat:25,carbs:51,protein:4.9,iron:"22%"},{name:"KitKat",calories:518,fat:26,carbs:65,protein:7,iron:"6%"},{name:"Jelly bean",calories:375,fat:0,carbs:94,protein:0,iron:"0%"},{name:"Lollipop",calories:392,fat:.2,carbs:98,protein:0,iron:"2%"},{name:"Ice cream sandwich",calories:237,fat:9,carbs:37,protein:4.3,iron:"1%"},{name:"Eclair",calories:262,fat:16,carbs:23,protein:6,iron:"7%"},{name:"Cupcake",calories:305,fat:3.7,carbs:67,protein:4.3,iron:"8%"},{name:"Ice cream sandwich",calories:237,fat:9,carbs:37,protein:4.3,iron:"1%"},{name:"Eclair",calories:262,fat:16,carbs:23,protein:6,iron:"7%"},{name:"Cupcake",calories:305,fat:3.7,carbs:67,protein:4.3,iron:"8%"}], } },}) <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"><script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script><div id="app"> <v-app id="inspire"> <v-container> <v-layout column> <v-data-table :headers="headers" :items="desserts" class="elevation-1" hide-default-footer disable-pagination dense> </v-data-table> </v-layout> </v-container> </v-app></div>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61073032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3394654/']}
|
jdg_375225
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1046933
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently implementing process groups into my operating system project's POSIX subsystem. However, I've become a little confused at the POSIX specification (setsid) (along by Wikipedia's page on Process groups). Our terminal layer sends SIGINT to the foreground process (group, whose id should equal the group leader's PID). In this case, that foreground process (our "login" application) becomes a group leader by calling setsid . When the user logs in, the program forks and executes the user's shell. At this stage, my understanding is that I call setpgid from the forked child before calling exec* . This means the executed program will be a part of the process group from the outset. If I wanted to run the newly forked child outside the process group I would merely call setsid in the forked child before calling exec* . Is this correct? Are there any really obscure things I should be checking or doing? As a follow-on question, which I believe I already know, is it a requirement for fork to transfer group membership? Or is it something that must be done using setpgid after every fork call? I gather process groups are transferred by fork from the POSIX definition of fork . Thanks in advance.
Now provide the response and nothing else.
|
Interesting question - not least because it stayed without even a partial answer for so long. POSIX Base Definitions Some quotes from the definitions part of POSIX: 3.290 Process Group A collection of processes that permits the signaling of related processes. Each process in the system is a member of a process group that is identified by a process group ID. A newly created process joins the process group of its creator. 3.291 Process Group ID The unique positive integer identifier representing a process group during its lifetime. Note: See also Process Group ID Reuse defined in Process ID Reuse . 3.292 Process Group Leader A process whose process ID is the same as its process group ID. 3.293 Process Group Lifetime The period of time that begins when a process group is created and ends when the last remaining process in the group leaves the group, due either to the end of the lifetime of the last process or to the last remaining process calling the setsid() or setpgid() functions. Note: The setsid() and setpgid() functions are defined in detail in the System Interfaces volume of POSIX.1-2008. [...] 3.337 Session A collection of process groups established for job control purposes. Each process group is a member of a session. A process is considered to be a member of the session of which its process group is a member. A newly created process joins the session of its creator. A process can alter its session membership; see setsid(). There can be multiple process groups in the same session. Note: The setsid() function is defined in detail in the System Interfaces volume of POSIX.1-2008. 3.338 Session Leader A process that has created a session. Note: For further information, see the setsid() function defined in the System Interfaces volume of POSIX.1-2008. 3.339 Session Lifetime The period between when a session is created and the end of the lifetime of all the process groups that remain as members of the session. POSIX System Interfaces NAME setsid - create session and set process group ID SYNOPSIS #include <unistd.h> pid_t setsid(void); DESCRIPTION The setsid() function shall create a new session, if the calling process is not a process group leader. Upon return the calling process shall be the session leader of this new session, shall be the process group leader of a new process group, and shall have no controlling terminal. The process group ID of the calling process shall be set equal to the process ID of the calling process. The calling process shall be the only process in the new process group and the only process in the new session. And: NAME setpgid - set process group ID for job control SYNOPSIS #include <unistd.h> int setpgid(pid_t pid, pid_t pgid); DESCRIPTION The setpgid() function shall either join an existing process group or create a new process group within the session of the calling process. The process group ID of a session leader shall not change. Upon successful completion, the process group ID of the process with a process ID that matches pid shall be set to pgid. As a special case, if pid is 0, the process ID of the calling process shall be used. Also, if pgid is 0, the process ID of the indicated process shall be used. Interpretation As the definitions make clear, a session may consist of multiple process groups. Within broad limits, a process may change process groups (though it belongs to just one process group at any time). The options for session handling are more limited; basically, a process either remains a member of its original session, or it can make itself the leader of a new session. Copying parts of the question: Our terminal layer sends SIGINT to the foreground process (group, whose id should equal the group leader's PID). In this case, that foreground process (our "login" application) becomes a group leader by calling setsid. When the user logs in, the program forks and executes the user's shell. At this stage, my understanding is that I call setpgid from the forked child before calling exec*. This means the executed program will be a part of the process group from the outset. I suspect the parentheses should be 'the foreground process group (whose id should equal the group leader's PID)'. By definition (3.292), the process group leader is the process whose PID is the same as the process group ID. I haven't quote the relevant material, but I believe that dispatching the signal to the process group leader is correct Note that the foreground process becomes a session leader by calling setsid() and also becomes the process group leader too. I would expect that the login program would set up the user's shell as a process group leader (and probably a session leader) after forking but before executing the shell. All child processes inherit process group and session from their parent processes automatically; you have to override that if you want it to be different. If I wanted to run the newly forked child outside the process group I would merely call setsid in the forked child before calling exec*. You could do that, but it would also create a new session. You probably want to use setpgid() (modern standard; possibly setpgrp() which is an older standard from SVID) rather than setsid() . Is this correct? Are there any really obscure things I should be checking or doing? Yes, this is mostly correct. Yes, there probably are some obscure things to keep track of too. For example, you might need to think about the controlling TTY. As a follow-on question, which I believe I already know, is it a requirement for fork to transfer group membership? Or is it something that must be done using setpgid after every fork call? I gather process groups are transferred by fork from the POSIX definition of fork. The child process after a fork() belongs to the same set of groups (as in /etc/group ), and also to the same session and same process group - but it is not a session leader nor is it a process group leader.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1046933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118364/']}
|
jdg_375226
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2001765
|
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 creating a library-style system in Ruby on Rails, and I'm trying to come up with a way to calculate the overdue days while excluding weekends when a borrowed item is returned. Right now I'm just calculating "dayslate" as the difference between the due date and the date the item was actually returned, but I want to exclude weekends, since items can only be returned on weekdays. This is my first real experience with Ruby and Rails, so my apologies if I'm missing something obvious. Thanks for any help you all can provide. Here's the code I have for the "return" function: def return @product = Product.find(params[:id]) today = Date.today dayslate = today - @product.due_date if @product.due_date >= today @product.borrower = @product.check_out = @product.due_date = @product.extended_checkout = nil @product.save! flash[:notice] = "Okay, it's checked in!" redirect_to(products_url) else @product.borrower = @product.check_out = @product.due_date = @product.extended_checkout = nil @product.save! flash[:notice] = "Checked in, but it was #{dayslate} days late!" redirect_to(products_url) end end
Now provide the response and nothing else.
|
Here's a snippet of code to find the number of weekdays in a Range of Date objects require 'date'# Calculate the number of weekdays since 14 days agop ( (Date.today - 14)..(Date.today) ).select {|d| (1..5).include?(d.wday) }.size This is how I would use it in your case. class Product def days_late weekdays_in_date_range( self.due_date..(Date.today) ) end protected def weekdays_in_date_range(range) # You could modify the select block to also check for holidays range.select { |d| (1..5).include?(d.wday) }.size endend
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2001765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/214991/']}
|
jdg_375227
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30144480
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Earlier to get user current location I have used LocationManager: LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);} It is easy to read and very straightforward code. But I have noticed that Google recently released New Client API Model in Google Play Services and suggests to use FusedLocationProviderApi which looks like much more complicated, it is async, it requires to handle callbacks etc. Are there any advantages of using FusedLocationProviderApi over LocationManager?
Now provide the response and nothing else.
|
FusedLocationProvider uses a mix of hardware to determine location based on the context of the request, meaning it's optimized transparently to you. It will also cache captured locations between applications to avoid unnecessary work to determine location info. So if a user has a variety of location-aware apps, they potentially avoid taxing the device (and waiting) for a location capture as one may have already been cached. While the ol' LocationManager will suffice in small, one-off situations, you should definitely consider the newer alternative as the benefits may be great, and the work to implement, easy. You may as well use it as Google Play Services is regularly updated across devices, and continuously includes improvements to location-based features (and more). A link to an explanation of the FusedLocationProvider at launch: https://www.youtube.com/watch?v=Bte_GHuxUGc
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30144480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4260554/']}
|
jdg_375228
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50274275
|
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 recently updated from Angular 5 to Angular 6. I'm getting this warning combineLatest is deprecated: resultSelector no longer supported, pipe to map instead . Rxjs is version 6.1.0, tslint is 5.10.0, Angular CLI is 6.0.0 and Typescript 2.7.2. I'm using it like this: const a$ = combineLatest( this.aStore.select(b.getAuth), this.cStore.select(b.getUrl), (auth, url) => ({auth, url}),); I've tried it also like this: empty().pipe(combineLatest(...), ...) But this gives me: combineLatest is deprecated: Deprecated in favor of static combineLatest and empty is also deprecated in favor of its static version.
Now provide the response and nothing else.
|
combineLatest is deprecated: resultSelector no longer supported, pipe to map instead The above warning is recommending to remove the resultSelector the last function you provided in combineLatest observable and provide it as part of map operator as follows const a$ = combineLatest( this.aStore.select(b.getAuth), this.cStore.select(b.getUrl));const result$ = a$.pipe( map(results => ({auth: results[0], url: results[1]}))) UPDATE: If you see combineLatest is deprecated: Pass arguments in a single array instead then just add []: const a$ = combineLatest([ this.aStore.select(b.getAuth), this.cStore.select(b.getUrl)]); const result$ = a$.pipe( map(results => ({auth: results[0], url: results[1]})))
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50274275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8362471/']}
|
jdg_375229
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1416018
|
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 the positive sequence $\{u_n\},n\in \mathbb{N}$ that meets the conditions: $\boxed{1}$. $u_{n+1}\le u_n+u_n^2$ $\boxed{2}$. Exist the constant $\text{M} >0$ so that $\displaystyle\sum\limits_{k=1}^n u_k\le \text{M},\, \forall n\in \mathbb{N}$ Prove that $$\lim\limits_{n\to +\infty}(n\cdot u_n)=0$$ I think that we can use the Stolz-Cesaro Theorem, 0/0 Case , but I haven't found how.
Now provide the response and nothing else.
|
Since$$u_{n+1}\le u_n+u_n^2\tag{1}$$we can apply the monotonically increasing function $\frac{x}{1+x}$ to both sides of $(1)$ to get$$\frac{u_{n+1}}{1+u_{n+1}}\le\frac{u_n+u_n^2}{1+u_n+u_n^2}\le u_n\tag{2}$$Suppose that$$\limsup_{n\to\infty}nu_n=\varepsilon\gt0\tag{3}$$This means that for infinitely many $n$, we have$$u_n\ge\frac\varepsilon{2n}\tag{4}$$For $m=\frac2\varepsilon n$, we have $u_n\ge\frac1m$, then by $(2)$, $u_{n-1}\ge\frac{\frac1m}{1+\frac1m}=\frac1{m+1}$ and by induction$$u_n\ge\frac1m\implies u_{n-k}\ge\frac1{m+k}\tag{5}$$thus,$$\sum_{k=n/2}^nu_k\ge\frac{n/2}{m+n/2}=\frac\varepsilon{\varepsilon+4}\tag{6}$$Since there are infinitely many $n$ that satisfy $(4)$, there are infinitely many intervals $\left[\frac n2,n\right]$ so that $(6)$ is true. However, then the sum of $u_n$ would diverge. Therefore, $(3)$ must be false and we must have$$\lim_{n\to\infty}nu_n=0\tag{7}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1416018', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/260949/']}
|
jdg_375230
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
637945
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a hard time understanding how the transition happens between the two. Starting from Schrödinger eqaution for kets: $$i\hbar\frac{d}{dt}\left|\psi\left(t\right)\right\rangle =\hat{H}\left|\psi\left(t\right)\right\rangle \implies\left\langle x\right|i\hbar\frac{d}{dt}\left|\psi\left(t\right)\right\rangle =\left\langle x\left|H\right|\psi\left(t\right)\right\rangle \implies i\hbar\frac{d}{dt}\left\langle x|\psi\left(t\right)\right\rangle =\left\langle x\left|H\right|\psi\left(t\right)\right\rangle \implies i\hbar\frac{d}{dt}\psi\left(x,t\right)=\left\langle x\left|H\right|\psi\left(t\right)\right\rangle \underbrace{=}_{?}\hat{H}\psi\left(x,t\right)$$ Meaning, I don't get why should: $$\left\langle x\left|\hat{H}\right|\psi\left(t\right)\right\rangle =\hat{H}\left\langle x|\psi\left(t\right)\right\rangle $$ Is it generally true for any operator and in any case?
Now provide the response and nothing else.
|
The notation here is confusing, because the same symbol $\hat{H}$ is used for two different things: The operator $\hat{H}$ that you start with, i.e. the one you use in $\hat{H} |\psi(t) \rangle$ , is the Hamiltonian as an abstract Hilbert space operator. The operator $\hat{H}$ that appears in $\hat{H} \langle x | \psi(t) \rangle$ is the representation of the Hamiltonian in the position representation. So it would be much cleaner to write something like: $\hat{H}^{(pos.)} \langle x | \psi(t) \rangle = \langle x | \hat{H} | \psi(t) \rangle $ This last equation is actually a definition of operators in the position representation of the Hilbert space. This can be easier understood by considering the momentum operator $\hat{p}$ . In the abstract Hilbert space of kets, it is just an abstract operator given by $\hat{p} = \int \mathrm{d} p \ p |p \rangle \langle p | \ $ . Its representation in position space, i.e. $\hat{p}^{(pos.)} \langle x | \psi \rangle = \langle x | \hat{p} | \psi \rangle$ , is the familiar: $ \ \hat{p}^{(pos.)} = - i \frac{\partial}{\partial x}$ In particular, it is a differential operator. However, its representation in momentum space, i.e. $\hat{p}^{(mom.)} \langle p | \psi \rangle = \langle p | \hat{p} | \psi \rangle$ is given by $\hat{p}^{(mom.)} = p \ $ . So in the momentum representation of the abstract Hilbert space, the momentum operator is represented by just a number. This is different from the differential operator we had in the position representation. It is quite common in textbooks and papers to not have this explicit label $(mom.)$ or $(pos.)$ , simply because people got used to representing the same physical operator in different ways. To go sure, $\psi(x) = \langle x | \psi \rangle$ is the wavefunction associated with the state $|\psi \rangle$ . The object $\widetilde{\psi}(p) := \langle p | \psi \rangle$ is the analogous object in momentum space.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/637945', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/254782/']}
|
jdg_375231
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6073914
|
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 might be completely off track by now, so I will just ask this here so someone can help me. What I want to do, is to insert a value from my web.config, stored in an applicationSettings area, into my aspx markup. Specifically I want to reade a URL from config. This is the configSection setup I use <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=123456"> <section name="MyApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=12345" requirePermission="false" /></configSections> Later in that file are the actual settings like so: <applicationSettings><MyApp.Properties.Settings> <setting name="ImagesUrl" serializeAs="String"> <value>http://resources/images/</value> </setting> Now I want to reference the above value in markup like this: <asp:Image ID="Image1" runat="server" ImageUrl="<%$AppSettings:ImagesUrl%>/Image1.jpg I know there's an expression available <%$ AppSettings: ImagesUrl %>, but I'm not using the appsettings part of web.config, rather the configSection. EDIT:I believe I can only do it with ExpressionBuilder, because I have to concatenate the string with the individual image name. I changed the example above to reflect that. I like Bert Smith Code Solution below for accessing the config section, only I need to put it in an expression builder. I'm stuck at overriding the GetCodeExpression method from where I would call the Configuration Manager, but I don't understand how to build an expression the parameters. public class SettingsExpressionBuilder: ExpressionBuilder{ public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) { return ?? } EDIT The result looks like this, and works for all kinds of files, not just images: <asp:ScriptReference Path='<%$Code:GetAppSetting("ResourcesUrl","JS/jquery/jquery.jqplot.js")%>' and I simply used the example from Microsoft to return any kind of code from the expression builder: return new CodeSnippetExpression(entry.Expression); And GetAppSetting is a method in my custom Page class.
Now provide the response and nothing else.
|
Typically you would create a custom settings class to read these values out as this artical describes. Personally, I would just use the appSettings as suggested above as this is existing functionality and for what your doing would on the surface seem adequate. However, not knowing your circumstances, what your attempting to do could be solved without the custom settings like so: In the code behind I created a protected function to retrieve the setting protected string GetCustomSetting(string Section, string Setting){ var config = ConfigurationManager.GetSection(Section); if (config != null) return ((ClientSettingsSection)config).Settings.Get(Setting).Value.ValueXml.InnerText; return string.Empty;} Then in the aspx markup I call this function <div> <label runat="server" id="label"><%=GetCustomSetting("applicationSettings/MyApp.Properties.Settings", "ImagesUrl") %></label></div> Hope this helps. Follow Up: The CodeExpression will look something like this: public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context){ var config = ConfigurationManager.GetSection("applicationSettings/MyApp.Properties.Settings"); return new CodePrimitiveExpression(((ClientSettingsSection)config).Settings.Get(entry.Expression).Value.ValueXml.InnerText);} In my Test, I created a class called CustomSettingsExpressionBuilder and added it to the App_Code folder. Added the configuration for the custom express to the web.config and called it from aspx like so: <asp:Label ID="Label1" runat="server" Text="<%$CustomSettings:ImagesUrl %>"></asp:Label>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6073914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240785/']}
|
jdg_375232
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46926809
|
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 written a custom loss function for my neural network but it can't compute any gradients. I thinks it is because I need the index of the highest value and are therefore using argmax to get this index. As argmax is not differentiable I to get around this but I don't know how it is possible. Can anyone help?
Now provide the response and nothing else.
|
If you are cool with approximates, import tensorflow as tfimport numpy as npsess = tf.Session()x = tf.placeholder(dtype=tf.float32, shape=(None,))beta = tf.placeholder(dtype=tf.float32)# Pseudo-math for the below# y = sum( i * exp(beta * x[i]) ) / sum( exp(beta * x[i]) )y = tf.reduce_sum(tf.cumsum(tf.ones_like(x)) * tf.exp(beta * x) / tf.reduce_sum(tf.exp(beta * x))) - 1print("I can compute the gradient", tf.gradients(y, x))for run in range(10): data = np.random.randn(10) print(data.argmax(), sess.run(y, feed_dict={x:data/np.linalg.norm(data), beta:1e2})) This is using a trick that computing the mean in low temperature environments gives to the approximate maximum of the probability space. Low temperature in this case correlates with beta being very large. In fact, as beta approaches infinity, my algorithm will converge to the maximum (assuming the maximum is unique). Unfortunately, beta can't get too large before you have numerical errors and get NaN , but there are tricks to solve that I can go into if you care. The output looks something like, 0 2.244599 9.08 8.04 4.04 4.08 8.09 9.06 6.09 8.999951 1.0 So you can see that it messes up in some spots, but often gets the right answer. Depending on your algorithm, this might be fine.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46926809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7199281/']}
|
jdg_375233
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
627898
|
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 am designing a two layer PCB with high speed signals with rise and fall times as low as 3ns. I was doing some studying and learned that for better signal intergrity and EMI a good grounding strategy is critial. To lower the effects of displacment current lowering crosstalk, routing a ground element along with each high speed tracks helps. May it be a ground plane underneath or ground track along side it.(Do correct me if I am wrong with my understanding.) Would it be a better strategy to have both layers as ground plane? A ground plane forces a return path next to most signals. Stitching vias make for even better return paths. Is there any other benefits to having power and ground plane? I understand that this strategy has the advantage of creating decoupling capacitence. EDIT:What is meant by 2 ground planes, I actually meant Signal-Ground/Signal-Ground.ANDWhat is meant by 1-power 1-ground planes, I actually meant Signal-Power/Signal-Ground.
Now provide the response and nothing else.
|
If a 2 layer PCB is your only option: make the second layer ground and route your signals and power on the first. A proper ground/return plane is key for every signal and avoid sharing of the return path as much as possible. (A GND plane is preferable compared to a return trace) High speed signals tend to follow underneath the signal trace, in the dielectric the energy will travel: between the two layers. Any obstacles will produce problems. The higher the frequency, the more the return path of the signal will follow the signal trace: Image source: https://www.signalintegrityjournal.com/ext/resources/article-images-2020/A-Simple-Demonstration-of-Where-Return-Current-Flows/F1.jpg The nice thing of a 4-layer pcb is the distance between layer 1-2 and 3-4, very close. In a signal-gnd-gnd-signal configuration any inductance related to your traces will have less effect in 3D perspective compared to the much bigger distance between layer 2 and 3 and in case of a 2 layer pcb between both layers. Inductance around traces, stopped by the gnd layers top/bottom: Image source: https://www.signalintegrityjournal.com/ext/resources/Blogs/2020/What-is-Differential-Impedance-and-Why-do-We-Care/F1.jpg Compare the distances between the layers: 4-layer: Image source: https://www.bitweenie.com/wp-content/uploads/2013/04/4LayerPCB_Stackup.png 2-layer: Image source: https://manage.pcbgogo.com/img/js/ueditor/ueditor1.4.3.3/net/upload/image/20200114/6371460255595880006009080.png In that way I don’t believe in ground poured next to traces and pads; the effect is too small and a possible cause of trouble if not designed very carefully.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/627898', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/317868/']}
|
jdg_375234
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5748476
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Prelim caveat: I am very new to js and have mainly gotten by through doing web searches for examples/tutorials. I am writing js which should run both on web and on mobile devices (e.g. iPad). We have a library to help abstract away the differences between mouse and touch : if (navigator.userAgent.search('Mobile') > 0) { window.FLAGS = { start: 'touchstart', end: 'touchend', move: 'touchmove', click: 'click', touchScreen: true };} else { window.FLAGS = { start: 'mousedown', end: 'mouseup', move: 'mousemove', click: 'click', touchScreen: false };} Then in code you can do things like: widget.view.bind(FLAGS.start, function(e) { I am trying to find a touch equivalent for mouseleave so I can do a similar trick. I can imagine ways to catch a leave event by tracking the position on move and comparing that to bounding box of widget in question, but I'm hoping there's a little one-liner like the touchstart / mousedown relationship.
Now provide the response and nothing else.
|
It's been suggested, but not implemented AFAIK: http://www.quirksmode.org/mobile/advisoryTouch.html Something like this might work (writing it from top of my head, untested): var element;document.addEventListener('touchstart', function(event) { event.preventDefault(); var touch = event.touches[0]; element = document.elementFromPoint(touch.pageX,touch.pageY);}, false);document.addEventListener('touchmove', function(event) { event.preventDefault(); var touch = event.touches[0]; if (element !== document.elementFromPoint(touch.pageX,touch.pageY)) { touchleave(); }}, false);function touchleave() { console.log ("You're not touching the element anymore");}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5748476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/719507/']}
|
jdg_375235
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
137849
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm a beginner in Mathematica, so please forgive me if the following question turns out to be completely trivial. My situation is that I'd like to rename certain terms of polynomials. Say I have a polynomial, which I've factorized in a certain way already so that it looks something like this (just an example):$$p=(a_1+a_2+a_3)(b_1+b_2)^2-(c_1-c_2)(d_1 d_2 + d_3 - d_4)$$Now I'd like to call$$a := a_1+a_2+a_3, \hspace{2mm} b := b_1+b_2, \hspace{2mm} c := c_1+c_2, \hspace{2mm} d := d_1 d_2 + d_3 - d_4$$so that the polynomial $p$ is then written as$$ p= a b^2 - c d. $$ This seems like a functionality that Mathematica could already have but I don't know about... I'm grateful for any help! EDIT: In the above case a simple "/." replacement seems to work. However, can someone tell me why it doesn't in the following case: z1 z2 z3 z4 (z1 z2 + z1 z3 + z2 z3 + z1 z4 + z2 z4 + z3 z4) (z1 z2 z3 + z1 z2 z4 + z1 z3 z4 + z2 z3 z4) /. {z1 z2 + z1 z3 + z2 z3 + z1 z4 + z2 z4 + z3 z4 -> a1, z1 z2 z3 + z1 z2 z4 + z1 z3 z4 + z2 z3 z4 -> a2, z1 z2 z3 z4 -> a3} which evaluates to a3 (z1 z2 + z1 z3 + z2 z3 + z1 z4 + z2 z4 + z3 z4) (z1 z2 z3 + z1 z2 z4 + z1 z3 z4 + z2 z3 z4)
Now provide the response and nothing else.
|
PolynomialReduce is usually the best function for this type of replacement. One often does better by first "canonicalizing" the reducers, using GroebnerBasis . The idea is to order terms/variables so that the ones desired in the result are "smaller" than those being replaced. This can be done by specifying the ones to remove in the variable lists, since all others that appear will automatically be ordered lower by PolynomialReduce and GroebnerBasis . Here is one example in question. poly = z1 z2 z3 z4 (z1 z2 + z1 z3 + z2 z3 + z1 z4 + z2 z4 + z3 z4) (z1 z2 z3 + z1 z2 z4 + z1 z3 z4 + z2 z3 z4);reducers = {z1 z2 + z1 z3 + z2 z3 + z1 z4 + z2 z4 + z3 z4 - a1, z1 z2 z3 + z1 z2 z4 + z1 z3 z4 + z2 z3 z4 - a2, z1 z2 z3 z4 - a3};gb = GroebnerBasis[reducers, Variables[poly]];PolynomialReduce[poly, gb, Variables[poly]][[2]](* Out[58]= a1 a2 a3 *) Related: 1 2 3 4
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/137849', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/46247/']}
|
jdg_375236
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45692490
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Have tried every solution on stackoverflow but it does not solve my problem,my output is not showing. The output does appear in logs and everywhere else but due to some reason angular is unable to render it. In my real scenario i will be receiving data from a server and i have mimicked the object structure i will be getting in the 'controller.js' file Html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <div ng-app="application" ng-controller="controller"> <ng-view> <h2> Todo List: </h2> <ul> <li> {{t}}</li> <li> {{s}}</li> </ul> </ng-view> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <script src="application.js"></script> <script src="controller.js"></script> </body> </html> Controller.js var app=angular.module('application', []); app.controller("controller", function($scope) { var d= [{'Task':'Say hi!','Status':'failed'}]; $scope.t=d[0].Task; $scope.s=d[0].Status; console.log("Task",$scope.t); console.log("Status",$scope.s); }); Application.js var app = angular.module("application", []); app.run(function(){ console.log("App running!"); });
Now provide the response and nothing else.
|
I had the issue when I put jcenter() before google() in project level build.gradle. When I changed the order and put google() before jcenter() in build.gradle the problem disappeared Here is my final build.gradle // Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.1.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }}allprojects { repositories { google() jcenter() }}task clean(type: Delete) { delete rootProject.buildDir}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/45692490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8466816/']}
|
jdg_375237
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37367331
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to use argparse to capture an arbitrary set of optional arguments? For example both the following should be accepted as inputs: python script.py required_arg1 --var1 value1 --var2 value2 --var3 value3python script.py required_arg1 --varA valueA --var2 value2 --varB valueB a priori I don't know what optional arguments would be specified receive but would handle them accordingly.
Now provide the response and nothing else.
|
This is kind of a hackish way, but it works well: Check, which arguments are not added and add them import argparseparser = argparse.ArgumentParser()parser.add_argument("foo")parser.add_argument("-bar", type=int)# parser can have any arguments, whatever you want!parsed, unknown = parser.parse_known_args() # this is an 'internal' method# which returns 'parsed', the same as what parse_args() would return# and 'unknown', the remainder of that# the difference to parse_args() is that it does not exit when it finds redundant argumentsfor arg in unknown: if arg.startswith(("-", "--")): # you can pass any arguments to add_argument parser.add_argument(arg.split('=')[0], type=<your type>, ...)args = parser.parse_args() For example: python3 arbitrary_parser.py ha -bar 12 -extra1 value1 -extra2 value2 Then the result would be args = Namespace(bar=12, foo='ha', extra1='value1' extra2='value2')
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37367331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2320823/']}
|
jdg_375238
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3105746
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This question may sound cliched, but I am in a situation here. I am trying to implement a finite state automaton to parse a certain string in C. As I started writing the code, I realised the code may be more readable if I used labels to mark the different states and use goto to jump from one state to another as the case comes. Using the standard breaks and flag variables is quite cumbersome in this case and hard to keep track of the state. What approach is better? More than anything else I am worried it may leave a bad impression on my boss, as I am on an internship.
Now provide the response and nothing else.
|
Using a goto for implementing a state machine often makes good sense. If you're really concerned about using a goto, a reasonable alternative is often to have a state variable that you modify, and a switch statement based on that: typedef enum {s0,s1,s2,s3,s4,...,sn,sexit} state;state nextstate;int done = 0;nextstate = s0; /* set up to start with the first state */while(!done) switch(nextstate) { case s0: nextstate = do_state_0(); break; case s1: nextstate = do_state_1(); break; case s2: nextstate = do_state_2(); break; case s3: . . . . case sn: nextstate = do_state_n(); break; case sexit: done = TRUE; break; default: /* some sort of unknown state */ break; }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3105746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/348637/']}
|
jdg_375239
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
735842
|
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:
Does there exist a function $f: \mathbb{R} \to \mathbb{R}$ that takes each value in $\mathbb{R}$ three times? If not, how could I prove that such a function does not exist?
Now provide the response and nothing else.
|
Here's a continuous solution: $$ f(x) = \begin{cases} 4x-3\lfloor x\rfloor & \text{when $\lfloor x\rfloor$ is even} \\3\lfloor x\rfloor + 3 - 2x & \text{when $\lfloor x \rfloor$ is odd} \end{cases} $$ This takes on the values $0,4,2,6,4,8,6,10,8,\ldots$ at integer $x$ and interpolates linearly between them. Any even number $2m$ is hit at $f(2m)$ (a local minimum), $f(2m-\frac32)$ (the middle of an increasing line segment), and $f(2m-3)$ (a local maximum). All other numbers are hit by a point in an increasing line segment, then a decreasing one, and finally another increasing one. A smoother function with the same overall shape would be $g(x)=ax+\sin x$, except the coefficient $a$ has to be just right in order to get the local maxima and minima to coincide, and I'm too lazy to figure out what it should be.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/735842', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/138749/']}
|
jdg_375240
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.