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
325788
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 change assembly binding (from one version to another) dynamically. I've tried this code but it doesn't work: Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationSection assemblyBindingSection = config.Sections["assemblyBinding"]; assemblyBindingSection.SectionInformation.ConfigSource = "bindingConf.xml"; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("assemblyBinding"); with bindingConf.xml containing the assemblyBinding section configuration. So can a change this section at runtime? how to do it? What alternatives do I have? Now provide the response and nothing else.
The best way I've found to dynamically bind to a different version of an assembly is to hook the AppDomain.AssemblyResolve event. This event is fired whenever the runtime is unable to locate the exact assembly that the application was linked against, and it allows you to provide another assembly, that you load yourself, in its place (as long as it is compatible). For example, you can put in a static constructor on your application's main class that hooks the event like this: using System.Reflection;static Program(){ AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e) { AssemblyName requestedName = new AssemblyName(e.Name); if (requestedName.Name == "AssemblyNameToRedirect") { // Put code here to load whatever version of the assembly you actually have return Assembly.LoadFrom("RedirectedAssembly.DLL"); } else { return null; } };} This method avoids the need to deal with the assembly bindings in configuration files and is a bit more flexible in terms of what you can do with it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/325788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12248/']}
jdg_83241
stackexchange
llm_judgeable_groundtruth_similarity
897356
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: When I'm solving problems, I'm often confronted to solving equations, and when I'm solving equations, I'm often confronted to find the natural solutions of these equations. My actual personal insolvable problem is : How to determine the natural solutions of an equation ? For example, let's take this rather simple equation : $9 = a+b$ I want to solve it, knowing that $a$ and $b$ are natural numbers. How can I get all the possible answers ? Am I obliged to test every possible value for $a$ and $b$ ? I need Mathematics wisdom. Now provide the response and nothing else.
$a+b=9$ Notice that $(a,b)=(1,8)$ is one particular solution to the equation, and the null solution is $(-t, t)$. All the solutions in integers can be given by: $\text{particular solution + null solution} = (1,8)+ (t,-t) = \color{red}{(1+t, 8-t)}$ Since you want solutions in naturals: $1+t > 0$ and $8-t > 0$ which is same as $\color{Red}{-1\lt t\lt 8}$ so these $t$ values give you all the solutions in naturals : $\{(1+0,8-0), (1+1,8-1), \cdots (1+7,8-7)\} \\\{(1,8), (2,7), \cdots (8,1)\} $ That's it for the example problem. Next, see if you can extend this to solving $a+b= \text{any number}$, and finally try solving the linear diophantine equation : $ax+by=c$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/897356', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/90538/']}
jdg_83242
stackexchange
llm_judgeable_groundtruth_similarity
25984827
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 get a value as a Swift type from an object of type Unmanaged<AnyObject> . My example is using an ABRecordRef I'm creating a contact object to manage once I get the ABRecordRef , but I'm having trouble translating from ObjC. Here's what I have: init(recordRef: ABRecordRef) { if let firstName = ABRecordCopyValue(recordRef, kABPersonFirstNameProperty) { self.firstName = firstName }} If it were ObjC, I would do: CFTypeRef firstNameRef = ABRecordCopyValue(recordRef, kABPersonFirstNameProperty);if (firstNameRef) { self.firstName = (__bridge NSString *)firstNameRef;} I can't seem to find the right combination of downcasting / conversion, so any help is appreciated. Now provide the response and nothing else.
Since NoOne answered before I solved it, I'll add the answer here: firstName.takeRetainedValue() as? String If you look at the header of the Unmanaged struct type, you'll find this: /// Get the value of this unmanaged reference as a managed/// reference and consume an unbalanced retain of it.////// This is useful when a function returns an unmanaged reference/// and you know that you're responsible for releasing the result.func takeRetainedValue() -> T So, because the CFTypeRef is converted to Unmanaged<AnyObject> in Swift. Unmanaged uses generics to define a return type, and it is declared like so: Unmanaged<T> Our object is of type Unmanaged<AnyObject> which means that takeRetainedValue() will return type T , or in our case, type AnyObject . I use optional downcasting since my property firstName is of type String? . You can use the takeRetainedValue method to get your value out of your Unmanaged object. In Foundation API's, I'm guessing that they will mostly be of type Unmanaged<AnyObject>! and a downcast will be required. The generic formula appears to be: var unmanagedObject: Unmanaged<AnyObject> = someFunctionThatReturnsAnUnmanagedObject()var newValue: Type = unmanagedObject.takeRetainedValue as Type
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25984827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2611971/']}
jdg_83243
stackexchange
llm_judgeable_groundtruth_similarity
29369599
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Having a few issues with simply adding a day to a few dates in an Appcelerator project using moment.js All I want to do, is grab today's date and then display it in the DD format (01) and then get the next 6 days as well. Here is what I'm trying: var todayDate = moment();var day1 = todayDate.format("DD");var day2 = todayDate.add(1, 'days').format("DD");var day3 = todayDate.add(2, 'days').format("DD");var day4 = todayDate.add(3, 'days').format("DD");var day5 = todayDate.add(4, 'days').format("DD");var day6 = todayDate.add(5, 'days').format("DD");var day7 = todayDate.add(6, 'days').format("DD"); But, the output I get is the following: [INFO] : 31[INFO] : 01[INFO] : 03[INFO] : 06[INFO] : 10[INFO] : 15[INFO] : 21 It should read: [INFO] : 31[INFO] : 01[INFO] : 02[INFO] : 03[INFO] : 04[INFO] : 05[INFO] : 06 What am I doing wrong? Simon Now provide the response and nothing else.
You add days to the same variable : say todayDate is 31.First line, you add 1 day to todayDate , so it becomes 01.Then you add 2 days to todayDate (that is now "01") so it becomes 03etc ... Do this instead (depending on what you need of course) : var day1 = moment().format("DD");var day2 = moment().add(1, 'days').format("DD");var day3 = moment().add(2, 'days').format("DD");var day4 = moment().add(3, 'days').format("DD");var day5 = moment().add(4, 'days').format("DD");var day6 = moment().add(5, 'days').format("DD");var day7 = moment().add(6, 'days').format("DD"); or just add 1 every time ;) var todayDate = moment();var day1 = todayDate.format("DD");var day2 = todayDate.add(1, 'days').format("DD");var day3 = todayDate.add(1, 'days').format("DD");var day4 = todayDate.add(1, 'days').format("DD");var day5 = todayDate.add(1, 'days').format("DD");var day6 = todayDate.add(1, 'days').format("DD");var day7 = todayDate.add(1, 'days').format("DD");
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29369599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/228674/']}
jdg_83244
stackexchange
llm_judgeable_groundtruth_similarity
8991995
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to sort a number of posts alphabetically, using Jekyll? I have something like this now: {% for post in site.categories.threat %}<li><a href="{{ post.url }}">{{ post.title }}</a></li>{% endfor %} It works, but the posts are jumbled up. Would look much nicer if they were sorted alphabetically I think. Thanks Now provide the response and nothing else.
It can be done without a plugin, which means that it works with Github Pages . You have to use some ugly string manipulation tricks, though. I used a similar approach to implement a tag page (that lists all posts for each tag) . Same approach, slightly modified: {% capture posts %} {% for post in site.posts %} |{{ post.title }}#{{ post.url }} {% endfor %}{% endcapture %}{% assign sortedposts = posts | split: '|' | sort %}{% for post in sortedposts %} {% assign postitems = post | split: '#' %} <a href={{ postitems[1] }}">{{ postitems[0] }}</a><br>{% endfor %} Beware: You need two different separator characters inside the first loop (and of course again in the split calls later on) . In order for this to work, both characters must not occur in any of the post titles or URLs!! I'm using | and # in this example, which works for me (I just tested it with my blog) . But you might need to use different characters, depending on your post titles and how your URLs are constructed. Bonus: If you want to display only the posts in a certain tag/category (and not all posts) , you can change the first for loop (the one inside the capture ) to one of these: {% for post in site.tags['whatever'] %}{% for post in site.categories['whatever'] %}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8991995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/299194/']}
jdg_83245
stackexchange
llm_judgeable_groundtruth_similarity
1349999
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it true that $$\sin x > \dfrac x{\sqrt {x^2+1}} , \forall x \in \left(0, \dfrac {\pi}2\right)$$ (I tried differentiating , but it's not coming , please help) Now provide the response and nothing else.
$\arcsin$ is an increasing function, and you can rewrite $$x>\arcsin\left(\frac{x}{\sqrt{x^2+1}}\right).$$ Then, deriving (and using equality at $x=0$) $$1>\frac{\frac{\sqrt{x^2+1}-\frac{x^2}{\sqrt{x^2+1}}}{x^2+1}}{\sqrt{1-\left(\frac{x}{\sqrt{x^2+1}}\right)^2}}=\frac1{x^2+1}.$$ The original inequation is a mixture of trigonometric and algebraic expressions, which makes it intractable as such. The "trick" is to let the sine disappear, knowing that the derivative of the $\arcsin$ is an algebraic expression.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1349999', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_83246
stackexchange
llm_judgeable_groundtruth_similarity
20449428
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 $resource for loading array of items in my controller: $scope.items = api.items.query(); The $scope.items is now promise. Once it is resolved, it contains array of items. Than I have some methods, manipulating the items, for example: // template<div ng-repeat="item in items"> <a href="" ng-click="doSomething(item)">Do it!</a></div>// controller:$scope.doSomething = function(item) { item.$doSomething(); // the items }; Here I would like to watch changes in $scope.items , so it gets notified once any of the item changes . I tried this: $scope.$watch($scope.items, function() { console.log('changed');}); but this doesn't work - it is not triggered after the doSomething changes the object. Neither helps the third objectEquality parameter. I also tried $watchCollection , but with no luck. I found this worked for a short period of time - since Angular 1.2.rc2 the promises unwraping was introduced ( https://github.com/angular/angular.js/issues/3503 ), but it was removed in 1.2.0 ( https://github.com/angular/angular.js/issues/4158 ). So is there now (current stable is Angular 1.2.4) any way how to do this? Thanks! P.S.: This was also discussed in this question: AngularJS - binding/watching a function which returns a promise , but this is not applicable for 1.2.0+. Now provide the response and nothing else.
Solution Since Python 3, input returns a string which you have to explicitly convert to int s, with int , like this x = int(input("Enter a number: "))y = int(input("Enter a number: ")) You can accept numbers of any base and convert them directly to base-10 with the int function, like this >>> data = int(input("Enter a number: "), 8)Enter a number: 777>>> data511>>> data = int(input("Enter a number: "), 16)Enter a number: FFFF>>> data65535>>> data = int(input("Enter a number: "), 2)Enter a number: 10101010101>>> data1365 The second parameter tells what is the base of the numbers entered and then internally it understands and converts it. If the entered data is wrong it will throw a ValueError . >>> data = int(input("Enter a number: "), 2)Enter a number: 1234Traceback (most recent call last): File "<input>", line 1, in <module>ValueError: invalid literal for int() with base 2: '1234' For values that can have a fractional component, the type would be float rather than int : x = float(input("Enter a number:")) Differences between Python 2 and 3 Summary Python 2's input function evaluated the received data, converting it to an integer implicitly (read the next section to understand the implication), but Python 3's input function does not do that anymore. Python 2's equivalent of Python 3's input is the raw_input function. Python 2.x There were two functions to get user input, called input and raw_input . The difference between them is, raw_input doesn't evaluate the data and returns as it is, in string form. But, input will evaluate whatever you entered and the result of evaluation will be returned. For example, >>> import sys>>> sys.version'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'>>> data = input("Enter a number: ")Enter a number: 5 + 17>>> data, type(data)(22, <type 'int'>) The data 5 + 17 is evaluated and the result is 22 . When it evaluates the expression 5 + 17 , it detects that you are adding two numbers and so the result will also be of the same int type. So, the type conversion is done for free and 22 is returned as the result of input and stored in data variable. You can think of input as the raw_input composed with an eval call. >>> data = eval(raw_input("Enter a number: "))Enter a number: 5 + 17>>> data, type(data)(22, <type 'int'>) Note: you should be careful when you are using input in Python 2.x. I explained why one should be careful when using it, in this answer . But, raw_input doesn't evaluate the input and returns as it is, as a string. >>> import sys>>> sys.version'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'>>> data = raw_input("Enter a number: ")Enter a number: 5 + 17>>> data, type(data)('5 + 17', <type 'str'>) Python 3.x Python 3.x's input and Python 2.x's raw_input are similar and raw_input is not available in Python 3.x. >>> import sys>>> sys.version'3.4.0 (default, Apr 11 2014, 13:05:11) \n[GCC 4.8.2]'>>> data = input("Enter a number: ")Enter a number: 5 + 17>>> data, type(data)('5 + 17', <class 'str'>)
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/20449428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/464890/']}
jdg_83247
stackexchange
llm_judgeable_groundtruth_similarity
26783
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 planning to use the IRFR5305PBF Power MOSFET (http://www.irf.com/product-info/datasheets/data/irfr5305pbf.pdf) to switch on a load. I have determined that I need an external heatsink with Rthsa < 29 C/W. How would I go about determining the area of copper on the PCB required to provide a thermal resistance of < 29 C/W? I have tried searching on Google and the IEEE database, but the articles do not clearly show me how to calculate this. edit: I am using a 4 layer PCB with 1 oz copper on the top and bottom, and 0.5oz copper for the inner layers. Now provide the response and nothing else.
Unfortunately there's no simple answer to your question. There's too many variables in the problem for anyone to have measured or characterized every possible configuration: thickness of the FR4, number of copper plane layers, number of vias between the plane layers, the amount of air flow over the board and the inlet air temperature, the thermal contribution of other nearby parts, etc., etc. There are standard test methods, but these are hardly relevant to any real situation, mainly because they use just bare FR4 with no copper layers as the heat spreading element. Various vendors have also published values for certain configurations. The datasheet you linked, for example, refers to IRF's AN-994 , where they give thermal resistance values for various packages offered by that company. But note that their standard test condition uses 2 oz. copper on the outer layers. Linear technology is another company that publishes informative thermal results. If you can find one of their parts in the same package as your FET, and check the datasheet, they'll likely give a table of thermal resistance for various sized heat spreaders on the top and bottom layers. For example, for their DDPAK package, which is not quite the same as the DPAK of your IRF part, they give: (From the LT1965 datasheet, see there for more detail on the test conditions) At least you can see that getting to less than 29 C/W is somewhat challenging. The only test conditions in the Linear results that achieved that required 4 square inches of copper on both the top and bottom layers. But again, you can only count on these figures as guidelines, because factors like airflow will strongly influence the actual results in your application.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/26783', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/8169/']}
jdg_83248
stackexchange
llm_judgeable_groundtruth_similarity
196936
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing some code for a class constructor which loops through all the properties of the class and calls a generic static method which populates my class with data from an external API. So I've got this as an example class: public class MyClass{ public string Property1 { get; set; } public int Property2 { get; set; } public bool Property3 { get; set; } public static T DoStuff<T>(string name){ // get the data for the property from the external API // or if there's a problem return 'default(T)' }} Now in my constructor I want something like this: public MyClass(){ var properties = this.GetType().GetProperties(); foreach(PropertyInfo p in properties){ p.SetValue(this, DoStuff(p.Name), new object[0]); }} So the above constructor will thrown an error because I'm not supplying the generic type. So how do I pass in the type of the property in? Now provide the response and nothing else.
Do you want to call DoStuff<T> with T = the type of each property? In which case, "as is" you would need to use reflection and MakeGenericMethod - i.e. var properties = this.GetType().GetProperties();foreach (PropertyInfo p in properties){ object value = typeof(MyClass) .GetMethod("DoStuff") .MakeGenericMethod(p.PropertyType) .Invoke(null, new object[] { p.Name }); p.SetValue(this, value, null);} However, this isn't very pretty. In reality I wonder if it wouldn't be better just to have: static object DoStuff(string name, Type propertyType);... and thenobject value = DoStuff(p.Name, p.PropertyType); What does the generics give you in this example? Note that value-types will still get boxed etc during the reflection call - and even then boxing isn't as bad as you might think . Finally, in many scenarios, TypeDescriptor.GetProperties() is more appropriate than Type.GetProperties() - allows for flexible object models etc.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/196936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11388/']}
jdg_83249
stackexchange
llm_judgeable_groundtruth_similarity
38884424
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I've been fiddling around with the UI elements and have found that a lot of things call for using the UIElement.layer to style the element over the UIElement itself even though they both have a lot of similar properties. What would be the difference between using let button = UIButton()button.backgroundColor(color) over let button = UIButton()button.layer.backgroundColor(color) or any other property that can be set on the UI Element? Now provide the response and nothing else.
I couldn't find any official documentation of those new attributes (it's probably being worked on), but given the existing GCD documentation, and reading between the lines, it's pretty easy to intuit what's intended here. In the new DispatchQueue.Attributes, .serial is no longer a member. Does this mean that the absence of .concurrent creates a serial queue. An initial test I did in Swift Playgrounds seems to confirm this. Can anyone else confirm? Yes. A queue is either serial or concurrent. Most queues you create will be serial, so you only need to set them to be concurrent if you don't want the default behavior. I see that DispatchQueue.AutoreleaseFrequency is a new type with .inherit, .never, and .workItem. What do these mean? I did some research on GCD and autoreleasing but I'm not very familiar with the concept of autorelease pools. Previously, DispatchQueues would pop their autorelease pools at unspecified times (when the thread became inactive). In practice, this meant that you either created an autorelease pool for each dispatch item you submitted, or your autoreleased objects would hang around for an unpredictable amount of time. Non-determinism is not a great thing to have (particularly in a concurrency library!), so they now allow you to specify one of three behaviors: .inherit: Not sure, probably the previously-default behavior .workItem: Create and drain an autorelease pool for each item that gets executed .never: GCD doesn't manage autorelease pools for you Out of all of these, you're likely only going to want to use .workItem, because it'll clean up your temporary objects when the item completes. The other options are presumably for either buggy code that depends on the old behavior, or for that rare user that actually wants to manage this stuff themselves. Actually, thinking about it a bit more, if you're submitting work items that are Swift-only (they don't call into any Objective-C code), then .never is probably safe & correct. Given that any/all Swift standard library classes might call some Objective-C code, you'd probably want to limit this to computations which reside entirely within your own Swift code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38884424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1017320/']}
jdg_83250
stackexchange
llm_judgeable_groundtruth_similarity
1972672
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 other argument than key , for example: value ? Now provide the response and nothing else.
Arguments of sort and sorted Both sort and sorted have three keyword arguments: cmp , key and reverse . L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;cmp(x, y) -> -1, 0, 1sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list Using key and reverse is preferred, because they work much faster than an equivalent cmp . key should be a function which takes an item and returns a value to compare and sort by. reverse allows to reverse sort order. Using key argument You can use operator.itemgetter as a key argument to sort by second, third etc. item in a tuple. Example >>> from operator import itemgetter>>> a = range(5)>>> b = a[::-1]>>> c = map(lambda x: chr(((x+3)%5)+97), a)>>> sequence = zip(a,b,c)# sort by first item in a tuple>>> sorted(sequence, key = itemgetter(0))[(0, 4, 'd'), (1, 3, 'e'), (2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c')]# sort by second item in a tuple>>> sorted(sequence, key = itemgetter(1))[(4, 0, 'c'), (3, 1, 'b'), (2, 2, 'a'), (1, 3, 'e'), (0, 4, 'd')]# sort by third item in a tuple>>> sorted(sequence, key = itemgetter(2))[(2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c'), (0, 4, 'd'), (1, 3, 'e')] Explanation Sequences can contain any objects, not even comparable, but if we can define a function which produces something we can compare for each of the items, we can pass this function in key argument to sort or sorted . itemgetter , in particular, creates such a function that fetches the given item from its operand. An example from its documentation: After, f=itemgetter(2) , the call f(r) returns r[2] . Mini-benchmark, key vs cmp Just out of curiosity, key and cmp performance compared, smaller is better: >>> from timeit import Timer>>> Timer(stmt="sorted(xs,key=itemgetter(1))",setup="from operator import itemgetter;xs=range(100);xs=zip(xs,xs);").timeit(300000)6.7079150676727295>>> Timer(stmt="sorted(xs,key=lambda x:x[1])",setup="xs=range(100);xs=zip(xs,xs);").timeit(300000)11.609490871429443>>> Timer(stmt="sorted(xs,cmp=lambda a,b: cmp(a[1],b[1]))",setup="xs=range(100);xs=zip(xs,xs);").timeit(300000)22.335839986801147 So, sorting with key seems to be at least twice as fast as sorting with cmp . Using itemgetter instead of lambda x: x[1] makes sort even faster.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1972672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234322/']}
jdg_83251
stackexchange
llm_judgeable_groundtruth_similarity
12007811
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to Python as you might tell. I have read various documents but I still can not figure out if there's a "naming best practices" for strings functions and of course, classes . If I want to name a class or a function as a SiteMap, is it ok to use SiteMap? Should it be Site_map or any other thing, for example? Thank you! PS. any further reading resource is GREATLY appreciated!PS. I am doing web-app development (learning, better to say!) Now provide the response and nothing else.
Naming Conventions: There are various Python naming conventions I use. Consistency here is certainly good as it helps to identify what sort of object names point to. I think the conventions I use basically follow PEP8 . 1) Module names should be lowercase with underscores instead of spaces. (And should be valid module names for importing.) 2) Variable names and function/method names should also be lowercase with underscores to separate words. 3) Class names should be CamelCase (uppercase letter to start with, words run together, each starting with an uppercase letter). 4) Module constants should be all uppercase. E.g. You would typically have module.ClassName.method_name . 5) Module names in CamelCase with a main class name identical to the module name are annoying. (e.g. ConfigParser.ConfigParser, which should always be spelt configobj.ConfigObj .) 6) Also, variables, functions, methods and classes which aren't part of your public API, should begin with a single underscore. (using double underscores to make attributes private almost always turns out to be a mistake - especially for testability.) Whitespace And finally, you should always have whitespace around operators and after punctuation. The exception is default arguments to methods and functions. E.g. def function(default=argument): and x = a * b + c
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12007811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/853934/']}
jdg_83252
stackexchange
llm_judgeable_groundtruth_similarity
866778
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: We have a two player game with this rules: First player throws two dice and the bigger number will be his number. Second player throws only one die. If the number of first player was bigger than that of the second player, the first player wins; if not, the first player loses. For example if first one have 2 and 4 and second have 4,first one loses and second one wins. Please help me finding probability of winning of first player. Now provide the response and nothing else.
You care most about the maximum of the first roll. This will be 1 with probability 1/36. It will be 2 with probability 3/36 etc. (it will be n with probability (2n-1)/36) The first player will win if the second player throws less than his max. $\large P=\frac{1}{36}\frac{0}{6}+\frac{3}{36}\frac{1}{6}+\frac{5}{36}\frac{2}{6}+\frac{7}{36}\frac{3}{6}+\frac{9}{36}\frac{4}{6}+\frac{11}{36}\frac{5}{6}=\frac{125}{216}$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/866778', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/162158/']}
jdg_83253
stackexchange
llm_judgeable_groundtruth_similarity
157633
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: We know that there is a physical interpretation for symplectic manifolds (briefly, the fact that a sympletic form assigns to any Hamiltoninan a vector field which describes the motion of particles). My question is if there is a physical meaning to the fact that all symplectic forms locally look alike, i.e. they are standard locally,(for instance, for the cotangent bundle of a manifold, what does it mean that any non-standard symplectic form locally looks like the standard one- which basically imposes the Hamilton's equations on the hamiltonian H)? Now provide the response and nothing else.
Obviously, this is a question that could be interpreted in different ways. For me, Darboux's theorem is the symplectic analogue of the theorem that a flat Riemannian manifold (i.e. one where Riemann's curvature tensor vanishes) is locally the same as $\mathbb{R}^n$. For Darboux, the analogue of the Riemann curvature tensor is $d\omega$, the differential of the symplectic form. So one variation on your question is "why should the symplectic form on phase space be closed?" which has a very clear answer: If $d\omega\neq 0$, then the form $\omega$ is not invariant under time translation! That is definitely not very physically realistic. The way to compute this is by taking the Lie derivative of $\omega$ by a Hamiltonian vector field $X_f$, using Cartan's magic formula $\mathcal{L}=d\iota+\iota d$. One finds that $$\mathcal{L}_{X_f}\omega=d(\omega(X_f,-))+d\omega(X_f,-,-)=ddf+d\omega(X_f,-,-))=d\omega(X_f,-,-),$$ so closedness is essentially equivalent to invariance of $\omega$ under time translation.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/157633', 'https://mathoverflow.net', 'https://mathoverflow.net/users/31475/']}
jdg_83254
stackexchange
llm_judgeable_groundtruth_similarity
1111361
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 can I solve the following functional equation?$$f(2x) = \frac{f(x)+x}{2},$$for $x \in \mathbb{R}$ with $f$ being a continuous function. Now provide the response and nothing else.
Let $f(x)=ax$. Then it's easy to show that $a=1/3$. Next prove uniqueness. Claim: The only function $h(x)$ which is continuous at $x=0$ and satisfying $h(2x)=h(x)/2$ is $h(x)=0$. Proof: It's easy to show that $h(0)=0$. Suppose $h(b)\ne0$ for some non-zero $b$. Then $h(b/2^N)=2^Nh(b)$. For all $\epsilon$, $\delta$, there exists $N$ such that $|b/2^N|<\delta$ but $|h(b/2^N)|>\epsilon$, contradicting the continuity of $h(x)$ at $0$. Now suppose there are two functions $f(x)$ and $g(x)$ both continues at $x=0$ and satisfying $f(2x)=\frac{f(x)+x}{2}$ and $g(2x)=\frac{g(x)+x}{2}$. Define $h(x)=f(x)-g(x)$ which is continuous at $x=0$. Then $h(2x)=\frac{h(x)}{2}$ and hence $f(x)=g(x)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1111361', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/174765/']}
jdg_83255
stackexchange
llm_judgeable_groundtruth_similarity
5137
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the physical mechanism that causes temperature to rise during a fever? I know that somehow the hypothalamus "orders" to increase the standard body temperature regulation, and this should stimulate mitochondria to produce more ATP. Is that right? Is this the only heating physical mechanism (through increasing production of ATP) that acts during a fever? Now provide the response and nothing else.
As John mentioned, pyrokines such as IL1 and TNF affect the hypothalamus. Your hypothalamus is a thermostat, similar to central heating for example. So when you set your core temperature higher, your body thinks it is cold. To warm up it does several things: Vasoconstriction directs blood to the core body and prevents heatloss Brown fat break down in infants makes heat Shivering which requires respiration which produces a lot of heat. Metabolism alsoincreases in other ways - this is why it is commonly advised toincrease food consumption during illness We wrap up warm - an often overlooked mechanism that is incredibly important. Limited piloerection: if we are hairy our hair will stand up attempting tocreate a barrier for heat loss We stop sweating (breaking of a fever or when the hypothalamus is reset to normal causes us to sweat) Hormonal regulation via (nor)adrenaline/epinephrine, thyroxine - these are related to the increased metabolism.
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/5137', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/1620/']}
jdg_83256
stackexchange
llm_judgeable_groundtruth_similarity
254673
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was reviewing suggested edits when I came across this edit . The original answer had a complete function , along with the code snippet (note that this is just a partial code, not the whole function) : FILE *secretFile = fopen(pathCString, "r");RSA *rsa = NULL;PEM_read_RSAPrivateKey(secretFile, &rsa, NULL, NULL); The suggested edit by a new user added a fclose(secretFile); , so that the function in the accepted answer does not leak a file descriptor. The change is not a trivial one, yes, so I actually did go through the trouble to verify that he is right, and went to accept the edit. But the edit had been rejected already with 3 votes stating that "This edit changes too much in the original post; the original meaning or intent of the post would be lost." The user, having just 1 reputation on SO, then had no other choice to report his findings as to post in a new answer with just one line of code changed from the original. Someone else could have been discouraged by the rejection outright, and this could have been unnoticed already; certainly not a way to commend a new user for a contribution. What is the rationale of rejecting this code edit? To me it was an exemplary one, and certainly not changing the intent of the post, unless the intent was to leak file descriptors. Furthermore it is not trivial knowledge that PEM_read_RSAPrivateKey would not close the file. Furthermore I hardly ever can even go through my 20 daily edit quota as the edit queue is almost always flushed, due to hordes of trigger-happy badge hunters. I have always skipped edits to code where I am not a domain expert, but this does not seem to be the case for the most reviewers. Even on Meta, many state that they outright reject any edits that touch any code, good or bad, if it is not for an obvious typo or formatting issue. Now provide the response and nothing else.
Given just the portion of the code that you pasted into the question here, I, too, would have questioned the necessity of adding the fclose(). However, seeing the entire function in your link, the fclose() is definitely necessary as the function is absolutely leaking the handle without it. secretFile goes out of scope at the end of the function and it isn't being passed to anything else that could close it later. The edit should have been approved, IMO. The only reason I could potentially see for not approving the edit would be if you instead added fclose() further up in the function than the user who made the edit did.
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/254673', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/918959/']}
jdg_83257
stackexchange
llm_judgeable_groundtruth_similarity
436825
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: Determine whether the function$$f(x)={\sin x \over x}$$is uniformly continuous in $\mathbb{R}$. I am using the definition that for $\epsilon>0$ there exists $\delta>0$ such that $|f(x)-f(y)|<\epsilon$ whenever $|x-y|<\delta$. Now provide the response and nothing else.
One has$$f(x):={\sin x\over x}=\int_0^1 \cos(\tau x)\ d\tau\ .$$It follows that$$|f(x)-f(y)|\leq \int_0^1|\cos(\tau x)-\cos(\tau y)|\ d\tau\leq \int_0^1\tau |x-y|\ d\tau={1\over2}|x-y|\ .$$This proves that $f$ is even Lipschitz-continuous.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/436825', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74167/']}
jdg_83258
stackexchange
llm_judgeable_groundtruth_similarity
196294
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 learn about catamorphisms and I've read the Wikipedia article and the first couple posts in the series of the topic for F# on the Inside F# blog. I understand that it's a generalization of folds (i.e., mapping a structure of many values to one value, including a list of values to another list). And I gather that the fold-list and fold-tree is a canonical example. Can this be shown to be done in C#, using LINQ's Aggregate operator or some other higher-order method? Now provide the response and nothing else.
LINQ's Aggregate() is just for IEnumerables . Catamorphisms in general refer to the pattern of folding for an arbitrary data type. So Aggregate() is to IEnumerables what FoldTree (below) is to Trees (below); both are catamorphisms for their respective data types. I translated some of the code in part 4 of the series into C#. The code is below. Note that the equivalent F# used three less-than characters (for generic type parameter annotations), whereas this C# code uses more than 60. This is evidence why no one writes such code in C# - there are too many type annotations. I present the code in case it helps people who know C# but not F# play with this. But the code is so dense in C#, it's very hard to make sense of. Given the following definition for a binary tree: using System;using System.Collections.Generic;using System.Windows;using System.Windows.Controls;using System.Windows.Input;using System.Windows.Media;using System.Windows.Shapes;class Tree<T> // use null for Leaf{ public T Data { get; private set; } public Tree<T> Left { get; private set; } public Tree<T> Right { get; private set; } public Tree(T data, Tree<T> left, Tree<T> rright) { this.Data = data; this.Left = left; this.Right = right; } public static Tree<T> Node<T>(T data, Tree<T> left, Tree<T> right) { return new Tree<T>(data, left, right); }} One can fold trees and e.g. measure if two trees have different nodes: class Tree{ public static Tree<int> Tree7 = Node(4, Node(2, Node(1, null, null), Node(3, null, null)), Node(6, Node(5, null, null), Node(7, null, null))); public static R XFoldTree<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> tree) { return Loop(nodeF, leafV, tree, x => x); } public static R Loop<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> t, Func<R, R> cont) { if (t == null) return cont(leafV(t)); else return Loop(nodeF, leafV, t.Left, lacc => Loop(nodeF, leafV, t.Right, racc => cont(nodeF(t.Data, lacc, racc, t)))); } public static R FoldTree<A, R>(Func<A, R, R, R> nodeF, R leafV, Tree<A> tree) { return XFoldTree((x, l, r, _) => nodeF(x, l, r), _ => leafV, tree); } public static Func<Tree<A>, Tree<A>> XNode<A>(A x, Tree<A> l, Tree<A> r) { return (Tree<A> t) => x.Equals(t.Data) && l == t.Left && r == t.Right ? t : Node(x, l, r); } // DiffTree: Tree<'a> * Tree<'a> -> Tree<'a * bool> // return second tree with extra bool // the bool signifies whether the Node "ReferenceEquals" the first tree public static Tree<KeyValuePair<A, bool>> DiffTree<A>(Tree<A> tree, Tree<A> tree2) { return XFoldTree((A x, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> l, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> r, Tree<A> t) => (Tree<A> t2) => Node(new KeyValuePair<A, bool>(t2.Data, object.ReferenceEquals(t, t2)), l(t2.Left), r(t2.Right)), x => y => null, tree)(tree2); }} In this second example, another tree is reconstructed differently: class Example{ // original version recreates entire tree, yuck public static Tree<int> Change5to0(Tree<int> tree) { return Tree.FoldTree((int x, Tree<int> l, Tree<int> r) => Tree.Node(x == 5 ? 0 : x, l, r), null, tree); } // here it is with XFold - same as original, only with Xs public static Tree<int> XChange5to0(Tree<int> tree) { return Tree.XFoldTree((int x, Tree<int> l, Tree<int> r, Tree<int> orig) => Tree.XNode(x == 5 ? 0 : x, l, r)(orig), _ => null, tree); }} And in this third example, folding a tree is used for drawing: class MyWPFWindow : Window { void Draw(Canvas canvas, Tree<KeyValuePair<int, bool>> tree) { // assumes canvas is normalized to 1.0 x 1.0 Tree.FoldTree((KeyValuePair<int, bool> kvp, Func<Transform, Transform> l, Func<Transform, Transform> r) => trans => { // current node in top half, centered left-to-right var tb = new TextBox(); tb.Width = 100.0; tb.Height = 100.0; tb.FontSize = 70.0; // the tree is a "diff tree" where the bool represents // "ReferenceEquals" differences, so color diffs Red tb.Foreground = (kvp.Value ? Brushes.Black : Brushes.Red); tb.HorizontalContentAlignment = HorizontalAlignment.Center; tb.VerticalContentAlignment = VerticalAlignment.Center; tb.RenderTransform = AddT(trans, TranslateT(0.25, 0.0, ScaleT(0.005, 0.005, new TransformGroup()))); tb.Text = kvp.Key.ToString(); canvas.Children.Add(tb); // left child in bottom-left quadrant l(AddT(trans, TranslateT(0.0, 0.5, ScaleT(0.5, 0.5, new TransformGroup())))); // right child in bottom-right quadrant r(AddT(trans, TranslateT(0.5, 0.5, ScaleT(0.5, 0.5, new TransformGroup())))); return null; }, _ => null, tree)(new TransformGroup()); } public MyWPFWindow(Tree<KeyValuePair<int, bool>> tree) { var canvas = new Canvas(); canvas.Width=1.0; canvas.Height=1.0; canvas.Background = Brushes.Blue; canvas.LayoutTransform=new ScaleTransform(200.0, 200.0); Draw(canvas, tree); this.Content = canvas; this.Title = "MyWPFWindow"; this.SizeToContent = SizeToContent.WidthAndHeight; } TransformGroup AddT(Transform t, TransformGroup tg) { tg.Children.Add(t); return tg; } TransformGroup ScaleT(double x, double y, TransformGroup tg) { tg.Children.Add(new ScaleTransform(x,y)); return tg; } TransformGroup TranslateT(double x, double y, TransformGroup tg) { tg.Children.Add(new TranslateTransform(x,y)); return tg; } [STAThread] static void Main(string[] args) { var app = new Application(); //app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7,Example.Change5to0(Tree.Tree7)))); app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7, Example.XChange5to0(Tree.Tree7)))); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/196294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1659/']}
jdg_83259
stackexchange
llm_judgeable_groundtruth_similarity
799997
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 app that was renamed and I want Haproxy to redirect to the correct path while preserving the request parameters This is what I have: acl old_name path_dir -i /old_name http-request set-path /new_name/%[query] if old_name I want it to change from www.site.com/old_name/Default.aspx?Id=123 to www.site.com/new_name/Default.aspx?Id=123 but this is not working. Now provide the response and nothing else.
With HAProxy 1.5 : use a temporary header to build a new path from the existing one in the request and then directly perform a redirect # Clean the request and remove any existing header named X-Rewritehttp-request del-header X-REWRITE# Copy the full request URL into X-Rewrite unchangedhttp-request add-header X-REWRITE %[url] if { path_beg /old_path }# Change the X-REWRITE header to contain out new pathhttp-request replace-header X-REWRITE ^/old_path(/.*)?$ /new_path\1 if { hdr_cnt(X-REWRITE) gt 0 }# Perform the 301 redirecthttp-request redirect code 301 location http://%[hdr(host)]%[hdr(X-REWRITE)] if { hdr_cnt(X-REWRITE) gt 0 } In HAProxy 1.6, use the regsub filter http-request redirect code 301 location http://%[hdr(host)]%[url,regsub(^/old_path,/new_path,)] if { path_beg /old_path } source among other useful configuration snippets More information is available in the HAProxy documentation for the regsub keyword .
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/799997', 'https://serverfault.com', 'https://serverfault.com/users/373059/']}
jdg_83260
stackexchange
llm_judgeable_groundtruth_similarity
336472
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 $0<x < y < 1$ be given. Prove $$4x^{2}+4y^{2}-4xy-4y+1 + \frac{4}{\pi^2}\Big[\sin^{2}(\pi x)+ \sin^{2}(\pi y) + \sin^{2}[\pi(y-x)] \Big] \geq \frac{1}{2}$$ I have been working on this problem for a while now and I have hit a wall. I have plotted this and it seems to be true. I also tried to prove that it is greater than some other fraction such as $\frac{2}{5}$ or something. So far, I have tried doing partial derivative with respect to x but unfortunately, it is very hard to find the roots as it involve equation involving $\sin(2 \pi x)$ , $\sin[2 \pi (x-y)]$ and $x$ . I think Taylor Series expansion would look very ugly. I would really appreciate it if anyone has any suggestions on what to try or any branch of math I can read on, as I am not sure how to deal with this kind of expression except the elementary tool I have. Now provide the response and nothing else.
Let $$f(x,y):=4x^{2}+4y^{2}-4xy-4y+1 + \frac{4}{\pi^2}\Bigl(\sin^{2}(\pi x)+ \sin^{2}(\pi y) + \sin^{2}(\pi y-\pi x) \Bigr).$$ I will show that $$\min_{0\leq x\leq y\leq 1}f(x,y)=\min_{0\leq x\leq 1/3}f(x,2x).\tag{$\ast$}$$ This suffices, because the minimum of the one-variable function $f(x,2x)$ is easy to analyze numerically: it occurs around $x_0\approx 0.146625$ , and has value $f(x_0,2x_0)\approx 0.502187$ . In order to prove $(\ast)$ , observe that $f(x,y)$ is invariant under the following two permutations of the closed triangle $T:=\{(x,y):0\leq x\leq y\leq 1\}$ : $$(x,y)\mapsto (y-x,1-x)\qquad\text{and}\qquad (x,y)\mapsto (x,1-y+x).$$ These two bijections generate a group $G\cong S_3$ of permutations of $T$ . The elements of $G$ are: \begin{align*}&(x,y)\mapsto(x,y),&&(x,y)\mapsto(y-x,1-x),&&(x,y)\mapsto(1-y,1-y+x),\\&(x,y)\mapsto(x,1-y+x),&&(x,y)\mapsto(1-y,1-x),&&(x,y)\mapsto(y-x,y).\end{align*} The closed triangle $U$ with vertices $$A:=(0,0),\qquad B:=(1/2,1/2), \qquad C:=(1/3,2/3)$$ is a fundamental domain for the action of $G$ on $T$ , hence $$\min_T f(x,y)=\min_U f(x,y).$$ For any interior point $(x,y)\in\mathrm{int\,} U$ , we have $0<y<2x<1$ and $0<y<2/3$ , therefore $$\frac{\pi}{4}\cdot\frac{\partial f}{\partial x}=(2\pi x-\pi y)+2\cos(\pi y)\sin(2\pi x-\pi y)>(2\pi x-\pi y)-\sin(2\pi x-\pi y)>0.$$ So there is no local extremum on the interior of $U$ , which implies that $$\min_T f(x,y)=\min_{\partial U} f(x,y).$$ It is straightforward to verify that the minimum over the side $AB$ (resp. $BC$ ) exceeds $0.6$ (resp. $0.57$ ). Hence the minimum over $\partial U$ equals the minimum over the side $CA$ , and $(\ast)$ follows.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/336472', 'https://mathoverflow.net', 'https://mathoverflow.net/users/143222/']}
jdg_83261
stackexchange
llm_judgeable_groundtruth_similarity
21418091
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So this has been bugging me for a while, but sometimes in my Visual Studio 2013 ASP.NET MVC4 project, I will delete an unused ViewModel class, and will get an error on the next compile that looks like this (for a ViewModel called "MostRecentMemberListing.cs" that I just deleted): Error 9 The type or namespace name 'MostRecentMemberListing' does not exist in the namespace 'MembershipCenter.ViewModels' (are you missing an assembly reference?) c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\temp\3e932790\42b7ff67\App_Web_cvlbfbci.1.cs 29 MembershipCenter If I double-click the error in the "Error List" panel of VS, it opens a file located in this path: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\temp\3e932790\42b7ff67 , which is a system-generated view file(?) with a classname of _Page_Views_Home_MostRecentMember_cshtml . I've tried deleting the weird file itself, as well as its containing folder, and ITS containing folder, all the way up the path to the temp folder under Temporary ASP.NET Files . But everytime I re-compile my project all those folders and files are re-created in that directly and I get the same compile error. I am building my Views during the compilation, via <MvcBuildViews>true</MvcBuildViews> in the project file. If I turn this setting off, I can build + run just fine, but when I turn it back to true , the build error returns. Has anyone encountered this error before? Is it related to IIS? I am running Local IIS, not IIS Express. Now provide the response and nothing else.
This is not related to IIS, local or otherwise. That long, strange file name you are seeing is the name the compiler gives to a view when it compiles it. What everything you have described is telling you is that you have a compilation error in one of your views. It could be mismatched HTML tags, a bad model property call, etc. Looking at your error message, you have a view in the /Views/Home/MostRecentMember.cshtml . Further, it appears that you are indeed either missing the namespace for your model declaration or declared the wrong namespace for the model that you are trying to send in. Deleting the strangely named file will do nothing as when you rebuild, it will come back, most likely with a different name.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21418091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131785/']}
jdg_83262
stackexchange
llm_judgeable_groundtruth_similarity
498599
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is the sum of two prime ideals (of a ring) again a prime ideal? Please can someone give me a hint? I know that the intersection of two prime ideals is again a prime ideal iff one is contained in the other, but I'm not sure about the sum. Now provide the response and nothing else.
Th answer is no, consider the ring $\mathbb{Z}$ and the prime ideals $(2)$ and $(5)$. Since two and five are relative primes then every number can be written as a linear combination over $\mathbb{Z}$ of 2 and 5. To see this. note that if if $k$ is any interger, since we know that$$5-(2)2=1$$by multiplying by $k$ we obtain the expression$$k5-(2k)2=k$$which is a $\mathbb{Z}$-linear combination of $k$ in therms of $2$ and $5$. Note that $k5\in(5)$ and $-2k(2)=-4k\in(2)$. This means that $(2)+(5)=\mathbb{Z}$, which is not a prime ideal. Note that the sum of ideals is an ideal when one is contained in the other. This is not possible in $\mathbb{Z}$ with the exemption when of the ideals is the prime ideal $(0)$, but other rings can give more interesting examples. Have a look at polynomials rings for example.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/498599', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/95324/']}
jdg_83263
stackexchange
llm_judgeable_groundtruth_similarity
2026637
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: My mathematics teacher explained how to find slope using 2 different points but I was never taught how to use the X-Intercept and the Y-Intercept to find the slope. Example question:What is the slope of a line that has an X-Intercept of 8 and a Y-Intercept of 11? Now provide the response and nothing else.
If we know the X-Intercept and the Y-Intercept, then we have two points. With two points, we can define the slope of the line and, indeed, an equation for the line through those two points. Using your example, suppose the X-Intercept is 8 and Y-Intercept is 11. Then we know that $(8,0)$ and $(0,11)$ are points on this line. Therefore, the slope of the line is $\frac {\Delta y}{\Delta x}$, or the change in $y$ over the change in $x$. Therefore, $slope=\frac {0-11}{8-0}=\frac{-11}{8}$. Now we can use point-slope form for a line through a point to give a formula for the line. Point-slope form is defined by $y-y_1=m(x-x_1)$ where $x_1,y_1$ are the $x$ and $y$ values from one of your points, and $m$ is the slope. I will use the point $(8,0)$, although we can very easily choose the other point and get the same formula, so that the formula for this line is $y-0=\frac{-11}{8}(x-8) \implies y=\frac{-11}{8}x+11$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2026637', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/392187/']}
jdg_83264
stackexchange
llm_judgeable_groundtruth_similarity
2113275
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Find $f:\mathbb{R}\to\mathbb{R}$, such that $f$ is continuous at $0$ and $f(2x)-f(x)=x^2$ for all $x\in\mathbb{R}$. Now provide the response and nothing else.
Given $$f(2x)-f(x)=x^2$$we can form $$f(x)-f(x/2)=\left(\frac{x}{2^1}\right)^2\\f(x/2)-f(x/4)=\left(\frac{x}{2^2}\right)^2\\.\\.\\.\\f(x/2^{n-1})-f(x/2^n)=\left(\frac{x}{2^n}\right)^2$$ Adding above equations telescopically as $n\to\infty$ gives $$\begin{align}f(x)&=f(0)+x^2\cdot\frac{(\frac{1}{2})^2}{1-(\frac{1}{2})^2}\\&=\frac{1}{3}\cdot x^2 +f(0)\end{align}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2113275', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/386934/']}
jdg_83265
stackexchange
llm_judgeable_groundtruth_similarity
52523724
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 very strange situation I don't understand. Below is the case simplified: double? d = 2;int? i = 2;Console.WriteLine(d.Equals((2))); // falseConsole.WriteLine(i.Equals((2))); // true I don't understand why one expression will net me true and another false. They seem identical. Now provide the response and nothing else.
You are completely right to find this confusing. It is a mess. Let's start by clearly saying what happens by looking at more examples, and then we will deduce the correct rules that are being applied here. Let's extend your program to consider all these cases: double d = 2; double? nd = d; int i = 2; int? ni = i; Console.WriteLine(d == d); Console.WriteLine(d == nd); Console.WriteLine(d == i); Console.WriteLine(d == ni); Console.WriteLine(nd == d); Console.WriteLine(nd == nd); Console.WriteLine(nd == i); Console.WriteLine(nd == ni); Console.WriteLine(i == d); Console.WriteLine(i == nd); Console.WriteLine(i == i); Console.WriteLine(i == ni); Console.WriteLine(ni == d); Console.WriteLine(ni == nd); Console.WriteLine(ni == i); Console.WriteLine(ni == ni); Console.WriteLine(d.Equals(d)); Console.WriteLine(d.Equals(nd)); Console.WriteLine(d.Equals(i)); Console.WriteLine(d.Equals(ni)); // False Console.WriteLine(nd.Equals(d)); Console.WriteLine(nd.Equals(nd)); Console.WriteLine(nd.Equals(i)); // False Console.WriteLine(nd.Equals(ni)); // False Console.WriteLine(i.Equals(d)); // False Console.WriteLine(i.Equals(nd)); // False Console.WriteLine(i.Equals(i)); Console.WriteLine(i.Equals(ni)); Console.WriteLine(ni.Equals(d)); // False Console.WriteLine(ni.Equals(nd)); // False Console.WriteLine(ni.Equals(i)); Console.WriteLine(ni.Equals(ni)); All of those print True except the ones I have notated as printing false. I'll now give an analysis of those cases. The first thing to notice is that the == operator always says True . Why is that? The semantics of non-nullable == are as follows: int == int -- compare the integersint == double -- convert the int to double, compare the doublesdouble == int -- samedouble == double -- compare the doubles So in every non-nullable case, integer 2 is equal to double 2.0 because the int 2 is converted to double 2.0, and the comparison is true. The semantics of nullable == are: If both operands are null, they're equal If one is null and the other is not, they're unequal If both are not null, then fall back to the non-nullable case above. So again, we see that for the nullable comparisons, int? == double? , int? == double , and so on, we always fall back to the non-nullable cases, convert the int? to double , and do the comparison in doubles. Thus these are also all true. Now we come to Equals , which is where things get messed up. There is a fundamental design problem here, which I wrote about in 2009: https://blogs.msdn.microsoft.com/ericlippert/2009/04/09/double-your-dispatch-double-your-fun/ -- the problem is that the meaning of == is resolved based on the compile time types of both operands . But Equals is resolved on the basis of the run time type of the left operand (the receiver), but the compile time type of the right operand (the argument), and that's why things go off the rails. Let's begin by looking at what double.Equals(object) does. If the receiver of a call to Equals(object) is double then if the argument is not a boxed double, they are considered not equal . That is, Equals requires that the types match , whereas == requires that the types be convertible to a common type . I'll say that again. double.Equals does not try to convert its argument to double, unlike == . It just checks to see if it already is double, and if it is not, then it says they are not equal. That then explains why d.Equals(i) is false... but... wait a minute, it is not false above! What explains this? double.Equals is overloaded! Above we are actually calling double.Equals(double) , which -- you guessed it -- converts the int to a double before doing the call! If we had said d.Equals((object)i)) then that would be false. All right, so we know why double.Equals(int) is true -- because the int is converted to double. We also know why double.Equals(int?) is false. int? is not convertible to double, but it is to object . So we call double.Equals(object) and box the int , and now its not equal. What about nd.Equals(object) ? The semantics of that is: If the receiver is null and the argument is null, they are equal If the receiver is not null then defer to the non-nullable semantics of d.Equals(object) So now we know why nd.Equals(x) works if x is a double or double? but not if it is int or int? . (Though interestingly, of course (default(double?)).Equals(default(int?)) would be true since they are both null!) Finally, by similar logic we see why int.Equals(object) gives the behaviour it has. It checks to see if its argument is a boxed int, and if it is not, then it returns false. Thus i.Equals(d) is false. The i cannot be converted to double, and the d cannot be converted to int. This is a huge mess . We would like equality to be an equivalence relation , and it is not! An equality relationship should have these properties: Reflexivity: a thing is equal to itself. That is usually true in C# though there are a few exceptions. Symmetry: If A is equal to B then B is equal to A. That is true of == in C# but not of A.Equals(B) , as we've seen. Transitivity: If A equals B and B equals C then A also equals C. That is absolutely not the case in C#. So, its a mess on all levels. == and Equals have different dispatch mechanisms and give different results, neither of them are equivalence relations, and it's all confusing all the time. Apologies for getting you into this mess, but it was a mess when I arrived. For a slightly different take on why equality is terrible in C#, see item number nine on my list of regrettable language decisions, here: http://www.informit.com/articles/article.aspx?p=2425867 BONUS EXERCISE: Repeat the above analysis, but for x?.Equals(y) for the cases where x is nullable. When do you get the same results as for non-nullable receivers, and when do you get different results?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52523724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1658153/']}
jdg_83266
stackexchange
llm_judgeable_groundtruth_similarity
10577
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 need a VM Hypervisor that will not leak to the guest that its in a VM. The guest should believe its on a full physical machine. Apparently VirtualBox fails at this , along with Virtual PC and VMWare . Before I dive into monsters like Xen, is there any hyperviosr that can do this? Now provide the response and nothing else.
Xen , by definition, is virtualized. It assumes a specific guest code for the operating system kernel. It does not try to hide the presence of virtualization, it actually advertises it plainly. This is not the VM you are looking for. A fully invisible hypervisor is theoretically feasible, but not cheap. The problem is with timing. An hypervisor works by being able to intercept some "sensitive operations", notably related to memory access, and alter their behaviour. The alteration is done with software, which can effectively remain hidden by blocking some memory accesses, emulating an absence of RAM instead. However, such an interception takes a bit of time: handling of an intercepted memory access will use some extra clock cycles over what a non-intercepted call on "raw hardware" would do. Since code can access a clock with clock-cycle precision (not accuracy) through the rdtsc opcode, interception can be detected. Unless the rdtsc opcode is also intercepted, to make it "slower". In effect, our invisible hypervisor can remain invisible only by "slowing down" the virtual machine, so that it gets enough hidden "extra cycles" for its interceptions. So the guest OS must: either have access to no external time source (and, if the guest OS has some network, it can access external time sources); or believe that the hardware is clocked at a lower rate than what the physical hardware really runs at. As an extreme case, consider emulators . Emulators for older, 1980s-era systems can have clock-cycle accuracy, i.e. make the emulation so perfect that the code running in it is not capable of detecting that it does not run on the genuine hardware. But they can do that only by throwing a lot of computational power at it; the overhead is tremendous (we are talking about a 10x or 20x loss of computing power here). Moreover, emulating timing effects for an Atari ST is a relatively simple task because there is no cache in such a machine. The Blue Pill is a demonstration of such a so-called "invisible hypervisor", and it generated some hot debate (as they say, "with more heat than light"), mostly because there is no equality between skills at assembly system programming, and capacity to explain things to other people with pedagogy and serenity. Nevertheless, the "blue pill" should be detectable, although finding actual code which does it, published on the Web, might be challenging. An interesting point raised by the blue pill developer is that hypervisors are supposed to become mainstream and "normal", so that the presence of an hypervisor should not, in the long run , indicate that virtualization is occurring. It is conceivable, and even probable, that future operating systems will always activate an hypervisor upon boot time, so detecting that virtualization is in place would no longer indicate possible foul play. We have not reached that point yet, though.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/10577', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/176/']}
jdg_83267
stackexchange
llm_judgeable_groundtruth_similarity
32249389
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 database in Firebird 2.5 filled with data.I need to change the character set from UTF-8 to ISO8859_1 , I tried: alter database default character set ISO8859_1 collation ES_ES But it doesn't work. How can I convert the character set? Now provide the response and nothing else.
Changing the default character set only affects columns created (without an explicit character set) after the change. Existing columns are unaffected as the character set is a property of each individual column. This means that you have to alter all (relevant) columns. There are several problems Firebird doesn't change the data at alter time, but instead creates a new format version, and converting on the fly from the old format to the new format at select time. This has a performance impact, but can also result in string conversion errors at runtime (eg because an UTF-8 character doesn't exist in ISO-8859-1). Changing the character set only works correctly if the column currently has a real character set (ie other than NONE or OCTETS ).Conversion from NONE or OCTETS to another character set may result in string conversion errors, or garbage because the content may not match your expectations, or maybe invalid bytes in the target character set. Some versions - iirc - don't actually change the character set at all To address these problems you can do: Export the DDL of your database, change character set definitions, create a new database and use a data pump tool (like FBCopy) to copy the data from the old to the new or, for each column you want to change: Create a new column UPDATE table SET newcolumn = oldcolumn (or if oldcolumn is NONE or OCTETS : UPDATE table SET newcolumn = cast(cast(oldcolumn as VARCHAR(...) CHARACTER SET assumedcharset) as VARCHAR(...) CHARACTER SET targetcharset) Drop old column Rename the new column Fix any other dependency problems (indexes, triggers, foreign keys, etc) This second option is only preferable if you want to change a small database (in terms of tables, columns and dependencies) or you need to perform odd conversions, otherwise I'd strongly suggest to use the data pumping solution.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32249389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4287167/']}
jdg_83268
stackexchange
llm_judgeable_groundtruth_similarity
37954625
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using NiFi v0.6.1 is there a way to import backups/archives? And by backups I mean the files that are generated when you call POST /controller/archive using the REST api or "Controller Settings" (tool bar button) and then "Back-up flow" (link). I tried unzipping the backup and importing it as a template but that didn't work. But after comparing it to an exported template file, the formats are reasonably different. But perhaps there is a way to transform it into a template? At the moment my current work around is to not select any components on the top level flow and then select "create template"; which will add a template with all my components. Then I just export that. My issue with this is it's a bit more tricky to automate via the REST API. I used Fiddler to determine what the UI is doing and it first generates a snippet that includes all the components (labels, processors, connections, etc.). Then it calls create template ( POST /nifi-api/contorller/templates ) using the snippet ID. So the template call is easy enough but generating the definition for the snippet is going to take some work. Note: Once the following feature request is implemented I'm assuming I would just use that instead: https://cwiki.apache.org/confluence/display/NIFI/Configuration+Management+of+Flows Now provide the response and nothing else.
The entire flow for a NiFi instance is stored in a file called flow.xml.gz in the conf directory (flow.xml.tar in a cluster). The back-up functionality is essentially taking a snapshot of that file at the given point in time and saving it to the conf/archive directory. At a later point in time you could stop NiFi and replace conf/flow.xml.gz with one of those back-ups to restore the flow to that state. Templates are a different format from the flow.xml.gz. Templates are more public facing and shareable, and can be used to represent portions of a flow, or the entire flow if no components are selected. Some people have used templates as a model to deploy their flows, essentially organizing their flow into process groups and making template for each group. This project provides some automation to work with templates: https://github.com/aperepel/nifi-api-deploy
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37954625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3483050/']}
jdg_83269
stackexchange
llm_judgeable_groundtruth_similarity
7868218
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 reading Pro C# 2010 and the .Net 4 Platform by Andrew Troelsen. In Chapter 15 about Attributes exists a note: Note: For security reasons, it is considered a .Net best practice to design all custom attributes as sealed. The author doesn't explain why, can someone explain why? Now provide the response and nothing else.
CA1813: Avoid unsealed attributes: The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy; for example Attribute.GetCustomAttribute searches for the specified attribute type, or any attribute type that extends the specified attribute type. Sealing the attribute eliminates the search through the inheritance hierarchy, and can improve performance. Ref: https://learn.microsoft.com/visualstudio/code-quality/ca1813-avoid-unsealed-attributes Attributes are simply metadata discovered at runtime. As it is quoted, if someone else derives from your custom attribute class, by default .NET will find them too, which may imply a security risk if the derived attribute class is modifying the behavior of your original attribute in a way to you never intended to. Even though performance is the prime reason to seal attribute classes, here is a formidable article dealing with its security side .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7868218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492460/']}
jdg_83270
stackexchange
llm_judgeable_groundtruth_similarity
13402782
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 showing a DialogFragment when the user taps on a row in a ListView . I'd like to animate the showing of the dialog so that it grows from the center of the row. A similar effect can be seen when opening a folder from the launcher. One idea that I've had is a combination of TranslateAnimation and ScaleAnimation . Is there another way? Now provide the response and nothing else.
Being DialogFragment a wrapper for the Dialog class, you should set a theme to your base Dialog to get the animation you want: public class CustomDialogFragment extends DialogFragment implements OnEditorActionListener{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Set a theme on the dialog builder constructor! AlertDialog.Builder builder = new AlertDialog.Builder( getActivity(), R.style.MyCustomTheme ); builder .setTitle( "Your title" ) .setMessage( "Your message" ) .setPositiveButton( "OK" , new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); }} Then you just need to define the theme that will include your desired animation. In styles.xml add your custom theme: <style name="MyCustomTheme" parent="@android:style/Theme.Panel"> <item name="android:windowAnimationStyle">@style/MyAnimation.Window</item></style><style name="MyAnimation.Window" parent="@android:style/Animation.Activity"> <item name="android:windowEnterAnimation">@anim/anim_in</item> <item name="android:windowExitAnimation">@anim/anim_out</item></style> Now add the animation files in the res/anim folder: ( the android:pivotY is the key ) anim_in.xml <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <scale android:interpolator="@android:anim/linear_interpolator" android:fromXScale="0.0" android:toXScale="1.0" android:fromYScale="0.0" android:toYScale="1.0" android:fillAfter="false" android:startOffset="200" android:duration="200" android:pivotX = "50%" android:pivotY = "-90%" /> <translate android:fromYDelta="50%" android:toYDelta="0" android:startOffset="200" android:duration="200" /></set> anim_out.xml <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <scale android:interpolator="@android:anim/linear_interpolator" android:fromXScale="1.0" android:toXScale="0.0" android:fromYScale="1.0" android:toYScale="0.0" android:fillAfter="false" android:duration="200" android:pivotX = "50%" android:pivotY = "-90%" /> <translate android:fromYDelta="0" android:toYDelta="50%" android:duration="200" /></set> Finally, the tricky thing here is to get your animation grow from the center of each row. I suppose the row is filling the screen horizontally so, on one hand the android:pivotX value will be static. On the other hand, you can't modify the android:pivotY value programmatically. What I suggest is, you define several animations each of which having a different percentage value on the android:pivotY attribute (and several themes referencing those animations). Then, when the user taps the row, calculate the Y position in percentage of the row on the screen. Knowing the position in percentage, assign a theme to your dialog that has the appropriate android:pivotY value. It is not a perfect solution but could do the trick for you. If you don't like the result, then I would suggest forgetting the DialogFragment and animating a simple View growing from the exact center of the row. Good luck!
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13402782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111777/']}
jdg_83271
stackexchange
llm_judgeable_groundtruth_similarity
46815821
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 following snippet of code that assigned nullptr to bool type. #include <iostream>int main(){ bool b = nullptr; std::cout << b;} In clang 3.8.0 working fine. it's give an output 0 . Clang Demo But g++ 5.4.0 give an error: source_file.cpp: In function ‘int main()’:source_file.cpp:5:18: error: converting to ‘bool’ from ‘std::nullptr_t’ requires direct-initialization [-fpermissive] bool b = nullptr; Which compiler is correct? Now provide the response and nothing else.
From the C++ Standard (4.12 Boolean conversions) 1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false. So this declaration bool b( nullptr ); is valid and this bool b = nullptr; is wrong. I myself pointed out already this problem at isocpp
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46815821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5612562/']}
jdg_83272
stackexchange
llm_judgeable_groundtruth_similarity
12553570
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The methods of RestTemplate such as postForEntity() throw RestClientException . I would like to extract the HTTP status code and response body from that exception object in the catch block. How can I do that? Now provide the response and nothing else.
Instead of catching RestClientException , catch the special HttpClientErrorException . Here's an example: try { Link dataCenterLink = serviceInstance.getLink("dataCenter"); String dataCenterUrl = dataCenterLink.getHref(); DataCenterResource dataCenter = restTemplate.getForObject(dataCenterUrl, DataCenterResource.class); serviceInstance.setDataCenter(dataCenter);} catch (HttpClientErrorException e) { HttpStatus status = e.getStatusCode(); if (status != HttpStatus.NOT_FOUND) { throw e; }} HttpClientErrorException provides getStatusCode and getResponseBodyAsByteArray to get the status code and body, respectively.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12553570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1692496/']}
jdg_83273
stackexchange
llm_judgeable_groundtruth_similarity
22791071
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The multiple nested views functionality of the ui-router is very nice - you can easily jump from one state of your app to another. Sometimes you might want to change the URL, but sometimes not. I feel like the concept of state should be separate/optional from routing . Here's a plunker that shows what I mean. This is a fork of one of the plunkers in the ui-router documentation, with 2 minor changes noted below: .state('route1', { url: "/route", // <---- URL IS SHARED WITH ROUTE2 views: { "viewA": { template: "route1.viewA" }, "viewB": { template: "route1.viewB" } } }) .state('route2', { url: "/route", // <---- URL IS SHARED WITH ROUTE1 views: { "viewA": { template: "route2.viewA" }, "viewB": { template: "route2.viewB" } } }) This seems to work - the URL stays the same. Again, how much redundant work is done here? Is this an approved/tested usage? It would be nice if you could omit the url from a state.. UPDATE: You can omit a url from a state. plunker Update question: Is this an approved/tested usage? Now provide the response and nothing else.
You can absolutely have a state without a URL. In fact, none of your states need URLs. That's a core part of the design. Having said that, I wouldn't do what you did above. If you want two states to have the same URL, create an abstract parent state , assign a URL to it, and make the two states children of it (with no URL for either one).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22791071', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015232/']}
jdg_83274
stackexchange
llm_judgeable_groundtruth_similarity
3684367
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to read a single character at-a-time from the command line in PHP, however it seems as though there is some kind of input buffering from somewhere preventing this. Consider this code: #!/usr/bin/php<?phpecho "input# ";while ($c = fread(STDIN, 1)) { echo "Read from STDIN: " . $c . "\ninput# ";}?> Typing in "foo" as the input (and pressing enter), the output I am getting is: input# fooRead from STDIN: finput# Read from STDIN: oinput# Read from STDIN: oinput# Read from STDIN: input# The output I am expecting is: input# finput# Read from STDIN: finput# oinput# Read from STDIN: oinput# oinput# Read from STDIN: oinput# input# Read from STDIN: input# (That is, with characters being read and processed as they are typed). However, currently, each character is being read only after enter is pressed. I have a suspicion the TTY is buffering the input. Ultimately I want to be able to read keypresses such as UP arrow, DOWN arrow, etc. Now provide the response and nothing else.
The solution for me was to set -icanon mode on the TTY (using stty ). Eg.: stty -icanon So, the the code that now works is: #!/usr/bin/php<?phpsystem("stty -icanon");echo "input# ";while ($c = fread(STDIN, 1)) { echo "Read from STDIN: " . $c . "\ninput# ";}?> Output: input# fRead from STDIN: finput# oRead from STDIN: oinput# oRead from STDIN: oinput# Read from STDIN: input# Props to the answer given here: Is there a way to wait for and get a key press from a (remote) terminal session? For more information, see: http://www.faqs.org/docs/Linux-HOWTO/Serial-Programming-HOWTO.html#AEN92 Don't forget to restore the TTY when you're done with it... Restoring the tty configuration Resetting the terminal back to the way it was can be done by saving the tty state before you make changes to it. You can then restore to that state when you're done. For example: <?php// Save existing tty configuration$term = `stty -g`;// Make lots of drastic changes to the ttysystem("stty raw opost -ocrnl onlcr -onocr -onlret icrnl -inlcr -echo isig intr undef");// Reset the tty back to the original configurationsystem("stty '" . $term . "'");?> This is the only way to preserve the tty and put it back how the user had it before you began. Note that if you're not worried about preserving the original state, you can reset it back to a default "sane" configuration simply by doing: <?php// Make lots of drastic changes to the ttysystem("stty raw opost -ocrnl onlcr -onocr -onlret icrnl -inlcr -echo isig intr undef");// Reset the tty back to sane defaultssystem("stty sane");?>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3684367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/417083/']}
jdg_83275
stackexchange
llm_judgeable_groundtruth_similarity
18841952
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Since with help of const_cast anyone can modify my declared constant object - what use is the const qualifier? I mean how can someone ensure that what he declared const is not going to be modified anyway? Now provide the response and nothing else.
You are right, uses of const_cast often indicates a design flaw, or an API that is out of your control. However, there is an exception, it's useful in the context of overloaded functions. I'm quoting an example from the book C++ Primer : // return a reference to the shorter of two stringsconst string &shorterString(const string &s1, const string &s2){ return s1.size() <= s2.size() ? s1 : s2;} This function takes and returns references to const string . We can call the function on a pair of non-const string arguments, but we’ll get a reference to a const string as the result. We might want to have a version of shorterString that, when given non-const arguments, would yield a plain reference. We can write this version of our function using a const_cast : string &shorterString(string &s1, string &s2){ auto &r = shorterString(const_cast<const string&>(s1), const_cast<const string&>(s2)); return const_cast<string&>(r);} This version calls the const version of shorterString by casting its arguments to references to const . That function returns a reference to a const string , which weknow is bound to one of our original, non-const arguments. Therefore, we know it is safe to cast that string back to a plain string& in the return.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18841952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2786097/']}
jdg_83276
stackexchange
llm_judgeable_groundtruth_similarity
39981650
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 limit the size of the batches returned by the Kafka consumer for Spark Streaming? I am asking because the first batch I get has hundred of millions of records and it takes ages to process and checkpoint them. Now provide the response and nothing else.
I think your problem can be solved by Spark Streaming Backpressure . Check spark.streaming.backpressure.enabled and spark.streaming.backpressure.initialRate . By default spark.streaming.backpressure.initialRate is not set and spark.streaming.backpressure.enabled is disabled by default so I suppose spark will take as much as he can. From Apache Spark Kafka configuration spark.streaming.backpressure.enabled : This enables the Spark Streaming to control the receiving rate based on the current batch scheduling delays and processing times so that the system receives only as fast as the system can process. Internally, this dynamically sets the maximum receiving rate of receivers. This rate is upper bounded by the values spark.streaming.receiver.maxRate and spark.streaming.kafka.maxRatePerPartition if they are set (see below). And since you want to control first batch, or to be more specific - number of messages in first batch, I think you need spark.streaming.backpressure.initialRate spark.streaming.backpressure.initialRate : This is the initial maximum receiving rate at which each receiver will receive data for the first batch when the backpressure mechanism is enabled. This one is good when your Spark job (respectively Spark workers at all) is able to process let say 10000 messages from kafka, but kafka brokers give to your job 100000 messages. Maybe you will be also interested to check spark.streaming.kafka.maxRatePerPartition and also some research and suggestions for these properties on real example by Jeroen van Wilgenburg on his blog .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39981650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/604041/']}
jdg_83277
stackexchange
llm_judgeable_groundtruth_similarity
45929493
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 Node.js, is there a maximum safe floating-point number like Number.MAX_SAFE_INTEGER ? I had a little experiment to find out the (approximate) number I can use for subtracting 0.13 from it: console.log(Math.floor(Number.MAX_SAFE_INTEGER)); // 9007199254740991console.log(Math.floor(Number.MAX_SAFE_INTEGER)-0.13); // 9007199254740991console.log(Math.floor(Number.MAX_SAFE_INTEGER/2)); // 4503599627370495console.log(Math.floor(Number.MAX_SAFE_INTEGER/2)-0.13); // 4503599627370495console.log(Math.floor(Number.MAX_SAFE_INTEGER/4)); // 2251799813685247console.log(Math.floor(Number.MAX_SAFE_INTEGER/4)-0.13); // 2251799813685246.8console.log(Math.floor(Number.MAX_SAFE_INTEGER/64)); // 140737488355327console.log(Math.floor(Number.MAX_SAFE_INTEGER/64)-0.13); // 140737488355326.88console.log(Math.floor(Number.MAX_SAFE_INTEGER/128)); // 70368744177663console.log(Math.floor(Number.MAX_SAFE_INTEGER/128)-0.13); // 70368744177662.87 My guess is that as the target precision increases, the maximum value decreases. Now provide the response and nothing else.
To a precision of 1 decimal digits, the maximum number you can work with is 562949953421311 . To a precision of 2 decimal digits, it's 70368744177663 .Interestingly, the first number is equal to: (Number.MAX_SAFE_INTEGER + 1) / 16 - 1 And the second number is equal to: (Number.MAX_SAFE_INTEGER + 1) / 128 - 1 What we're looking for , is the maximum safe number to support a precision of d digits after the decimal point.By "support" I mean "can reliably do basic arithmetic". For example, we know that Number.MAX_SAFE_INTEGER (aka 2**53-1) is not safe, because basic arithmetic is broken: Number.MAX_SAFE_INTEGER - 0.1 === Number.MAX_SAFE_INTEGER>>> true // unsafe And we know that 0 is safe, since: 0 + 0.1 === 0>>> false // safe BTW, 0 is reliable as far as 1e-323 (including): 0 + 1e-323 === 0>>> false // safe0 + 1e-324 === 0>>> true // unsafe I binary-searched between 0 and Number.MAX_SAFE_INTEGER for the biggest number that answers that definition, and came up with these numbers. Here's the code (pass any other number to findMaxSafeFloat() at the end of snippet) /**Returns whether basic arithmetic breaks between n and n+1, to a precision of `digits` after the decimal point*/function isUnsafe(n, digits) { // digits = 1 loops 10 times with 0.1 increases. // digits = 2 means 100 steps of 0.01, and so on. let prev = n; for (let i = 10 ** -digits; i < 1; i += 10 ** -digits) { if (n + i === prev) { // eg 10.2 === 10.1 return true; } prev = n + i; } return false;}/**Binary search between 0 and Number.MAX_SAFE_INTEGER (2**53 - 1) for the biggest number that is safe to the `digits` level of precision. * digits=9 took ~30s, I wouldn't pass anything bigger.*/function findMaxSafeFloat(digits, log = false) { let n = Number.MAX_SAFE_INTEGER; let lastSafe = 0; let lastUnsafe = undefined; while (true) { if (log) { console.table({ '': { n, 'Relative to Number.MAX_SAFE_INTEGER': `(MAX + 1) / ${(Number.MAX_SAFE_INTEGER + 1) / (n + 1)} - 1`, lastSafe, lastUnsafe, 'lastUnsafe - lastSafe': lastUnsafe - lastSafe } }); } if (isUnsafe(n, digits)) { lastUnsafe = n; } else { // safe if (lastSafe + 1 === n) { // Closed in as far as possible console.log(`\n\nMax safe number to a precision of ${digits} digits after the decimal point: ${n}\t((MAX + 1) / ${(Number.MAX_SAFE_INTEGER + 1) / (n + 1)} - 1)\n\n`); return n; } else { lastSafe = n; } } n = Math.round((lastSafe + lastUnsafe) / 2); }}console.log(findMaxSafeFloat(1)); An interesting thing I've found by lining up the safe numbers, is that the exponents don't step up in a consistent manner.Look at the table below; once in a while, the exponent increases (or decreases) by 4, and not 3. Not sure why. | Precision | First UNsafe | 2^53/x ||-----------|-----------------------------|--------------------------|| 1 | 5,629,499,534,21,312 = 2^49 | x = 16 = 2^4 || 2 | 703,687,441,77,664 = 2^46 | x = 128 = 2^7 || 3 | 87,960,930,22,208 = 2^43 | x = 1,024 = 2^10 || 4 | 5,497,558,13,888 = 2^39 | x = 16,384 = 2^14 || 5 | 68,719,476,736 = 2^36 | x = 131,072 = 2^17 || 6 | 8,589,934,592 = 2^33 | x = 1,048,576 = 2^20 || 7 | 536,870,912 = 2^29 | x = 16,777,216 = 2^24 || 8 | 67,108,864 = 2^26 | x = 134,217,728 = 2^27 || 9 | 8,388,608 = 2^23 | x = 1,073,741,824 = 2^30 |
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45929493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2708763/']}
jdg_83278
stackexchange
llm_judgeable_groundtruth_similarity
12182701
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wrote this code for generating Continued Fraction of a square root N. But it fails when N = 139. The output should be {11,1,3,1,3,7,1,1,2,11,2,1,1,7,3,1,3,1,22} Whilst my code gives me a sequence of 394 terms... of which the first few terms are correct but when it reaches 22 it gives 12! Can somebody help me with this? vector <int> f;int B;double A;A = sqrt(N*1.0);B = floor(A);f.push_back(B); while (B != 2 * f[0])) { A = 1.0 / (A - B); B =floor(A); f.push_back(B); }f.push_back(B); Now provide the response and nothing else.
The root problem is that you cannot exactly represent the square root of a non-square as a floating-point number. If ξ is the exact value and x the approximation (which is supposed to be still quite good, so that in particular floor(ξ) = a = floor(x) still holds), then the difference after the next step of the continued fraction algorithm is ξ' - x' = 1/(ξ - a) - 1/(x - a) = (x - ξ) / ((ξ - a)*(x - a)) ≈ (x - ξ) / (ξ - a)^2 Thus we see that in each step the absolute value of the difference between the approximation and the real value increases, since 0 < ξ - a < 1 . Every time a large partial quotient occurs ( ξ - a is close to 0), the difference increases by a large factor. Once (the absolute value of) the difference is 1 or greater, the next computed partial quotient is guaranteed to be wrong, but very probably the first wrong partial quotient occurs earlier. Charles mentioned the approximation that with an original approximation with n correct digits, you can compute about n partial quotients of the continued fraction. That is a good rule of thumb, but as we saw, any large partial quotients cost more precision and thus reduce the number of obtainable partial quotients, and occasionally you get wrong partial quotients much earlier. The case of √139 is one with a relatively long period with a couple of large partial quotients, so it's not surprising that the first wrongly computed partial quotient appears before the period is completed (I'm rather surprised that it doesn't occur earlier). Using floating-point arithmetic, there's no way to prevent that. But for the case of quadratic surds, we can avoid that problem by using integer arithmetic only. Say you want to compute the continued fraction expansion of ξ = (√D + P) / Q where Q divides D - P² and D > 1 is not a perfect square (if the divisibility condition is not satisfied, you can replace D with D*Q² , P with P*Q and Q with Q² ; your case is P = 0, Q = 1 , where it is trivially satisfied). Write the complete quotients as ξ_k = (√D + P_k) / Q_k (with ξ_0 = ξ, P_0 = P, Q_0 = Q) and denote the partial quotients a_k . Then ξ_k - a_k = (√D - (a_k*Q_k - P_k)) / Q_k and, with P_{k+1} = a_k*Q_k - P_k , ξ_{k+1} = 1/(ξ_k - a_k) = Q_k / (√D - P_{k+1}) = (√D + P_{k+1}) / [(D - P_{k+1}^2) / Q_k], so Q_{k+1} = (D - P_{k+1}^2) / Q_k — since P_{k+1}^2 - P_k^2 is a multiple of Q_k , by induction Q_{k+1} is an integer and Q_{k+1} divides D - P_{k+1}^2 . The continued fraction expansion of a real number ξ is periodic if and only if ξ is a quadratic surd, and the period is completed when in the above algorithm, the first pair (P_k, Q_k) repeats. The case of pure square roots is particularly simple, the period is completed when first Q_k = 1 for a k > 0 , and P_k, Q_k are always nonnegative. With R = floor(√D) , the partial quotients can be calculated as a_k = floor((R + P_k) / Q_k) so the code for the above algorithm becomes std::vector<unsigned long> sqrtCF(unsigned long D) { // sqrt(D) may be slightly off for large D. // If large D are expected, a correction for R is needed. unsigned long R = floor(sqrt(D)); std::vector<unsigned long> f; f.push_back(R); if (R*R == D) { // Oops, a square return f; } unsigned long a = R, P = 0, Q = 1; do { P = a*Q - P; Q = (D - P*P)/Q; a = (R + P)/Q; f.push_back(a); }while(Q != 1); return f;} which easily calculates the continued fraction of (e.g.) √7981 with a period length of 182.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12182701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1508640/']}
jdg_83279
stackexchange
llm_judgeable_groundtruth_similarity
33708197
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given that uglification involves some minification in the process, does it still make sense to do both minify and uglify? If yes, should one minify or uglify first? Is it enough to do uglify only? Will the code be more obfuscated if both are done? Now provide the response and nothing else.
There is no real distinction between the two. Even Uglify calls itself a minification toolkit. The distinction could be more relevant when comparing JS minification to CSS minification - CSS minification involves only removing whitespace - the original code remains intact. With JS it is possible to not only remove whitespace, but also to make transformations to the code, such as truncating variable names to single characters. Minifying JavaScript not only makes the source smaller, it also makes the code less readable, or obfuscates it. But do not operate under the assumption that minification or uglification, or whatever you want to call it, is a security measure. It isn't encryption. The code is harder to read, but not impossible to read, and while it's not usually possible to return minified code back to its original form, it is possible to 'beautify' it and make it more readable. It doesn't make sense to both minify and uglify because most minifiers will both remove whitespace and unnecessary characters, as well as obfuscate the code. All you're doing is introducing another build step.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33708197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1709088/']}
jdg_83280
stackexchange
llm_judgeable_groundtruth_similarity
64411
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: What's the best way to check if an SMTP server is SSL-enabled or not? Follow-up question: How do I make it SSL-enabled if it's not yet SSL-enabled. The OS is CentOS. Now provide the response and nothing else.
That depends whether you mean SSL or TLS. SSL has it's own dedicated port at TCP/465. The best way to test for it's presence would be to use OpenSSL's wonderful s_client which will negotiate the SSL trickery for you. openssl s_client -connect localhost:465 If your server isn't bound to localhost then obviously replace that with the IP or hostname. TLS looks just like normal SMTP at first. The encryption is negotiated from and on-top of the plain-text protocol. You can test whether it is available by issuing an EHLO request to the server. You can use Netcat or Telnet clients for this. $ nc -v localhost 25 localhost [127.0.0.1] 25 (smtp) open 220 mail.example.com ESMTP Exim 4.69 Fri, 11 Sep 2009 09:25:20 +0100 ehlo test 250-mail.example.com Hello localhost [127.0.0.1] 250-SIZE 10485760 250-PIPELINING 250-STARTTLS 250 HELP The important line is second from last ( 250-STARTTLS ) which advertises the STARTTLS capability. In order to say how to enable SSL/TLS for your mail server you'll need to tell us what mail package you're using.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/64411', 'https://serverfault.com', 'https://serverfault.com/users/14037/']}
jdg_83281
stackexchange
llm_judgeable_groundtruth_similarity
19030115
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 import a sub-module programmatically. My file tree looks like this: oopsd/__init__.pyoopsd/oopsd.pyoopsd/driver/__init__.pyoopsd/driver/optiups.py The optiups.py simply prints "Hello World". The oopsd.py looks like this: import importlibimportlib.import_module('oopsd.driver.optiups') Now with this, I'm getting this exception: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1521, in _find_and_load_unlockedAttributeError: 'module' object has no attribute '__path__'During handling of the above exception, another exception occurred:Traceback (most recent call last): File "oopsd/oopsd.py", line 29, in <module> sys.exit(main()) File "oopsd/oopsd.py", line 23, in main loaddriver() File "oopsd/oopsd.py", line 26, in loaddriver importlib.import_module('oopsd.driver.optiups') File "/usr/lib/python3.3/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1586, in _gcd_import File "<frozen importlib._bootstrap>", line 1567, in _find_and_load File "<frozen importlib._bootstrap>", line 1514, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 313, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1586, in _gcd_import File "<frozen importlib._bootstrap>", line 1567, in _find_and_load File "<frozen importlib._bootstrap>", line 1524, in _find_and_load_unlockedImportError: No module named 'oopsd.driver'; oopsd is not a package Does __path__ even still exist in Python 3? I also tried importing .driver.optiups instead, but this yields: TypeError: relative imports require the 'package' argument __package__ seems unset, so I'm lost. How do I do this the right way? Now provide the response and nothing else.
This is an old question, but since it was bumped, the other answer is totally wrong, and this is a common problem: You're probably doing this. python oopsd/oopsd.py Don't do this. :) Specifically, NEVER try to directly run a file that's part of a parent package. When you run python FILENAME , Python adds the file's containing directory to sys.path , and DOESN'T add the current directory. So you have oopsd/ in your path, and every module in oopsd/ just became a top-level module. Python has no way of even knowing that any of them are supposed to have an oopsd. prefix, because the parent directory doesn't exist anywhere in sys.path . If you want to execute a module directly, do this: python -m oopsd.oopsd This puts the current directory in sys.path and ensures that imports of your source tree work as you'd expect them to. Alex Z's answer is wrong because it doesn't actually fix this problem, and it's not a relative import — implicit relative imports no longer exist in Python 3.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19030115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2085149/']}
jdg_83282
stackexchange
llm_judgeable_groundtruth_similarity
514025
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 do I demonstrate the relationship between the Beta and the Gamma function, in the cleanest way possible? I am thinking one (or two) substitution of variables is necessary, but when and how is the question. Here is the beta function: $B(\alpha,\beta)=\int_0^1x^{\alpha-1}(1-x)^{\beta-1}dx$. Here is the gamma function $\Gamma(\alpha)=\int_0^{\infty}t^{\alpha-1}e^{-t}dt$. Here is the relationship between the Beta and Gamma functions: $B(\alpha,\beta)=\frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}$. Thanks for any help! Now provide the response and nothing else.
Compute the double integral$$\Gamma(\alpha)\Gamma(\beta)=\iint t^{\alpha-1}\mathrm e^{-t}s^{\beta-1}\mathrm e^{-s}\mathrm ds\mathrm dt,$$using the change of variable $x=t/(t+s)$, $y=t+s$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/514025', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_83283
stackexchange
llm_judgeable_groundtruth_similarity
146903
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that a sum of Gaussians is Gaussian. So, how is a mixture of Gaussians different? I mean, a mixture of Gaussians is just a sum of Gaussians (where each Gaussian is multiplied by the respective mixing coefficient) right? Now provide the response and nothing else.
A weighted sum of Gaussian random variables $X_1,\ldots,X_p$$$\sum_{i=1}^p \beta_i X_i$$is a Gaussian random variable : if$$(X_1,\ldots,X_p)\sim\text{N}_p(\mu,\Sigma)$$then$$\beta^\text{T}(X_1,\ldots,X_p)\sim\text{N}_1(\beta^\text{T}\mu,\beta^\text{T}\Sigma\beta)$$ A mixture of Gaussian densities has a density given as a weighted sum of Gaussian densities :$$f(\cdot;\theta)=\sum_{i=1}^p \omega_i \varphi(\cdot;\mu_i,\sigma_i)$$which is almost invariably not equal to a Gaussian density. See e.g. the blue estimated mixture density below (where the yellow band is a measure of variability of the estimated mixture): [Source: Marin and Robert, Bayesian Core , 2007] A random variable with this density, $X\sim f(\cdot;\theta)$ can be represented as $$X=\sum_{i=1}^p \mathbb{I}(Z=i) X_i = X_{Z}$$where $X_i\sim\text{N}_p(\mu_i,\sigma_i)$ and $Z$ is Multinomial with $\mathbb{P}(Z=i)=\omega_i$:$$Z\sim\text{M}(1;\omega_1,\ldots,\omega_p)$$
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/146903', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/66310/']}
jdg_83284
stackexchange
llm_judgeable_groundtruth_similarity
39072235
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 problems with save some values in @Service method.My code: @Service(value = "SettingsService")public class SettingsService {... public String getGlobalSettingsValue(Settings setting) { getTotalEhCacheSize(); if(!setting.getGlobal()){ throw new IllegalStateException(setting.name() + " is not global setting"); } GlobalSettings globalSettings = globalSettingsRepository.findBySetting(setting); if(globalSettings != null) return globalSettings.getValue(); else return getGlobalEnumValue(setting) }@Cacheable(value = "noTimeCache", key = "#setting.name()") public String getGlobalEnumValue(Settings setting) { return Settings.valueOf(setting.name()).getDefaultValue(); } My repository class: @Repositorypublic interface GlobalSettingsRepository extends CrudRepository<GlobalSettings, Settings> { @Cacheable(value = "noTimeCache", key = "#setting.name()", unless="#result == null") GlobalSettings findBySetting(Settings setting); It should work like this: get value form DB if data exist, if not save value from enum. but it didn't save any data from DB or enum. My cache config: @Configuration@EnableCachingpublic class CacheConfig { @Bean public EhCacheCacheManager cacheManager(CacheManager cm) { return new EhCacheCacheManager(cm); } @Bean public EhCacheManagerFactoryBean ehcache() { EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean(); ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml")); return ehCacheManagerFactoryBean; }} I have some example to make sure that cache is working in my project in rest method: @RequestMapping(value = "/system/status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> systemStatus() { Object[] list = userPuzzleRepository.getAverageResponseByDateBetween(startDate, endDate);...}public interface UserPuzzleRepository extends CrudRepository<UserPuzzle, Long> { @Cacheable(value = "averageTimeAnswer", key = "#startDate") @Query("select AVG(case when up.status='SUCCESS' OR up.status='FAILURE' OR up.status='TO_CHECK' then up.solvedTime else null end) from UserPuzzle up where up.solvedDate BETWEEN ?1 AND ?2") Object[] getAverageResponseByDateBetween(Timestamp startDate, Timestamp endDate); and it's work well. What am I doing wwrong? Now provide the response and nothing else.
You have two methods in your SettingsService , one that is cached ( getGlobalEnumValue(...) ) and another one that isn't cached, but calls the other method ( getGlobalSettingsValue(...) ). The way the Spring cache abstraction works however is by proxying your class (using Spring AOP ). However, calls to methods within the same class will not call the proxied logic, but the direct business logic beneath. This means caching does not work if you're calling methods in the same bean. So, if you're calling getGlobalSettingsValue() , it will not populate, nor use the cache when that method calls getGlobalEnumValue(...) . The possible solutions are: Not calling another method in the same class when using proxies Caching the other method as well Using AspectJ rather than Spring AOP, which weaves the code directly into the byte code at compile time, rather than proxying the class. You can switch the mode by setting the @EnableCaching(mode = AdviceMode.ASPECTJ) . However, you'll have to set up load time weaving as well. Autowire the service into your service, and use that service rather than calling the method directly. By autowiring the service, you inject the proxy into your service.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39072235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6051000/']}
jdg_83285
stackexchange
llm_judgeable_groundtruth_similarity
103556
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Is there a unified description (or a set of axioms) of the zeta function of an algebraic curve over a finite field $\mathbb{F}_q$ and the Riemann zeta function? Now provide the response and nothing else.
Let $D$ be a ring which is infinite, not a field, and in which $D/I$ is finite for any nonzero ideal $I$ (what Pete Clark calls a abstract number ring ). Then we can define $N(I) = |D/I|$ and write down a zeta function $$\zeta_D(s) = \sum_{I \neq 0} \frac{1}{N(I)^s}.$$ This specializes to the Riemann zeta function when $D = \mathbb{Z}$ , to the Dedekind zeta function when $D = \mathcal{O}_K$ , and to the zeta function of an affine algebraic curve over a finite field when $D$ is its ring of functions. If $D$ is Dedekind, then unique factorization of ideals gives an Euler product for this zeta function. To get the zeta function of a curve, not necessarily affine, we replace ideals with effective divisors, that is, non-negative formal integer linear combinations $$\sum n_i P_i, n_i \ge 0$$ of points of $C$ over $\overline{\mathbb{F}_q}$ which are $\text{Gal}(\overline{\mathbb{F}_q}/\mathbb{F}_q)$ -invariant, and the appropriate replacement for the norm here is $q^{\sum n_i}$ . This reduces to the above description in the case of a (nonsingular, geometrically integral) affine curve. (The more standard expression for the zeta function of a curve over a finite field, which tells you what the logarithm of the zeta function is in terms of counting points over finite extensions of $\mathbb{F}_q$ , can be shown to be equivalent to this description using the exponential formula in combinatorics. See this blog post .)
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/103556', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_83286
stackexchange
llm_judgeable_groundtruth_similarity
187432
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: Can we evaluate the integral using Jordan lemma ?$$ \int_{-\infty}^{\infty} {\sin ^2 (x) \over x^2 (x^2 + 1)}\:dx$$ What de we do if removeable singularity occurs at the path of integration? Now provide the response and nothing else.
Using $\sin^2(z)=\frac12(1-\cos(2z))$, you should be able to handle this in much the same way as this answer . Details (modified from the answer mentioned above) Since $\lim\limits_{z\to0}\frac{1-\cos(2z)}{2z^2}=1$, the singularity of the integrand near $z=0$ is removable. Therefore, since the integrand vanishes for $z$ within $\frac12$ of the real axis as $|z|\to\infty$ and there are no singularities within $\frac12$ of the real axis, the integral does not change when shifting the path of integration from $z=t$ to $z=t-\frac{i}{2}$. Now we can break up the integral as$$\int_{-\infty-i/2}^{\infty-i/2}\frac{1-\cos(2z)}{2z^2(z^2+1)}\,\mathrm{d}z=\frac14\int_{\gamma^+}\frac{1-e^{2iz}}{z^2(z^2+1)}\mathrm{d}z+\frac14\int_{\gamma^-}\frac{1-e^{-2iz}}{z^2(z^2+1)}\mathrm{d}z\tag{1}$$where $\gamma^+$ and $\gamma^-$ are as depicted below: $\hspace{4.6cm}$ $\gamma^+$ circles two singularities ($z=0$ and $z=i$) clockwise, and $\gamma^-$ circles one singularity ($z=-i$) counter-clockwise. All of the singularities are simple, so to get the residue at $z=z_0$, we just need to multiply by $z-z_0$ and taking $\displaystyle\lim_{z\to z_0}$ At $z=0$ the residue of $\displaystyle\frac{1-e^{2iz}}{z^2(z^2+1)}$ is $-2i$ At $z=i$ the residue of $\displaystyle\frac{1-e^{2iz}}{z^2(z^2+1)}$ is $\displaystyle\frac{1-e^{-2}}{-2i}$ At $z=-i$ the residue of $\displaystyle\frac{1-e^{-2iz}}{z^2(z^2+1)}$ is $\displaystyle\frac{1-e^{-2}}{2i}$ Putting these together with $(1)$ yields$$\begin{align}\int_{-\infty}^\infty\frac{1-\cos(z)}{z^2(z^2+1)}\,\mathrm{d}z&=\frac{2\pi i}{4}\left(-2i+\frac{1-e^{-2}}{-2i}\right)-\frac{2\pi i}{4}\left(\frac{1-e^{-2}}{2i}\right)\\&=\frac{\pi}{2}\left(2-\frac{1-e^{-2}}{2}-\frac{1-e^{-2}}{2}\right)\\&=\frac\pi2+\frac{\pi}{2e^2}\tag{2}\end{align}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/187432', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38504/']}
jdg_83287
stackexchange
llm_judgeable_groundtruth_similarity
373087
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I use jQuery to make an AJAX POST request to my server, which can return HTTP response with status 302. Then JavaScript just sends GET request to this URL, while I'd like to redirect user to URL in this response. Is this possible? Now provide the response and nothing else.
The accepted answer does not work for the reasons given. I posted a comment with a link to a question that described a hack to get round the problem of the 302 being transparently handled by the browser: How to manage a redirect request after a jQuery Ajax call However, it is a bit of a dirty hack and after much digging around I found what I think is a better solution - use JSON . In this case, you can make all responses to ajax requests have the code 200 and, in the body of the response, you add some sort of JSON object which your ajax response handler can then use in the appropriate manner.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/373087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46854/']}
jdg_83288
stackexchange
llm_judgeable_groundtruth_similarity
198931
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 find out if SP1 has been installed on a server which has .NET 3.5? Now provide the response and nothing else.
Look at HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\ . One of these must be true: The Version value in that key should be 3.5.30729.01 Or the SP value in the same key should be 1 In C# (taken from the first comment), you could do something along these lines: const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);var version = subKey.GetValue("Version").ToString();var servicePack = subKey.GetValue("SP").ToString();
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/198931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1463/']}
jdg_83289
stackexchange
llm_judgeable_groundtruth_similarity
29256888
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 PostgreSQL 9.3. I want to duplicate some of the db records. Since I'm using an auto-increment pk id for the table, I want to get back the id mappings from the generated ids of duplicated records to the original ones. For example, say I have a table posts with 2 records in it: [{'id': 1, 'title': 'first'}, {'id': 2. 'title': 'second'}] With SQL: INSERT INTO posts (title) SELECT title FROM posts RETURNING id, ?? I expect to see mappings like: [{'id': 3, 'from_id': 1}, {'id': 4, 'from_id': 2}] Any idea on how to fill in the question marks above to make it work? Thanks a lot! Now provide the response and nothing else.
This would be simpler for UPDATE , where additional rows joined into the update are visible to the RETURNING clause: Return pre-UPDATE column values using SQL only The same is currently not possible for INSERT . The manual: The expression can use any column names of the table named by table_name table_name being the target of the INSERT command. You can use (data-modifying) CTEs to get this to work. Assuming title to be unique per query , else you need to do more: WITH sel AS ( SELECT id, title FROM posts WHERE id IN (1,2) -- select rows to copy ), ins AS ( INSERT INTO posts (title) SELECT title FROM sel RETURNING id, title )SELECT ins.id, sel.id AS from_idFROM insJOIN sel USING (title); If title is not unique per query (but at least id is unique per table): WITH sel AS ( SELECT id, title, row_number() OVER (ORDER BY id) AS rn FROM posts WHERE id IN (1,2) -- select rows to copy ORDER BY id ), ins AS ( INSERT INTO posts (title) SELECT title FROM sel ORDER BY id -- ORDER redundant to be sure RETURNING id )SELECT i.id, s.id AS from_idFROM (SELECT id, row_number() OVER (ORDER BY id) AS rn FROM ins) iJOIN sel s USING (rn); This second query relies on the undocumented implementation detail that rows are inserted in the order provided. It works in all current versions of Postgres and is probably not going to break. db<>fiddle here Old sqlfiddle
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29256888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2944502/']}
jdg_83290
stackexchange
llm_judgeable_groundtruth_similarity
19021821
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Enum flags in my application. The Enum can have around 50+ values, so values go up to 2^50. I was just wondering, can I use Math.Pow(2, variable) to calculate these? When I try to do that I get a constant value compile-time error. Is there another way, other than calculating these powers of 2 manually and putting it in? Here's what I am doing: [Flags]internal enum RiskStates : long { None = 0, AL = Convert.ToInt64(Math.Pow(2,0)), AK = 2, AZ = 4, AR = 8, CA = 16, CO = 32, CT = 64, DC = 128, DE = 256, FL = 512, GA = 1024, HI = 2048, ID = 4096, IL = 8192, IN = 16384, IA = 32768, KS = 65536, KY = 131072, LA = 262144, ME = 524288, MD = 1048576, MA = 2097152, MI = 4194304} Now provide the response and nothing else.
When I try to do that I get a constant value compile-time error. You'd actually be okay if you used the L suffix to force it to be a long literal - but it's still not ideal to have to specify them all manually. (It's not "obviously correct" when reading the code.) You can't use Math.Pow as the expression has to be a compile-time constant - but you can use bit-shifting: None = 0,AL = 1L << 0,AK = 1L << 1,AZ = 1L << 2 etc. I'd argue that's more readable anyway :)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19021821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/433595/']}
jdg_83291
stackexchange
llm_judgeable_groundtruth_similarity
7228296
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to change the file permission for all the files from my current directory tree. I am trying to open each directory and open the files and change the permission using os.chmod() , But getting an error. import osimport statfor files in os.walk('.'): os.chmod(files,stat.S_IXGRP) The error I get is: File "delhis.py", line 4, in ? os.chmod(files,stat.S_IXGRP) TypeError: coercing to Unicode: need string or buffer, tuple found Now provide the response and nothing else.
You are using os.walk incorrectly. for dirpath, dirnames, filenames in os.walk('.'): for filename in filenames: path = os.path.join(dirpath, filename) os.chmod(path, 0o777) # for example
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7228296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430294/']}
jdg_83292
stackexchange
llm_judgeable_groundtruth_similarity
57594045
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 with a react form validation using Yup along with Formik .There is a react-select element in the form which needs to be validated as well. For validation i'm making use of validationSchema of Formik to validate form on value change.I need only value of the select field as a string so cant take the complete object (key-value).The select field is working fine how ever the validation error message is not cleared.The question is how can I validate the select field with existing approach? Below is the minimal code sample. import ReactDOM from "react-dom";import React, { useState } from "react";import { Grid, TextField, Button } from "@material-ui/core";import { Formik } from "formik";import * as Yup from "yup";import Select from "react-select";import "./styles.css";function App() { const [selectedYear, setSelectedYear] = useState(""); const testSchema = Yup.object().shape({ name: Yup.string().required("Enter Name"), year: Yup.string().required("Select Year") }); const initialValues = { name: "", year: "" }; const handleYearChange = (selectedYear, values) => { values.year = selectedYear.value; console.log(selectedYear); setSelectedYear(selectedYear); }; const yearOptions = [ { value: "1960", label: "1960" }, { value: "1961", label: "1961" }, { value: "1962", label: "1962" }, { value: "1963", label: "1963" }, { value: "1964", label: "1964" }, { value: "1965", label: "1965" } ]; return ( <Formik validationSchema={testSchema} initialValues={initialValues}> {({ handleChange, handleBlur, values, errors, touched, handleSubmit, setFieldTouched }) => { return ( <> <Grid container spacing={2}> <Grid item md={12} xs={12}> <TextField label="Name" name="name" margin="normal" variant="outlined" onChange={handleChange("name")} style={{ width: "100%", zIndex: 0 }} value={values.name} onBlur={() => { console.log("name"); }} /> {errors.name} </Grid> <Grid item md={6} xs={12}> <Select placeholder="Year" value={selectedYear} onChange={selectedOption => { handleYearChange(selectedOption); // handleYearChange(selectedOption, values); // values.year = selectedOption.value; console.log("values", values.year); handleChange("year"); }} isSearchable={true} options={yearOptions} name="year" isLoading={false} loadingMessage={() => "Fetching year"} noOptionsMessage={() => "Year appears here"} /> {errors.year} </Grid> <Grid item md={4} style={{ marginTop: "24px", marginBottom: "10px" }} xs={12} > <Button onClick={handleSubmit}>Save</Button> </Grid> </Grid> </> ); }} </Formik> );}const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement); Here is the codesandbox : PS: I'm new to Reactjs. Now provide the response and nothing else.
Change handleChange("year") To handleChange("year")(selectedOption.value); Currently the year field in the Formik value isn't updated. The handleChange() function returns a new function that can be called with a value to update the Formik state. Easiest way to spot these things is by outputting the Formik props with the following code: <pre>{JSON.stringify(props, null, 2)}</pre> See this sandbox for an example. In the sandbox I have completely removed the need for the custom year state. I'd recommend using only the Formik state to manipulate the values. Using only Formik state you will probably have to extract only the year part when saving, because react-select uses the complete object by default.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57594045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/963604/']}
jdg_83293
stackexchange
llm_judgeable_groundtruth_similarity
32654896
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 make a Spring Batch and I have no experience with it. Is it possible to pass information from each batch step or must they be completely independent? For example if I have <batch:step id="getSQLs" next="runSQLs"> <batch:tasklet transaction-manager="TransactionManager" ref="runGetSQLs" /> </batch:step> <batch:step id="runSQLs"> <batch:tasklet transaction-manager="TransactionManager" ref="runRunSQLs" /> </batch:step> And getSQLs triggers a bean which executes a class which generates a List of type String. Is it possible to reference that list for the bean triggered by runSQLs? ("triggered" may not be the right term but I think you know what I mean) UPDATE:So getSQLs step triggers this bean: <bean id="runGetSQLs" class="myTask" scope="step"> <property name="filePath" value="C:\Users\username\Desktop\sample.txt" /></bean> which triggers myTask class which executes this method: @Overridepublic RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { ExecutionContext stepContext = this.stepExecution.getExecutionContext(); stepContext.put("theListKey", sourceQueries); return RepeatStatus.FINISHED;} Do I need to somehow pass stepExecution to the execute method? Now provide the response and nothing else.
Spring Batch supports pushing data to future job steps, and this can be done through the ExecutionContext , more precisely the JobExecutionContext . Here I'm referring to example from the official documentation , as it is the ultimate reference for me: To make the data available to future Steps, it will have to be "promoted" to the Job ExecutionContext after the step has finished. Spring Batch provides the ExecutionContextPromotionListener for this purpose. The listener should be configured with your step, the one sharing data with future ones: <batch:step id="getSQLs" next="runSQLs"> <batch:tasklet transaction-manager="TransactionManager" ref="runGetSQLs" /> <listeners> <listener> <beans:bean id="promotionListener" class="org.springframework.batch.core.listener.ExecutionContextPromotionListener"> <beans:property name="keys" value="theListKey"/> </beans:bean> </listener> </listeners></batch:step><batch:step id="runSQLs"> <batch:tasklet transaction-manager="TransactionManager" ref="runRunSQLs" /></batch:step> The data should be populated from your execution code block as follows: // ...ExecutionContext stepContext = this.stepExecution.getExecutionContext();stepContext.put("theListKey", yourList); Then in subsequent steps, this List can be retrieved with a post computation hook annotated with @BeforeStep a as follows: @BeforeSteppublic void retrieveSharedData(StepExecution stepExecution) { JobExecution jobExecution = stepExecution.getJobExecution(); ExecutionContext jobContext = jobExecution.getExecutionContext(); this.myList = jobContext.get("theListKey");}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32654896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2665166/']}
jdg_83294
stackexchange
llm_judgeable_groundtruth_similarity
613829
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: This is a Canonical Question about CNAMEs at the apices (or roots) of zones It's relatively common knowledge that CNAME records at the apex of a domain are a taboo practice. Example: example.com. IN CNAME ithurts.example.net. In a best case scenario nameserver software might refuse to load the configuration, and in the worst case it might accept this configuration and invalidate the configuration for example.com. Recently I had a webhosting company pass instructions to a business unit that we needed to CNAME the apex of our domain to a new record. Knowing that this would be a suicide config when fed to BIND, I advised them that we would not be able to comply and that this was bunk advice in general. The webhosting company took the stance that it is not outright forbidden by standard defining RFCs and that their software supports it. If we could not CNAME the apex, their advice was to have no apex record at all and they would not provide a redirecting webserver. ...What? Most of us know that RFC1912 insists that A CNAME record is not allowed to coexist with any other data. , but let's be honest with ourselves here, that RFC is only Informational. The closest I know to verbiage that forbids the practice is from RFC1034 : If a CNAME RR is present at a node, no other data should bepresent; this ensures that the data for a canonical name and its aliasescannot be different. Unfortunately I've been in the industry long enough to know that "should not" is not the same as "must not", and that's enough rope for most software designers to hang themselves with. Knowing that anything short of a concise link to a slam dunk would be a waste of my time, I ended up letting the company get away with a scolding for recommending configurations that could break commonly used software without proper disclosure. This brings us to the Q&A. For once I'd like us to get really technical about the insanity of apex CNAMEs, and not skirt around the issue like we usually do when someone posts on the subject. RFC1912 is off limits, as are any other Informational RFC applicable here that I didn't think of. Let's shut this baby down. Now provide the response and nothing else.
CNAME records were originally created to allow multiple names that provide the same resource to be aliased to a single "canonical name" for the resource. With the advent of name based virtual hosting, it has instead become commonplace to use them as a generic form of IP address aliasing. Unfortunately, most people who come from a web hosting background expect CNAME records to indicate equivalence in the DNS , which has never been the intent. The apex contains record types which are clearly not used in the identification of a canonical host resource ( NS , SOA ), which cannot be aliased without breaking the standard at a fundamental level. (particularly in regards to zone cuts ) Unfortunately, the original DNS standard was written before the standards governing bodies realized that explicit verbiage was necessary to define consistent behavior ( RFC 2119 ). It was necessary to create RFC 2181 to clarify several corner cases due to vague wording, and the updated verbiage makes it clearer that a CNAME cannot be used to achieve apex aliasing without breaking the standard. 6.1. Zone authority The authoritative servers for a zone are enumerated in the NS recordsfor the origin of the zone, which, along with a Start of Authority(SOA) record are the mandatory records in every zone. Such a serveris authoritative for all resource records in a zone that are not inanother zone. The NS records that indicate a zone cut are theproperty of the child zone created, as are any other records for theorigin of that child zone, or any sub-domains of it. A server for azone should not return authoritative answers for queries related tonames in another zone, which includes the NS, and perhaps A, recordsat a zone cut, unless it also happens to be a server for the otherzone. This establishes that SOA and NS records are mandatory, but it says nothing about A or other types appearing here. It may seem superfluous that I quote this then, but it will become more relevant in a moment. RFC 1034 was somewhat vague about the problems that can arise when a CNAME exists alongside other record types. RFC 2181 removes the ambiguity and explicitly states the record types that are allowed to exist alongside them: 10.1. CNAME resource records The DNS CNAME ("canonical name") record exists to provide thecanonical name associated with an alias name. There may be only onesuch canonical name for any one alias. That name should generally bea name that exists elsewhere in the DNS, though there are some rareapplications for aliases with the accompanying canonical nameundefined in the DNS. An alias name (label of a CNAME record) may,if DNSSEC is in use, have SIG, NXT, and KEY RRs, but may have noother data. That is, for any label in the DNS (any domain name)exactly one of the following is true: one CNAME record exists, optionally accompanied by SIG, NXT, andKEY RRs, one or more records exist, none being CNAME records, the name exists, but has no associated RRs of any type, the name does not exist at all. "alias name" in this context is referring to the left hand side of the CNAME record. The bulleted list makes it explicitly clear that a SOA , NS , and A records cannot be seen at a node where a CNAME also appears. When we combine this with section 6.1, it is impossible for a CNAME to exist at the apex as it would have to live alongside mandatory SOA and NS records. (This seems to do the job, but if someone has a shorter path to proof please give a crack at it.) Update: It seems that the more recent confusion is coming from Cloudflare's recent decision to allow an illegal CNAME record to be defined at the apex of domains, for which they will synthesize A records. "RFC compliant" as described by the linked article refers to the fact that the records synthesized by Cloudflare will play nicely with DNS. This does not change the fact that it is a completely custom behavior. In my opinion this is a disservice to the larger DNS community: it is not in fact a CNAME record, and it misleads people into believing that other software is deficient for not allowing it. (as my question demonstrates)
{}
{'log_upvote_score': 8, 'links': ['https://serverfault.com/questions/613829', 'https://serverfault.com', 'https://serverfault.com/users/152073/']}
jdg_83295
stackexchange
llm_judgeable_groundtruth_similarity
8170717
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 modify the red/yellow/green window buttons for close/minimize/zoom in Mac OS X? There must be an editable resource or plist somewhere. Here are the buttons I'm talking about: For red/green colorblind individuals, those colors can be maddening. I wish they chose the actual bluish shade of green used in a traffic light instead of the puke grass green. That grassy green is indeterminable from the red. Changing the theme to graphite is a poor alternative, so any other method is much preferred. Now provide the response and nothing else.
Okay, after a long and seemingly endless research cycle, I've located where the window buttons are stored. They're in a file called ArtFile.bin in /System/Library/PrivateFrameworks/CoreUI.framework/Versions/A/Resources/ . Also, a guy named Alex Zielenski with the help of Indragie Karunaratne created a utility named artFileTool to get to its contents. The second link is the code repository for the utility. http://macthemes.net/forum/viewtopic.php?t=16810624 https://github.com/alexzielenski/artFileTool Here's the process to extract and then rebuild the resource as described on the MacThemes forum by a user named toutheme : For ArtFile.bin - Lion Preparation Create new folder: TheFolder Copy the Lion ArtFile.bin (/System/Library/PrivateFrameworks/CoreUI.framework/Resources) and artFileTool on TheFolder. Terminal Launch Terminal, type "cd" + "space" + (drag TheFolder on Terminal window). Type enter. Decoding To decode ArtFile.bin and compile a folder Resources Disconnected Classified: ./artFileTool -d ArtFile.bin ResourcesDisconnectedClassified -- or -- To decode ArtFile.bin and compile a folder Named Connected Images: ./artFileTool -d -c ArtFile.bin NamedConnectedImages Edition Edit your files with PhotoShop, for example… Encoding To re-encode the Resources Disconnected Classified: ./artFileTool -e ResourcesDisconnectedClassified ArtFile.bin ArtFile.new.bin -- or -- To re-encode the Named Connected Images: ./artFileTool -e -c NamedConnectedImages ArtFile.bin ArtFile.new.bin For ArtFile.bin - Snow Leopard: ./artFileTool -d -l ArtFile.bin ResourcesDisconnectedClassified ./artFileTool -d -l -c ArtFile.bin NamedConnectedImages ./artFileTool -e -l ResourcesDisconnectedClassified ArtFile.bin ArtFile.new.bin ./artFileTool -e -l -c NamedConnectedImages ArtFile.bin ArtFile.new.bin For ArtFile200.bin (Lion only): Create new folder: TheFolder Copy the Lion ArtFile200.bin (/System/Library/PrivateFrameworks/CoreUI.framework/Resources) and artFileTool on TheFolder. Launch Terminal, type "cd" + "space" + (drag TheFolder on Terminal window). Type enter. Decoding ./artFileTool -d ArtFile200.bin ResourcesDisconnectedClassified ./artFileTool -d -c ArtFile200.bin NamedConnectedImages Encoding ./artFileTool -e ResourcesDisconnectedClassified ArtFile200.bin ArtFile200.new.bin ./artFileTool -e -c NamedConnectedImages ArtFile200.bin ArtFile200.new.bin Make sure to check the size of the newly created file. (4.0-5.2 mb) Rename ArtFile.new.bin to ArtFile.bin and replace the one location in the CoreUI.framework directory Logout I hope this helps anyone who got as frustrated as I did at how difficult it is discovering basic information about the inner workings of OS X.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8170717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/639580/']}
jdg_83296
stackexchange
llm_judgeable_groundtruth_similarity
24797155
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: PMD is warning me to avoid Boolean instantiation (for efficiency reasons).I have something like this Boolean variable = new Boolean(somestringIGotRepresentingABoolean); And I'm supposed to use this Boolean variable = Boolean.valueOf(somestringIGotRepresentingABoolean); Why is that better? Now provide the response and nothing else.
The reason is that new Boolean always returns a new instance. Since Boolean instances are immutable it does not make sense to have more than 2 instances. One for false and one for true. Try this and you will see Boolean boolean1 = new Boolean("true");Boolean boolean2 = new Boolean("true");Boolean boolean3 = new Boolean("true");System.out.println(System.identityHashCode(boolean1));System.out.println(System.identityHashCode(boolean2));System.out.println(System.identityHashCode(boolean3));Boolean valueOf1 = Boolean.valueOf("true");Boolean valueOf2 = Boolean.valueOf("true");System.out.println(System.identityHashCode(valueOf1));System.out.println(System.identityHashCode(valueOf2));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24797155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65967/']}
jdg_83297
stackexchange
llm_judgeable_groundtruth_similarity
2027539
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am currently using Visual Studio 2008 on XP Pro SP3. Developing against http://localhost/ everything including debugging works fine. I need a second website on my machine. IIS 5.1 only allows one website at a time so I used the JetStat XP Pro IIS Admin tool to create a second website. This runs by stopping the Default website and starting the other. I have added the new website name into the Hosts file and mapped to 127.0.0.1. Websites can be accessed via this address http://NewHostname/VirtualDirectoryName Projects can be started without debugging (Web Applications & Websites). However, when I try to debug I get an error: "Unable to start debugging on the web server. An authentication error occurred while communicating with the web server." Integrated Authentication is enabled in IIS. I have seen a lot of documentation with many fixes for "unable to start debugging on the web server" errors but they all seem like huge overkill for my problem, after all, debugging works fine provided I'm not doing it on this different hostname. They talk about doing things that I would do if debugging did not work at all even with http://localhost/ . Is there a place where I can just add this new hostname so that VS debugging is allowed? Do I need to change permissions somewhere? I feel like there should be a really simple solution that I'm just overlooking. Now provide the response and nothing else.
This isn't directly supported by the .NET Form class, so you have two options: 1) Use the Win32 API SetWindowPos function. pinvoke.net shows how to declare this for use in C#: [DllImport("user32.dll")]static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);static readonly IntPtr HWND_BOTTOM = new IntPtr(1);const UInt32 SWP_NOSIZE = 0x0001;const UInt32 SWP_NOMOVE = 0x0002;const UInt32 SWP_NOACTIVATE = 0x0010; So in your code, call: SetWindowPos(Handle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); As you commented, this moves the form to the bottom of the z-order but doesn't keep it there. The only workaround I can see for this is to call SetWindowPos from the Form_Load and Form_Activate events. If your application is maximized and the user is unable to move or minimise the form then you might get away with this approach, but it's still something of a hack. Also the user might see a slight "flicker" if the form gets brought to the front of the z-order before the SetWindowPos call gets made. 2) subclass the form , override the WndProc function and intercept the WM_WINDOWPOSCHANGING Windows message, setting the SWP_NOZORDER flag (taken from this page ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2027539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/77301/']}
jdg_83298
stackexchange
llm_judgeable_groundtruth_similarity
13700030
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the recommended way to implement multiple user types using Django 1.5's new configurable user model functionality? I would like to have two user types: private users and trade users, each with their own set of required fields. There are two ways I can think to implement this: 1) Multi-table inheritance class BaseUser(AbstractBaseUser): email = models.EmailField(max_length=254, unique=True) # ...class PrivateUser(BaseUser): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) # ...class TradeUser(BaseUser): company_name = models.CharField(max_length=100) # ... Are there any problems with using multi-table inheritance in conjunction with the configurable user model? 2) Using a single model with a "type" attribute class User(AbstractBaseUser): email = models.EmailField(max_length=254, unique=True) user_type = models.CharField(max_length=30, choices={ 'P': 'Private', 'T': 'Trade', }) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) company_name = models.CharField(max_length=100, blank=True) # ... This method would require some conditional validation dependent upon user_type . Which of these methods best suits my use case? Or perhaps there is a better way of achieving this? Also, In case number 1, how can I filter my users? Thanks. Now provide the response and nothing else.
Warning: Django 1.5 is very new and the people are still investigating its new features. So my answer is nothing more than my opinion, based on recent research to answer this question. Both ways are valid ways to achieve the result, with its advantages and disadvantages. Let's start with the: Second option Without nested models and not modular. AbstractBaseUser , as the name says, is an abstract model and does not have a specific table Has unused fields You need to check the user_type for any iteration with the model that uses the extra fields: def foo(): if user.user_type == 'Private': # ... else: # ... The resulting SQL would be approximately as follows: CREATE TABLE "myapp_user" ( "id" integer NOT NULL PRIMARY KEY, "password" varchar(128) NOT NULL, "last_login" datetime NOT NULL, "email" varchar(254) NOT NULL UNIQUE, "user_type" varchar(30) NOT NULL, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL, "company_name" varchar(100) NOT NULL); First option Nested models with logical separation of entities Very lean You must implement BaseUserManager for each child if you want to use create_user -like functions You cannot access the subclasses with a simple BaseUser.objects.all() * The resulting SQL would be approximately as follows: CREATE TABLE "myapp_baseuser" ( "id" integer NOT NULL PRIMARY KEY, "password" varchar(128) NOT NULL, "last_login" datetime NOT NULL, "email" varchar(254) NOT NULL UNIQUE);CREATE TABLE "myapp_privateuser" ( "baseuser_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "myapp_baseuser" ("id"), "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL);CREATE TABLE "myapp_tradeuser" ( "baseuser_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "myapp_baseuser" ("id"), "company_name" varchar(100) NOT NULL); * Imagine the following situation: >>> BaseUser.objects.create_user('[email protected]', password='baseuser')>>> PrivateUser.objects.create_user('[email protected]', password='privateuser', first_name='His', last_name='Name')>>> TradeUser.objects.create_user('[email protected]', password='tradeuser', company_name='Tech Inc.')>>> BaseUser.objects.all()[<BaseUser: [email protected]>, <BaseUser: [email protected]>, <BaseUser: [email protected]>]>>> PrivateUser.objects.all()[<PrivateUser: [email protected]>]>>> TradeUser.objects.all()[<TradeUser: [email protected]>] So, you cannot directly retrieve the subclasses instances by using BaseUser.objects.all() . There is an excellent blog post by Jeff explaining better how to accomplish "automatic downcast" from BaseUser to its childs. That said, you should consider the advantages and disadvantages of each approach and their impact on your project. When the involved logic is small (as in the example described), both approaches are valid. But in a more complex scenario, an approach can be better than the other one. I would choose the multi model option because it is more extensible.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13700030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/289872/']}
jdg_83299
stackexchange
llm_judgeable_groundtruth_similarity
33161347
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 install Visual Studio 2015 and I get the following message (at each debug / Round about 2 minutes). VS-Message What can I do? With VS 2013 I never got this message. I use Windows 10 (64 bit). Sorry for the short description... I can read and understand English very well but it is difficult for me to talk and write. Thanks for all your help and answering! Now provide the response and nothing else.
With the design library v 23.1.0 the NavigationView works with a RecyclerView . Also the Header is now a type of row. It means that the header could not be immediately available in the view hierarchy . It can cause issues if you are using methods like navigationView.findViewById(XXX) to get a view inside the header. There is a bug in the Google Tracker . EDIT 12/10/2015: Design library 23.1.1 The 23.1.1 introduces a new API for retrieving header views for NavigationView with getHeaderView() BEFORE 23.1.1 workaround fot 23.1.0 can be to use a addOnLayoutChangeListener . Somenthing like: navigationView.addOnLayoutChangeListener( new View.OnLayoutChangeListener(){ @Override public void onLayoutChange( ... ) { navigationView.removeOnLayoutChangeListener( this ); View view = navigationView.findViewById( ... ); }} ); Another possible workaround are: remove the app:headerLayout attribute from the xml, and then add the header programatically. Inflate the headerView programmatically. Use somenthing like this: View headerLayout = navigationView.inflateHeaderView(R.layout.navigation_header);headerLayout.findViewById(xxx);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33161347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5215065/']}
jdg_83300
stackexchange
llm_judgeable_groundtruth_similarity
1054850
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: Prove that if a graph does not have two disjoint odd cycles then χ(G) ≤ 5, where χ(G) denotes the minimum number of colors needed to color the vertices of G. χ(G) is the chromatic number of G. Intuitions: It is clear that any odd-cycle must have a chromatic number of 3. Each clique of the graph that has an odd-cycle must thus have a chromatic number of three, but I don't see how this helps the proof. On a related note: would it be easier to prove the contrapositive or use a proof by contradiction? For self-study. Now provide the response and nothing else.
$$\forall n\geqslant1,\qquad a_{2n}=a_{2n-1}=2^{-n}$$ Edit: To see that the ratios $a_{n+1}/a_n$ can have $0$ and $+\infty$ as limit points simultaneously, consider $$\forall n\geqslant1,\qquad a_{2n}=2^{-n},\quad a_{2n-1}=3^{-n}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1054850', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/198146/']}
jdg_83301
stackexchange
llm_judgeable_groundtruth_similarity
47110489
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to continue background service in android Oreo without showing notification dot? i continues my background service using notification but i don't want to show notification for running service. Now provide the response and nothing else.
If you would have read the Android Oreo 8.0 Documentation properly somewhere in here , you might not have posted this question here. Step 1: Make sure you start a service as a foreground Service as given in below code ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), GpsServices.class));ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BluetoothService.class));ContextCompat.startForegroundService(mainActivity, new Intent(getContext(), BackgroundApiService.class)); Step 2: Use notification to show that your service is running. Add below line of code in onCreate method of Service . @Overridepublic void onCreate() { ... if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForeground(NOTIFICATION_ID, notification); } ...} Step 3: Remove the notification when the service is stopped or destroyed. @Overridepublic void onDestroy() { ... if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { stopForeground(true); //true will remove notification } ...} One problem with this solution is that it will keep showing the notification until your Service is running on all devices running on Android Oreo 8.0 . I'm sure that this solution will work even when the app is in the background or in kill state. IMPORTANT NOTE: SHOWING A NOTIFICATION FOR RUNNING A SERVICE IN BACKGROUND (APP IN BACKGROUND OR KILLED STATE) IS MANDATORY IN ANDROID OREO 8.0. YOU CANNOT RUN AWAY WITH IT. SO IT IS RECOMMENDED THAT YOU MAKE NECESSARY CHANGES IN YOUR APP TO MAKE IT WORK PROPERLY AS PER THE BEST PRACTICES FOLLOWED OR ASKED BY ANDROID. I hope this might help to solve your problem.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47110489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6540604/']}
jdg_83302
stackexchange
llm_judgeable_groundtruth_similarity
16450
Below is a question asked on the forum softwarerecs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For writing command line applications in Java, what is the best library for parsing and managing arguments and paramenters? Note: this question is an updated version of this closed question on Stack Overflow . Now provide the response and nothing else.
picocli is different from other Java CLI libraries: It is designed to be included in source form. This lets users run picocli-based applications without requiring picocli as an external dependency. Generates polished and easily tailored usage help, using ANSI colors when the underlying platform supports it. Autocompletion for your Java command line applications on supported platforms Example usage help message: Quick overview: Effortless command line parsing - just annotate fields Strongly typed everything - command line options as well as positional parameters full support for both GNU style and POSIX clustered short options (so it handles <command> -xvfInputFile as well as <command> -x -v -f InputFile ) An arity model that allows a minimum, maximum and variable number of parameters, e.g, "1..*" , "3..5" Subcommands Works with Java 5 and higher Well-structured user manual Usage help is the face of your application, so be creative and have fun! Update: Picocli is also actively maintained. Since the original post, many new features were added, for example: programmatic API as well as annotations API Dependency Injection container integration JLine integration: delegate to AutoComplete for your command’s Completer implementation interface methods can be annotated with @Option or @Parameters (picocli creates a synthetic implementation that returns the matched options) class methods can be annotated with @Option or @Parameters (so you can validate options and positional parameters) support for @Command methods for extra compact code internationalization with resource bundles Disclaimer: I am the author.
{}
{'log_upvote_score': 4, 'links': ['https://softwarerecs.stackexchange.com/questions/16450', 'https://softwarerecs.stackexchange.com', 'https://softwarerecs.stackexchange.com/users/12008/']}
jdg_83303
stackexchange
llm_judgeable_groundtruth_similarity
24968960
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following expression compiles: Object oa = new float[20]; How is this expression valid? As per my opinion, the correct syntax would be Object [] oa = new float[20]; Now provide the response and nothing else.
Arrays are objects in Java. So an array of floats is an object. BTW, Object o = new Object[20]; is also valid, since an array of objects is an object. Also note that Object[] oa = new float[20]; is invalid, since primitive floats are not objects, and an array of floats is thus not an array of objects. What would be correct is Object[] oa = new Float[20]; Regarding arrays, since they are objects, they have all the methods of java.lang.Object. They also have a public final attribute length , and they are Cloneable and Serializable: Object o = new float[20];System.out.println("o instanceof Serializable = " + (o instanceof Serializable)); // trueSystem.out.println("o instanceof Cloneable = " + (o instanceof Cloneable)); // true
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24968960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1960543/']}
jdg_83304
stackexchange
llm_judgeable_groundtruth_similarity
63386
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm relatively familiar with the distinction between the terms statistic and parameter. I see a statistic as the value obtained from applying a function to the sample data. However, most examples of parameters relate to defining a parametric distribution. A common example is the mean and standard deviation to parameterise the normal distribution or the coefficients and error variance to parameterise a linear regression. However, there are many other values of the population distribution that are less prototypical (e.g., minimum, maximum, r-square in multiple regression, the .25 quantile, median, the number of predictors with non-zero coefficients, skewness, the number of correlations in a correlation matrix greater than .3, etc.). Thus, my questions are: Should any quantitative property of a population be labelled a "parameter"? If yes, then why? If no, what characteristics should not be labelled a parameter? What should they be labelled? And why? Elaboration on confusion The Wikipedia article on estimators states: An "estimator" or "point estimate" is a statistic (that is, a function of the data) that is used to infer the value of an unknown parameter in a statistical model. But I can define the unknown value as .25 quantile and I can develop an estimator for that unknown. I.e., not all quantitative properties of a population are parameters in the same way that say the mean and sd are parameters of a normal distribution, yet it is legitimate to seek to estimate any quantitative population property. Now provide the response and nothing else.
As with many questions on definitions, answers need to have an eye both on the underlying principles and on the ways terms are used in practice, which can often be at least a little loose or inconsistent, even by individuals who are well informed, and more importantly, variable from community to community. One common principle is that a statistic is a property of a sample, and a known constant, and a parameter is the corresponding property of the population, and so an unknown constant. The word "corresponding" is to be understood as quite elastic here. Incidentally, precisely this distinction and precisely this terminology are less than a century old, having being introduced by R.A. Fisher. But A set-up of sample and population doesn't characterise all our own problems. Time series are one major class of examples in which the idea is rather of an underlying generating process, and something like that is arguably the deeper and more general idea. There are set-ups in which parameters change. Again, time series analysis provides examples. To the main point here, we don't in practice think of all the properties of a population or process as parameters. If some procedure assumes a model of a normal distribution, then the minimum and maximum are not parameters. (Indeed, according to the model, the minimum and maximum are arbitrarily large negative and positive numbers any way, not that that should worry us.) I would say that for once Wikipedia is pointing in the right direction here, and practice and principle are both respected if we say that a parameter is whatever we are estimating . This helps too with other questions that have caused puzzlement. For example, if we calculate a 25% trimmed mean, what we are estimating? A reasonable answer is the corresponding property of the population, which in effect is defined by the estimation method. One terminology is that an estimator has an estimand, whatever it is estimating. Starting with some Platonic idea of a property "out there" (say the mode of a distribution) and thinking how to estimate that is reasonable, as is thinking up good recipes for analysing data and thinking through what they imply when regarded as inference. As often in applied mathematics or science, there is a twofold aspect to a parameter. We often think of it as something real out there which we are discovering, but it is also true that it is something defined by our model of the process, so that it has no meaning outside the context of the model. Two quite different points: Many scientists use the word "parameter" in the way that statisticians use variable. I have a scientist persona as well as a statistical one, and I would say that is unfortunate. Variables and properties are better words. It is remarkably common in wider English usage that parameter is thought to mean limits or bounds, which may stem from some original confusion between "parameter" and "perimeter". A note on the estimand point of view The classical position is that we identify a parameter in advance and then decide how to estimate it, and this remains majority practice, but reversing the process is not absurd and can be helpful for some problems. I call this the estimand point of view. It has been in the literature for at least 50 years. Tukey (1962, p.60) urged that "We must give even more attention to starting with an estimator and discovering what is a reasonable estimand, to discovering what is it reasonable to think ofthe estimator as estimating." A similar point of view has been elaborated formally in considerable detail and depth by Bickel and Lehmann (1975) and informally with considerable lucidity by Mosteller and Tukey (1977, pp.32-34). There is also an elementary version. Using(say) sample median or geometric mean to estimate the correspondingpopulation parameter makes sense regardless of whether the underlyingdistribution is symmetric, and the same goodwill can be extended to (e.g.) sample trimmed means, which are regarded as estimators of theirpopulation counterparts. Bickel, P.J. and E.L. Lehmann. 1975. Descriptive statistics for nonparametric models. II. Location . Annals of Statistics 3: 1045-1069. Mosteller, F. and J.W. Tukey. 1977. Data Analysis and Regression. Reading, MA: Addison-Wesley. Tukey, J.W. 1962. The future of data analysis . Annals of Mathematical Statistics 33: 1-67.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/63386', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/183/']}
jdg_83305
stackexchange
llm_judgeable_groundtruth_similarity
1111039
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 a domain name in a bash variable ( $TARGET ), and I want to get the IPv4 ( A record) address of it in my bash script (I also want to get the IPv6 AAAA record (if exists)), in a robust manner. i.e. What bash/unix command will: (i) print the IP address (and only the IP address) of the DNS resolution (ii) print nothing to stdout (or non-zero exit) if there is no DNS record for that domain found (iii) allow me to choose to ask for A or AAAA record. host "$TARGET" prints lots of human readable stuff, and I'm reluctant to parse that. dig +short looked promising, but in some scenarios, it also prints other warning messages which I do not understand, or care about. $ dig +short -t A "$TARGET";; Warning: Client COOKIE mismatch1.2.3.4 Debian test/bookworm. Bash v5.2 (installed via apt) Now provide the response and nothing else.
I'm unsure if you want to actually query nameservers or rather rely on your system's name resolution: $ getent ahosts one.one.one.one. | awk '{ print $1 }' | sort -u1.0.0.11.1.1.12606:4700:4700::10012606:4700:4700::1111$ getent ahosts nonexistent.host | awk '{ print $1 }' | sort -u$ getent ahosts www.what-is-my-ipv4.com | awk '{ print $1 }' | sort -u185.26.156.187 You can also make it return v4 or v6 addresses with ahostsv4 and ahostsv6 . If you just use hosts , you are subject to your /etc/gai.conf 's settings. Found this on https://unix.stackexchange.com/questions/212897/nslookup-dig-firefox-ignoring-etc-hosts-file-entries : nslookup , dig , and host are tools for querying DNS name servers. If your configuration is not provided by a name server (like theinformation given in /etc/hosts) those tools will not show them,because they directly ask the name server. If you want to check that the "usual" resolution is working (i.e. theway specified in /etc/nsswitch.conf ) you can use getent : getent hosts www.winaproduct.com
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/1111039', 'https://serverfault.com', 'https://serverfault.com/users/8950/']}
jdg_83306
stackexchange
llm_judgeable_groundtruth_similarity
49810838
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 stringdict and following sentence I want to translate in several languages: <key>myKey</key><dict> <key>NSStringLocalizedFormatKey</key> <string>My friend %#@name@ has %#@count@.</string> <key>count</key> <dict> <key>NSStringFormatSpecTypeKey</key> <string>NSStringPluralRuleType</string> <key>one</key> <string>one dog</string> <key>other</key> <string>%d dogs</string> </dict></dict> What I want is to use following code, to create my String let name = "Peter"let dogs = 3let myString = String(format: NSLocalizedString("myKey", comment:""), name, dogs) I have expected to get "My friend Peter has 3 dogs.", but I get an error. So maybe have someone a tip and can help me, how I could use strings in the dict, or maybe there is another way to do it? Now provide the response and nothing else.
In addition to what Andreas said : There is no dictionary for the %#@name@ variable in the format string, but you can simply use %@ for a Swift string instead. The complete stringsdict entry thenbecomes <key>myKey</key><dict> <key>NSStringLocalizedFormatKey</key> <string>My friend %@ has %#@count@.</string> <key>count</key> <dict> <key>NSStringFormatValueTypeKey</key> <string>d</string> <key>NSStringFormatSpecTypeKey</key> <string>NSStringPluralRuleType</string> <key>one</key> <string>one dog</string> <key>other</key> <string>%d dogs</string> </dict></dict>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49810838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9639895/']}
jdg_83307
stackexchange
llm_judgeable_groundtruth_similarity
7151890
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 set of arrays that are very large and expensive to compute, and not all will necessarily be needed by my code on any given run. I would like to make their declaration optional, but ideally without having to rewrite my whole code. Example of how it is now: x = function_that_generates_huge_array_slowly(0)y = function_that_generates_huge_array_slowly(1) Example of what I'd like to do: x = lambda: function_that_generates_huge_array_slowly(0)y = lambda: function_that_generates_huge_array_slowly(1)z = x * 5 # this doesn't work because lambda is a function # is there something that would make this line behave like # z = x() * 5?g = x * 6 While using lambda as above achieves one of the desired effects - computation of the array is delayed until it is needed - if you use the variable "x" more than once, it has to be computed each time. I'd like to compute it only once. EDIT:After some additional searching, it looks like it is possible to do what I want (approximately) with "lazy" attributes in a class (e.g. http://code.activestate.com/recipes/131495-lazy-attributes/ ). I don't suppose there's any way to do something similar without making a separate class? EDIT2: I'm trying to implement some of the solutions, but I'm running in to an issue because I don't understand the difference between: class sample(object): def __init__(self): class one(object): def __get__(self, obj, type=None): print "computing ..." obj.one = 1 return 1 self.one = one() and class sample(object): class one(object): def __get__(self, obj, type=None): print "computing ... " obj.one = 1 return 1 one = one() I think some variation on these is what I'm looking for, since the expensive variables are intended to be part of a class. Now provide the response and nothing else.
The first half of your problem (reusing the value) is easily solved: class LazyWrapper(object): def __init__(self, func): self.func = func self.value = None def __call__(self): if self.value is None: self.value = self.func() return self.valuelazy_wrapper = LazyWrapper(lambda: function_that_generates_huge_array_slowly(0)) But you still have to use it as lazy_wrapper() not lazy_wrapper . If you're going to be accessing some of the variables many times, it may be faster to use: class LazyWrapper(object): def __init__(self, func): self.func = func def __call__(self): try: return self.value except AttributeError: self.value = self.func() return self.value Which will make the first call slower and subsequent uses faster. Edit: I see you found a similar solution that requires you to use attributes on a class. Either way requires you rewrite every lazy variable access, so just pick whichever you like. Edit 2: You can also do: class YourClass(object) def __init__(self, func): self.func = func @property def x(self): try: return self.value except AttributeError: self.value = self.func() return self.value If you want to access x as an instance attribute. No additional class is needed. If you don't want to change the class signature (by making it require func ), you can hard code the function call into the property.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7151890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/814354/']}
jdg_83308
stackexchange
llm_judgeable_groundtruth_similarity
5829122
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 single direction linked list without knowing its size. I want to get a random element in this list, and I just have one time chance to traverse the list. (I am not allowed to traverse twice or more) What’s the algorithm for this problem? Thanks! Now provide the response and nothing else.
This is just reservoir sampling with a reservoir of size 1. Essentially it is really simple Pick the first element regardless (for a list of length 1, the first element is always the sample). For every other element with probability 1/n where n is the number of elements observed so far, you replace the already picked element with the current element you are on. This is uniformly sampled, since the probability of picking any element at the end of the day is 1/n (exercise to the reader).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5829122', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/290629/']}
jdg_83309
stackexchange
llm_judgeable_groundtruth_similarity
7786823
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am wondering if a static class in an ASP.NET MVC app could be initialized more than once . I initially designed my app so that a static component would fetch some stuff from the database and serve as a cache, and I added a refresh method to the class which was called from the constructor. The refresh method was also made available through the administration portion of the app. At some point I noticed that the data was updated without requiring this manual trigger, which implies that the static constructor run more than once. There are several scenarios where I could reasonably see this happen, such as an unhandled Exception causing re-initialization. But I am having trouble reproducing this, so I would like to know for sure. Now provide the response and nothing else.
The most usual scenarios would be: a reload of the web application touched Web.config touched binaries abnormal termination (out-of-memory, permission errors) a reload of the Application Pool a restart of IIS a restart of w3wp.exe (at least once in 29 hours!) The app-domain will get reloaded (recompiling the dynamic parts as necessary) and this would void any statically initialized data. You can get around that by persisting the static data somewhere if creating it is expensive, or avoid reloading the AppDomain, the Application Pool or the IIS server. Update : Phil Haack just published a relevant blog entry here: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx Bye Bye App Domain it does a better job at explaining the above. Notable, IIS will recycle it's worker process very 29 hours at minimum and shared hosters will recycle AppDomain much more often (perhaps in 20 minutes of idle time) So tell ASP.NET, “Hey, I’m working here!” outlines techniques you can apply to get notified of an AppDomain take down - you could use this to get your Singleton instance behaving 'correctly' Recommendation I suggest you read it :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7786823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427673/']}
jdg_83310
stackexchange
llm_judgeable_groundtruth_similarity
26720011
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 comparing two strings in a bash script as follows: x="hello"y="hello"if [[ "$x" != "$y" ]]; then echo "different"else echo "same"fi This comparison works. When I execute the script with -x , the comparison still works, but it shows the output + x=hello+ y=hello+ [[ -n hello ]]+ [[ hello != \h\e\l\l\o ]]+ echo same I'm curious why the right side of the string shows as \h\e\l\l\o and not hello Now provide the response and nothing else.
The simple explanation is for the same reason that the left-hand side doesn't have quotes around it. -x is showing you an equivalent but not exact representation of what it ran. The right-hand side of = and != in [[ ... ]] is matched as a pattern. From the manual: When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below under Pattern Matching. .... Any part of the pattern may be quoted to force it to be matched as a string. The -x output, for some reason, chooses to use escaping instead quoting to disable pattern matching there.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26720011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121993/']}
jdg_83311
stackexchange
llm_judgeable_groundtruth_similarity
33016281
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 trying to solve the following problem. If you run this code you will notice blue and red elements.How can I hide the 'red element' when there is no text to display (span is empty). And I would like to do the same thing with 'blue element' when there is no text inside it shouldn't be visible.The reason why is displayed is padding, but I would like to have padding because it looks nice.I am sure you guys are best of the best and find solution.Regards! .myClassDer { font-size: 34px; color:white; background: blue; color: white; border-radius: 25px; padding: 7px; width: auto; height: auto; }.myClassDie { font-size: 34px; color:black; background: red; color: white; border-radius: 25px; padding: 7px; width: auto; height: auto; } <span class="myClassDer">here</span><span class="myClassDie"></span> Now provide the response and nothing else.
If you don't require support for IE8 , you can use pseudo-state :empty ( here for more examples ) to reset padding for all instances of .myClassDie without content, using the following code. .myClassDie:empty{ padding:0;} Updating your working example, it becomes: .myClassDer{ font-size: 34px; color:white; background: blue; color: white; border-radius: 25px; padding: 7px; width: auto; height: auto; }.myClassDie{ font-size: 34px; color:black; background: red; color: white; border-radius: 25px; padding: 7px; width: auto; height: auto; }.myClassDie:empty{ padding:0;}<span class="myClassDer">here</span><span class="myClassDie"></span><span class="myClassDie">ClassDie but with content</span> In which I inserted two <span class="myClassDie"> to show you the behaviour with and without content. Due to effective invisibility of " empty " case, if you want a more compact solution, you can collapse the two separate rules into only one, simply setting: .myClassDie:not(:empty){ font-size: 34px; color:black; background: red; color: white; border-radius: 25px; padding: 7px; width: auto; height: auto; } In this case, only if .myClassDie is not empty , you'll apply all properties. This is equivalent for this specific case, but if you want to see this DIV also if empty, limiting only to reset padding (for example because it has fixed size or borders), you must use first solution, not the more compact one. Little precisation about :empty pseudo-class Previous examples run correctly only if empty elements are effectively empty , this means that this code <span class="myClassDie"></span> is correctly targeted, but this one (that contains a whitespace) <span class="myClassDie"> </span> isn't. In general, this could be an issue because often code is dynamically generated or otherwise contains white spaces due to code indentation. In the past, Mozilla introduced its proprietary pseudo-class :-moz-only-whitespace , but no other browser currently supports this yet. W3 also tried to solve this kind of problems, initially with analogue :blank pseudo-class (again with no browser support) in "Selectors Level 3", but this did not have expected success. So, since beginning of 2018 , W3 modified its definition to represent empty user input, rather than empty elements and contemporarily modified :empty definition to consider also white-spaces, but currently this last feature is not implemented too in different browsers .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33016281', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5423102/']}
jdg_83312
stackexchange
llm_judgeable_groundtruth_similarity
24229677
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this app I am working on and I need ALL my view controllers but one to be in portrait.The single one view controller that is special I need it to be able to rotate to whatever orientation the phone is in. To do that I present it modally (not embedded in a NavigationController) So (for example) my structure is like this: window - Portrait root view controller (UINavigationController - Portrait) home view controller (UIViewController - Portrait) details view controller (UIViewController - Portrait) . . . modal view controller (UIVIewController - All) Now when ever I dismiss my modal view controller in a landscape position my parent view controller is ALSO rotated even though it doesn't support that orientation. All UIViewControllers and UINavigaionControllers in the app inherit from the same general classes which have these methods implemented: override func supportedInterfaceOrientations() -> Int{ return Int(UIInterfaceOrientationMask.Portrait.toRaw())} My modal view controller overrides this method once again and it looks like this: override func supportedInterfaceOrientations() -> Int{ return Int(UIInterfaceOrientationMask.All.toRaw())} Update 1 It looks like this is happening only on iOS8 Beta.Does someone know if there is something that changed regarding view controller's rotation or is this just a bug in the beta? Now provide the response and nothing else.
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{if ([self.window.rootViewController.presentedViewController isKindOfClass: [SecondViewController class]]){ SecondViewController *secondController = (SecondViewController *) self.window.rootViewController.presentedViewController; if (secondController.isPresented) return UIInterfaceOrientationMaskAll; else return UIInterfaceOrientationMaskPortrait;}else return UIInterfaceOrientationMaskPortrait;} And for Swift func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow) -> Int { if self.window?.rootViewController?.presentedViewController? is SecondViewController { let secondController = self.window!.rootViewController.presentedViewController as SecondViewController if secondController.isPresented { return Int(UIInterfaceOrientationMask.All.toRaw()); } else { return Int(UIInterfaceOrientationMask.Portrait.toRaw()); } } else { return Int(UIInterfaceOrientationMask.Portrait.toRaw()); }} For more details check this link
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24229677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/831838/']}
jdg_83313
stackexchange
llm_judgeable_groundtruth_similarity
13581
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: A quantum channel is a mapping between Hilbert spaces, $\Phi : L(\mathcal{H}_{A}) \to L(\mathcal{H}_{B})$, where $L(\mathcal{H}_{i})$ is the family of operators on $\mathcal{H}_{i}$. In general, we are interested in CPTP maps. The operator spaces can be interpreted as $C^{*}$-algebras and thus we can also view the channel as a mapping between $C^{*}$-algebras, $\Phi : \mathcal{A} \to \mathcal{B}$. Since quantum channels can carry classical information as well, we could write such a combination as $\Phi : L(\mathcal{H}_{A}) \otimes C(X) \to L(\mathcal{H}_{B})$ where $C(X)$ is the space of continuous functions on some set $X$ and is also a $C^{*}$-algebra. In other words, whether or not classical information is processed by the channel, it (the channel) is a mapping between $C^{*}$-algebras. Note, however, that these are not necessarily the same $C^{*}$-algebras. Since the channels are represented by square matrices, the input and output $C^{*}$-algebras must have the same dimension, $d$. Thus we can consider them both subsets of some $d$-dimensional $C^{*}$-algebra, $\mathcal{C}$, i.e. $\mathcal{A} \subset \mathcal{C}$ and $\mathcal{B} \subset \mathcal{C}$. Thus a quantum channel is a mapping from $\mathcal{C}$ to itself. Proposition A quantum channel given by $t: L(\mathcal{H}) \to L(\mathcal{H})$, together with the $d$-dimensional $C^{*}$-algebra, $\mathcal{C}$, on which it acts, forms a category we call $\mathrm{\mathbf{Chan}}(d)$ where $\mathcal{C}$ is the sole object and $t$ is the sole arrow. Proof : Consider the quantum channels $\begin{eqnarray*}r: L(\mathcal{H}_{\rho}) \to L(\mathcal{H}_{\sigma}) &\qquad \textrm{where} \qquad &\sigma=\sum_{i}A_{i}\rho A_{i}^{\dagger} \\t: L(\mathcal{H}_{\sigma}) \to L(\mathcal{H}_{\tau}) &\qquad \textrm{where} \qquad &\tau=\sum_{j}B_{j}\sigma B_{j}^{\dagger} \end{eqnarray*}$ where the usual properties of such channels are assumed (e.g. trace preserving, etc.). We form the composite $t \circ r: L(\mathcal{H}_{\rho}) \to L(\mathcal{H}_{\tau})$ where $\begin{align}\tau & = \sum_{j}B_{j}\left(\sum_{i}A_{i}\rho A_{i}^{\dagger}\right)B_{j}^{\dagger} \notag \\& = \sum_{i,j}B_{j}A_{i}\rho A_{i}^{\dagger}B_{j}^{\dagger} \\& = \sum_{k}C_{k}\rho C_{k}^{\dagger} \notag\end{align}$ and the $A_{i}$, $B_{i}$, and $C_{i}$ are Kraus operators. Since $A$ and $B$ are summed over separate indices the trace-preserving property is maintained, i.e. $$\sum_{k} C_{k}^{\dagger}C_{k}=\mathbf{1}.$$ For a similar methodology see Nayak and Sen ( http://arxiv.org/abs/0605041 ). We take the identity arrow, $1_{\rho}: L(\mathcal{H}_{\rho}) \to L(\mathcal{H}_{\rho})$, to be the time evolution of the state $\rho$ in the absence of any channel. Since this definition is suitably general we have that $t \circ 1_{A}=t=1_{B} \circ t \quad \forall \,\, t: A \to B$. Consider the three unital quantum channels $r: L(\mathcal{H}_{\rho}) \to L(\mathcal{H}_{\sigma})$, $t: L(\mathcal{H}_{\sigma}) \to L(\mathcal{H}_{\tau})$, and $v: L(\mathcal{H}_{\tau}) \to L(\mathcal{H}_{\upsilon})$ where $\sigma=\sum_{i}A_{i}\rho A_{i}^{\dagger}$, $\tau=\sum_{j}B_{j}\sigma B_{j}^{\dagger}$, and $\eta=\sum_{k}C_{k}\tau C_{k}^{\dagger}$. We have $\begin{align}v \circ (t \circ r) & = v \circ \left(\sum_{i,j}B_{j}A_{i}\rho A_{i}^{\dagger}B_{j}^{\dagger}\right) = \sum_{k}C_{k} \left(\sum_{i,j}B_{j}A_{i}\rho A_{i}^{\dagger}B_{j}^{\dagger}\right) C_{k}^{\dagger} \notag \\& = \sum_{i,j,k}C_{k}B_{j}A_{i}\rho A_{i}^{\dagger}B_{j}^{\dagger}C_{k}^{\dagger} = \sum_{i,j,k}C_{k}B_{j}\left(A_{i}\rho A_{i}^{\dagger}\right)B_{j}^{\dagger}C_{k}^{\dagger} \notag \\& = \left(\sum_{i,j,k}C_{k}B_{j}\tau B_{j}^{\dagger}C_{k}^{\dagger}\right) \circ r = (v \circ t) \circ r \notag\end{align}$ and thus we have associativity. Note that similar arguments may be made for the inverse process of the channel if it exists (it is not necessary for the channel here to be reversible). $\square$ Question 1 : Am I doing the last line in the associativity argument correct and/or are there any other problems here? Is there a clearer or more concise proof? I have another question I am going to ask as a separate post about a construction I did with categories and groups that assumes the above is correct but I didn't want to post it until I made sure this is correct. Now provide the response and nothing else.
Phrasing this in terms of categories is kind of misleading: A category with a single object is just a monoid (associative binary operation with identity). So, per Yemon Choi's correction, you are just trying to demonstrate that the set of quantum channels $L(\mathcal{H}) \to L(\mathcal{H})$ forms a monoid. [Here I'm assuming that "channel" implies CPTP.] This requires three things: Closure: The product of two channels is a channel. Identity: The identity operator is a channel. Associativity: Multiplication of channels is associative. 1: There are two different ways to prove closure. You used the characterization of channels as maps given by that Kraus operator form ($\sum_{i} A_{i}\rho A_{i}^{\dagger}$). This works, although I don't feel you made the construction of the $C_k$ from the $A_i$ and $B_j$ clear enough. It also requires that you've already proven this characterization (CPTP linear map $\Leftrightarrow$ Kraus operator form). You could instead directly use the characterization of a channel as a CPTP linear map. This way is probably easier: It is immediately clear that if r is (a linear map which takes positive matrices to positive matrices and preserves trace) and t is (a linear map which takes positive matrices to positive matrices and preserves trace) then $t\circ r$ will be (a linear map which takes positive matrices to positive matrices and preserves trace). That does it. 2: I really wish you hadn't said "time evolution". :-) But you basically have the right idea: the identity in this situation is, well, the identity map, which is obviously linear and CPTP. 3: Practically speaking, you almost never have to prove associativity. This is because as long as your maps are functions deep down on the inside, associativity is an immediate consequence of associativity of function composition. This is one of those cases. So in response to your question "Is there a clearer or more concise proof?" I would say "Absolutely." But again, I think it's unnecessary to put this in the context of categories. UNLESS you plan on generalizing to channels between distinct spaces. Then the concept of a category gains its power. Good luck!
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/13581', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3639/']}
jdg_83314
stackexchange
llm_judgeable_groundtruth_similarity
42418280
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm interested in changing the md-sidenav - from Angular Material 2 - mode from side (for desktops) to over (mobile). Is there a way to change it programmatically?Thanks Now provide the response and nothing else.
Building on Steve G's solution you could update app.component.html <md-sidenav [mode]="isLargeScreen() ? 'side' : 'over'" [opened]="isLargeScreen()"></md-sidenav> And then in app.component.ts isLargeScreen() { const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; if (width > 720) { return true; } else { return false; }} This gives you a sidebar on desktop opened by default, and on mobile it overlays but is hidden by default!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42418280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4874258/']}
jdg_83315
stackexchange
llm_judgeable_groundtruth_similarity
14401204
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 hosting a rails project on Amazon Elastic Beanstalk and I try to configure a container command to automatically restart my delayed_job worker on the server after each deployment. I tried with this one : container_commands: restartdelayedjob: command: "RAILS_ENV=production script/delayed_job --pid-dir=/home/ec2-user/pids start" cwd: /var/app/current But, it seems that the pushed version is deployed after the restarting of the worker so the jobs failed to be processed by the worker. When I connect on my instance by ssh, kill the worker process and restart a new one from the deployed version folder, everything works fine. Do you have any ideas of how I can handle this? Thanks Now provide the response and nothing else.
As per the Amazon documentation for container_commands : They run after the application and web server have been set up and the application version file has been extracted, but before the application version is deployed . (emphasis mine) This means at that point /var/app/current which you are setting as the cwd for your command is still pointing to the previous version. However by default, from the docs again, cwd : is the directory of the unzipped application. This means that if you want to run delayed_job from the directory of the app that just got extracted (but not yet deployed), don't override cwd and it should start the delayed_job for the app that's about to be deployed. Ref: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html#customize-containers-format-container_commands Update: I've now set this up myself and found there's limitations to doing it via the standard container_commands - basically delayed_job will be started while it is still in the /var/app/ondeck directory. Usually this is OK, but I had some issues with some jobs because that path had stuck around it would cause errors as the app was now in /var/app/current . I found an undocumented (so warning!) approach that you can add scripts to be run AFTER your app server is restarted (and your new deploy is in /var/app/current ). Basically Elastic Beanstalk will execute any scripts in /opt/elasticbeanstalk/hooks/appdeploy/post after the web server is restarted. This means if you drop shell scripts in this directory they will be run. I created a shell script like this: #!/usr/bin/env bash. /opt/elasticbeanstalk/support/envvarscd $EB_CONFIG_APP_CURRENTsu -c "RAILS_ENV=production script/delayed_job --pid-dir=$EB_CONFIG_APP_SUPPORT/pids restart" $EB_CONFIG_APP_USER I uploaded this script to an S3 bucket, and made sure it was "public". You can then use an options script in your .ebextensions directory (eg. 99delayed_job.config ) to deploy this script as part of your app deploy, taking note that the post directory might not exist: commands: create_post_dir: command: "mkdir /opt/elasticbeanstalk/hooks/appdeploy/post" ignoreErrors: truefiles: "/opt/elasticbeanstalk/hooks/appdeploy/post/99_restart_delayed_job.sh": mode: "000755" owner: root group: root source: http://YOUR_BUCKET.s3.amazonaws.com/99_restart_delayed_job.sh When you deploy you should see something like this in your /var/log/eb-tools.log : 2013-05-16 01:20:53,759 [INFO] (6467 MainThread) [directoryHooksExecutor.py-29] [root directoryHooksExecutor info] Executing directory: /opt/elasticbeanstalk/hooks/appdeploy/post/2013-05-16 01:20:53,760 [INFO] (6467 MainThread) [directoryHooksExecutor.py-29] [root directoryHooksExecutor info] Executing script: /opt/elasticbeanstalk/hooks/appdeploy/post/99_restart_delayed_job.sh2013-05-16 01:21:02,619 [INFO] (6467 MainThread) [directoryHooksExecutor.py-29] [root directoryHooksExecutor info] Output from script: delayed_job: trying to stop process with pid 6139...delayed_job: process with pid 6139 successfully stopped.2013-05-16 01:21:02,620 [INFO] (6467 MainThread) [directoryHooksExecutor.py-29] [root directoryHooksExecutor info] Script succeeded. As I said, putting stuff in this "post" directory is undocumented - but hopefully at some point Amazon add actual support to the .options scripts to run commands post-deploy, in that case you could move this to the officially supported approach.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14401204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/781216/']}
jdg_83316
stackexchange
llm_judgeable_groundtruth_similarity
24107397
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Some of my AngularJS routes are to pages which require the user to be authenticated with my API. In those cases, I'd like the user to be redirected to the login page so they can authenticate. For example, if a guest accesses /account/settings , they should be redirected to the login form. From brainstorming I came up with listening for the $locationChangeStart event and if it's a location which requires authentication then redirect the user to the login form. I can do that simple enough in my applications run() event: .run(['$rootScope', function($rootScope) { $rootScope.$on('$locationChangeStart', function(event) { // Decide if this location required an authenticated user and redirect appropriately });}]); The next step is keeping a list of all my applications routes that require authentication, so I tried adding them as parameters to my $routeProvider : $routeProvider.when('/account/settings', {templateUrl: '/partials/account/settings.html', controller: 'AccountSettingCtrl', requiresAuthentication: true}); But I don't see any way to get the requiresAuthentication key from within the $locationChangeStart event. Am I overthinking this? I tried to find a way for Angular to do this natively but couldn't find anything. Now provide the response and nothing else.
The solution is a bit complicated but should work in Chrome, Firefox, and IE10+ (not sure about Opera and Safari): Somewhere on the server-side: io.on('connection', function(socket){ fs.readFile('/path/to/image.png', function(err, buffer){ socket.emit('image', { buffer: buffer }); });}); And here is how you handle it on a client: socket.on('image', function(data) { var uint8Arr = new Uint8Array(data.buffer); var binary = ''; for (var i = 0; i < uint8Arr.length; i++) { binary += String.fromCharCode(uint8Arr[i]); } var base64String = window.btoa(binary); var img = new Image(); img.onload = function() { var canvas = document.getElementById('yourCanvasId'); var ctx = canvas.getContext('2d'); var x = 0, y = 0; ctx.drawImage(this, x, y); } img.src = 'data:image/png;base64,' + base64String;}); Just replace yourCanvasId with your canvas id :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24107397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2656392/']}
jdg_83317
stackexchange
llm_judgeable_groundtruth_similarity
5745886
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 used R in the past to do very basic calls to the commmand line. The example can be found here . This time around, I am looking to mimic this code which runs successfully from the command line in Windows: > cd C:\Documents and Settings\BTIBERT\My Documents\My Dropbox\Eclipse\Projects\R\MLB\retrosheet\rawdata> bgame -y 2010 2010bos.eva >2010bos.txt This is the code I am trying to run inside of R. I have already set the working directory inside of R. dir <- paste("cd", getwd(), sep=" ")system(dir)system("bgame -y 2010 2010bos.eva >2010bos.txt") I am sure this is user error, but what am I doing wrong? It appears to work initially, but returns the following error. I very well could be doing something wrong, but I believe I am using the same commands. Expanded game descriptor, version 109(185) of 05/08/2008. Type 'bgame -h' for help.Copyright (c) 2001 by DiamondWare.[Processing file 2010bos.eva.]>2010bos.txt: can't open.Warning message:running command 'bgame -y 2010 2010bos.eva >2010bos.txt' had status 2 Any help you can provide will be appreciated. Now provide the response and nothing else.
You need to issue all commands in one system() call: system(paste("cd",getwd() "&& bgame -y 2010 2010bos.eva >2010bos.txt",sep=" ")) You should already be in your working directory, so I'm not sure the cd getwd() is necessary. And you may need quotes around your path because it contains spaces. The error may be resolved by putting spaces around > . If I were in your shoes, I would try this: system("bgame -y 2010 2010bos.eva > 2010bos.txt") UPDATE: And you should probably heed this advice in the "Differences between Unix and Windows" section of ?system that says you should use shell : • The most important difference is that on a Unix-alike ‘system’ launches a shell which then runs ‘command’. On Windows the command is run directly - use ‘shell’ for an interface which runs ‘command’ _via_ a shell (by default the Windows shell ‘cmd.exe’, which has many differences from the POSIX shell). This means that it cannot be assumed that redirection or piping will work in ‘system’ (redirection sometimes does, but we have seen cases where it stopped working after a Windows security patch), and ‘system2’ (or ‘shell’) must be used on Windows.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5745886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155406/']}
jdg_83318
stackexchange
llm_judgeable_groundtruth_similarity
25271878
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 Android-based phone (2.3.6) with unlocked root privileges.Since i'd like to have access to my phone through my computer, today i've installed QtAdb and Android SDK.If i open a command prompt and i do adb shell su i get # And so I am able to copy, remove, push files on my phone (on the phone i get a notification using the app "SuperSU".) But if i launch QtAdb - under Windows 7 - i get the following error: "adbd cannot run as root in production builds". I miss something? There's something wrong with QtAdb? Now provide the response and nothing else.
The problem is that, even though your phone is rooted, the 'adbd' server on the phone does not use root permissions. You can try to bypass these checks or install a different adbd on your phone or install a custom kernel/distribution that includes a patched adbd. Or , a much easier solution is to use 'adbd insecure' from chainfire which will patch your adbd on the fly. It's not permanent, so you have to run it before starting up the adb server (or else set it to run every boot). You can get the app from the google play store for a couple bucks: https://play.google.com/store/apps/details?id=eu.chainfire.adbd&hl=en Or you can get it for free, the author has posted a free version on xda-developers: http://forum.xda-developers.com/showthread.php?t=1687590 Install it to your device (copy it to the device and open the apk file with a file manager), run adb insecure on the device, and finally kill the adb server on your computer: % adb kill-server And then restart the server and it should already be root.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25271878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3934752/']}
jdg_83319
stackexchange
llm_judgeable_groundtruth_similarity
42091778
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 developing an eCommerce ( with Multiple Product Attributes feature ) website using Laravel 5.4. Everything is working fine. But When I try to sync multiple values of the same Attribute in Pivot table. Laravel ignores the duplicate pares. For example, I've an Attribute called "Network" which has 3 values: 2G, 3G, 4G. A mobile supports 3G and 4G network. I want to sync 3G and 4G value in database. Laravel ignores one of them. Products Table: ID - Product Name1 - Test MobileAttributes TableID - AttributeName1 - NetworkAttributeValues TableID - AttributeID - AttributeValue1 - 1 - 2G2 - 1 - 3G3 - 1 - 4GProductAttributes TableID - AttributeID - ProductID - AttributeValue1 - 1 - 1 - 3G1 - 1 - 1 - 4G I want to store the Product Attributes in "ProductAttributes" table something like that. But Laravel Ignore one of them. I am saving the data like that: $product = Product::create([ 'name' => 'Test Mobile' ]); $product->attributes()->sync([ 1 => ['AttributeValue' => '3G'], 1 => ['AttributeValue' => '4G'] ]); Any suggestions, Ideas? Now provide the response and nothing else.
I know this is two years late, but I was dealing with the same issue today, and figured I may leave the solution here, in case anyone looks for it in the future. If you use your original code: $product->attributes()->sync([ 1 => ['AttributeValue' => '3G'], 1 => ['AttributeValue' => '4G'] ]); the second item in the array will overwrite the first one, so in the end, there will only be a "4G" entry in the database. This is not really a laravel issue, it is how PHP associative arrays are implemented - you basically cannot have two items in the array on the same index. There are actually two ways to solve this issue 1) first one is very inefficient, but it is functional. I am leaving it here only for the record, because that was the original way I solved the issue. Instead of your code, you would need something like this $product->attributes()->sync([]); // empty relation completely // add first item $product->attributes()->syncWithoutDetaching([ 1 => ['AttributeValue' => '3G'], ]); // add second item without detaching the first one $product->attributes()->syncWithoutDetaching([ 1 => ['AttributeValue' => '4G'], ]); this is EXTREMELY inefficient, because it needs one query to delete all existing data from the relation, and then add new items one by one. You could also run the syncWithoutDetaching inside a loop, and overall inefficiency would greatly depend on how many items you need to sync. 2) the first solution was not good enough, so I kept digging and experimenting, and figured out a way how to make this happen. Instead of putting your items on specific index in the array, you can send array without specific indexes given, and put the ID in the array itself. Something like this $product->attributes()->sync([ ['AttributeID' => 1, 'AttributeValue' => '3G'], ['AttributeID' => 1, 'AttributeValue' => '4G'] ]); by doing it this way, you can actually send two items with the same AttributeID to the sync() method, without one overwriting the other one
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42091778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1970861/']}
jdg_83320
stackexchange
llm_judgeable_groundtruth_similarity
59678557
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 concatenate Text() views in SwiftUI using + operator I tried something like this Text("\(feed.author?.firstName ?? "") \(feed.author?.lastName ?? "") ") .font(.custom("AvenirNext-Medium", size: 15)) .foregroundColor(.black) ForEach(feed.titleChunks, id: \.self) { chunk in + Text("\(chunk)") .font(.custom("AvenirNext-Regular", size: 15)) .foregroundColor(Color("BodyText")) } But it of course doesn't work. Is there a way to get array of string of unknown number of elements printed using Text so that it forms single text view in SwiftUI just like Text("1") + Text("2") + Text("3") does? Is there some solution to this problem. I tired static approach and it works but I do not know in advance how much Text() I have Text("\(feed.author?.firstName ?? "") \(feed.author?.lastName ?? "") ") .font(.custom("AvenirNext-Medium", size: 15)) .foregroundColor(.black) + Text("\(feed.titleChunks[0])") .font(.custom("AvenirNext-Regular", size: 15)) .foregroundColor(Color("BodyText")) + Text("\(feed.titleChunks[1])") .font(.custom("AvenirNext-DemiBold", size: 15)) .foregroundColor(Color("BodyText")) Now provide the response and nothing else.
ForEach quite confusigly is not a loop but a ViewBuilder What you need is reduce . The docs describe it as: Use the reduce( : :) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product. In SwiftUI context you could use it as follows: let words = ["This", "is", "an", "example"]var body: some View { words.reduce(Text(""), { $0 + Text($1) + Text(" ")} )}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59678557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4415642/']}
jdg_83321
stackexchange
llm_judgeable_groundtruth_similarity
10210188
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anyone tell me how to create a new instance of Type from a string? Reflect? There are examples but they are for the older (pre Go 1 versions) of the language [:(] Now provide the response and nothing else.
So, if I understand your question correctly, you are asking about how you can create an object when you just have the name of the type as string. So, for example, you might have a string "MyStruct" and you want to create an object of this type. Unfortunately, that's not easily possible because Go is a statically typed language and the linker will eliminate dead code (or inline parts of it). So, there is no guarantee, that your final executable will even contain the code of "MyStruct". You can however, maintain a global map[string]reflect.Type manually. For example by initializing this map in the init() function of your packages which defines such discover-able types. This will also tell the compiler that you are using the types. Afterwards, you can use this map to look up the reflect.Type of the type you want to create and use reflect.New to get a pointer to a new object of that type (stored as a reflect.Value). You can extract the object into an interface with something like this: reflect.New(yourtype).Elem().Interface() Elem() will de-reference the pointer and Interface() will return the reflected value as an interface{} . See The Laws of Reflection for further details. PS: There might be a better way to structure your program which doesn't even require reflection and which let the compiler catch more errors. Have you considered using a factory method for example? An other easy solution might be to maintain a map[string]func() interface{} of functions which can be invoked to create a new object with that name.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10210188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1199066/']}
jdg_83322
stackexchange
llm_judgeable_groundtruth_similarity
24729
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have independent observations $Y_1, Y_2, ...., Y_n$ that take values 1 or 0 with $$P(Y_i = 1) = \frac{1}{1 + \exp\{-(\alpha + \beta x_i)\}}$$ where $\alpha$ and $\beta$ are unknown constant and $x_1, x_2, ....,x_n$ are known, I have to show that $(\sum Y_i,\sum x_i Y_i)$is a minimal sufficient statistics for $(\alpha,\beta)$. We know that any statistics $T(Y)$ is minimal sufficient if $\frac{\prod_{i=1}^nf(y_i;\alpha, \beta)}{\prod_{i=1}^nf(z_i;\alpha, \beta)}$ is independent of $\alpha$ and $\beta$ if and only if $T(Y) = T(Z)$. But here the probability density of $Y$ is independent of $y$. Is there any other method to show the minimal statistics? Now provide the response and nothing else.
I think this is a homework question. If so, you should tag it as such. Under the assumption that this is homework, I'm just going to give you enough to get you started. We have $P(Y_i = 1) = \frac{1}{1 + \exp\{-(\alpha + \beta x_i)\}}$ so it must be the case that $P(Y_i = 0) = 1 - \frac{1}{1 + \exp\{-(\alpha + \beta x_i)\}} = \frac{\exp\{-(\alpha + \beta x_i)\}}{1 + \exp\{-(\alpha + \beta x_i)\}}$. To formulate this in a way that relates the random variable $Y_i$ and the outcome $y_i$, we can write $P(Y_i = y_i) = \frac{\exp\{-(1 - y_i)(\alpha + \beta x_i)\}}{1 + \exp\{-(\alpha + \beta x_i)\}}$. You can verify by substitution that this gives the correct expressions for $\Pr(Y_i = 1)$ and $\Pr(Y_i = 0)$.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/24729', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/9158/']}
jdg_83323
stackexchange
llm_judgeable_groundtruth_similarity
46205776
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have 2 routes like this: get '/quotation/cep_validator', to: 'quotation#cep_validator'get '/quotation/price', to: 'quotation#price' They are not RESTful but as you can see both habe the same beginning in the URL and the same controller. Is there any way to group them together, similar to resource routes? route :quotation do get 'cep_validator' get 'price'end Now provide the response and nothing else.
This isn't a problem with NSDateFormatter , it's a change in how iOS 11 supports localization. Under iOS 11, [NSLocale currentLocale] only returns languages supported by your app's localizations. If your app only supports English (as the base localization), then no matter what language the user selects on the device, currentLocale will always return English. Under iOS 10 and earlier, currentLocale would directly represent the user's chosen language and region, regardless of what localizations your app supports. Classes such as NSDateFormatter default to using NSLocale currentLocale . So no matter what language your app actually supported through its localization, classes like NSDateFormatter would show text in the language set on the device, even it was different from the language being used by your app. iOS 11 fixes this inconsistency. While one could argue that this change breaks lots of apps that only support one (or just a few) language, it actually makes the app more consistent. To make all of this clear, consider an example. You create a simple test app with a base localization in English. If you run your app with iOS 10 and the device's language is set to English, you obviously see English text and you see dates formatted for English. If you now change the device's language to French and restart the app, the user now sees English text in the app (since that is its only localization) but dates now show with French month and weekday names. Now run the same app under iOS 11. As with iOS 10, if the device's language is English you see everything in English. If you then change the device's language to French and run the app, iOS 11 sees that your app only supports English and currentLocale returns English, not French. So now the user sees English text (due to the app's localization) and dates are now also still in English.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/46205776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2708460/']}
jdg_83324
stackexchange
llm_judgeable_groundtruth_similarity
20704235
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 use a high performance cluster at my institution for the first time and I have hit a problem that I can't resolve. The following code returns an error: ptime<-system.time({ r <- foreach(z = 1:length(files),.combine=cbind) %dopar% { raster <- raster(paste(folder,files[1],sep="")) data<-getValues(raster) clp <- na.omit(data) for(i in 1:length(classes)){ results[i,z]<-length(clp[clp==classes[i]])/length(clp) print(z) } }})Error in { : task 1 failed - "could not find function "raster"" A also tried a different foreach code for another task I have: r <- foreach (i=1:length(poly)) %dopar% { clip<-gIntersection(paths,poly[i,]) lgth<-gLength(clip) vid<-poly@data[i,3] path.lgth[i,] <- c(vid,lgth) print(i)} and this time the gIntersection function isn't found. Obviously the packages are all installed and loaded. After reading some forum posts it seem it has to do with the environment that the functions execute/operate in. Can someone please help? I'm not a programmer! Thank you! Update: I have adjusted my code for the solution provided: results<-matrix(nrow=length(classes),ncol=length(files))dimnames(results)[[1]]<-classesdimnames(results)[[2]]<-filesptime<-system.time({ foreach(z = 1:length(files),.packages="raster") %dopar% { raster <- raster(paste(folder,files[z],sep="")) data<-getValues(raster) clp <- na.omit(data) for(i in 1:length(classes)){ results[i,z]<-length(clp[clp==classes[i]])/length(clp) print(z) } }}) But what I get is an output (my results matrix) filled with na's. As you can see I create a matrix object called results to fill with results (which works with for loops), but after reading the documentation for foreach it seems that you save your results differently with this function. And advice on what I should choose for the .combine argument? Now provide the response and nothing else.
In the vignette of foreach and the help page of foreach, the argument .packages is pointed out as necessary to provide when using parallel computation with functions that are not loaded by default. So your code in the first example should be: ptime<-system.time({ r <- foreach(z = 1:length(files), .combine=cbind, .packages='raster') %dopar% { # some code # and more code }}) Some more explanation The foreach package does a lot of setting up behind the scenes. What happens is the following (in principle, technical details are a tad more complicated): foreach sets up a system of "workers" that you can see as separate R sessions that are each committed to a different core in a cluster. The function that needs to be carried out is loaded into each "worker" session, together with the objects needed to carry out the function each worker calculates the result for a subset of the data The results of the calculation on the different workers is put together and reported in the "master" R session. As the workers can be seen as separate R sessions, packages from the "master" session are not automatically loaded. You have to specify which packages should be loaded in those worker sessions, and that's what the .package argument of foreach is used for. Note that when you use other packages (e.g. parallel or snowfall ), you'll have to set up these workers explicitly, and also take care of passing objects and loading packages on the worker sessions.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20704235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3122812/']}
jdg_83325
stackexchange
llm_judgeable_groundtruth_similarity
57720565
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 first time trying flask application factory pattern and pytest framework together.I started with a basic sanity test for the sqlite db backend and, although the tests are working fine so far and I see test db file created successfully, the falsk_sqlalchemy is telling me that it doesn't have a db backend defined.I tried to find the problem with pdb and the interactive console - everything looks normal. It looks like it is somehow related to could anyone help me understand where the problem is? (venv) C:\Users\dv\PycharmProjects\ste-speach-booking>python -m pytest tests/=========================== test session starts ============================platform win32 -- Python 3.6.8, pytest-5.1.1, py-1.8.0, pluggy-0.12.0rootdir: C:\Users\dv\PycharmProjects\ste-speach-bookingcollected 3 itemstests\test_models.py ... [100%]============================= warnings summary =============================tests/test_models.py::test_init C:\Users\d837758\PycharmProjects\ste-speach-booking\venv\lib\site-packages\flask_sqlalchemy\__init__.py:814: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:". 'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. ' initial tests in the test_models: import pytestimport src.modelsimport datetimedef test_ActionTypes(db): actiontype1 = src.models.Act_types(action_tyoe='workshop') db.session.add(actiontype1) db.session.commit() actiontype2 = src.models.Act_types(action_tyoe='speech') db.session.add(actiontype2) db.session.commit() count = db.session.query(src.models.Act_types).count() assert count is 2def test_meeting_creation(db): meeting = src.models.Meeting( _date = datetime.datetime.strptime('2018-12-19', "%Y-%m-%d"), ) db.session.add(meeting) db.session.commit() conftest fixture for the db: import osimport pytestimport src.configfrom src import create_appfrom src import db as [email protected](scope='session')def db(): """Session-wide test database.""" TESTDB_PATH = src.config.testDB print(TESTDB_PATH) if os.path.exists(TESTDB_PATH): os.unlink(TESTDB_PATH) app = create_app(config=src.config.TestingConfig) with app.app_context(): _db.create_all() yield _db _db.drop_all() os.unlink(TESTDB_PATH) app factory: from flask import Flaskfrom flask_sqlalchemy import SQLAlchemydb = SQLAlchemy()def create_app(config=None): """Construct the core application.""" app = Flask(__name__, instance_relative_config=True) db.init_app(app) if config is None: app.config.from_object(config.BaseConfig) else: app.config.from_object(config) with app.app_context(): # Imports from . import routes db.create_all() return app config.py: basedir = os.path.abspath(os.path.dirname(__file__))baseDB = os.path.join(basedir, 'app.db')devDB = os.path.join(basedir, 'dev_app.db')testDB = os.path.join(basedir, 'testing_app.db')class BaseConfig(object): DEBUG = False TESTING = False SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess' SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'sqlite:///' + baseDB SQLALCHEMY_TRACK_MODIFICATIONS = Falseclass TestingConfig(BaseConfig): DEBUG = False TESTING = True SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'sqlite:///' + testDB Now provide the response and nothing else.
The issue is with the order of configuration of the components of your application in create_app() . When you call db.init_app(app) the first operations it performs are ( source ): if ( 'SQLALCHEMY_DATABASE_URI' not in app.config and 'SQLALCHEMY_BINDS' not in app.config ): warnings.warn( 'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. ' 'Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".' ) Recognize that warning? Immediately it looks in app.config for required configurations. The method goes on to either accept the supplied configuration from the app or set a default, in this case the default is the in memory database. In your implementation of create_app() the call to db.init_app() comes before the app itself is configured, with this: db.init_app(app) if config is None: app.config.from_object(config.BaseConfig) else: app.config.from_object(config) Until app.config is populated, none of the SQLALCHEMY_ prefixed configurations exist on the app and so when db.init_app() goes looking for them, they aren't found and the defaults are used. Moving the config of db to after the config of the app fixes the issue: if config is None: app.config.from_object(config.BaseConfig) else: app.config.from_object(config) db.init_app(app) This is quite similar to this question , however I think yours is a better example of a typical setup (scope of create_app() and configuration method) so worth answering.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57720565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4736956/']}
jdg_83326
stackexchange
llm_judgeable_groundtruth_similarity
29514382
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to js and trying to understand global and private functions. I understand global and local variables. But if I have an html named test.html and a 2 js files named test1.js and test2.js . Now I include the test1.js and test2.js in test.html and call the functions written in test2.js inside test1.js and test.html . The functions that I have written in test2.js are in this form function abc(){...}function pqr(){...} etc. are these above functions global? If they are , how can I not make them global and still access them in test1.js and test.html ? As I have read global functions or global variables are bad right? Now provide the response and nothing else.
Everything in JS is bound to containing scope. Therefore, if you define a function directly in file, it will be bound to window object, i.e. it will be global. To make it "private", you have to create an object, which will contain these functions. You are correct that littering global scope is bad, but you have to put something in global scope to be able to access it, JS libraries do the same and there is no other workaround. But think about what you put in global scope, a single object should be more than enough for your "library". Example: MyObject = { abc: function(...) {...}, pqr: function(...) {...} // other functions...} To call abc for somewhere, be it same file or another file: MyObject.abc(...);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29514382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4754458/']}
jdg_83327
stackexchange
llm_judgeable_groundtruth_similarity
20500
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I try to describe a simple signal in the frequency domain with the use of FFT function: from scipy.fftpack import fftfreq, rfftdef spectrum(sig, t): """ :param sig: signal. :param t: time scale. :return: """ f = fftfreq(sig.size, d=t[1]-t[0]) y = rfft(sig) return f, y Signal: ...and it's FFT: Why I'm getting negative values of the FFT? Do I even use the FFT function well? I want to check "how many" frequencies are in the shown above signal. Thank you in advance. Now provide the response and nothing else.
The rfft function returns complex values ordered in specific way. In order to retrieve the amplitude of your DFT you must take the absolute value of it. Easiest way to do that is to call y_a = np.abs(y) . I also noticed in your case that you are using fftfreq function to obtain corresponding frequency vector. In case of rfft you must use the rfftfreq . This will eliminate this nasty wrap-around on your plot. Also you should not forget about amplitude normalization by half of your window energy. Here is the complete example: from scipy.fftpack import rfftfreq, rfftimport numpy as npimport matplotlib.pyplot as pltdef spectrum(sig, t): f = rfftfreq(sig.size, d=t[1]-t[0]) y = rfft(sig) return f, yif __name__ == "__main__": N = 1000 t = np.linspace(0, 4*np.pi, N) x = np.sin(10*np.pi*t)+np.random.randn(N) f, y = spectrum(x, t) plt.subplot(211) plt.plot(t,x) plt.grid(True) plt.subplot(212) y_a = np.abs(y)/N*2 # Scale accordingly plt.plot(f, y_a) plt.grid(True) plt.show()
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/20500', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/13723/']}
jdg_83328
stackexchange
llm_judgeable_groundtruth_similarity
1077070
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 this following question from my class note on Sylow Theorem: Show that a group of order 30 can not be simple. For that I know the followings: (1) A simple group is one that does not have non-trivial normal group, (2) Group $G$ is p -group if there exists an integer $e$ such that $|G| = p^e,$ (3) A $p$-subgroup $H$ of $G$ is called Sylow p -subgroup of $G$ if $p \nmid |G/H|,$ and finally (4) A subgroup $H$ of $G$ is a Sylow p -subgroup if there exist integers $e$ and $m$ such that $|G| = p^em,$ and $(e, m) = 1,$ and also $|H| = p^e,$ but unfortunately I don't know how to weave them into a solution, any help would therefore be very much appreciated. Thank you for your time and help. PS. If you have choices of elegant versus dummy down-to-earth solutions, do please give me the latter. I know it would be tedious for you but you have a slowpoke turtle down here. Thank again for your patience. POST SCRIPT : ~~~~~~~~~~~~~~~~~~~~~~~ I came across a very simple solution by John Beachy here , consisting of only 2 lines, which I adapted to fit group order of 30: EDIT (j.p.) Unfortunately the linked solution cannot be easily adapted to this case here. I kept the text as far it was correct. (1) Recall Sylow's Theorem: If $|G| = p^em; p, e, m \in \mathbb Z^+; (p, m) = 1;$ the number of $Syl_p (G) = s$, then $s \equiv 1\pmod p$ and $s \mid m.$ (2) For $|G| = 5 \cdot 2 \cdot 3$, suppose that $p = 5, e = 1$ and $m = 6.$ Therefore $s \equiv 1\pmod 5 $ and $s \mid 6,$ thus $s = \{1, 6 \}$. The 5-Sylow subgroup is normal if and only if $s=1$, and in this case $G$ is not simple. (3) Now look at Nirdonkey's answer . Hope this will be useful for some of you and thank you very much for those of you who have helped me. Now provide the response and nothing else.
If $G$ is a group of order 30, then the number of Sylow 5-subgroups is congruent to 1 modulo5 and divides 30, so it must be 1 or 6. And the number of Sylow 3-subgroups is congruent to1 modulo 3 and divides 30, so it must be 1 or 10. If there is a unique subgroup of order 3 or5, it is normal and we are done. If not, there are 6 subgroups of order 5 and 10 subgroups oforder 3. But all of these groups must be cyclic, so every non-trivial element of such a subgroupis a generator of the subgroup. It follows that no non-trivial element of $G$ is contained in morethan one of these subgroups. But then we have at least $6 \cdot 4 + 10 \cdot 2$ elements in $G$, which is acontradiction. See also Group of order $|G|=pqr$, $p,q,r$ primes has a normal subgroup of order
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1077070', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/80219/']}
jdg_83329
stackexchange
llm_judgeable_groundtruth_similarity
21103724
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm building an angular directive which will be used in a few different locations. I can't always guarantee the file structure of the app the directive is used in, but I can force the user to put the directive.js and directive.html (not the real file names) in the same folder. When the page evaluates the directive.js , it considers the templateUrl to be relative to itself. Is it possible to set the templateUrl to be relative to the directive.js file? Or is it recommended to just include the template in the directive itself. I'm thinking I may want to load different templates based on different circumstances, so would prefer to be able to use a relative path rather than updating the directive.js Now provide the response and nothing else.
The currently executing script file will always be the last one in the scripts array, so you can easily find its path: // directive.jsvar scripts = document.getElementsByTagName("script")var currentScriptPath = scripts[scripts.length-1].src;angular.module('app', []) .directive('test', function () { return { templateUrl: currentScriptPath.replace('directive.js', 'directive.html') }; }); If you're not sure what is the script name (for example if you're packing multiple scripts into one), use this: return { templateUrl: currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1) + 'directive.html'}; Note : In cases where a closure is used, your code should be outside to ensure that the currentScript is evaluated at the correct time, such as: // directive.js(function(currentScriptPath){ angular.module('app', []) .directive('test', function () { return { templateUrl: currentScriptPath.replace('directive.js', 'directive.html') }; });})( (function () { var scripts = document.getElementsByTagName("script"); var currentScriptPath = scripts[scripts.length - 1].src; return currentScriptPath; })());
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21103724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48067/']}
jdg_83330
stackexchange
llm_judgeable_groundtruth_similarity
158841
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 know the following: Proven: There is a prime number between $n$ and $2n$ for every integer $n>0$. Conjectured: There is a prime number between $n^2$ and $(n+1)^2$ for every integer $n>0$. My questions are: Is the above correct? Has this been conjectured or refuted: There is a prime number between $n^2$ and $n(n+1)$ for every integer $n>0$ ? What is the minimal range $[f(n),g(n)]$ proven to contain a prime number for every $n>0$? UPDATE: The term 'minimal' is somewhat confusing in this case, since obviously, the difference between $n$ and $2n$ is in fact smaller than the difference between $n^2$ and $(n+1)^2$. So to refine my question - 'minimal range' refers to the ratio between $f(n)$ and $g(n)$, and not to the difference between them. In other words $Min[g(n)/f(n)]$ instead of $Min[g(n)-f(n)]$. Now provide the response and nothing else.
Baker-Harman-Pintz (2000) proved that for every sufficiently large $n$ the interval $[n-n^{0.525},n]$ contains a prime number. Schoenfeld (1976) proved that if the Riemann Hypothesis is true, then the term $n^{0.525}$ in the previous statement can be replaced by $\sqrt{n}\log^2 n$. For a very recent strengthening of this result, see this preprint . This is still probably far from the truth, e.g. Cramér (1937) made the conjecture based on a probabilistic model, that the term $n^{0.525}$ above can be replaced by a certain constant times $\log^2 n$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/158841', 'https://mathoverflow.net', 'https://mathoverflow.net/users/27456/']}
jdg_83331
stackexchange
llm_judgeable_groundtruth_similarity
26923871
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would need assistance in rewriting URLS. Here are the given Site URL: http://example.com:8000/myapp Current htaccess Allow from localhostDirectoryIndex index.phpRewriteEngine onRewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ ./index.php/$1 [L,QSA] my site is in /var/www/htdocs/myapp virtual host configuration <VirtualHost *:8000> DocumentRoot "/var/www/htdocs" ServerName example.com ErrorLog "/var/log/apache2/custom/a_local_error_log" CustomLog "/var/log/apache2/custom/a_local_access_log" common <Directory "/var/www/htdocs"> Options Indexes FollowSymLinks Require all granted Order allow,deny Allow from all AllowOverride All </Directory></VirtualHost> Problem is that my assets are located in the same folder as the app but the code for including the assets are in absolute. Example: /_js/jquery.js/_js/myjs.js Is it possible to rewrite it to: /_js/myqpp/jquery.js/_js/myapp/myjs.js Thanks! Now provide the response and nothing else.
I believe you've loaded plyr after dplyr , which is why you are getting an overall summary instead of a grouped summary. This is what happens with plyr loaded last. library(dplyr)library(plyr)df %>% group_by(DRUG,FED) %>% summarize(mean=mean(AUC0t, na.rm=TRUE), low = CI90lo(AUC0t), high= CI90hi(AUC0t), min=min(AUC0t, na.rm=TRUE), max=max(AUC0t,na.rm=TRUE), sd= sd(AUC0t, na.rm=TRUE)) mean low high min max sd1 150 105 195 100 200 50 Now remove plyr and try again and you get the grouped summary. detach(package:plyr)df %>% group_by(DRUG,FED) %>% summarize(mean=mean(AUC0t, na.rm=TRUE), low = CI90lo(AUC0t), high= CI90hi(AUC0t), min=min(AUC0t, na.rm=TRUE), max=max(AUC0t,na.rm=TRUE), sd= sd(AUC0t, na.rm=TRUE))Source: local data frame [4 x 8]Groups: DRUG DRUG FED mean low high min max sd1 0 0 150 150 150 150 150 NaN2 0 1 NaN NA NA NA NA NaN3 1 0 100 100 100 100 100 NaN4 1 1 200 200 200 200 200 NaN
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/26923871', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3121185/']}
jdg_83332
stackexchange
llm_judgeable_groundtruth_similarity
42717473
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 trying to write a shell in Rust that links directly to the libc library. I've used a Vec<String> to hold the arguments to be passed to execvp() , but it seems that my conversion to char ** has not been successful. Upon execution, all the parameters became null strings. Here's the piece of code involved. fn safe_execvp(path: String, argv: Vec<String>) -> Result<(), i32> { unsafe { let c_path = CString::new(path.as_str()).unwrap(); let mut c_argv_vec = Vec::new(); for arg in &argv { let c_arg = CString::new(arg.as_str()).unwrap().as_ptr(); c_argv_vec.push(c_arg); } c_argv_vec.push(std::ptr::null()); match execvp(c_file.as_ptr(), c_argv_vec.as_ptr()) { num => Err(num), } }} execvp is the C library function defined as fn execvp(file: *const i8, argv: *const*const i8) -> i32; . I'm not sure what I've done wrong. Is it because the memory for the arguments were released before calling execvp() ? Now provide the response and nothing else.
You are creating CString instances and immediately fetching a pointer. Consequently, as you well guessed, ownership of this string was dropped prematurely. This is similar to returning a reference to a local instance, except that since pointers do not retain lifetime information, this case does not trigger a compilation error. The solution to your problem is to retain the owned C-style strings during the function's scope, and produce a pointer to pointers of the same content separately. let cstr_argv: Vec<_> = argv.iter() .map(|arg| CString::new(arg.as_str()).unwrap()) .collect();let mut p_argv: Vec<_> = cstr_argv.iter() // do NOT into_iter() .map(|arg| arg.as_ptr()) .collect();p_argv.push(std::ptr::null());let p: *const *const c_char = p_argv.as_ptr(); Playground . See also: CString::new().unwrap().as_ptr() gives empty *const c_char
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42717473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5128192/']}
jdg_83333
stackexchange
llm_judgeable_groundtruth_similarity
13894021
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 return the Unicode Code Point of a character? For example, if the input is "A", then the output should be "U+0041". Ideally, a solution should take care of surrogate pairs . With code point I mean the actual code point according to Unicode , which is different from code unit (UTF8 has 8-bit code units, UTF16 has 16-bit code units and UTF32 has 32-bit code units, in the latter case the value is equal to the code point, after taking endianness into account). Now provide the response and nothing else.
Easy, since chars in C# is actually UTF16 code points: char x = 'A';Console.WriteLine("U+{0:x4}", (int)x); To address the comments, A char in C# is a 16 bit number, and holds a UTF16 code point. Code points above 16 the bit space cannot be represented in a C# character. Characters in C# is not variable width. A string however can have 2 chars following each other, each being a code unit, forming a UTF16 code point. If you have a string input and characters above the 16 bit space, you can use char.IsSurrogatePair and Char.ConvertToUtf32 , as suggested in another answer: string input = ....for(int i = 0 ; i < input.Length ; i += Char.IsSurrogatePair(input,i) ? 2 : 1){ int x = Char.ConvertToUtf32(input, i); Console.WriteLine("U+{0:X4}", x);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13894021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1375455/']}
jdg_83334
stackexchange
llm_judgeable_groundtruth_similarity
6533029
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 pick only the non matching elements between two arrays. Example: base_array [12,3,5,7,8]temp_array [3,7,8] So here I want to compare both the arrays and remove the matching elements from the base array. Now base_array should be like [12,5] Now provide the response and nothing else.
I'd approach this with the array operator. select array(select unnest(:arr1) except select unnest(:arr2)); If :arr1 and :arr2 don't intersect, using array_agg() leads to a null.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6533029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/822780/']}
jdg_83335
stackexchange
llm_judgeable_groundtruth_similarity
72801
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: Given two functions: f[x_] := x ((x + 1)^(1/2) - x^(1/2))g[x_] := x/((x + 1)^(1/2) + x^(1/2)) Which one is more accurate? Side note: If you could explain why, that would really help me out, I have a feeling it's f(x) as there isn't a denominator but I'm not 100% certain. Now provide the response and nothing else.
You can compare the precision empirically: prec[f_, x_] := Abs[SetPrecision[f[x], 30] - f[SetPrecision[x, 30]]]/ Abs@f[SetPrecision[x, 30]];LogPlot[{prec[f, x], $MachineEpsilon}, {x, -10, 10}] LogPlot[{prec[g, x], $MachineEpsilon}, {x, -10, 10}] So g has better numerical precision (around $MachineEpsilon ). It is because f contains the difference of potentially big numbers. See also Control the Precision and Accuracy of Numerical Results .
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/72801', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/25034/']}
jdg_83336
stackexchange
llm_judgeable_groundtruth_similarity
5112992
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 print Hello World 200,000 times and it took me forever, so I have to stop. But right after I add a char array to act as a buffer, it took less than 10 seconds. Why? Before adding a buffer: #include <iostream> using namespace std;int main() { int count = 0; std::ios_base::sync_with_stdio(false); for(int i = 1; i < 200000; i++) { cout << "Hello world!\n"; count++; } cout<<"Count:%d\n"<<count;return 0;} And this is after adding a buffer: #include <iostream> using namespace std;int main() { int count = 0; std::ios_base::sync_with_stdio(false); char buffer[1024]; cout.rdbuf()->pubsetbuf(buffer, 1024); for(int i = 1; i < 200000; i++) { cout << "Hello world!\n"; count++; } cout<<"Count:%d\n"<<count;return 0;} This makes me think about Java. What's the advantages of a using BufferReader to read in file? Now provide the response and nothing else.
For the stand of file operations, writing to memory (RAM) is always faster than writing to the file on the disk directly. For illustration, let's define: each write IO operation to a file on the disk costs 1 ms each write IO operation to a file on the disk over a network costs 5 ms each write IO operation to the memory costs 0.5 ms Let's say we have to write some data to a file 100 times. Case 1: Directly Writing to File On Disk 100 times x 1 ms = 100 ms Case 2: Directly Writing to File On Disk Over Network 100 times x 5 ms = 500 ms Case 3: Buffering in Memory before Writing to File on Disk (100 times x 0.5 ms) + 1 ms = 51 ms Case 4: Buffering in Memory before Writing to File on Disk Over Network (100 times x 0.5 ms) + 5 ms = 55 ms Conclusion Buffering in memory is always faster than direct operation. However if your system is low on memory and has to swap with page file, it'll be slow again. Thus you have to balance your IO operations between memory and disk/network.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5112992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496700/']}
jdg_83337
stackexchange
llm_judgeable_groundtruth_similarity
243875
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: If an application's code contains even minor and subtle inaccuracies, it can open up the entire database to SQL injection. In this example (see section 'Delete All Method'), the entire Users table gets deleted with a trivial SQL injection ( "1) OR 1=1--" ). This had me wondering, have any white hats / bounty hunters (perhaps amateurs) looked for vulnerabilities and accidentally caused massive, real damage to the site/app/business? How do bounty programs deal with such a risk? Now provide the response and nothing else.
Can bounty hunting cause real damage? Sure. As you pointed out, some SQL injection vectors may inadvertently cause data deletion. Similarly, a persistent XSS attack may trigger in the browser of a real user. Or unusual characters in a username may crash a web application backend due to an unhandled encoding error. More generally, a large part of black box pentesting involves experimenting with unexpected/invalid input to the target application. Some level of fuzzing is usually unavoidable - and this always carries the risk of causing behavior that breaks the application or corrupts data. So, while blindly trying out DELETE queries may be reckless and avoidable, vendors have to face that even benign bug hunting occasionally impacts service integrity or availability. Did a bounty hunter ever cause actual damage? This report is an example of where the researcher caused a DOS by submitting invalid data. I'm entirely sure there are more severe examples, many of which simply weren't made public. Anecdotally, I remember several occasions where bug hunters were banned from programs because the tools they used were too disruptive. How do bug bounty programs manage this risk? A testing environment. While some bug bounties assume you're testing against production, many provide a separate sandbox and only allow you to test there. E.g., the program of Bitmex includes the rule: Only test on testnet.bitmex.com. A "responsible research" policy which asks that hunters make an effort to avoid damage. Rules would include not accessing real user data, limiting automated testing tools, etc. For example, Facebook's program demands: You make a good faith effort to avoid privacy violations and disruptions to others, including (but not limited to) unauthorized access to or destruction of data, and interruption or degradation of our services. You must not intentionally violate any applicable laws or regulations, including (but not limited to) laws and regulations prohibiting the unauthorized access to data. An emergency contact point. Some providers instruct hunters how to notify them immediately if their actions have caused service disruption. From the program of Exodus : If you do accidentally cause some noticeable interruption of service, please immediately email us so we can handle it accordingly [email protected] and please include the subject title "HackerOne Outage: " for the alert to trigger. Safe harbor clauses protect participants Nowadays, many program policies come with a safe harbor clause . This is intended to protect hunters from liability if they act in good faith, even if their actions have caused damage. Since IANAL, I can't comment on the effectiveness of such a policy, but it's an established practice. Here is an example of a safe harbor clause in the program of Dropbox : We will not pursue civil action or initiate a complaint to law enforcement for accidental, good faith violations of this policy. We consider activities conducted consistent with this policy to constitute “authorized” conduct under the Computer Fraud and Abuse Act. To the extent your activities are inconsistent with certain restrictions in our Acceptable Use Policy, we waive those restrictions for the limited purpose of permitting security research under this policy. We will not bring a DMCA claim against you for circumventing the technological measures we have used to protect the applications in scope. You'll find a similar passage in the rules of most large programs.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/243875', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/211696/']}
jdg_83338
stackexchange
llm_judgeable_groundtruth_similarity
31054012
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 ASP.NET MVC 5 you could throw a HttpException with a HTTP code and this would set the response like so: throw new HttpException((int)HttpStatusCode.BadRequest, "Bad Request."); HttpException does not exist in ASP.NET Core. What is the equivalent code? Now provide the response and nothing else.
I implemented my own HttpException and supporting middleware which catches all HttpException 's and turns them into the corresponding error response. A short extract can be seen below. You can also use the Boxed.AspNetCore Nuget package. Usage Example in Startup.cs public void Configure(IApplicationBuilder application){ application.UseIISPlatformHandler(); application.UseStatusCodePagesWithReExecute("/error/{0}"); application.UseHttpException(); application.UseMvc();} Extension Method public static class ApplicationBuilderExtensions{ public static IApplicationBuilder UseHttpException(this IApplicationBuilder application) { return application.UseMiddleware<HttpExceptionMiddleware>(); }} Middleware internal class HttpExceptionMiddleware{ private readonly RequestDelegate next; public HttpExceptionMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { try { await this.next.Invoke(context); } catch (HttpException httpException) { context.Response.StatusCode = httpException.StatusCode; var responseFeature = context.Features.Get<IHttpResponseFeature>(); responseFeature.ReasonPhrase = httpException.Message; } }} HttpException public class HttpException : Exception{ private readonly int httpStatusCode; public HttpException(int httpStatusCode) { this.httpStatusCode = httpStatusCode; } public HttpException(HttpStatusCode httpStatusCode) { this.httpStatusCode = (int)httpStatusCode; } public HttpException(int httpStatusCode, string message) : base(message) { this.httpStatusCode = httpStatusCode; } public HttpException(HttpStatusCode httpStatusCode, string message) : base(message) { this.httpStatusCode = (int)httpStatusCode; } public HttpException(int httpStatusCode, string message, Exception inner) : base(message, inner) { this.httpStatusCode = httpStatusCode; } public HttpException(HttpStatusCode httpStatusCode, string message, Exception inner) : base(message, inner) { this.httpStatusCode = (int)httpStatusCode; } public int StatusCode { get { return this.httpStatusCode; } }} In the long term, I would advise against using exceptions for returning errors. Exceptions are slower than just returning an error from a method.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31054012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1212017/']}
jdg_83339
stackexchange
llm_judgeable_groundtruth_similarity
20684038
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 found the sample code to open calendar from my app, but i can't open at a specific date. NSString* launchUrl = @"calshow://";[[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]]; Is there a way to add specific date at the end of the "lunchUrl" string so when the user opens the calendar it displays the given date. I have already tried the following formats: @"calshow://?=2013 12 19", @"calshow://?=2013-12-19", @"calshow://?=2013+12+19". None of these seem to work for me... any ideas what am i'm doing wrong? Now provide the response and nothing else.
I played with this url scheme a little and found the way to do it. The main two points are: Don't use "//" after the calshow: Pass timestamp since reference date (1 Jan 2001) Here is the code: - (void)showCalendarOnDate:(NSDate *)date{ // calc time interval since 1 January 2001, GMT NSInteger interval = [date timeIntervalSinceReferenceDate]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"calshow:%ld", interval]]; [[UIApplication sharedApplication] openURL:url];} And this is how I call it: // create some date and show the calendar with it- (IBAction)showCalendar:(id)sender{ NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:4]; [comps setMonth:7]; [comps setYear:2010]; NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; [self showCalendarOnDate:[cal dateFromComponents:comps]];} Perhaps you should take into account that calshow: is not a public url scheme, so maybe Apple would frown upon using it in this way. Or maybe they wouldn't (I haven't researched that).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20684038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2830692/']}
jdg_83340