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
|
24218
|
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I read somewhere that the temperature of an atom is not defined. The definition of temperature is only for larger systems. Why is this so?
Now provide the response and nothing else.
|
Thermodynamic functions are strictly defined only for macroscopic systems (systems that have an essentially infinite number of atoms). You can't apply them to individual atoms because that would be confusing large-scale averages with individual microscopic values . Here's an analogy: the average speed of cars on a stretch of highway might be 55 mph, but it's possible that no individual car is traveling at that exact speed. Another analogy: the average global temperature is rising over long periods of time, but if I look at the thermometer outside my window, the local temperature is falling over a short period of time... I can't say that my local temperature drop disproves global warming, because weather is a different thing from climate. Suppose that you knew the speed of a single atom. Now, for a macroscopic ideal gas, the average speed of molecules $\overline{v}$ is $$\overline{v} = \sqrt{\frac{8 R T}{\pi M}}$$ It would be wrong for you to plug in the speed of your single atom and solve for its temperature, because that equation was derived by assuming that you had a macroscopic system (with a certain speed distribution over many molecules); it only applies to average velocities, not individual velocities. This applies to other thermodynamic functions, too. Let's look at a simple chemical example. For a macroscopic crystal, the Gibbs free energy might be written as $$G = Ng(P,T)$$ where $N$ is the number of atoms and $g$ is the Gibbs free energy per atom. Little $g$ is a function of pressure and temperature. So can we say that little $g$ is the Gibbs free energy of a single atom? No. It's the average Gibbs free energy per atom for a huge number of atoms. To see the difference, consider a small cluster of atoms from that same crystal, the previous equation will need some correction terms: $$G = Ng(P,T) + a(P,T)N^{2/3} + b(T)\ln{N} + c(P,T)$$where the "a" term is a surface free energy and the last couple of terms might come from free energy contributed by things like rotation of the cluster (Source: T. L. Hill, Thermodynamics of Small Systems , Dover, 1962.) You can't say that $g(P,T)$ is the Gibbs free energy of a single atom in the cluster because of those correction terms. TL;DR: Thermodynamic functions are averages over very large numbers of particles; random fluctuations are tiny compared to the mean values. But with small systems, those fluctuations become quite important, and there are additional effects that cause macroscopic averages to poorly describe microscopic systems.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/24218', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/2190/']}
|
jdg_370141
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34340465
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Editing the original question, as I wanted to ask question about std::map , instead of std::vector . My mistake. Sorry. My data is actually in 2 std::map s. I want to merge both the maps into a 3rd map. My first and second maps contain entries with the same key. So I would like to merge data under those keys as well, into my resultant 3rd map. So if I use std::merge , will I be loosing data from the first or second maps common entries? As I have mentioned that there are common data (values) in both the maps?
Now provide the response and nothing else.
|
Info for sequential containers If vector s (or other sequential containers like list or deque ) are sorted, then you can use std::set_union . There is an std::merge , in case you want to save duplicates Code taken from linked page : #include <vector>#include <iostream>#include <algorithm>#include <iterator>int main(){ std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = { 3, 4, 5, 6, 7}; std::vector<int> dest1; std::set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(dest1)); for (const auto &i : dest1) { std::cout << i << ' '; } std::cout << '\n';} Output: 1 2 3 4 5 6 7 Info for associative containers You can add unique keys to the map (or set and their unordered counterparts) using insert method. Any key already existing in original map will not be replaced (in multiset and multimap duplicate keys will be added, use set_union discussed before if this should be avoided). Example for map (ignoring entries with duplicate keys) : #include <map>#include <iostream>int main(){ std::map<int, int> v1 = {{1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}}; std::map<int, int> v2 = { {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}}; std::map<int, int> dest1 = v1; dest1.insert(v2.begin(), v2.end()); for (const auto &i : dest1) { std::cout << i.first << ':' << i.second << ' '; } std::cout << '\n';} Output (first number is the key, second — which map it comes from): 1:1 2:1 3:1 4:1 5:1 6:2 7:2 If you switch maps around (set dest1 to be copy of v2 at the beginning and inser values of v1 ), then output will be: 1:1 2:1 3:2 4:2 5:2 6:2 7:2 Example for multimaps (entries from both maps are preserved) : #include <map>#include <iostream>int main(){ std::map<int, int> v1 = {{1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}}; std::map<int, int> v2 = { {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}}; std::multimap<int, int> dest1 {v1.begin(), v1.end()}; dest1.insert(v2.begin(), v2.end()); for (const auto &i : dest1) { std::cout << i.first << ':' << i.second << ' '; } std::cout << '\n';} Output: 1:1 2:1 3:1 3:2 4:1 4:2 5:1 5:2 6:2 7:2 Notice that you cannot use multimap exactly the same way you use maps. For example, operator[] is unavaliable. You will need to use insert to add entries, and use lower_bound or equal_range member functions to extract entries.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34340465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/683589/']}
|
jdg_370142
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50145150
|
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 something like this. I am having difficulty understanding this error.Why does accessing filterController here give this error here, but it doesn't give this error if I move the current entire TextFormField creation (between comments A and B) inside the build method? How does moving the entire TextFormField inside the build method make filterController static then and resolve this issue? class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin{ TabController _tabController; final filterController = new TextEditingController(text: "Search"); //----A TextFormField email = new TextFormField( keyboardType: TextInputType.emailAddress, controller: filterController, ------>ERROR : Error: Only static members can be accessed in initializers ); //----B @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar(..), ); }} How can I resolve this issue?
Now provide the response and nothing else.
|
class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin { TabController _tabController; final filterController = new TextEditingController(text: "Search"); TextFormField email = ... ... is an initializer and there is no way to access this at this point.Initializers are executed before the constructor, but this is only allowed to be accessed after the call to the super constructor (implicit in your example) was completed.Therefore only in the constructor body (or later) access to this is allowed. This is why you get the error message: controller: filterController, accesses this.filterController ( this is implicit if you don't write it explicit). To work around your issue (assuming email needs to be final ) you can use a factory constructor and a constructor initializer list: class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin { factory SingleTickerProviderStateMixin() => new SingleTickerProviderStateMixin._(new TextEditingController(text: "Search")); SingleTickerProviderStateMixin._(TextEditingController textEditingController) : this.filterController = textEditingController, this.email = new TextFormField( keyboardType: TextInputType.emailAddress, controller: textEditingController); TabController _tabController; final filterController; final TextFormField email; or when the email field does not need to be final email can be initialized in the constructor initializer list: class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin { SingleTickerProviderStateMixin() { email = new TextFormField( keyboardType: TextInputType.emailAddress, controller: filterController, ); } TabController _tabController; final filterController = new TextEditingController(text: "Search"); TextFormField email; but in Flutter widgets initState is usually used for that class AppHomeState extends State<AppHome> with SingleTickerProviderStateMixin { @override void initState() { super.initState(); email = new TextFormField( keyboardType: TextInputType.emailAddress, controller: filterController, ); } TabController _tabController; final filterController = new TextEditingController(text: "Search"); TextFormField email;
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50145150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/990502/']}
|
jdg_370143
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5376576
|
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 code like this: @doc = Nokogiri::HTML(open(url)@doc.xpath(query).each do |html| puts html # how get content of a nodeend How do I get the content of the node instead of something like this: <li class="stat">
Now provide the response and nothing else.
|
This is the Synopsis example in the README file for Nokogiri showing one way to do it using CSS, XPath or a hybrid: require 'nokogiri'require 'open-uri'# Get a Nokogiri::HTML:Document for the page we’re interested in...doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))# Do funky things with it using Nokogiri::XML::Node methods...##### Search for nodes by cssdoc.css('h3.r a.l').each do |link| puts link.contentend##### Search for nodes by xpathdoc.xpath('//h3/a[@class="l"]').each do |link| puts link.contentend##### Or mix and match.doc.search('h3.r a.l', '//h3/a[@class="l"]').each do |link| puts link.contentend
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5376576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/451023/']}
|
jdg_370144
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2024954
|
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 do a scatter plot with a line of best fit in matlab, I can get a scatter plot using either scatter(x1,x2) or scatterplot(x1,x2) but the basic fitting option is shadowed out and lsline returns the error 'No allowed line types found. Nothing done' Any help would be great, Thanks,Jon.
Now provide the response and nothing else.
|
lsline is only available in the Statistics Toolbox, do you have the statistics toolbox? A more general solution might be to use polyfit . You need to use polyfit to fit a line to your data. Suppose you have some data in y and you have corresponding domain values in x , (ie you have data approximating y = f(x) for arbitrary f ) then you can fit a linear curve as follows: p = polyfit(x,y,1); % p returns 2 coefficients fitting r = a_1 * x + a_2r = p(1) .* x + p(2); % compute a new vector r that has matching datapoints in x% now plot both the points in y and the curve fit in rplot(x, y, 'x');hold on;plot(x, r, '-');hold off; Note that if you want to fit an arbitrary polynomial to your data you can do so by changing the last parameter of polyfit to be the dimensionality of the curvefit. Suppose we call this dimension d , you'll receive back d+1 coefficients in p , which represent a polynomial conforming to an estimate of f(x) : f(x) = p(1) * x^d + p(2) * x^(d-1) + ... + p(d)*x + p(d+1) Edit, as noted in a comment you can also use polyval to compute r , its syntax would like like this: r = polyval(p, x);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2024954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/232873/']}
|
jdg_370145
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
239340
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anybody know a way to recursively remove all files in a working copy that are not under version control? (I need this to get more reliable results in my automatic build VMware.)
Now provide the response and nothing else.
|
this works for me in bash: svn status | egrep '^\?' | cut -c8- | xargs rm Seth Reno 's is better: svn status | grep ^\? | cut -c9- | xargs -d \\n rm -r It handles unversioned folders and spaces in filenames As per comments below, this only works on files that subversion doesn't know about (status=?). Anything that subversion does know about (including Ignored files/folders) will not be deleted. If you are using subversion 1.9 or greater you can simply use the svn cleanup command with --remove-unversioned and --remove-ignored options
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/239340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6358/']}
|
jdg_370146
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44048166
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please help, so I'll avoid tearing my hair out ... I need to simple Copy folderA to FolderB using a groovy that gets the data from an XML. I have to use XMLSlurper or XMLParser This is it - println "Start"def Folders = new XmlSlurper().parse(new File("CopyParams.xml"))Folders.Folder.each{it.DirectoryToCopy.each{println "Copying ${it.@source} into folder ${it.@target}"new AntBuilder().copy (todir: "${it.@target}"){fileset(dir: "${it.@source}" )}}}println "End"System.exit(0) Then I get - > Copying C:\Temp\Groovy\Source_Folders into folder C:\Temp\Groovy\Target_FolerCaught: groovy.lang.MissingFieldException: No such field: source for class: org.codehaus.groovy.runtime.NullObjectgroovy.lang.MissingFieldException: No such field: source for class: org.codehaus.groovy.runtime.NullObjectat testCopy$_run_closure1_closure2_closure3.doCall(testCopy.gvy:14)at testCopy$_run_closure1_closure2_closure3.doCall(testCopy.gvy)at testCopy$_run_closure1_closure2.doCall(testCopy.gvy:11)at testCopy$_run_closure1.doCall(testCopy.gvy:7)at testCopy.run(testCopy.gvy:5) I tried to use before the Copy - String src = ${it.@source[0]}String dst = ${it.@target[0]} Or String src = new XmlNodePrinter().print(${it.@source})String dst = new XmlNodePrinter().print(${it.@target}) Then I get - > Copying C:\Temp\Groovy\Source_Folders into folder C:\Temp\Groovy\Target_FolerCaught: groovy.lang.MissingMethodException: No signature of method: testCopy.$() is applicable for argument types: (testCopy$_run_closure1_closure2_closure3) values: [testCopy$_run_closure1_closure2_closure3@1b06cab]Possible solutions: is(java.lang.Object), run(), run(), any(), any(groovy.lang.Closure), use([Ljava.lang.Object;)groovy.lang.MissingMethodException: No signature of method: testCopy.$() is applicable for argument types: (testCopy$_run_closure1_closure2_closure3) values: [testCopy$_run_closure1_closure2_closure3@1b06cab]Possible solutions: is(java.lang.Object), run(), run(), any(), any(groovy.lang.Closure), use([Ljava.lang.Object;)at testCopy$_run_closure1_closure2.doCall(testCopy.gvy:11)at testCopy$_run_closure1.doCall(testCopy.gvy:7)at testCopy.run(testCopy.gvy:5) I also tried using FileUtils but got even more none understood errors What am I doing wrong ? Will it be better if I'll use "XMLParser" ? Thanks,Eli
Now provide the response and nothing else.
|
To use Django Filter and paginate the filtered result you can do the following: Create a filter class for your model: On my_project/my_app/filters.py : import django_filtersclass MyModelFilter(django_filters.FilterSet): class Meta: model = MyModel # Declare all your model fields by which you will filter # your queryset here: fields = ['field_1', 'field_2', ...] Every FilterSet object has a .qs property which contains the filtered queryset and you can even override it if you want . We will paginate the .qs property of our MyModelFilter : On my_project/my_app/views.py : from . import filtersfrom django.core.paginator import Paginator, EmptyPage, PageNotAnIntegerdef my_view(request): # BTW you do not need .all() after a .filter() # local_url.objects.filter(global_url__id=1) will do filtered_qs = filters.MyModelFilter( request.GET, queryset=MyModel.objects.all() ).qs paginator = Paginator(filtered_qs, YOUR_PAGE_SIZE) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) return render( request, 'your_template.html', {'response': response} ) And there you have it! PS_1: Django filter in my experience, "plays" better with Django Rest Framework . PS_2: If you are about to utilize DRF, I have written an example on how to use pagination in a function based view which you can easily combine with a FilterSet : @api_view(['GET',])def my_function_based_list_view(request): paginator = PageNumberPagination() filtered_set = filters.MyModelFilter( request.GET, queryset=MyModel.objects.all() ).qs context = paginator.paginate_queryset(filtered_set, request) serializer = MyModelSerializer(context, many=True) return paginator.get_paginated_response(serializer.data)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44048166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1977045/']}
|
jdg_370147
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
63682956
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have following views, from fastapi import FastAPIapp = FastAPI()@app.get('/hello/')def hello_world(): return {"msg": "Hello World"}@app.get('/hello/{number}/')def hello_world_number(number: int): return {"msg": "Hello World Number", "number": number} I have been using these functions in Flask and Django Flask: url_for(...) Django: reverse(...) So, how can I obtain/build the URLs of hello_world and hello_world_number in a similar way?
Now provide the response and nothing else.
|
We have got Router.url_path_for(...) method which is located inside the starlette package Method-1: Using FastAPI instance This method is useful when you are able to access the FastAPI instance in your current context. (Thanks to @Yagizcan Degirmenci ) from fastapi import FastAPIapp = FastAPI()@app.get('/hello/')def hello_world(): return {"msg": "Hello World"}@app.get('/hello/{number}/')def hello_world_number(number: int): return {"msg": "Hello World Number", "number": number}print(app.url_path_for('hello_world'))print(app.url_path_for('hello_world_number', number=1))print(app.url_path_for('hello_world_number', number=2))# Results"/hello/""/hello/1/""/hello/2/" Drawback If we are using APIRouter , router.url_path_for('hello_world') may not work since router isn't an instance of FastAPI class. That is, we must have the FastAPI instance to resolve the URL Method-2: Request instance This method is useful when you are able to access the Request instance (the incoming request), usually, within a view. from fastapi import FastAPI, Requestapp = FastAPI()@app.get('/hello/')def hello_world(): return {"msg": "Hello World"}@app.get('/hello/{number}/')def hello_world_number(number: int): return {"msg": "Hello World Number", "number": number}@app.get('/')def named_url_reveres(request: Request): return { "URL for 'hello_world'": request.url_for("hello_world"), "URL for 'hello_world_number' with number '1'": request.url_for("hello_world_number", number=1), "URL for 'hello_world_number' with number '2''": request.url_for("hello_world_number", number=2}) }# Result Response{ "URL for 'hello_world'": "http://0.0.0.0:6022/hello/", "URL for 'hello_world_number' with number '1'": "http://0.0.0.0:6022/hello/1/", "URL for 'hello_world_number' with number '2''": "http://0.0.0.0:6022/hello/2/"} Drawback We must include the request parameter in every (or required) view to resolve the URL, which might raise an ugly feel to developers.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/63682956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8283848/']}
|
jdg_370148
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20270029
|
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 sublime text 3 and I want to exclude files/directories but not in my sidebar. For example... I have those files: /doc/blabla/event.rb with the text some content in it. /app/event.rb with the text other content in it. So, with Ctrl + P (find files) and writing "event " I want to see only /app/event.rb . and, with Ctrl + Shift + F (find in all files) and writing "content" I want to see results, again, only for /app/event.rb I configure sublime with this values into my Preferences.sublime-settings: "folder_exclude_patterns": ["doc"], this works beautifully but, it hides doc directory from sidebar too. I don't want this behavior. I only want to hide files from my search
Now provide the response and nothing else.
|
For me, using Sublime 3 build 3083 binary_file_patterns was not working while I had the setting in the project.sublime-project file. Once I moved it to my Preferences.sublime-settings and added an '*' to the search it started excluding the folder from search results while leaving it in the sidebar. My Preferences.sublime-settings looks like so: "binary_file_patterns": [ "public/bower_components/*", "public/javascripts/vendor/*", "public-built/*" ], and it works beautifully for me in sublime 3. Also talked about in this post: http://blog.lysender.com/2014/08/sublime-text-exclude-files-or-directories-from-go-to-anything-feature/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20270029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1329461/']}
|
jdg_370149
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18138166
|
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 the Python Guide's chapter on project structure , the term "top-level statement" is brought up a few times. I'm not sure exactly what this refers to. My guess is it's any variable declarations that happen outside of any functions or class methods that fire as soon as a module is loaded. Is this correct? Does it also include a module's import statements?
Now provide the response and nothing else.
|
It's not just variable declarations (and there aren't any variable declarations anyway). It's pretty much anything that starts at indentation level 0. import sys # top-level3 + 4 # top-levelx = 0 # top-leveldef f(): # top-level import os # not top-level! return 3 # not top-levelif x: # top-level print 3 # not top-levelelse: print 4 # not top-level, but executes as part of an if statement # that is top-levelclass TopLevel(object): # top-level x = 3 # not top-level, but executes as part of the class statement def foo(self): # not top-level, but executes as part of the class statement print 5 # not top-level
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18138166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155175/']}
|
jdg_370150
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2288262
|
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 three Points $A(x0,y0), B(x1,y1), C(x2,y2)$ and a distance $d$. From those I want to calculate $D(x3,y3)$ which is in the center between $AB$ and $AC$ and has the specified distance to those line segments. I attempted to use the answer from this Question and rearrange the formula for $d$ to get the parameter $t$ as a result:$$\frac{d^2 *((y0-y1)^2+(x1-x0)^2)}{((y0-y1)(x3-x0)+(x1-x0)(y3-y0))^2}=t^2$$Where I need $D$ because of $x3$ and $y3$, which I then replaced with the vector $\frac{AB}{||AB||}+\frac{AC}{||AC||}$ because it should describe the same line. I did not use the center because if the vector $AD$ is in the center, then it should be enough to calculate this for one side. For context, I am doing this to calculate this point for each point in the convex hull of a convex polygon. I am trying to create a smaller version of this polygon, where each point has the distance $d$ to the outer polygon edges. This does not work as I wanted it to. Is there a better approach or did I forget something?
Now provide the response and nothing else.
|
Supposing $m$ is not a perfect square, then $m=n^2+k$, where $n^2$ is the largest perfect square less than $m$. Without loss of generality, if $k>n$ we can take $m_0=m-n$ and $k_0=k-n$, otherwise $m_0=m, k_0=k$. Then we can see that $f^2(m_0) = n^2+k_0+2n = (n+1)^2+(k_0-1)$. Taking $m_1=f^2(m_0)$ and $k_1=(k_0-1)$ we can see the same process applies relative to $(n+1)^2$ and so in a total of $2k_0$ applications of $f$ we will have a perfect square, $f^{2k_0}(m_0) = (n+k_0)^2$. Additional observation : Note that once a square is found, $s_0^2 = f^d(m)$, the same process can be applied to $f^{d+1}(m) = s_0^2+s_0$, which will then give another perfect square at $f^{d+1+2s_0}(m) = (2s_0)^2$. Thus there are an infinite number of perfect squares in the given sequence, of the form $(2^as_0)^2$, where $a$ is a non-negative integer. This also means there is at most one odd square in the sequence, which only occurs if $m_0$ is odd (or if $m$ itself is an odd square).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2288262', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/447887/']}
|
jdg_370151
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3609469
|
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 heard that under linux on multicore server it would be impossible to reach top performance when you have just 1 process but multiple threads because Linux have some limitations on the IO, so that 1 process with 8 threads on 8-core server might be slower than 8 processes. Any comments? Are there other limitation which might slow the applications?The applications is a network C++ application, serving 100s of clients, with some disk IO. Update: I am concerned that there are some more IO-related issues other than the locking I implement myself... Aren't there any issues doing simultanious network/disk IO in several threads?
Now provide the response and nothing else.
|
Drawbacks of Threads Threads: Serialize on memory operations. That is the kernel, and in turn the MMU must service operations such as mmap() that perform page allocations. Share the same file descriptor table. There is locking involved making changes and performing lookups in this table, which stores stuff like file offsets, and other flags. Every system call made that uses this table such as open() , accept() , fcntl() must lock it to translate fd to internal file handle, and when make changes. Share some scheduling attributes. Processes are constantly evaluated to determine the load they're putting on the system, and scheduled accordingly. Lots of threads implies a higher CPU load, which the scheduler typically dislikes, and it will increase the response time on events for that process (such as reading incoming data on a socket). May share some writable memory. Any memory being written to by multiple threads (especially slow if it requires fancy locking), will generate all kinds of cache contention and convoying issues. For example heap operations such as malloc() and free() operate on a global data structure (that can to some degree be worked around). There are other global structures also. Share credentials, this might be an issue for service-type processes. Share signal handling, these will interrupt the entire process while they're handled. Processes or Threads? If you want to make debugging easier, use threads. If you are on Windows, use threads. (Processes are extremely heavyweight in Windows). If stability is a huge concern, try to use processes. (One SIGSEGV/PIPE is all it takes...). If threads aren't available, use processes. (Not so common now, but it did happen). If your threads share resources that can't be use from multiple processes, use threads. (Or provide an IPC mechanism to allow communicating with the "owner" thread of the resource). If you use resources that are only available on a one-per-process basis (and you one per context), obviously use processes. If your processing contexts share absolutely nothing (such as a socket server that spawns and forgets connections as it accept() s them), and CPU is a bottleneck, use processes and single-threaded runtimes (which are devoid of all kinds of intense locking such as on the heap and other places). One of the biggest differences between threads and processes is this: Threads use software constructs to protect data structures, processes use hardware (which is significantly faster). Links pthreads(7) About Processes and Threads (MSDN) Threads vs. Processes
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3609469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/250540/']}
|
jdg_370152
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
73889
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
For any space $X$, the first Steenrod square cohomology operation$$Sq^1\colon H^\ast(X;\mathbb{Z}_2)\to H^{\ast +1}(X;\mathbb{Z}_2)$$is a derivation, meaning that $Sq^1\circ Sq^1 = 0$ and $Sq^1(a\cup b) = Sq^1(a)\cup b + a\cup Sq^1(b)$ (there are no signs since we are working in characteristic two). Hence we may form the $Sq^1$-cohomology of the space,$$H\left(H^\ast(X;\mathbb{Z}_2),Sq^1\right)$$which will be a graded algebra over $\mathbb{Z}_2$. I am looking for references on this object. From McCleary's "User's guide to spectral sequences", I know that this is related to the Bockstein spectral sequence. More specifically, I would like to know: What is the precise relationship between the $Sq^1$-cohomology of a space $X$ and $2$-torsion of higher order in $H^\ast(X;\mathbb{Z})$? Is there a reference with specific calculations of the $Sq^1$-cohomology of the Eilenberg-Mac Lane spaces $K(\mathbb{Z}_2,n)$? Are there any canonical references I should know about (besides McCleary and Mosher-Tangora)?
Now provide the response and nothing else.
|
I think the easiest way to understand the Bockstein spectral sequence is through the exact couple coming from the long exact sequence of cohomology associated to $0\to\mathbb Z\to\mathbb Z\to \mathbb Z/2\to0$. This shows first that indeed the first differential is $Sq^1$ and tells you that the next page is the direct sum of the cokernel and kernel (shifted one step) of multiplication by $2$ on $2H^\ast(X,\mathbb Z)$. Hence it is like what you would get from applying the universal coefficient formula to $2H^\ast(X,\mathbb Z)$ (instead of $H^\ast(X,\mathbb Z)$). When each cohomology group $H^\ast(X,\mathbb Z)$ is finitely generated this means concretely that you "keep" each $\mathbb Z$-factor (as well as odd torsion) and downgrade each $\mathbb Z/2^n$ to $\mathbb Z/2^{n-1}$. In particular the difference between the dimension of $H^n(X,\mathbb Z/2)$ and that of the $Sq^1$-cohomology is equal to the number of $\mathbb Z/2$-factors in $H^n(X,\mathbb Z)$ and $H^{n+1}(X,\mathbb Z)$. I found a reference to Q2. In Madsen, Milgram: The classifying spaces for surgery and cobordism of manifolds, Ann of Math Studies 92 where they refer to Browder: Torsion in H-spaces, Ann of Math 74 for the Bockstein s.s. of $K(\mathbb Z_{(2)},n)$ and $K(\mathbb Z/2,n)$. The Madsen-Milgram book also contains other examples of computations with the Bss.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/73889', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8103/']}
|
jdg_370153
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
340610
|
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've never seen a Linux server I admin. How can I find out if it has IPMI of some sort installed? I tried answering my own question by installing ipmitool: Setting up ipmitool (1.8.9-2) ...Starting IPMI event daemon ipmievdipmievd: using pidfile /var/run/ipmievd.pid0Could not open device at /dev/ipmi0 or /dev/ipmi/0 or /dev/ipmidev/0: No such file or directoryUnable to open interfacefailed!invoke-rc.d: initscript ipmievd, action "start" failed. was the answer. Can I find out what the ISP uses to remote-control the server or how the ISP probably hooked it into their remote-management HTML panel?
Now provide the response and nothing else.
|
From FreeIPMI's FAQ section: 7. Does my system support IPMI? . Does my system support IPMI? Unfortunately, there are no universally defined mechanisms fordetermining if a system supports IPMI via Inband communication.Assuming IPMI is set up correctly for over LAN communication, a fairlyreliable mechanism exists out-of-band. Here are some suggestions. FreeIPMI’s ipmi-locate can be used to determine if IPMI can be found on your system. Users are cautioned though, the failure todiscover IPMI via ipmi-locate is not sufficient to disprove that IPMIexists on your system. Your system may not publish such information ormay expect clients to communicate at default locations. dmidecode may be similarly used to probe for devices that support IPMI on your system. You may grep for IPMI or specify the IPMI DMItype on the command line. # > dmidecode --type 38 # dmidecode 2.10 SMBIOS 2.5 present. Handle 0x0049, DMI type 38, 18 bytes IPMI Device Information Interface Type: KCS (Keyboard Control Style) Specification Version: 2.0 I2C Slave Address: 0x10 NV Storage Device: Not Present Base Address: 0x0000000000000CA2 (I/O) Register Spacing: Successive Byte Boundaries FreeIPMI’s ipmi-ping can be used to see if a machine has an IPMI service at a specific host/IP address. For more wide scale IPMIdiscovery, the ipmi-detectd daemon and ipmi-detect tool can be used. Again, the failure to find an IPMI supported device is not sufficientto show lack of IPMI support. Ultimately, some amount of information from product documents or trialand error may be necessary to determine if IPMI is supported on yoursystem.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/340610', 'https://serverfault.com', 'https://serverfault.com/users/102280/']}
|
jdg_370154
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50985397
|
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 created a Record Set Name: www.nevermind.com.Type: AAlias Target: nevermind.com. nevermind.com is working but www.nevermind.com is not working. I get an error: 404 Not Found update: I'm using s3 service to host my code. Any ideas?
Now provide the response and nothing else.
|
For s3 hosted websites - to enable the www subdomain for your domain, you need to do the following - Create another s3 bucket with your subdomain name - www.nevermind.com In the www.nevermind.com bucket choose properties -> static website hosting -> choose redirect requests -> in target bucket/domain put your domain "nevermind.com" save In route53 DNS record, create a new record set -> enter "www" for the Name -> select Alias: "Yes" -> use the "www.nevermind.com" s3 bucket alias endpoint. After this, your www.nevermind.com should redirect to nevermind.com.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50985397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6108211/']}
|
jdg_370155
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3162777
|
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 the limit $$\lim\limits_{x\to\infty}\int^{2x}_{x}\frac{1}{t}dt$$ My trial \begin{align}\lim\limits_{x\to\infty}\int^{2x}_{x}\frac{1}{t}dt &= \lim\limits_{x\to\infty}\large\left[\ln t \large\right]^{2x}_{x}\\&= \lim\limits_{x\to\infty}\large\left[\ln 2x -\ln x \large\right]\end{align} This yields the indeterminate form $\infty-\infty.$ I'm thinking of applying L'Hopital's rule but no headway. Any hints, please?
Now provide the response and nothing else.
|
$\displaystyle \lim_{x \to \infty} \int_x^{2x} \dfrac{dt}{t} = \lim_{x \to \infty} [\ln(2x) - \ln x] = \lim_{x \to \infty}[\ln x + \ln 2 - \ln x] = \lim_{x \to \infty} [\ln 2] = \ln 2. \tag 1$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3162777', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/544685/']}
|
jdg_370156
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33178862
|
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 blog like rails app with posts. the posts can be order by most popular or newest. The most popular is the default order and the homepage, Id like to change this to be the newest order instead. Since Im still pretty new to rails I hired a programmer to do most of the work, However I know this is a pretty simple fix, I just don't know what to change. I think its something I need to change in either the post_controller or the post model, but If you nee to see something else let me know and ill put it up. post.rb class Post < ActiveRecord::Base include UrlHelp def self.highest_voted self.order(:cached_votes_down) endend post_controller.rb def index @posts = grab_correct_post enddef grab_correct_post if params[:sort_by] == "added_on" @added_on = "sort-active" Post.all.order("created_at DESC").paginate(page: params[:page], per_page: 7)else @most_popular = "sort-active" Post.all.order(:cached_votes_score =>:desc).paginate(page: params[:page], per_page: 7) end
Now provide the response and nothing else.
|
The export default {...} construction is just a shortcut for something like this: const funcs = { foo() { console.log('foo') }, bar() { console.log('bar') }, baz() { foo(); bar() }}export default funcs It must become obvious now that there are no foo , bar or baz functions in the module's scope. But there is an object named funcs (though in reality it has no name) that contains these functions as its properties and which will become the module's default export. So, to fix your code, re-write it without using the shortcut and refer to foo and bar as properties of funcs : const funcs = { foo() { console.log('foo') }, bar() { console.log('bar') }, baz() { funcs.foo(); funcs.bar() } // here is the fix}export default funcs Another option is to use this keyword to refer to funcs object without having to declare it explicitly, as @pawel has pointed out . Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly: function foo() { console.log('foo') }function bar() { console.log('bar') }function baz() { foo(); bar() }export default {foo, bar, baz} And if you want the convenience of default export and ability to import items individually, you can also export all functions individually: // util.jsexport function foo() { console.log('foo') }export function bar() { console.log('bar') }export function baz() { foo(); bar() }export default {foo, bar, baz}// a.js, using default exportimport util from './util'util.foo()// b.js, using named exportsimport {bar} from './util'bar() Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util' to get all named exports in one object.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/33178862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4118694/']}
|
jdg_370157
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3109158
|
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 I parse kml file in order to display paths or points in Android? Please could you help me with that? This is kml sample code which I would like to display in android google map: <?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>Paths</name><description>Examples of paths. Note that the tessellate tag is by default set to 0. If you want to create tessellated lines, they must be authored (or edited) directly in KML.</description><Style id="yellowLineGreenPoly"> <LineStyle> <color>7f00ffff</color> <width>4</width> </LineStyle> <PolyStyle> <color>7f00ff00</color> </PolyStyle></Style><Placemark> <name>Absolute Extruded</name> <description>Transparent green wall with yellow outlines</description> <styleUrl>#yellowLineGreenPoly</styleUrl> <LineString> <extrude>1</extrude> <tessellate>1</tessellate> <altitudeMode>absolute</altitudeMode> <coordinates> -112.2550785337791,36.07954952145647,2357 -112.2549277039738,36.08117083492122,2357 -112.2552505069063,36.08260761307279,2357 -112.2564540158376,36.08395660588506,2357 -112.2580238976449,36.08511401044813,2357 -112.2595218489022,36.08584355239394,2357 -112.2608216347552,36.08612634548589,2357 -112.262073428656,36.08626019085147,2357 -112.2633204928495,36.08621519860091,2357 -112.2644963846444,36.08627897945274,2357 -112.2656969554589,36.08649599090644,2357 </coordinates> <LineString> </Placemark> </Document> </kml> When I'm loading this file to standard web google map it displays it nicely but when I'm trying the same thing with android google map it doesn't do that. It just takes me to some locations and that's it. I was thinking of changing listener class. Currently it looks like that: private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { if (loc != null) { latitude = (loc.getLatitude() * 1E6); longitude = (loc.getLongitude() * 1E6); Toast.makeText(getBaseContext(), "Location changed : Lat: " + latitude + " Lng: " + longitude, Toast.LENGTH_SHORT).show(); GeoPoint p = new GeoPoint( (int) (loc.getLatitude() * 1E6), (int) (loc.getLongitude() * 1E6)); mc.animateTo(p); mapView.invalidate(); } }//--------------------------------------------------------------- @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { //TODO Auto-generated method stub } Please can someone tell me what's I'm doing wrong here?
Now provide the response and nothing else.
|
In above code, you don't pass the kml data to your mapView anywhere in your code, as far as I can see.To display the route, you should parse the kml data i.e. via SAX parser, then display the route markers on the map. See the code below for an example, but it's not complete though - just for you as a reference and get some idea. This is a simple bean I use to hold the route information I will be parsing. package com.myapp.android.model.navigation;import java.util.ArrayList;import java.util.Iterator;public class NavigationDataSet { private ArrayList<Placemark> placemarks = new ArrayList<Placemark>();private Placemark currentPlacemark;private Placemark routePlacemark;public String toString() { String s= ""; for (Iterator<Placemark> iter=placemarks.iterator();iter.hasNext();) { Placemark p = (Placemark)iter.next(); s += p.getTitle() + "\n" + p.getDescription() + "\n\n"; } return s;}public void addCurrentPlacemark() { placemarks.add(currentPlacemark);}public ArrayList<Placemark> getPlacemarks() { return placemarks;}public void setPlacemarks(ArrayList<Placemark> placemarks) { this.placemarks = placemarks;}public Placemark getCurrentPlacemark() { return currentPlacemark;}public void setCurrentPlacemark(Placemark currentPlacemark) { this.currentPlacemark = currentPlacemark;}public Placemark getRoutePlacemark() { return routePlacemark;}public void setRoutePlacemark(Placemark routePlacemark) { this.routePlacemark = routePlacemark;}} And the SAX Handler to parse the kml: package com.myapp.android.model.navigation;import android.util.Log;import com.myapp.android.myapp;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import com.myapp.android.model.navigation.NavigationDataSet;import com.myapp.android.model.navigation.Placemark;public class NavigationSaxHandler extends DefaultHandler{ // =========================================================== // Fields // =========================================================== private boolean in_kmltag = false; private boolean in_placemarktag = false; private boolean in_nametag = false; private boolean in_descriptiontag = false; private boolean in_geometrycollectiontag = false; private boolean in_linestringtag = false; private boolean in_pointtag = false; private boolean in_coordinatestag = false; private StringBuffer buffer; private NavigationDataSet navigationDataSet = new NavigationDataSet(); // =========================================================== // Getter & Setter // =========================================================== public NavigationDataSet getParsedData() { navigationDataSet.getCurrentPlacemark().setCoordinates(buffer.toString().trim()); return this.navigationDataSet; } // =========================================================== // Methods // =========================================================== @Override public void startDocument() throws SAXException { this.navigationDataSet = new NavigationDataSet(); } @Override public void endDocument() throws SAXException { // Nothing to do } /** Gets be called on opening tags like: * <tag> * Can provide attribute(s), when xml was like: * <tag attribute="attributeValue">*/ @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { if (localName.equals("kml")) { this.in_kmltag = true; } else if (localName.equals("Placemark")) { this.in_placemarktag = true; navigationDataSet.setCurrentPlacemark(new Placemark()); } else if (localName.equals("name")) { this.in_nametag = true; } else if (localName.equals("description")) { this.in_descriptiontag = true; } else if (localName.equals("GeometryCollection")) { this.in_geometrycollectiontag = true; } else if (localName.equals("LineString")) { this.in_linestringtag = true; } else if (localName.equals("point")) { this.in_pointtag = true; } else if (localName.equals("coordinates")) { buffer = new StringBuffer(); this.in_coordinatestag = true; } } /** Gets be called on closing tags like: * </tag> */ @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (localName.equals("kml")) { this.in_kmltag = false; } else if (localName.equals("Placemark")) { this.in_placemarktag = false; if ("Route".equals(navigationDataSet.getCurrentPlacemark().getTitle())) navigationDataSet.setRoutePlacemark(navigationDataSet.getCurrentPlacemark()); else navigationDataSet.addCurrentPlacemark(); } else if (localName.equals("name")) { this.in_nametag = false; } else if (localName.equals("description")) { this.in_descriptiontag = false; } else if (localName.equals("GeometryCollection")) { this.in_geometrycollectiontag = false; } else if (localName.equals("LineString")) { this.in_linestringtag = false; } else if (localName.equals("point")) { this.in_pointtag = false; } else if (localName.equals("coordinates")) { this.in_coordinatestag = false; } } /** Gets be called on the following structure: * <tag>characters</tag> */ @Override public void characters(char ch[], int start, int length) { if(this.in_nametag){ if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark()); navigationDataSet.getCurrentPlacemark().setTitle(new String(ch, start, length)); } else if(this.in_descriptiontag){ if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark()); navigationDataSet.getCurrentPlacemark().setDescription(new String(ch, start, length)); } else if(this.in_coordinatestag){ if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark()); //navigationDataSet.getCurrentPlacemark().setCoordinates(new String(ch, start, length)); buffer.append(ch, start, length); }} } and a simple placeMark bean: package com.myapp.android.model.navigation;public class Placemark {String title;String description;String coordinates;String address;public String getTitle() { return title;}public void setTitle(String title) { this.title = title;}public String getDescription() { return description;}public void setDescription(String description) { this.description = description;}public String getCoordinates() { return coordinates;}public void setCoordinates(String coordinates) { this.coordinates = coordinates;}public String getAddress() { return address;}public void setAddress(String address) { this.address = address;}} Finally the service class in my model that calls the calculation: package com.myapp.android.model.navigation;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import com.myapp.android.myapp;import org.xml.sax.InputSource;import org.xml.sax.XMLReader;import android.util.Log;public class MapService {public static final int MODE_ANY = 0;public static final int MODE_CAR = 1;public static final int MODE_WALKING = 2;public static String inputStreamToString (InputStream in) throws IOException { StringBuffer out = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = in.read(b)) != -1;) { out.append(new String(b, 0, n)); } return out.toString();}public static NavigationDataSet calculateRoute(Double startLat, Double startLng, Double targetLat, Double targetLng, int mode) { return calculateRoute(startLat + "," + startLng, targetLat + "," + targetLng, mode);}public static NavigationDataSet calculateRoute(String startCoords, String targetCoords, int mode) { String urlPedestrianMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr=" + targetCoords + "&sll=" + startCoords + "&dirflg=w&hl=en&ie=UTF8&z=14&output=kml"; Log.d(myapp.APP, "urlPedestrianMode: "+urlPedestrianMode); String urlCarMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr=" + targetCoords + "&sll=" + startCoords + "&hl=en&ie=UTF8&z=14&output=kml"; Log.d(myapp.APP, "urlCarMode: "+urlCarMode); NavigationDataSet navSet = null; // for mode_any: try pedestrian route calculation first, if it fails, fall back to car route if (mode==MODE_ANY||mode==MODE_WALKING) navSet = MapService.getNavigationDataSet(urlPedestrianMode); if (mode==MODE_ANY&&navSet==null||mode==MODE_CAR) navSet = MapService.getNavigationDataSet(urlCarMode); return navSet;}/** * Retrieve navigation data set from either remote URL or String * @param url * @return navigation set */public static NavigationDataSet getNavigationDataSet(String url) { // urlString = "http://192.168.1.100:80/test.kml"; Log.d(myapp.APP,"urlString -->> " + url); NavigationDataSet navigationDataSet = null; try { final URL aUrl = new URL(url); final URLConnection conn = aUrl.openConnection(); conn.setReadTimeout(15 * 1000); // timeout for reading the google maps data: 15 secs conn.connect(); /* Get a SAXParser from the SAXPArserFactory. */ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); /* Get the XMLReader of the SAXParser we created. */ XMLReader xr = sp.getXMLReader(); /* Create a new ContentHandler and apply it to the XML-Reader*/ NavigationSaxHandler navSax2Handler = new NavigationSaxHandler(); xr.setContentHandler(navSax2Handler); /* Parse the xml-data from our URL. */ xr.parse(new InputSource(aUrl.openStream())); /* Our NavigationSaxHandler now provides the parsed data to us. */ navigationDataSet = navSax2Handler.getParsedData(); /* Set the result to be displayed in our GUI. */ Log.d(myapp.APP,"navigationDataSet: "+navigationDataSet.toString()); } catch (Exception e) { // Log.e(myapp.APP, "error with kml xml", e); navigationDataSet = null; } return navigationDataSet;}} Drawing: /** * Does the actual drawing of the route, based on the geo points provided in the nav set * * @param navSet Navigation set bean that holds the route information, incl. geo pos * @param color Color in which to draw the lines * @param mMapView01 Map view to draw onto */public void drawPath(NavigationDataSet navSet, int color, MapView mMapView01) { Log.d(myapp.APP, "map color before: " + color); // color correction for dining, make it darker if (color == Color.parseColor("#add331")) color = Color.parseColor("#6C8715"); Log.d(myapp.APP, "map color after: " + color); Collection overlaysToAddAgain = new ArrayList(); for (Iterator iter = mMapView01.getOverlays().iterator(); iter.hasNext();) { Object o = iter.next(); Log.d(myapp.APP, "overlay type: " + o.getClass().getName()); if (!RouteOverlay.class.getName().equals(o.getClass().getName())) { // mMapView01.getOverlays().remove(o); overlaysToAddAgain.add(o); } } mMapView01.getOverlays().clear(); mMapView01.getOverlays().addAll(overlaysToAddAgain); String path = navSet.getRoutePlacemark().getCoordinates(); Log.d(myapp.APP, "path=" + path); if (path != null && path.trim().length() > 0) { String[] pairs = path.trim().split(" "); Log.d(myapp.APP, "pairs.length=" + pairs.length); String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height Log.d(myapp.APP, "lnglat =" + lngLat + ", length: " + lngLat.length); if (lngLat.length<3) lngLat = pairs[1].split(","); // if first pair is not transferred completely, take seconds pair //TODO try { GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); mMapView01.getOverlays().add(new RouteOverlay(startGP, startGP, 1)); GeoPoint gp1; GeoPoint gp2 = startGP; for (int i = 1; i < pairs.length; i++) // the last one would be crash { lngLat = pairs[i].split(","); gp1 = gp2; if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0 && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) { // for GeoPoint, first:latitude, second:longitude gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); if (gp2.getLatitudeE6() != 22200000) { mMapView01.getOverlays().add(new RouteOverlay(gp1, gp2, 2, color)); Log.d(myapp.APP, "draw:" + gp1.getLatitudeE6() + "/" + gp1.getLongitudeE6() + " TO " + gp2.getLatitudeE6() + "/" + gp2.getLongitudeE6()); } } // Log.d(myapp.APP,"pair:" + pairs[i]); } //routeOverlays.add(new RouteOverlay(gp2,gp2, 3)); mMapView01.getOverlays().add(new RouteOverlay(gp2, gp2, 3)); } catch (NumberFormatException e) { Log.e(myapp.APP, "Cannot draw route.", e); } } // mMapView01.getOverlays().addAll(routeOverlays); // use the default color mMapView01.setEnabled(true);} This is the RouteOverlay class: package com.myapp.android.activity.map.nav;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Point;import android.graphics.RectF;import com.google.android.maps.GeoPoint;import com.google.android.maps.MapView;import com.google.android.maps.Overlay;import com.google.android.maps.Projection;public class RouteOverlay extends Overlay { private GeoPoint gp1;private GeoPoint gp2;private int mRadius=6;private int mode=0;private int defaultColor;private String text="";private Bitmap img = null;public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode) { // GeoPoint is a int. (6E) this.gp1 = gp1; this.gp2 = gp2; this.mode = mode; defaultColor = 999; // no defaultColor}public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor) { this.gp1 = gp1; this.gp2 = gp2; this.mode = mode; this.defaultColor = defaultColor;}public void setText(String t) { this.text = t;}public void setBitmap(Bitmap bitmap) { this.img = bitmap;}public int getMode() { return mode;}@Overridepublic boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when) { Projection projection = mapView.getProjection(); if (shadow == false) { Paint paint = new Paint(); paint.setAntiAlias(true); Point point = new Point(); projection.toPixels(gp1, point); // mode=1:start if(mode==1) { if(defaultColor==999) paint.setColor(Color.BLACK); // Color.BLUE else paint.setColor(defaultColor); RectF oval=new RectF(point.x - mRadius, point.y - mRadius, point.x + mRadius, point.y + mRadius); // start point canvas.drawOval(oval, paint); } // mode=2:path else if(mode==2) { if(defaultColor==999) paint.setColor(Color.RED); else paint.setColor(defaultColor); Point point2 = new Point(); projection.toPixels(gp2, point2); paint.setStrokeWidth(5); paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120); canvas.drawLine(point.x, point.y, point2.x,point2.y, paint); } /* mode=3:end */ else if(mode==3) { /* the last path */ if(defaultColor==999) paint.setColor(Color.BLACK); // Color.GREEN else paint.setColor(defaultColor); Point point2 = new Point(); projection.toPixels(gp2, point2); paint.setStrokeWidth(5); paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120); canvas.drawLine(point.x, point.y, point2.x,point2.y, paint); RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius, point2.x + mRadius,point2.y + mRadius); /* end point */ paint.setAlpha(255); canvas.drawOval(oval, paint); } } return super.draw(canvas, mapView, shadow, when);}}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3109158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/359656/']}
|
jdg_370158
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1123045
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to get an explanation in words, or math, of what the $d\mu$ means in an integration statement. Such as:$$\int f \ d\mu$$ How does the measure change our old "calculus" notion of integration? What is going on here that is different?
Now provide the response and nothing else.
|
I actually struggled with this concept in grad school since I was studying applied math and was sort of thrust into higher level theory without building it up rigorously like I assume would be done in a pure math program. If we are integrating over a space $X$ , I sometimes prefer the notation $\int_X f(x)\mu(dx)$ . I like to think of it as splitting the space we are integrating over into infinitesimal pieces, but we have to take the measure of those infinitesimal pieces as they may not all be identical under $\mu$ . I'm used to working with probability measures, and at least in that case, you can often think of it similar to the way Lebesgue and Riemann integration are developed. Create a disjoint partition $X=\cup_{k=1}^N A_k$ , and define the sum which will approximate the integral using appropriately chosen sample points $x_k\in A_k$ . $$\int_X f(x)\mu(dx) \approx \sum_{k=1}^N f(x_k) \mu(A_k).$$ Ideally, taking the limit as $N\rightarrow\infty$ (carefully refining the partition and choosing appropriate sample points as $N$ increases) will make the sum converge to the integral. What we are doing here is effectively approximating the function $f$ with a simple function which is constant on a finite collection of measurable sets.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1123045', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/180252/']}
|
jdg_370159
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7718338
|
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 about 100 lines that look like the below: assertEquals(results.get(0).getID(),1); They all start with assertEquals and contain two arguments. Im looking for a way to use find and replace all to swap the arguments of all these lines. Thanks
Now provide the response and nothing else.
|
use the following regexp to find: assertEquals\((.*),(.*)\); and this replacement value: assertEquals(\2,\1); The regexp means "assertEquals( followed by a first group of chars followed by a comma followed by a second group of chars followed by );" . The replacement value means "assertEquals( followed by the second group of chars found followed by a comma followed by the first group of chars found followed by );" .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7718338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/988362/']}
|
jdg_370160
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4618734
|
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:
Three disks are placed on the ground like this: From left to right, their radii are $\frac{1}{x-1}, \frac{1}{x}, \frac{1}{x+1}$ metres. They lie in a plane perpendicular to the ground. The middle disk touches the other two disks. Using only paper and pen, approximate the value of $x$ such that the middle disk is tangent to the line that is tangent to and above the other two disks. You may assume that the earth is a sphere of radius $R$ metres. (Before you read the last sentence, it seems like there's something wrong with the question, because it seems like the middle disk should never touch the line. But the ground is actually a circular arc of the earth, so the middle disk is "pushed up" and touches the line for some value of $x$ .) The answer turns out to be, elegantly, $x\approx R/2$ . But the algebra seems to be horrendous and I needed to use my computer to find the answer. My attempt Call the angles at the centre of the middle disk $A, B, C, D, E$ with $A$ at the lower-left and going clockwise. $A=\arccos{\left(\dfrac{\left(\frac{1}{x}+\frac{1}{x-1}\right)^2+\left(R+\frac{1}{x}\right)^2-\left(R+\frac{1}{x-1}\right)^2}{2\left(\frac{1}{x}+\frac{1}{x-1}\right)\left(R+\frac{1}{x}\right)}\right)}$ $B=\arcsin{\left(\dfrac{\frac{1}{x-1}-\frac{1}{x}}{\frac{1}{x-1}+\frac{1}{x}}\right)}$ $C=\dfrac{\pi}{2}$ $D=\arccos{\left(\dfrac{\frac{1}{x}-\frac{1}{x+1}}{\frac{1}{x}+\frac{1}{x+1}}\right)}$ $E=\arccos{\left(\dfrac{\left(\frac{1}{x}+\frac{1}{x+1}\right)^2+\left(R+\frac{1}{x}\right)^2-\left(R+\frac{1}{x+1}\right)^2}{2\left(\frac{1}{x}+\frac{1}{x+1}\right)\left(R+\frac{1}{x}\right)}\right)}$ We assume that the middle disk is tangent to the line that is tangent to and above the other two disks. This implies: $$A+B+C+D+E=2\pi$$ I am utterly unable to approximate $x$ without a computer, even after attempting to simplify it. And yet the computer-assisted answer is just $x\approx R/2$ . Can $x$ be approximated without a computer? (This question was inspired by a frame challenge .)
Now provide the response and nothing else.
|
They simplify to $$A=\frac\pi2+\arcsin\frac{\left(R+\frac1x\right)-2}{\left(R+\frac1x\right)(2x-1)}\\B=\arcsin\frac1{2x-1}\\C=\frac\pi2\\D=\frac\pi2-\arcsin\frac1{2x+1}\\E=\frac\pi2-\arcsin\frac{\left(R+\frac1x\right)+2}{\left(R+\frac1x\right)(2x+1)}$$ Suppose $x=O(R)$ . All four key angles turn out to be $O(1/R)$ , which is small enough that I can ignore the arcsine at the precision I need, which is $O(1/R^3)$ . Since the $O(1/R)$ terms cancel exactly, the nonlinear $O(1/R^3)$ terms in arcsines will cancel as well. $$A\approx\frac\pi2+B-\frac2{\left(R+\frac1x\right)(2x-1)}\\B+D\approx\frac\pi2+\frac2{4x^2-1}\\E\approx D-\frac2{\left(R+\frac1x\right)(2x+1)}\\A+B+C+D+E\approx2\pi+\frac4{4x^2-1}\left(1-\frac{2x}{R+\frac1x}\right)$$ So my leading order estimate is $$x\approx\frac R2+\frac1R$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4618734', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/398708/']}
|
jdg_370161
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38385936
|
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 textarea in React that I want to turn into a "notepad". Which means I want the "tab" key to indent instead of unfocus. I looked at this answer , but I can't get it to work with React. Here is my code: handleKeyDown(event) { if (event.keyCode === 9) { // tab was pressed event.preventDefault(); var val = this.state.scriptString, start = event.target.selectionStart, end = event.target.selectionEnd; this.setState({"scriptString": val.substring(0, start) + '\t' + val.substring(end)}); // This line doesn't work. The caret position is always at the end of the line this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1; }}onScriptChange(event) { this.setState({scriptString: event.target.value});}render() { return ( <textarea rows="30" cols="100" ref="input" onKeyDown={this.handleKeyDown.bind(this)} onChange={this.onScriptChange.bind(this)} value={this.state.scriptString}/> )} When I run this code, even if I press the "tab" key in the middle of the string, my cursor always appears at the end of the string instead. Anyone knows how to correctly set the cursor position?
Now provide the response and nothing else.
|
You have to change the cursor position after the state has been updated( setState() does not immediately mutate this.state ) In order to do that, you have to wrap this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1; in a function and pass it as the second argument to setState (callback). handleKeyDown(event) { if (event.keyCode === 9) { // tab was pressed event.preventDefault(); var val = this.state.scriptString, start = event.target.selectionStart, end = event.target.selectionEnd; this.setState( { "scriptString": val.substring(0, start) + '\t' + val.substring(end) }, () => { this.refs.input.selectionStart = this.refs.input.selectionEnd = start + 1 }); } } jsfiddle
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38385936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1563831/']}
|
jdg_370162
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7907337
|
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 the old values of an entity? follows the example.. public void Update(User user) ValidateEntity(user, OperationType.Update); oldUser = (how do I get the old values (database) of the entity User?) Set.Attach(user); Context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified); Context.SaveChanges(); OnUpdated(user, oldUser);}
Now provide the response and nothing else.
|
I believe that the following would be the optimal solution, at least based on time / space complexity: Step 1:Store the integers in a hash map, which holds the integer as a key and the count of the number of times it appears as the value. This is generally an O(n) operation and the insertion / updating of elements in the hash table should be constant time, on the average. If an integer is found to appear more than twice, you really don't have to increment the usage count further (if you don't want to). Step 2: Perform a second pass over the integers. Look each up in the hash map and the first one with an appearance count of one is the one you were looking for (i.e., the first single appearing integer). This is also O(n) , making the entire process O(n) . Some possible optimizations for special cases: Optimization A: It may be possible to use a simple array instead of a hash table. This guarantees O(1) even in the worst case for counting the number of occurrences of a particular integer as well as the lookup of its appearance count. Also, this enhances real time performance, since the hash algorithm does not need to be executed. There may be a hit due to potentially poorer locality of reference (i.e., a larger sparse table vs. the hash table implementation with a reasonable load factor). However, this would be for very special cases of integer orderings and may be mitigated by the hash table's hash function producing pseudorandom bucket placements based on the incoming integers (i.e., poor locality of reference to begin with). Each byte in the array would represent the count (up to 255) for the integer represented by the index of that byte. This would only be possible if the difference between the lowest integer and the highest (i.e., the cardinality of the domain of valid integers) was small enough such that this array would fit into memory. The index in the array of a particular integer would be its value minus the smallest integer present in the data set. For example on modern hardware with a 64-bit OS, it is quite conceivable that a 4GB array can be allocated which can handle the entire domain of 32-bit integers. Even larger arrays are conceivable with sufficient memory. The smallest and largest integers would have to be known before processing, or another linear pass through the data using the minmax algorithm to find out this information would be required. Optimization B: You could optimize Optimization A further, by using at most 2 bits per integer (One bit indicates presence and the other indicates multiplicity). This would allow for the representation of four integers per byte, extending the array implementation to handle a larger domain of integers for a given amount of available memory. More bit games could be played here to compress the representation further, but they would only support special cases of data coming in and therefore cannot be recommended for the still mostly general case.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7907337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015204/']}
|
jdg_370163
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18108521
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
class Product(models.Model): products = models.CharField(max_length=256) def __unicode__(self): return self.productsclass PurchaseOrder(models.Model): product = models.ManyToManyField('Product') vendor = models.ForeignKey('VendorProfile') dollar_amount = models.FloatField(verbose_name='Price') I have that code. Unfortunately, the error comes in admin.py with the ManyToManyField class PurchaseOrderAdmin(admin.ModelAdmin): fields = ['product', 'dollar_amount'] list_display = ('product', 'vendor') The error says: 'PurchaseOrderAdmin.list_display[0]', 'product' is a ManyToManyFieldwhich is not supported. However, it compiles when I take 'product' out of list_display . So how can I display 'product' in list_display without giving it errors? edit : Maybe a better question would be how do you display a ManyToManyField in list_display ?
Now provide the response and nothing else.
|
You may not be able to do it directly. From the documentation of list_display ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.) You can do something like this: class PurchaseOrderAdmin(admin.ModelAdmin): fields = ['product', 'dollar_amount'] list_display = ('get_products', 'vendor') def get_products(self, obj): return "\n".join([p.products for p in obj.product.all()]) OR define a model method, and use that class PurchaseOrder(models.Model): product = models.ManyToManyField('Product') vendor = models.ForeignKey('VendorProfile') dollar_amount = models.FloatField(verbose_name='Price') def get_products(self): return "\n".join([p.products for p in self.product.all()]) and in the admin list_display list_display = ('get_products', 'vendor')
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18108521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2611440/']}
|
jdg_370164
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40726
|
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have watched the following video (How Earth Moves by Vsauce) regarding how earth moves: Here are some screenshots: I have some questions: Does the earth spiral around the sun's path as it is shown in the video (exact time is 19:49) and screenshots? Is the spiraling movement caused by sun movement (on its path shown above) where the sun is dragging the earth (and other planets). Does the earth go in front of the sun then back, then fourth and back like it is shown on the video? I see both the sun and earth racing with each overtaking the other over and over. Is this assumption true? In this manner, would earth, at one point in time , be closer to the destination where the solar system is heading (I think they call the destination Vega) than the sun? I am working on a poetry piece. If I mention that earth and sun are locked in a never ending race with each taking the lead (earth moving in front of the sun's path / winning) and earth actually dropping out of the race (spiraling/moving out the race and falling behind), that they are destined to never meet (collide), would I be correct? P.S. My knowledge of astronomy/physics is very limited. I have tried my best to be as clear as possible. Sorry for any confusion. Thanks.
Now provide the response and nothing else.
|
Does the earth spiral around the sun's path as it is shown in thevideo (exact time is 19:49) and screenshots? The Earth does spiral around the Sun's path, but not quite as it's shown in the video. It isn't clear if the video accounts for the 60 degree tilt of the Solar System with respect to the galactic plane. The sizes and distances are not to scale. The Sun and the Earth are depicted far too large with respect to their distance from one another. The relative motion is not to scale. The distance from one side of the spiral to the other side should be about 2 AU, or 3x10^8km. But the Sun is moving at about 200km/s around the galaxy, or 6.3x10^9km per year. So the distance between two consecutive spirals should be more than 20 times the distance from one side of the spiral to the other! This can be visualized as an overextended slinky . Is the spiraling movement caused by sun movement (on its path shownabove) where the sun is dragging the earth (and other planets)? No, the Sun's and the Earth's mutual gravity cause the Earth to rotate around the Sun. The Milky Way's gravity causes our Solar System to revolve around the galactic center. The Sun and the Earth are on the same plane and moving through the galaxy together. The Earth would still rotate around the center of the Milky Way if the Sun magically disappeared. Does the earth go in front of the sun then back, then fourth and backlike it is shown on the video? I see both the sun and earth racingwith each overtaking the other over and over. Is this assumption true?In this manner, would earth, at one point in time, be closer to thedestination where the solar system is heading (I think they call thedestination Vega) than the sun? If you consider a plane tangent to the Sun's velocity vector, then the Earth will pass across that plane twice per year, appearing "in front of" and then "behind" the Sun. This is simply a geometric result since the Earth and Sun share another plane. I wouldn't call any future position of the Solar System a "destination" without evidence the Solar System was sentient, but I am not a philosopher. I am working on a poetry piece. If I mention that earth and sun arelocked in a never ending race with each taking the lead (earth movingin front of the sun's path / winning) and earth actually dropping outof the race (spiraling/moving out the race and falling behind), thatthey are destined to never meet (collide), would I be correct? We haven't ruled out the possibility that the Sun may someday envelope the Earth: What will "the Earth being consumed by the Sun" look like? . Also, the Earth isn't likely to leave its orbit before that time, but the Solar System is chaotic on long time scales . However, your poem would be consistent with current models, and we (humans) don't conclusively know how the Solar System will end. So my two cents is that your poem doesn't contradict modern astronomy. Besides, what's the use of a poetic license if you don't use it?
|
{}
|
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/40726', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/37549/']}
|
jdg_370165
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1364484
|
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 one register a dependency property whose value is calculated using the value of another dependency property? Because the .NET property wrappers are bypassed by WPF at run-time, one should not include logic in the getters and setters. The solution to that is typically to use PropertyChangedCallback s. But those are declared static. For example, what is the proper way to accomplish this contrived task: public bool TestBool{ get { return (bool)GetValue(TestBoolProperty); } set { SetValue(TestBoolProperty, value); TestDouble = ((value)?(100.0):(200.0)); // HERE IS THE DEPENDENCY }}public static readonly DependencyProperty TestBoolProperty = DependencyProperty.Register("TestBool", typeof(bool), typeof(ViewModel));public double TestDouble{ get { return ((double)GetValue(TestDoubleProperty)); } set { SetValue(TestDoubleProperty, value); }}public static readonly DependencyProperty TestDoubleProperty = DependencyProperty.Register("TestDouble", typeof(double), typeof(ViewModel)); As long as the dependency is not circular, is there a proper means to accomplish this?
Now provide the response and nothing else.
|
Hmmm... I think you'd better look at dependency properties value coercion . Here is an example with coercion: public class ViewModel : DependencyObject{ public bool TestBool { get { return (bool)GetValue(TestBoolProperty); } set { SetValue(TestBoolProperty, value); } } public static readonly DependencyProperty TestBoolProperty = DependencyProperty.Register("TestBool", typeof(bool), typeof(ViewModel), new PropertyMetadata(false, OnTestBoolPropertyChanged)); private static void OnTestBoolPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var vm = (ViewModel)d; vm.CoerceValue(TestDoubleProperty); } public double TestDouble { get { return ((double)GetValue(TestDoubleProperty)); } set { SetValue(TestDoubleProperty, value); } } public static readonly DependencyProperty TestDoubleProperty = DependencyProperty.Register("TestDouble", typeof(double), typeof(ViewModel), new PropertyMetadata(0.0, null, OnCoerceTestDouble)); private static object OnCoerceTestDouble(DependencyObject d, object baseValue) { var vm = (ViewModel) d; var testBool = vm.TestBool; return ((testBool) ? (100.0) : (200.0)); }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1364484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109117/']}
|
jdg_370166
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34592378
|
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 developed a 32-bit C++ application using Visual Studio 2015 (on Windows 10). I want to deploy it onto machines running Windows 7 and later. I put together a WiX installer and included the VC++ redistributable merge module as described here . The merge module I included was C:\Program Files (x86)\Common Files\Merge Modules\Microsoft_VC140_CRT_x86.msm . This installer appears to work fine but on Windows 7 the installed program will not run, complaining about missing api-ms-win-crt-runtime-l1-1-0.dll . From searching I suspect that there may be extra files in the redistributable package vc_redist.x86.exe from here , but the WiX docs tell me to use an msm rather than an exe. It's also possible that the merge module failed to install. I didn't see any errors but I haven't re-run it with logs enabled to check that possibility. Another option may be to use burn but I am not familiar with this tool; I will go that route if it's the correct one but I'd prefer to stick with MSI if possible.
Now provide the response and nothing else.
|
The VC++ runtime redistributables got more complicated in Visual Studio 2015. See the VC team blog post about the universal CRT. Basically, the merge module is insufficient: There will not be a merge module for the Universal CRT. If you currently use the CRT merge modules and still want to deploy the Visual C++ libraries centrally, we recommend that you move to the above mentioned Windows Update package or to the VCRedist. Alternatively, you may choose to link statically to the Universal CRT and the Visual C++ libraries.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34592378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231929/']}
|
jdg_370167
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1903095
|
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:
While looking up information on compact operators I came across these two conflicting posts. If a set is compact then it is closed Topology: Example of a compact set but its closure not compact So the first link says that if a set $U$ is compact then it is closed. $U$ closed means $U = \overline{U}$ and hence $\overline{U}$ is compact. This seems to be in direct contradiction with the second post?
Now provide the response and nothing else.
|
This is not a contradiction, because the main property is: A compact subspace $K$ of a Hausdorff space $X$ is closed. Indeed, we show that for every $x \in X \setminus K$, there is an open set $U$ such that $x \in U \subset X \setminus K$. Fix such an $x$. As $X$ is Hausdorff ($T2$), for every $y \in K$, there are disjoint open sets $U_y,V_y$ such that $x \in U_y$ and $y \in V_y$. Now you can use the compactness of $K \subset \bigcup_{y \in K} V_y$, so that $$K \subset \bigcup_{y \in E} V_y$$for some finite subset $E \subset K$. Define $U = \bigcap_{y \in E} U_y$, which is an open set because $E$ is finite. You can finally show that $U$ satisfies the desired conditions. I leave it to!
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1903095', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49759/']}
|
jdg_370168
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1595285
|
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 rotate a CGPoint on the screen depending on the angle and the rotation is anchored on another point. Was wondering what is the most efficient way of doing this?
Now provide the response and nothing else.
|
You can also use that: rotatedPoint = CGPointApplyAffineTransform(initialPoint, CGAffineTransformMakeRotation(angle)); EDIT: to perform rotation around custom point you must do like Adam described in his answer. Using CGAffineTransform it must look something like: CGAffineTransform translateTransform = CGAffineTransformMakeTranslation(customCenter.x, customCenter.y);CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(angle);CGAffineTransform customRotation = CGAffineTransformConcat(CGAffineTransformConcat( CGAffineTransformInvert(translateTransform), rotationTransform), translateTransform);rotatedPoint = CGPointApplyAffineTransform(initialPoint, customRotation);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1595285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175027/']}
|
jdg_370169
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
198424
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ be a subset, $A \subset \mathbb{R}$. A point $a \in \mathbb{\overline{R}}$ is a limit point(or accumulation point) of $A$ if every neighbourhood of $a$ contains at least one point of $A$ different from $a$ itself I cannot unerstand this definition very well. For this I will draw a picture. I have a set $A$, and two neighbourhoods $V$ and $W$. case I. For the neighbourhood $V$ our definition is verified because $V \cap A \neq \emptyset$ case II. neighbourhood $W$ is not ok because $A \cap W =\emptyset$. Why in the definition is specified the word every ? I can find at least a neighbourhood $U$ for that $U \cap A =\emptyset$. Thanks :)
Now provide the response and nothing else.
|
That point $a$ is not is not a limit point of $A$ precisely because it has a neighborhood, $W$, that does not contain any point of $A$ different from $a$ itself. (I’m assuming that you intended that $a$ belong to the set $A$, even though it’s detached from the rest of $A$.) Consider the set $A=(0,1]\cup\{2\}$. $1$ is a limit point of $A$, because every open set containing $1$ also contains other points of $A$. If $U$ is an open set containing $1$, then there is an $\epsilon>0$ such that $(1-\epsilon,1+\epsilon)\subseteq U$, and clearly $$\max\left\{1-\frac{\epsilon}2,\frac12\right\}\in U\cap(A\setminus\{a\})\;.$$ $2$, on the other hand, is not a limit point of $A$, because the open set $(1,3)$ contains $2$ and no other point of $A$. Finally, $0$ is a limit point of $A$, even though it does not belong to $A$: every open set $U$ containing $0$ contains an interval of the form $(-\epsilon,\epsilon)$, and $$\min\left\{\frac{\epsilon}2,1\right\}\in U\cap(A\setminus\{0\})=U\cap A\;.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/198424', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33954/']}
|
jdg_370170
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1459739
|
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 did a lot of searching and also read the PHP $_SERVER docs . Do I have this right regarding which to use for my PHP scripts for simple link definitions used throughout my site? $_SERVER['SERVER_NAME'] is based on your web server's config file (Apache2 in my case), and varies depending on a few directives: (1) VirtualHost, (2) ServerName, (3) UseCanonicalName, etc. $_SERVER['HTTP_HOST'] is based on the request from the client. Therefore, it would seem to me that the proper one to use in order to make my scripts as compatible as possible would be $_SERVER['HTTP_HOST'] . Is this assumption correct? Followup comments: I guess I got a little paranoid after reading this article and noting that some folks said "they wouldn't trust any of the $_SERVER vars": http://markjaquith.wordpress.com/2009/09/21/php-server-vars-not-safe-in-forms-or-links/ http://php.net/manual/en/reserved.variables.server.php#89567 (comment: Vladimir Kornea 14-Mar-2009 01:06) Apparently the discussion is mainly about $_SERVER['PHP_SELF'] and why you shouldn't use it in the form action attribute without proper escaping to prevent XSS attacks. My conclusion about my original question above is that it is "safe" to use $_SERVER['HTTP_HOST'] for all links on a site without having to worry about XSS attacks, even when used in forms. Please correct me if I'm wrong.
Now provide the response and nothing else.
|
That’s probably everyone’s first thought. But it’s a little bit more difficult. See Chris Shiflett’s article SERVER_NAME Versus HTTP_HOST . It seems that there is no silver bullet. Only when you force Apache to use the canonical name you will always get the right server name with SERVER_NAME . So you either go with that or you check the host name against a white list: $allowed_hosts = array('foo.example.com', 'bar.example.com');if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) { header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request'); exit;}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1459739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/142233/']}
|
jdg_370171
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29731183
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Issue: I have seen this overlap anytime I have a button under a textview or edittext. If I try to add text to one of these, the keyboard forces the buttons to raise. What causes this overlap and how can I avoid it?
Now provide the response and nothing else.
|
Different Android devices behave differently when scanning for connectable BLE advertisements. On some devices (e.g. the Nexus 4), the scanning APIs only get one callback per scan for transmitters sending a connectable advertisement, whereas they get a scan callback for every advertisement for non-connectable advertisements. Other devices (e.g. the Nexus 5) provide a scan callback every single advertisement regardless of whether it is connectable. The Locate app you mention uses the open source Android Beacon Library to detect beacons. It is built on top of the same scanning APIs you show in your question, but it gets around this problem by defining a scan period (1.1 seconds by default in the foreground) and stopping and restarting a scan at this interval. Stopping and restarting the scan causes Android to send a new callback. A few other notes here: This issue of getting multiple scan callbacks for connectable devices applies to both the 4.x and 5.x scanning APIs. It is unclear whether the difference in delivering scan callbacks for connectable advertisements on different devices is due to Android firmware differences or bluetooth hardware chipset differences. There doesn't seem to be a way to detect if a device requires a scan restart to get additional callbacks for connectable advertisements, so if you are targeting a wide variety of devices, you need to plan to stop and restart scanning. Using Android's raw scanning APIs is a great way to understand how BLE beacons work. But there are lots of complexities with working with BLE beacons (this is just one example) which is why using a SDK like the Android Beacon Library is a good choice to keep you from pulling your hair out. Full disclosure: I am the author of the Locate app in the lead developer on the Android Beacon Library open source project.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29731183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2938837/']}
|
jdg_370172
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25736271
|
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 both CakePHP and Eclipse and am having a problem. I downloaded the framework and unzipped it to htdocs/caketest, where I see the directory structure, including index.php. Then I opened the project in Eclipse. Last time it was fine, but today, I'm not able to locate index.php (or even other directories) in PHP explorer. Here's the screenshot: When I execute the project, I can see that index.php is getting run and I'm getting a message saying that CakePHP is not configured. But why isn't the file showing up in PHP Explorer?
Now provide the response and nothing else.
|
OK, I can reproduce this behaviour: by giving a service the same permissions as those of the mystery service, I can make it disappear from the list in services.msc. sc sdset myservice D:(D;;DCLCWPDTSD;;;IU)(D;;DCLCWPDTSD;;;SU)(D;;DCLCWPDTSD;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD) So it's all down to the permissions. OK, let's expand out that security descriptor string. This is a bit tricky because the mapping between the SDDL permissions and equivalent security manager permissions does not appear to be well documented in MSDN or in the SDK headers; luckily, Wayne Martin has already done the heavy lifting for us and posted the results in the blog entry Service Control Manager Security for non-admins . D: - this part is the DACL, the permissions on the service. Deny entries always come first, which also means they take precedence over the allow entries: (D;;DCLCWPDTSD;;;IU) - deny (D) interactive users (IU) the following rights: DC - SERVICE_CHANGE_CONFIG (the right to change the service configuration) LC - SERVICE_QUERY_STATUS (the right to query the service status) WP - SERVICE_STOP (the right to stop the service) DT - SERVICE_PAUSE_CONTINUE (the right to pause and continue the service) SD - DELETE (the right to delete the service)(D;;DCLCWPDTSD;;;SU) - deny services (SU) the same set of rights as above(D;;DCLCWPDTSD;;;BA) - deny the Administrators group (BA) the same as above The allow entries are just the same as the default permissions. (They are in a different order, but the order of allow entries is not significant.) (A;;CCLCSWLOCRRC;;;IU) - allow the interactive user the following rights: CC - SERVICE_QUERY_CONFIG (the right to query the service configuration) LC - overridden by the deny entry SW - SERVICE_ENUMERATE_DEPENDENTS (the right to see service dependencies) LO - SERVICE_INTERROGATE (the right to send SERVICE_CONTROL_INTERROGATE) CR - SERVICE_USER_DEFINED_CONTROL (the right to send a user defined control) RC - READ_CONTROL (the right to see the permissions)(A;;CCLCSWLOCRRC;;;SU) - allow services the following rights: same as for the interactive user(A;;CCLCSWRPWPDTLOCRRC;;;SY) - allow local system the following rights: same as for the interactive user, plus: RP - SERVICE_START (the right to start the service) WP - overridden by the deny entry for BA DT - overridden by the deny entry for BA(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA) - allow the Administrators group: same as for local system, plus: DC - overridden by the deny entry LC - overridden by the deny entry SW - overridden by the deny entry SD - overridden by the deny entry WD - WRITE_DAC (permission to change the permissions) WO - WRITE_OWNER (permission to take ownership) Finally, we have the SACL. This is also unchanged from the default for a service. S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD) S: - indicates that this is a SACL AU - indicates that this is an audit entry FA - indicates that failed attempts to access the object should be audited WD - controls whose failed attempts should be audited; the Everyone SID CCDCLCSWRPWPDTLOCRSDRCWDWO - the kinds of access attempts to audit - appears to include every right that applies to services So basically that just says "audit all failed attempts to access this service". It should be possible to significantly simplify those permissions, e.g., by removing all the allow permissions that are overridden by the deny permissions. In fact, it seems likely the only access permission you would really need is SERVICE_START and perhaps SERVICE_QUERY permission for local system, and maybe not even those. :-) On the other hand, the complexity of the permissions doesn't really matter, so it probably isn't worth the effort involved in testing the changes. PS: to restore the default permissions you can say: sc sdset myservice D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25736271', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1170686/']}
|
jdg_370173
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51970600
|
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 endpoint that requires a parameter passed via the query string (is a GET verb). What is the appropriated status code to give when this parameter is missing from the request? 400 is the one? or should I respond with a 404? [GET /search?q=ok] => 200 OK[GET /search] => 400 Bad Request? or 404 Not Found? Or 422 Unprocessable Entity? Others?
Now provide the response and nothing else.
|
TLDR It's an HTTP 400 - Bad Request. It's a 400 because the user did not send the Required input field. why not 422 - because this case fits to 400 . Keeping your consumers in mind, you shouldn't go to non-popular response codes if you don't really need to. Cases for HTTP 404: 1) Url which the client requested is not existing in your server (usually this will be handled by your server. Application developer usually doesn't have to do anything unless you want a nice looking 404 page and SEO reasons). 2) If it was a path parameter and client was looking for an entity with an id (for Example ( /students/{id} and your application couldn't find such entity, you may respond with an HTTP 404. Let's say, user send the query parameter and you did not find any items matching the query param, make no mistake, it's still an HTTP 200 with body as an empty array or so (not a 404 unlike mentioned in the previous case)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51970600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1283453/']}
|
jdg_370174
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13860
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there an idiomatic means to detect whether "find" found any matches? I'm currently using COUNT=`find ... | wc -l`if [ "$COUNT" -gt 0 ]; then but this seems a little indirect to me. Also, I'd like find to stop searching once it's found a match, so it doesn't waste time and effort. I just need to know whether or not there are any files that match. Update: I made the mistake of writing my question without the code in front of me: I use wc -l in a different case, where I need to know the total number of found files anyway. In the case where I'm only testing for whether there are any matches, I was using if [ -z $(find …) ] .
Now provide the response and nothing else.
|
If you know you have GNU find, use -quit to make it stop after the first match. Portably, pipe the output of find into head -n 1 . That way find will die of a broken pipe after a few matches (when it's filled head 's input buffer). Either way, you don't need wc to test whether a string is empty, the shell can do it on its own. if [ -n "$(find … | head -n 1)" ]; then …
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/13860', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/7814/']}
|
jdg_370175
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1337517
|
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 show that smooth functions are dense in the space of continuous function on $[0,1]$? I know that we can use mollifiers. I wiki-ed it but can someone give me a rigorous proof?
Now provide the response and nothing else.
|
The original proof of Weierstrass used the heat kernel to approximate continuous functions by smooth functions; Weierstrass then expanded the heat kernel in a power series to obtain a polynomial approximation. Start with a continuous function $f$ on $[0,1]$. Extend your function from $[0,1]$ to be continuous on $\mathbb{R}$ and to vanish outside $[-\delta,1+\delta]$ for some $\delta > 0$. Consider$$ u(t,x)=\frac{1}{\sqrt{4\pi t}}\int_{-\infty}^{\infty}e^{-(x-y)^{2}/4t}f(y)dy.$$This function naturally arises in the solution of the heat equation $u_{t}=u_{xx}$ with initial heat distribution $u(0,x)=f(x)$. As $t\downarrow 0$, the function $u(t,x)$ converges uniformly to $f(x)$ on $\mathbb{R}$, and $u(t,x)$ is infinitely differentiable in $x$ for any fixed $t > 0$. The argument for this uses properties of the heat kernel$$ H(t,x) = \frac{1}{\sqrt{4\pi t}}e^{-x^{2}/4t}.$$For example, $H(t,x) \ge 0$ for all $t > 0$, $x\in\mathbb{R}$; $\int_{-\infty}^{\infty}H(t,x)dx = 1,\;\;\; t > 0$; $\lim_{t\downarrow 0}\int_{|x|\ge \delta}H(t,x)dx =0$ for fixed $\delta > 0$. So, let $\epsilon > 0$ be given. By uniform continuity of $f$ on $\mathbb{R}$, there exists $\delta > 0$ such that $|f(x)-f(y)| < \epsilon/2$ whenever $|x-y| < \delta$. Therefore,$$ u(t,x)-f(x) = \int_{-\infty}^{\infty}H(t,x-y)(f(y)-f(x))dy.$$Hence, if $M$ is a bound for $f$ on $\mathbb{R}$,$$ |u(t,x)-f(x)| \le \int_{x-\delta/2}^{x+\delta/2}H(t,x-y)|f(y)-f(x)|dy +2M\int_{\delta/2}^{\infty}H(t,y)dy \\ \le \epsilon/2+2M\int_{\delta/2}^{\infty}H(t,y)dy.$$Therefore, there exists $t_0 > 0$ such that$$ |u(t,x)-f(x)| < \epsilon,\;\;\; 0 < t < t_0.$$Then, if you want a polynomial approximation, you can expand the heat kernel in a power series and approximate on a finite interval for some fixed $t \in (0,t_0)$:$$ H(t,y-x) \approx \frac{1}{\sqrt{4\pi t}}\sum_{n=0}^{N}\frac{1}{n!}\left(\frac{(y-x)^{2}}{4t}\right)^{n}.$$Therefore, $u \approx f$ and$$ u(x,t) \approx \sum_{n=0}^{N}\int_{-\delta}^{1+\delta}f(y)\frac{(x-y)^{2n}}{\sqrt{\pi}(4t)^{n+1/2}}dy = a_0 +a_1 x +a_2 x^{2}+ \cdots +a_{2n} x^{2n}.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1337517', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/143894/']}
|
jdg_370176
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7962
|
Below is a question asked on the forum ai.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible for a genetic algorithm + Neural Network that is used to learn to play one game such as a platform game able to be applied to another different game of the same genre. So for example, could an AI that learns to play Mario also learn to play another similar platform game. Also, if anyone could point me in the direction of material i should familiarise myself with in order to complete my project.
Now provide the response and nothing else.
|
Genetic algorithms and Neural Networks both are "general" methods, in the sense that they are not "domain-specific", they do not rely specifically on any domain knowledge of the game of Mario. So yes, if they can be used to successfully learn how to play Mario, it is likely that they can also be applied with similar success to other Platformers (or even completely different games). Of course, some games may be more complex than others. Learning Tic Tac Toe will likely be easier than Mario, and learning Mario will likely be easier than StarCraft. But in principle the techniques should be similarly applicable. If you only want to learn in one environment (e.g., Mario), and then immediately play a different game without separately training again, that's much more complicated. For research in that area you'll want to look for Transfer Learning and/or Multi-Task learning. There has definitely been research there, with the latest developments that I'm aware of having been published yesterday (this is Deep Reinforcement Learning though, no GAs I think). The most "famous" recent work on training Neural Networks to play games using Genetic Algorithms that I'm aware of is this work by Uber (blog post links to multiple papers). I'm not 100% sure if that really is the state of the art anymore, if it's the best work, etc... I didn't follow all the work on GAs in sufficient detail to tell for sure. It'll be relevant at least though. I know there's also been quite a lot of work on AI in general for Mario / other platformers (for instance in venues such as the IEEE Conference on Computational Intelligence and Games, and the TCIAIG journal).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://ai.stackexchange.com/questions/7962', 'https://ai.stackexchange.com', 'https://ai.stackexchange.com/users/18209/']}
|
jdg_370177
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25436
|
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:
Consider the following example: 4.*Mean@Table[ Boole[Random[]^2 + Random[]^2 < 1], {10^6}] // AbsoluteTiming(*{0.408023, 3.14105}*)With[{n = 10^6}, 4. Mean@Boole@Thread[(RandomReal[1, n]^2 + RandomReal[1, n]^2) < 1]] // AbsoluteTiming(*{1.460084, 3.14276}*) I expected the second method to be more efficient since it used vectorized operations, but it works slowly, and I don't know why. Is it possible to make it faster?I used Mathematica 9 on Windows 7.
Now provide the response and nothing else.
|
First, the old Random function uses an inferior PRN generator and should not be used other than for legacy compatibility, if I recall correctly. On my machine (version 7, Windows 7) the second method is faster than the first, though not by a great amount: 4.*Mean@Table[Boole[RandomReal[]^2 + RandomReal[]^2 < 1], {10^6}] // AbsoluteTimingWith[{n = 10^6}, 4. Mean@Boole@Thread[(RandomReal[1, n]^2 + RandomReal[1, n]^2) < 1]] // AbsoluteTiming {1.2840735, 3.14154} {0.4570262, 3.1401} Numeric methods will be much faster: With[{n = 10^6}, With[{r = RandomReal[1, n]^2 + RandomReal[1, n]^2}, 4. * Mean[1 - UnitStep[r - 1]] ]] // AbsoluteTiming {0.0510029, 3.14232} This is partly because the array is not unpacked, as it is in your code as can be seen by first running On["Packing"] : On["Packing"]With[{n = 10^6}, 4. Mean@Boole@Thread[(RandomReal[1, n]^2 + RandomReal[1, n]^2) < 1]] // AbsoluteTiming Developer`FromPackedArray::unpack: Unpacking array in call to Less. >> Developer`FromPackedArray::punpack1: Unpacking array with dimensions {1000000} to level 1. >>
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/25436', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7339/']}
|
jdg_370178
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
284060
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am writing code on top an established Enterprise application. I see that the application has 4 modules as shown below. -Srk-SrkEJB-SrkUtils-SrkWeb I have gone through the code and I see that some modules are tiny for example: SrkEJB module has got just 2 EJBS. I don't see any reason to create a separate module for 2 Java classes. I have simplified the above approach and is shown below. Srk - com.srk.utils - com.srk.ejb - com.srk.web How is the first module based architecture different from the second from an architectural stand point? Generally, which is the followed mostly, when creating an application from scratch? If not, What could be the trade-offs of each of the approaches? I believe this is a not specific to Java alone.
Now provide the response and nothing else.
|
As written (which may be oversimplified) it sounds like the Sensors are all the same in general behavior, but the Parameters for calibration are different. If this were the only difference, and you are using a language with generics, such as Java (used below), you could generify the class by the Parameters, something like: abstract class Sensor<CalibrationParameters> { // constructor, getters, setters, etc... abstract public void calibrated(CalibrationParameters parameters);} then a bunch of public class SensorN extends Sensor<CalibrationParametersForSensorN> { public void calibrated(CalibrationParametersForSensorN parameters) { ... }} Caveat: typed without an IDE so there may be typos or errors... p.s. Agree with Robert that better names would be, er, better. So a better concrete implementation would be: public class Thermometer extends Sensor<ThermometerCalibration> { public void calibrated(ThermometerCalibration parameters) { ... }}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/284060', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/42123/']}
|
jdg_370179
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40460808
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know you can get it on the settings page.I have multiple calendars on a single account. I can get the names back with service.list_calendar_lists(page_token: page_token) but how do I can the calendar ids associated with the names of the calendars
Now provide the response and nothing else.
|
This problem occurred because the TypeScript compiler tries to transpile everything, including files that are already JavaScript, in which case it understandably complains that it will overwrite its input. I found no combination of "include" and "exclude" statements which could stop this behaviour. The solution is to add a new field, "outDir", to the compilerOptions, so it looks like this { "compilerOptions": { "module": "commonjs", "sourceMap": true, "watch": true, "allowJs": true, "outDir": "generated" }} This will cause tsc to copy ALL ts and js in your project to the specified folder. There will be no more of those pesky TS5055 errors. If the import references in your project are all relative, this should be fine. Otherwise, for example, if your Node.js project is using a "public" folder at the top level, you might have to modify path references in your code accordingly.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40460808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136894/']}
|
jdg_370180
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15191888
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is the constructor: public PartyRoleRelationship(PartyRole firstRole, PartyRole secondRole) { if (firstRole == secondRole) throw new Exception("PartyRoleRelationship cannot relate a single role to itself."); if (firstRole.OccupiedBy == null || secondRole.OccupiedBy == null) throw new Exception("One or both of the PartyRole parameters is not occupied by a party."); // Connect this relationship with the two roles. _FirstRole = firstRole; _SecondRole = secondRole; T = _FirstRole.GetType().MakeGenericType(); _SecondRole.ProvisionRelationship<T>(_FirstRole); // Connect second role to this relationship. } On the last line, where it calls ProvisionRelationship on _SecondRole, it's giving me the run-time error: Type or namespace 'T' could not be found... How do I either (a) properly assign T, or (b) pass a generic type with the constructor? I've been looking through quite a few posts, but may have missed something due to a lack of understanding. Anyone's help on this would be greatly appreciated.
Now provide the response and nothing else.
|
Your class needs to be generic. So PartyRoleRelationship needs to look like this: public class PartyRoleRelationship<T>{ public PartyRoleRelationship(T arg, ...) { }} Read more about generic classes here: http://msdn.microsoft.com/en-us/library/sz6zd40f(v=vs.80).aspx http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx Edit: You could probably simplify you code a bit and do it like this: public class RoleRelationship<T>{ public RoleRelationship(T firstRole, T secondRole) { if (firstRole.OccupiedBy == null || secondRole.OccupiedBy == null) throw new Exception("One or both of the Role parameters is not occupied by a party."); // Connect this relationship with the two roles. _FirstRole = firstRole; _SecondRole = secondRole; _SecondRole.ProvisionRelationship<T>(_FirstRole); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15191888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1799005/']}
|
jdg_370181
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
374108
|
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:
In an earlier question I asked about driving a speaker with a BJT transistor. @Jonk offered a push-pull amplifier design of his own, and @G36 noted its similarity to the JLH amplifier described in a paper from 1969 . In 1969 NPN power transistors were easier to come by than PNPs, so the JLH amplifier, and @Jonk's amplifier, use two NPN transistors instead of an NPN and a PNP. This is interesting to me because I'm trying to understand tube guitar amplifiers, and tubes are more or less NPNs. (I know they're more like FETs, but my point is, there are no PNP-like tubes.) Using two NPNs requires a third NPN to act as a phase splitter. I've set this up, and it works fine: simulate this circuit – Schematic created using CircuitLab The base of Q1 is biased to about 6.7V (give or take). The input swings +/-5V because it is the output of a previous voltage-amplifying stage. With no signal the emitter is at 6V and and the collector at 18V, giving plenty of room the voltage swings. The problem is that when I attach the power NPNs, there is a zero-resistance path between the base of Q1 and ground, and all the current drains out. :-( simulate this circuit How can this be made to work? All the examples I've seen have the emitter of the "bottom" NPN (Q3 in this case) connected to ground. But that means its base will be at about 0.7V, and the base of Q1 will be 1.4V, and they will not be able to swing +/-5V, or at all. In the JLH and @Jonk amplifiers, there is a PNP upstream of the phase-splitter transistor that I suspect has something to do with the solution, but just can't figure out how it works. UPDATED: Added a decoupling capacitor in front of the speaker.
Now provide the response and nothing else.
|
Let's return to the basics: simulate this circuit – Schematic created using CircuitLab Output Stage Above is a fragment of the circuit in the earlier schematic you were examining. \$V_\text{CC}=12\:\text{V}\$ and the output at the emitter of \$Q_1\$ is assumed to be centered at about \$6\:\text{V}\$ and the output swing should be limited to peaks that stay at least \$1.5\:\text{V}\$ above or below the rails. So \$6\:\text{V}\pm 4.5\:\text{V}\$ at the emitter of \$Q_1\$. This should be able to exceed \$1\:\text{W}\$ into an \$8\:\Omega\$ speaker. The peak current is \$I_\text{PEAK}<570\:\text{mA}\$ into the speaker. Since this is supposed to be a class-A amplifier, it's important that there is always some current in \$Q_2\$'s collector (it should never reach zero.) To keep the \$V_\text{BE}\$ variation in \$Q_2\$ to about \$30\:\text{mV}\$, I want \$I_\text{MIN}=\frac{I_\text{PEAK}}{e^\frac{30\:\text{mV}}{V_T}-1}\approx 260\:\text{mA}\$. Let's call it \$I_\text{MIN}=250\:\text{mA}\$. So that is the minimum for this class-A. So \$I_\text{MAX}=250\:\text{mA}+570\:\text{mA}=820\:\text{mA}\$. Keep in mind, we are strictly talking about the collector current for \$Q_2\$. By implication, the emitter current for \$Q_1\$ will be the same minimums and maximums except that they will be \$180^\circ\$ out of phase with those of \$Q_2\$. The sum of both collector currents will be \$250\:\text{mA}+820\:\text{mA}=1.07\:\text{A}\$. (As you will see later, this sum is fairly constant as is the sum of the two base currents.) Given an NPN like the D44H11 I had figured \$\beta\ge 90\$ for \$Q_1\$ and \$Q_2\$. So the base drive for both output BJTs summed together worked out to about \$12\:\text{mA}\$. Bootstrap Loop \$R_2\$ is turned into a current source by the bootstrap loop. (The reason why I'm calling it a loop will be apparent soon enough.) We can assume that the \$V_\text{BE}\$ of \$Q_1\$ is approximately fixed (like a battery) throughout the operation of the amplifier. We can also assume that the voltage across \$C_1\$ is similarly approximately fixed (again, like a battery.) So, walk around the loop using KVL starting at the output. It must be the case that \$V_\text{OUT}+V_{C_1} + V_{R_2}+V_\text{BE}=V_\text{OUT}\$. But this means that \$V_{R_2}=-\left(V_{C_1} + V_\text{BE}\right)\$ and since the right side of that equation is fixed then it must be the case that the voltage across \$R_2\$ is fixed. And this means that the current in \$R_2\$ is fixed. And therefore, we have a constant current in \$R_2\$. Q.E.D. Given that the voltage across \$C_1\$ will be half the supply voltage and that the \$V_\text{BE}\$ of \$Q_1\$ will be about \$700\:\text{mV}\$, I can work out that the voltage across \$R_2\$ is \$\approx 5.3\:\text{V}\$. Given the needed base current sum noted in the previous section, I decided that I needed at least another \$1\:\text{mA}\$ (more would be fine.) So I figured \$R_2=\frac{5.3\:\text{V}}{13\:\text{mA}}\approx 407\:\Omega\$. I rounded that downward (more current is better) to the nearby \$R_2=390\:\Omega\$. With over \$1\:\text{mA}\$ remaining after subtracting output section base drive currents, and knowing that \$Q_2\$'s \$V_\text{BE}\$ needs about \$700\:\text{mV}\$, I set \$R_1=560\:\Omega\$. I would not set it lower than that. But I might also try one step higher at \$R_1=680\:\Omega\$, without batting an eye. In fact, thinking back though all this again now I'd probably prefer \$R_1=680\:\Omega\$. But either of those two values would be fine. A final note about this type of bootstrapping. It's really nice because it is a very simple method to create a constant current supply by just re-arranging parts you'd be using anyway. However, the constant current through \$R_2\$ comes through the speaker. So it creates a DC-biasing current in the speaker. We might wish it could be otherwise, but it's a price to pay for this arrangement. Phase Splitter We have a current source at the collector of \$Q_3\$ where \$R_2\$'s value sets the current source for \$Q_3\$'s collector and the base of \$Q_1\$. After subtraction of \$Q_1\$'s base current, what remains is then driven through \$Q_3\$'s emitter and, after subtracting the base drive for \$Q_2\$ produces a voltage via \$R_1\$. I think you may see the obvious. In effect, the collector currents of \$Q_1\$ and \$Q_2\$ are out of phase with each other but cover the same range. So their sum is a relative constant. Therefore, also, the sum of their base currents is also a relative constant. This implies that the constant current from \$R_2\$, after subtracting the sum of \$Q_1\$'s and \$Q_2\$'s base current, will leave a relatively constant current for \$R_1\$. So we can roughly predict a value for \$R_1\$, as done earlier. However, and this is important, the voltage across \$R_1\$ is not exactly constant. The variation will be just what's required to move \$Q_2\$ through its designed collector current variation. (As you read forward, you may also keep in mind now why it was important, as noted above, to limit this variation.) From the earlier design step we have \$30\:\text{mVpp}\$ for \$Q_2\$. I'd selected this operating point by completely ignoring the Ohmic resistances. These matter. For now, I'm just going to randomly double the earlier estimated variation over \$R_2\$. So about \$60\:\text{mVpp}\$ variation over \$R_1\$. What about the base of \$Q_3\$? Expect another \$30\:\text{mVpp}\$ to be added to the now planned \$60\:\text{mVpp}\$ for \$Q_2\$. (\$Q_3\$'s collector current is going through similar variations.) So that means, rounded up, about \$100\:\text{mVpp}\$ for the base of \$Q_3\$ as a reasoned plan. So that's the drive for \$Q_3\$. The entire output section and splitter combined must be driven by a voltage signal that cannot vary by more than \$100\:\text{mVpp}\$. We also know that the center of this voltage must be approximately two \$V_\text{BE}\$'s, right? This means \$1.4\:\text{V}\$ or thereabouts. So \$V_\text{DRIVE}=1.4\:\text{V}\pm 50\:\text{mV}\$. Also, we'll need a peak base current for \$Q_3\$ of perhaps \$60\:\mu\text{A}\$. Just to be safe, assume a worst case of \$100\:\mu\text{A}\$. NFB This part is relatively trivial. It's just a basic AC divider that, at DC, simply passes the output back with a gain of 1. But at AC passes back only a divided portion of the output. It's a voltage signal. As it is, we should expect a gain of about \$\lvert A_v\rvert \approx 15\$. But more on that later. (I actually set the gain to 15 first, and then worked out the resistor values later, as you'll see below.) Added PNP stage So. We have some NFB ready to go and a need for a DRIVE signal. Now we can consider the new circuit. simulate this circuit The amplifier output is already assumed to be capable of \$600\:\text{mA}\$ drive. So it will be perfectly able drive the emitter of the added PNP, \$Q_4\$. The much weaker input signal can't really drive that much (by assumption), so we feed that to the base of \$Q_4\$. \$Q_4\$'s collector current has to supply the base of \$Q_3\$ and we want this to be stiff , so the usual rule is to multiply by 10 (keep things under 10% variation.) So the collector current of \$Q_4\$ is determined to be \$1\:\text{mA}\$ (since earlier we set aside \$100\:\mu\text{A}\$ worst case base drive for \$Q_3\$.) We know we want about \$1.4\:\text{V}\$ at the base of \$Q_3\$, too. (Also determined earlier.) So this means that the collector resistor of \$Q_4\$ is set to the standard value you see above. Given \$4.5\:\text{Vp}\$ for the output and a gain of 15, we know the input signal must be \$V_\text{IN}\le 300\:\text{mVp}\$. Or \$600\:\text{mVpp}\$. Because of the Early effect on BJTs, I want to keep the variation of \$Q_4\$'s \$V_\text{CE}\$ to a minimum. But the emitter is going to follow that base around. So I decided that I wanted to set the center (quiescent) \$V_\text{CE}\$ of \$Q_4\$ at \$3\:\text{V}\$ or more. But given the tight quarters here (not a lot of voltage room), I decided to settle on \$V_{\text{CE}_\text{Q}}=3\:\text{V}\$ for \$Q_4\$. Given that, and knowing that I still need to get \$1\:\text{mA}\$ from the output to feed the emitter of \$Q_4\$, I set \$R_3\$ as you see. (From that, and knowing a gain of 15, that provided the value of \$R_4\$.) You might have chosen a different \$V_{\text{CE}_\text{Q}}\$ for \$Q_4\$ than I did. Perhaps set it a little higher yet. Or lower. And that would also work. But that's the figure I picked. I was just rushing through a design as quickly as my fingers could type (brain was moving faster) and I didn't want to waste any time trading off secondary considerations (there are a few.) That's really all there was. The only thing left was to figure out the quiescent base voltage for \$Q_4\$ (trivial) and work out a divider arrangement for it. Gain Notes Ignoring the \$Q_4\$ the open loop gain of the amplifier comes from converting about \$100\:\text{mVpp}\$ to about \$9\:\text{Vpp}\$ -- about \$A_{VOL}=90\$. (The actual value may be a little higher than that because I rounded up on the input swing.) But \$Q_4\$ is also what can be seen as a CE amplifier (look at the emitter load vs the collector load.) In this case, I figure \$r_e\approx 26\:\Omega\$ (at room temp) and \$100\:\Omega\mid\mid 1.5\:\text{k}\Omega\approx 94\:\Omega\$. So \$A_{VOL}=90\cdot\frac{1.5\:\text{k}\Omega}{94\:\Omega+26\Omega=120\:\Omega}=1125\$. So the closed loop gain should be \$\frac{1125}{1+\frac{100\:\Omega}{1.5\:\text{k}\Omega+100\:\Omega}\cdot 1125}= 15.8\$. (All this suggests that the input should be kept less than about \$250\:\text{mVp}\$ rather than the originally mentioned \$300\:\text{mVp}\$, and perhaps just a little less.) A remaining question to consider will turn out to be a minor detail. Because of the proximity of the magnitude of \$r_e\$ vs \$R_4\$, the above-mentioned open loop gain is temperature-dependent. \$Q_4\$ isn't likely to be self-heated that much, but ambient variations can be wide. Over the range of \$-20\:^\circ\text{C}\$ to \$+40\:^\circ\text{C}\$, \$22\:\Omega\le r_e\le 27\:\Omega\$. Anyone familiar with the power of NFB will immediately realize this won't matter that much (the open loop gain may be from 1115 to about 1165 here) in the end. The closed loop gain will still be rock solid. Try out the calculations yourself and see. Update I updated the final schematic above. I'd completely forgotten about the need to force a high frequency roll-off. I've added \$C_3\$ with a nominal value that is reasonably placed, I think. The Ohmic resistances in \$Q_1\$ and \$Q_2\$ should also be put under management and current limiting would be useful, too. But that compensation pole is a must. So it's added now.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/374108', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/96030/']}
|
jdg_370182
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
193507
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is the following guaranteed to return true for all numerical and non-zero values of x ? bool IsRoundTrip(double x){ double y = 1 / (1 / x); return x == y;} What conditions would cause a discrepency?
Now provide the response and nothing else.
|
To simplify things by defining a concrete implementation, I will assume (as other answers do) that we're talking about IEEE 754 64-bit floating point. Each floating point number has three parts: a sign, an exponent, and a mantissa. (Technical details about hidden bits are irrelevant to this discussion). Reciprocation doesn't affect the sign 1 / (2**e * m) = (1 / 2**e) * (1 / m) = 2**-e * (1 / m) , so there are two ways in which the double-reciprocation can fail to provide a fixpoint. The easy one is that the exponent can be an extreme value such that we move from a denormalised number to one which overflows. The second is that the mantissa can be a non-fixpoint of the double-reciprocation. I wrote a simple program to test random mantissas: import java.util.Random;strictfp class RoundTrip{ public static void main(String[] args) { long one = Double.doubleToLongBits(1.0); Random rnd = new Random(); for (int i = 1; i < 1<<30; i++) { long mantissa = rnd.nextLong() & 0xfffffffffffffL; double x = Double.longBitsToDouble(one + mantissa); double y = 1 / (1 / x); if (x != y) { System.out.println(Long.toHexString(one + mantissa)); System.out.println(x); System.out.println(y); break; } } }} It quickly gave some output: 3ffeca41c09ebb2b1.92437911264614561.9243791126461458 The program can be expected to find an answer if as few as 1 in 2**30 mantissas fail. With a slight modification, I found that about 17.15% of mantissas fail. Slightly handwavy analysis: There are 2**52-1 mantissas covering the open range (1, 2) , and they're uniformly spaced.The same uniformly spaced mantissas cover the open range (0.5, 1) , which contains the reciprocals. Note that in this range one unit in the last place (1ulp), i.e. the difference between consecutive values, has an absolute value half that of the ulp in the range (1, 2) . But reciprocation isn't a linear operation, so in some parts of the range the density of values required is higher than in others. Therefore we expect that the reciprocation will not be injective. Suppose values x and x+dx , both in (1, 2) , differ by 1ulp. If they map to the same reciprocal mantissa, at most one of them can round-trip. What is the probability of this collision? x^-1 differentiates to -x^-2 , so the difference between 1/x and 1/(x+dx) is approximately -dx/x^2 , or -2dx/x^2 ulps, so a difference of one ulp before reciprocation gives a difference of -2/x^2 ulps after reciprocation. Given that the separation between two exactly representable values is 1ulp (by definition), and assuming (for simplification) no particular alignment between mantissas and reciprocal mantissas, we can estimate the probability of a collision as max(0, 1 - 2/x^2) , and we can approximate the proportion of collisions as \int_1^2 max(0, 1 - 2/x^2) dx = \int_{\sqrt 2}^2 (1 - 2/x^2) dx = 3 - 2\sqrt 2 is approximately 0.1716. This is in very good agreement with my empirical results for the proportion of mantissas that don't round-trip, so it seems reasonable to hypothesise that a mantissa will round-trip unless its reciprocal collides with that of another mantissa, in which case only one of the two will round-trip.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/193507', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/33490/']}
|
jdg_370183
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9743838
|
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 run many processes in parallel with ability to take stdout in any time. How should I do it? Do I need to run thread for each subprocess.Popen() call, a what?
Now provide the response and nothing else.
|
You can do it in a single thread. Suppose you have a script that prints lines at random times: #!/usr/bin/env python#file: child.pyimport osimport randomimport sysimport timefor i in range(10): print("%2d %s %s" % (int(sys.argv[1]), os.getpid(), i)) sys.stdout.flush() time.sleep(random.random()) And you'd like to collect the output as soon as it becomes available, you could use select on POSIX systems as @zigg suggested : #!/usr/bin/env pythonfrom __future__ import print_functionfrom select import selectfrom subprocess import Popen, PIPE# start several subprocessesprocesses = [Popen(['./child.py', str(i)], stdout=PIPE, bufsize=1, close_fds=True, universal_newlines=True) for i in range(5)]# read outputtimeout = 0.1 # secondswhile processes: # remove finished processes from the list (O(N**2)) for p in processes[:]: if p.poll() is not None: # process ended print(p.stdout.read(), end='') # read the rest p.stdout.close() processes.remove(p) # wait until there is something to read rlist = select([p.stdout for p in processes], [],[], timeout)[0] # read a line from each process that has output ready for f in rlist: print(f.readline(), end='') #NOTE: it can block A more portable solution (that should work on Windows, Linux, OSX) can use reader threads for each process, see Non-blocking read on a subprocess.PIPE in python . Here's os.pipe() -based solution that works on Unix and Windows: #!/usr/bin/env pythonfrom __future__ import print_functionimport ioimport osimport sysfrom subprocess import PopenON_POSIX = 'posix' in sys.builtin_module_names# create a pipe to get datainput_fd, output_fd = os.pipe()# start several subprocessesprocesses = [Popen([sys.executable, 'child.py', str(i)], stdout=output_fd, close_fds=ON_POSIX) # close input_fd in children for i in range(5)]os.close(output_fd) # close unused end of the pipe# read output line by line as soon as it is availablewith io.open(input_fd, 'r', buffering=1) as file: for line in file: print(line, end='')#for p in processes: p.wait()
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9743838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/303381/']}
|
jdg_370184
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6100021
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently developing my own weblog in Django . But I've already stucked right in the beginning. So, here is my tree hierarchy: /pyroot/nemoden/|~blog/| |-__init__.py| |-admin.py| |-models.py| |-tests.py| `-views.py|+css/|+images/|+js/|~templates/| |-index.html| `-postslist.html|-__init__.py|-manage.py|-settings.py`-urls.py What I've done is: created new application called blog and described all the models I need for a blog in blog/models.py (User, Post, Comment, etc.), but then I watched Jeff Hui's video and realised that it is probably a bad idea and in Django-world people don't do that... what we do in... PHP-world using our PHP Frameworks . I guess it is better to have distinguished Django-applications for Tags, Comments, Users, etc... So, what I'm asking is: Is it better to have one model per Django-app? If so, are there some exceptions when I should not create a new Django-app for a model? I want to go with: /pyroot/nemoden/|~blog/ # this is actual application (not a django-application). It uses all the models in views.py, so django-apps becomes just models| |-__init__.py| |-tests.py| `-views.py # all the views (controllers in other frameworks) used by our (well,... my) weblog|+css/|+images/|+js/|~templates/| |-index.html| `-postslist.html|-__init__.py|~post/| |-__init__.py| |-tests.py| |-admin.py| |-models.py # only Post model goes here| `-views.py|~tag/| |-__init__.py| |-tests.py| |-admin.py| |-tag.py # only Tag model goes here| `-views.py # <---- I don't know why we still need it here!|-manage.py|-settings.py`-urls.py As you see I cut out models.py and admin.py from blog app, so now blog app more like the app or main app if you wish which uses all the models (django-apps) and mainly consists of views.py . And I think now we don't need all views.py in all django-apps (this one is under a BIG question mark, though - it is just in theory). Is my approach any good or I will suffer problems invisible for me now, maybe?
Now provide the response and nothing else.
|
Is it better to have one model per Django-app? One of the key ideas for a reusable application is: Do one thing, and do it well If an app needs several models (PostEntry, PostAuthor in case of a Blog App) this is by no means bad. Tags, Categories, Comments however represent distinct features which ideally can be reused in another context and therefore should be distributed as standalone apps. Is there best practices? To get a feeling for a good app organization I'd first take look at Django Reusable App Conventions . Then you are ready for James Bennett's talk about Resuable Apps from DjangoCon 2008 ( Slides ). Another, more recent take on the same subject is Pluggable Django Application Patterns from PyCon 2011
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6100021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485676/']}
|
jdg_370185
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
148044
|
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 am trying to understand how the choice of priors affects a Bayesian model estimated using MCMC. At a basic level I understand that the product of the prior and the likelihood are proportional to the posterior. However, I do not fully understand (a) how to place more or less weight on the prior or (b) how the prior in this example influences the results. The prior in this example is defined as: # Prior distributionprior <- function(param){ a = param[1] b = param[2] sd = param[3] aprior = dunif(a, min=0, max=10, log = T) bprior = dnorm(b, sd = 5, log = T) sdprior = dunif(sd, min=0, max=30, log = T) return(aprior+bprior+sdprior)} As I understand the example, whatever value of b was drawn by the proposal function is considered by the prior to be the most probable. Is that correct? Doesn't this prior essentially place all of the action on the likelihood function because all values of b will have the same density under the prior that the proposed b is the mean of b's distribution? More generally, how do I place more or less weight on the prior in the posterior. If $\text{posterior} \propto \text{prior} \times \text{likelihood}$ I don't know how to adjust the weight of the prior. If it's in log form as in the example the log of the posterior is defined as: posterior <- function(param){ return (likelihood(param) + prior(param))} Here it seems like I could put a weight in front of either the likelihod or the prior. For example, likelihood(param) + 2 * prior(param) would give the prior twice as much weight as the likelihood. Is that intuition correct or am I on the wrong track?
Now provide the response and nothing else.
|
A prior is a distribution. You don't really weight that distribution , Bayes' rule does. However, if you're thinking of your prior distribution as representing uncertainty "about" some value you expect a priori, so that the mode (or whatever measure of the center) of the prior expresses your prior knowledge of where you think it lies and the spread represents the uncertainty about where it is, then increasing the spread puts less weight near that prior central value and decreasing the spread puts more weight near that prior central value. So choose a more concentrated prior to put more weight near that value.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/148044', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/55649/']}
|
jdg_370186
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9553390
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
NSHomeDirectory() is retuning my sandbox root, not my home directory. [@"~" stringByExpandingTildeInPath] is doing the same thing. This /Users/username/Library/Containers/appID/Data is what's being returned. How do I get /Users/username/ ?
Now provide the response and nothing else.
|
If you want the path to the user's real home directory you can use: char *realHome = getpwuid(getuid())->pw_dir; Full example: #include <unistd.h>#include <sys/types.h>#include <pwd.h>#include <assert.h>NSString *RealHomeDirectory() { struct passwd *pw = getpwuid(getuid()); assert(pw); return [NSString stringWithUTF8String:pw->pw_dir];} This gives you the path to the user's home, but does not automatically give you access to that folder. As noted in comments, you can use this path for: providing a sane default folder for the open/save dialogs detecting whether you are in a sandbox, by comparing the result to NSHomeDirectory()
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9553390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/308079/']}
|
jdg_370187
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31097
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A famous problem: A lady is in the center of the circular lake and a monster is on the boundary of the lake. The speed of the monster is $v_m$ , and the speed of the swimming lady is $v_l$ . The goal of the lady is to come to the ground without meeting the monster, and the goal of the monster is to meet the lady. Under some conditions on $v_m,v_l$ the lady can always win. What if these conditions are not satisfied? Edited : the monster cannot swim. If the conditions are not satisfied, then monster can always perform a strategy such that the lady will not escape the lake. On the other hand this strategy is not desirable for both of them because they do not reach their goals. As there was mentioned, this deals with undecidability of the problem. On the other hand, if you imagine yourself to be this lady/monster, you can be interested in the strategy which is not optimal. What is it? If there are such strategies in the game theory? Edited2: My question is more general in fact. If we have a game with one parameter $v$ when two players $P_1, P_2$ are enemies and if $v>0$ then for any strategy of $P_2$ the player $P_1$ wins. If $v\leq 0$ then for any strategy of $P_2$ there is a strategy of $P_1$ such that $P_2$ does not win and vice versa. I am interested in this case. From the mathematical point of view as I have understood the problem is undecidable since there is no an ultimate strategy neither for $P_1$ nor for $P_2$ . But we are solving somehow these problem IRL. Imagine that you are a lady in this game - then you would like to win anyway even while knowing that your strategy can be covered by the strategy of the monster. On the other hand, the monster knows that if he will cover all strategies of the lady she will never reach the shore and he will never catch her. I mean they have to develop some non-optimal strategies. I hope now it's more clear.
Now provide the response and nothing else.
|
Since you seem to know the answer, I will give it here. Suppose that $v_l = v_m / k $ and the radius of the lake is $r$. Then the lady can reach a distance $\frac{r}{k}$ from the centre and keep the monster directly behind her, a distance $r\left(1 + \frac{1}{k}\right)$ away. One way would be to swim in a spiral gradually edging outwards as the monster runs trying to close the distance; another would be to swim in a semi-circle of radius $\frac{r}{2k}$ away from the monster once it starts to run. And the lady can sustain this distance by going round in a circle as the monster tries in vain to close the distance. The next stage is for the lady to try to swim direct to shore at some point away from the direction the monster is running. If the monster starts at the point $(-r,0)$ running anti-clockwise and the lady starts at the point $\left(\frac{r}{k},0\right)$ her best strategy is to head off in a straight line initially at right angles to the line between her and the monster: a less steep angle and the monster has proportionately less far to run than the lady has to swim, but a steeper angle and it is worth the monster changing direction. (If the monster changes direction in this right-angle case, the lady changes too but now starts closer to shore.) As they are both trying to get to the point $\left(\frac{r}{k},r \sqrt{1-\frac{1}{k^2}}\right)$ then they will arrive at the same time if $ \pi + \cos^{-1}(1/k) = k \sqrt{1 -1/k^2}$ which by numerical methods gives $k \approx 4.6033$. So if the monster is less than 4.6033 times as fast as the lady, the lady can escape; if not then she stays in the lake and the monster stays on the edge and they live unhappily ever after.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/31097', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5887/']}
|
jdg_370188
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
57665746
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This question has been asked quite a few times over the years, but it has changed again in Swift 5, particularly in the last two betas. Reading a JSON file seems to be quite simple: func readJSONFileData(_ fileName: String) -> Array<Dictionary<String, Any>> { var resultArr: Array<Dictionary<String, Any>> = [] if let url = Bundle.main.url(forResource: "file", withExtension: "json") { if let data = try? Data(contentsOf: url) { print("Data raw: ", data) if let json = try? (JSONSerialization.jsonObject(with: data, options: []) as! NSArray) { print("JSON: ", json) if let arr = json as? Array<Any> { print("Array: ", arr) resultArr = arr.map { $0 as! Dictionary<String, Any> } } } } } return resultArr} But writing is incredibly difficult, and all of the previous methods found on this site have failed in Swift 5 on Xcode 11 betas 5 and 6. How can I write data to a JSON file in Swift 5? I tried these approaches: How to save an array as a json file in Swift? Writing JSON file programmatically swift read/write local json file swift 4 There weren't any errors except for deprecation warnings, and when I fixed those, it simply didn't work.
Now provide the response and nothing else.
|
Let’s assume for a second that you had some random collection (either arrays or dictionaries or some nested combination thereof): let dictionary: [String: Any] = ["bar": "qux", "baz": 42] Then you could save it as JSON in the “Application Support” directory like so: do { let fileURL = try FileManager.default .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("example.json") try JSONSerialization.data(withJSONObject: dictionary) .write(to: fileURL)} catch { print(error)} For rationale why we now use “Application Support” directory rather than the “Documents” folder, see the iOS Storage Best Practices video or refer to the File System Programming Guide . But, regardless, we use those folders, not the Application’s “bundle” folder, which is read only. And to read that JSON file: do { let fileURL = try FileManager.default .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent("example.json") let data = try Data(contentsOf: fileURL) let dictionary = try JSONSerialization.jsonObject(with: data) print(dictionary)} catch { print(error)} That having been said, we generally prefer to use strongly typed custom types rather than random dictionaries where the burden falls upon the programmer to make sure there aren’t typos in the key names. Anyway, we make these custom struct or class types conform to Codable : struct Foo: Codable { let bar: String let baz: Int} Then we’d use JSONEncoder rather than the older JSONSerialization : let foo = Foo(bar: "qux", baz: 42)do { let fileURL = try FileManager.default .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("example.json") try JSONEncoder().encode(foo) .write(to: fileURL)} catch { print(error)} And to read that JSON file: do { let fileURL = try FileManager.default .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent("example.json") let data = try Data(contentsOf: fileURL) let foo = try JSONDecoder().decode(Foo.self, from: data) print(foo)} catch { print(error)} For more information about preparing JSON from custom types, see the Encoding and Decoding Custom Types article or the Using JSON with Custom Types sample code.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57665746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10221765/']}
|
jdg_370189
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44405748
|
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 validate my textField that check only Alphabet & whitespace allowed, If number was given then it will return warning error. //First I declare my value to variablevar nameValue: String = mainView.nameTextField.text!//Then I declare this let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ") //And this is the validationif(nameValue.rangeOfCharacter(from: set.inverted) != nil ){ self.showAlert(message: "Must not contain Number in Name") } else { //other code }ex: nameValue : "abcd" it works, but if nameValue : "ab cd" whitespace included, it returns the showAlert message. This code works but only for alphabets, What I need now is alphabets and a whitespace. and what I declare was a hardcode I guess. Maybe you guys have better code and options for this case. Thank you .
Now provide the response and nothing else.
|
The easiest way will be to add new line to the character set like let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ ") i.e, adding white space character at the end of the included character set" " Rather than hardcoding you can use regular expression like do { let regex = try NSRegularExpression(pattern: ".*[^A-Za-z ].*", options: []) if regex.firstMatch(in: nameValue, options: [], range: NSMakeRange(0, nameValue.characters.count)) != nil { self.showAlert(message: "Must not contain Number in Name") } else { }}catch {}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44405748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5553036/']}
|
jdg_370190
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25556955
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some image files that are encrypted with RNCryptor and I want to decrypt them and use them as a background of a Framelayout.I walk through sample files, but my application force closes after a while and didn't show any images.I use JNCryptor library I put encrypted image in raw folder as below: and this is my code in my activity: @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FrameLayout img = (FrameLayout) findViewById(R.id.scrollView); final String password = "myPasswordString"; JNCryptor cryptor = new AES256JNCryptor(); Resources res = getResources(); InputStream in_s = res.openRawResource(R.raw.troodon_ph); byte[] b = null; byte[] data = null; try { b = new byte[in_s.available()]; in_s.read(b); } catch (IOException e) { Log.i("decrypt error", e.toString()); } try { data = cryptor.decryptData(b, password.toCharArray()); } catch (InvalidHMACException e) { Log.i("decrypt error", e.toString()); } catch (CryptorException e) { Log.i("decrypt error", e.toString()); } Bitmap mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length); BitmapDrawable bDrawable = new BitmapDrawable(res, mBitmap); img.setBackgroundDrawable(bDrawable);} This file works great on iOS with this code: NSString *imagePath = [[NSBundle mainBundle] pathForResource:getName ofType:@"wod"];NSData *encryptedData = [NSData dataWithContentsOfFile:imagePath];NSData *decryptedData = [RNDecryptor decryptData:encryptedData withPassword:PASSWORD error:&error];UIImage* bgImage = [UIImage imageWithData:decryptedData];UIImageView * movingImageView = [[UIImageView alloc]initWithImage:bgImage]; And here is logcat output: 08-28 19:52:11.720: E/AndroidRuntime(1063): FATAL EXCEPTION: main 08-28 19:52:11.720: E/AndroidRuntime(1063): java.lang.RuntimeException: Unable to start activity ComponentInfo{net.appersian.android.wod/net.appersian.android.wod.MainActivity}: java.lang.NullPointerException 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.app.ActivityThread.access$600(ActivityThread.java:130) 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.os.Handler.dispatchMessage(Handler.java:99) 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.os.Looper.loop(Looper.java:137) 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.app.ActivityThread.main(ActivityThread.java:4745) 08-28 19:52:11.720: E/AndroidRuntime(1063): at java.lang.reflect.Method.invokeNative(Native Method) 08-28 19:52:11.720: E/AndroidRuntime(1063): at java.lang.reflect.Method.invoke(Method.java:511) 08-28 19:52:11.720: E/AndroidRuntime(1063): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 08-28 19:52:11.720: E/AndroidRuntime(1063): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 08-28 19:52:11.720: E/AndroidRuntime(1063): at dalvik.system.NativeStart.main(Native Method) 08-28 19:52:11.720: E/AndroidRuntime(1063): Caused by: java.lang.NullPointerException 08-28 19:52:11.720: E/AndroidRuntime(1063): at net.appersian.android.wod.MainActivity.onCreate(MainActivity.java:54) 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.app.Activity.performCreate(Activity.java:5008) 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 08-28 19:52:11.720: E/AndroidRuntime(1063): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 08-28 19:52:11.720: E/AndroidRuntime(1063): ... 11 more What am I doing wrong about decrypting the file? update:i added e.printStackTrace() to try/catch, and here is my new logcat: 08-28 20:54:10.496: W/System.err(1487): org.cryptonode.jncryptor.InvalidHMACException: Incorrect HMAC value. 08-28 20:54:10.496: W/System.err(1487): at org.cryptonode.jncryptor.AES256JNCryptor.decryptV3Data(AES256JNCryptor.java:244) 08-28 20:54:10.496: W/System.err(1487): at org.cryptonode.jncryptor.AES256JNCryptor.decryptV3Data(AES256JNCryptor.java:319) 08-28 20:54:10.496: W/System.err(1487): at org.cryptonode.jncryptor.AES256JNCryptor.decryptData(AES256JNCryptor.java:276) 08-28 20:54:10.496: W/System.err(1487): at net.appersian.android.wod.MainActivity.onCreate(MainActivity.java:50) 08-28 20:54:10.496: W/System.err(1487): at android.app.Activity.performCreate(Activity.java:5008) 08-28 20:54:10.496: W/System.err(1487): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 08-28 20:54:10.496: W/System.err(1487): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 08-28 20:54:10.496: W/System.err(1487): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 08-28 20:54:10.496: W/System.err(1487): at android.app.ActivityThread.access$600(ActivityThread.java:130) 08-28 20:54:10.496: W/System.err(1487): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 08-28 20:54:10.496: W/System.err(1487): at android.os.Handler.dispatchMessage(Handler.java:99) 08-28 20:54:10.496: W/System.err(1487): at android.os.Looper.loop(Looper.java:137) 08-28 20:54:10.496: W/System.err(1487): at android.app.ActivityThread.main(ActivityThread.java:4745) 08-28 20:54:10.496: W/System.err(1487): at java.lang.reflect.Method.invokeNative(Native Method) 08-28 20:54:10.496: W/System.err(1487): at java.lang.reflect.Method.invoke(Method.java:511) 08-28 20:54:10.496: W/System.err(1487): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 08-28 20:54:10.496: W/System.err(1487): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 08-28 20:54:10.496: W/System.err(1487): at dalvik.system.NativeStart.main(Native Method)
Now provide the response and nothing else.
|
To send an e-mail, a program needs to connect via TCP to an SMTP server and talk to it according to the SMTP protocol . It is not possible to send an e-mail directly using JavaScript / HTML5 APIs. A browser does not expose the capability to directly communicate with a TCP socket. While you can initiate a connection to any port in principle, the browser will "do the talking" and it does not "speak" SMTP. It can do HTTP, it can do WebSockets, but not the protocol you want. It's not possible to send an e-mail directly from a Chrome extension . While the Chrome extension APIs augment functionality offered by web APIs, they still don't offer you the chance to "do the talking" to a server. It is possible, but not easy, to send an e-mail directly from a Chrome app . Chrome Apps APIs are different from extensions, but more importantly they include raw access to TCP sockets, via chrome.sockets.tcp API . Note the words "raw access". You will have to implement your own mail client from scratch in JavaScript. This might be a starting point. Depending on what you want to achieve, a Chrome app can be an acceptable solution. Alternatively, if you need both extension and app APIs, you can create both and pass messages between them. Anything is possible with a Native Messaging host . Being basically a native application, you can do anything from a native host app. Chrome extension/app will then be able to call it with necessary data. However, this will limit your deployment options if you decide to publish the extension; you will have to worry about portability, and the native host cannot be uploaded to the Web Store; you would need a separate installer. And your messaging host will still need to implement your own SMTP client, though you have a much more broad choice of ready libraries for that. Anything is possible with an external API, but securing communication would be a challenge. If there's a website that your extension can talk to that can send an email on your behalf, you can make your extension trigger such an API. However, it's not realistically possible to bury an extension-specific secret into an extension to limit the use of the API. You could make the user log in to such a service with some credentials, and then store those user-specific credentials in an installed instance, e.g. an OAuth token. That basically offloads the problem to a web service you must control (or have an agreement with). For extra reading, here's Apps vs Extensions guide.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25556955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2399483/']}
|
jdg_370191
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12240299
|
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 unsigned char array[248]; filled with bytes. Like 2F AF FF 00 EB AB CD EF .....This Array is my Byte Stream which I store my Data from the UART (RS232) as a Buffer. Now I want to convert the bytes back to my uint16's and int32's. In C# I used the BitConverter Class to do this. e.g: byte[] Array = { 0A, AB, CD, 25 };int myint1 = BitConverter.ToInt32(bytes, 0);int myint2 = BitConverter.ToInt32(bytes, 4);int myint3 = BitConverter.ToInt32(bytes, 8);int myint4 = BitConverter.ToInt32(bytes, 12);//...enter code hereConsole.WriteLine("int: {0}", myint1); //output Data... Is there a similiar Function in C ? (no .net , I use the KEIL compiler because code is running on a microcontroller) With RegardsSam
Now provide the response and nothing else.
|
There's no standard function to do it for you in C. You'll have to assemble the bytes back into your 16- and 32-bit integers yourself. Be careful about endianness! Here's a simple little-endian example: extern uint8_t *bytes;uint32_t myInt1 = bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24); For a big-endian system, it's just the opposite order: uint32_t myInt1 = (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3]; You might be able to get away with: uint32_t myInt1 = *(uint32_t *)bytes; If you're careful about alignment issues.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12240299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1639980/']}
|
jdg_370192
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10953384
|
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 fundamental difference for having a '?' in every? and not in some functions of clojure? user> (every? true? [true true false])falseuser> (some true? [true false false])true Thanks.
Now provide the response and nothing else.
|
every? returns true or false, so it gets a question mark. some doesn't return a boolean, it returns "the first logically true value returned by pred", and returns nil otherwise. Here's the lame example I came up with: user=> (some #(if (= 0 %) 1 0) [1 3 5 0 9])0 The first element in the collection gets passed into the predicate, the predicate evaluates to 0, which is logically true so some returns 0. you can see some is not returning true or false. So every? gets a question mark because it returns true or false. some returns the value returned by pred or nil, so it doesn't get a question mark.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10953384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/745749/']}
|
jdg_370193
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19649984
|
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 cannot, for the life of me, successfully run "gem install thrift", the thing fails when building the gem's native extensions; this is the output: (acib708) ~ -> gem install thriftBuilding native extensions. This could take a while...ERROR: Error installing thrift: ERROR: Failed to build gem native extension. /Users/acib708/.rvm/rubies/ruby-2.0.0-p247/bin/ruby extconf.rbextconf.rb:25:in `<main>': Use RbConfig instead of obsolete and deprecated Config.extconf.rb:25:in `<main>': Use RbConfig instead of obsolete and deprecated Config.checking for strlcpy() in string.h... yescreating Makefilemake "DESTDIR="compiling binary_protocol_accelerated.ccompiling bytes.ccompiling compact_protocol.ccompiling memory_buffer.ccompiling protocol.ccompiling strlcpy.c ^ (...) In file included from strlcpy.c:20:./strlcpy.h:28:15: error: conflicting types for '__builtin___strlcpy_chk'/usr/include/secure/_string.h:105:3: note: expanded from macro 'strlcpy' __builtin___strlcpy_chk (dest, src, len, __darwin_obsz (dest)) ^./strlcpy.h:28:15: note: '__builtin___strlcpy_chk' is a builtin with type 'unsigned long (char *, const char *, unsigned long, unsigned long)'/usr/include/secure/_string.h:105:3: note: expanded from macro 'strlcpy' __builtin___strlcpy_chk (dest, src, len, __darwin_obsz (dest)) ^4 errors generated.make: *** [strlcpy.o] Error 1Gem files will remain installed in /Users/acib708/.rvm/gems/ruby-2.0.0-p247/gems/thrift-0.9.1 for inspection.Results logged to /Users/acib708/.rvm/gems/ruby-2.0.0-p247/gems/thrift-0.9.1/ext/gem_make.out I've seen lots of similar errors around the web, but I haven't found the solution. I'm running OS X 10.9, with a fresh rvm/ruby-2.0.0-p247 install. Any ideas? Thanks.
Now provide the response and nothing else.
|
the issue for the moment can be found at https://issues.apache.org/jira/browse/THRIFT-2219 As a temporary fix for folks using gems, you can try setting the #define'ing the _FORTIFY_SOURCE macro to 0 to make strlcpy a function rather than a macro: gem install thrift -- --with-cppflags='-D_FORTIFY_SOURCE=0' or if you're using bundler, you can set the cflags for thrift locally via: bundle config build.thrift --with-cppflags='-D_FORTIFY_SOURCE=0'
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19649984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1668834/']}
|
jdg_370194
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40494672
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Background : I came from Microsoft world, in which I used to have websites stored on IIS. Experience taught me to recycle my application pool once a day in order to eliminate weird problems due to fragmentation. Recycling the app pool basically means to restart your application without restarting the entire IIS. I also watched a lecture that explained how Microsoft had reduced the fragmentation a lot in .Net 4.5. Now, I'm deploying a Node.js application to production environment and I have to make sure that it works flawlessly all the time. I originally thought to make my app restarted once a day. Then I did some research in order to find some clues about fragmentation problems in Node.js. The only thing I've found is a scrap of paragraph from an article describing GC in V8 : To ensure fast object allocation, short garbage collection pauses, and the “no memory fragmentation V8” employs a stop-the-world, generational, accurate, garbage collector. This statement is really not enough for me to give up building a restart mechanism for my app, but on the other hand I don't want to do some work if there is no problem. So my quesion is: Should or shouldn't I restart my app every now and then in order to prevent fragmentation?
Now provide the response and nothing else.
|
Implementing a server restart before you know that memory consumption is indeed a problem is a premature optimization. As such, I don't think you should do it until you actually find that it is a problem. You will likely find more important issues to optimize for as opposed to memory consumption. To figure out if you need a server restart, I recommend doing the following: Set up some monitoring tools like https://newrelic.com/ that let's your monitor your performance. Monitor your memory continuously. Try to see if there is steady increase in the amount of memory consumed, or if it levels off. Decide upon an acceptable threshold before you need to act. For example once your app consumes 60% of system memory you need to start thinking about a server restart and decide upon the restart interval. Decide if you are ok with having "downtime" while restarting the sever or not. If you don't want downtime, you may need to build a proxy layer to direct traffic. In general, I'd recommend server restarts for all dynamic, garbage collected languages. This is fairly common in those types of large applications. It is almost inevitable that a small mistake somewhere in your code base, or one of the libraries you depend on will leak memory. Even if you fix one leak, you'll get another one eventually. This may frustrate your team, which will basically lead to a server restart policy, and a definition of what is acceptable in regards to memory consumption for your application.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40494672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1026271/']}
|
jdg_370195
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
751444
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
suppose $X$ and $Y$ are independent and identically distributed random variables that are uniformly distributed on $[0,1]$ What is the PDF of $ W=Y-X $ i tried to draw a picture to illustrated it but it seems very difficult, can anyone guide me a bit?
Now provide the response and nothing else.
|
Expand the expression $$x(1+y)+y(1+z)+z(1+x) = x+yz+y+xz+z+yx $$From $\rm{AM} \geq \rm{GM}$ we get $ x+yz \geq 2 \sqrt{xyz}$, do the same for the other terms and add to conclude.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/751444', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/113368/']}
|
jdg_370196
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2531684
|
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 two functions $g(x)$ and $h(z)$ where $h:\mathbb R^n\to \mathbb R$ and $g: \mathbb R\to \mathbb R$. Both are convex, neither are smooth. How can I apply the chain rule to find $\partial (g\circ h)$? (in terms of $\partial g$ and $\partial h$). What I have so far: the definition for subdifferential (that's all)$$\partial(g\circ h)(x) = \{ z : g(h(y)) \geq g(h(x)) + z^T(y-x), \forall y\}$$ If in fact $h$ was smooth, we do have this result:$$\partial(g\circ h)(x) = \nabla h(x)^T \partial g(h(x))$$ My guess is that the answer will be something like $\partial(g\circ h)(x)=S$ where$$S = \{b \cdot a: a\in \partial h(x), b\in \partial g(h(x))\}$$though I'm not sure... Also does the problem become easier if I restrict the domain of $g$ to nonnegative scalars and claim that $g$ is monotonic? Edit: Ok one of the special cases I am thinking of is that $h$ is a norm, and is nonsmooth only at 0, with $h(0)=0$. So, we only need to consider $\partial(g\circ h)(0)$; the rest follows the chain rule for smooth $h$. If, in addition, $g$ is monotonic, then $$a\in \partial h(0) \iff a^Ty \leq h(y) \forall y.$$$$b\in \partial g(0) \Rightarrow b(a^Ty) \leq g(a^Ty) \leq g(h(y))$$which gives $S \subseteq \partial (g\circ h)$. The general case is still open!
Now provide the response and nothing else.
|
Check out Corollary 16.72 in the book by Bauschke and Combettes (second edition), which states: Let $f\colon H\to\mathbb{R}$ be continuous and convex, and let $\phi$ be lowersemicontinuous, convex, and increasing on the range of $f$ . Suppose that (the relative interior of the range of $f$ + the positive reals) intersected with the relative interior of the domain of $\phi$ is nonempty.Let $\bar{x}$ be in $H$ such that $f(\bar{x})$ is in the domain of $\phi$ . Then $$ \partial (\phi\circ f)(\bar{x}) = \left\{ \alpha u \mid (\alpha,u)\in\partial\phi(f(\bar{x}))\times\partial f(\bar{x})\right\}.$$ So your conjecture is true, with some assumptions. The proof is nontrivial and makes use of coderivatives.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2531684', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/188022/']}
|
jdg_370197
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7973894
|
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 MVC app and I wrote a custom roleprovider for it as shown: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Security;using VectorCheck.Models;namespace VectorCheck.Security{ public class MyRoleProvider : RoleProvider { private VectorCheckRepository<User> _repository { get; set; } public MyRoleProvider() { _repository = new VectorCheckRepository<User>(); } public MyRoleProvider(VectorCheckRepository<User> repository) { _repository = repository; } public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override string ApplicationName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void CreateRole(string roleName) { throw new NotImplementedException(); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new NotImplementedException(); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new NotImplementedException(); } public override string[] GetAllRoles() { throw new NotImplementedException(); } public override string[] GetRolesForUser(string username) { var user = _repository.GetUser(username); return new string[] { user.Role.Name }; } public override string[] GetUsersInRole(string roleName) { throw new NotImplementedException(); } public override bool IsUserInRole(string username, string roleName) { var user = _repository.GetUser(username); return string.Compare(user.Role.Name, roleName, true) == 0; } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new NotImplementedException(); } public override bool RoleExists(string roleName) { throw new NotImplementedException(); } }} This works really well with restricting access to controllers and actions using: [Authorize(Roles = "Administrator")] above the controller or action. I also want restricted access to some things in the view though using: HttpContext.Current.User.IsInRole("Administrator") This method isn't part of my roleprovider though so isn't getting overridden. Does anyone know how to do it for this method as well?
Now provide the response and nothing else.
|
If you've hooked your RoleProvider as the role provider for the application in web.config, then this should work automatically; the framework will create a RolePrincipal for an authenticated user at the start of the request that will call the GetRolesForUser method on your role provider, passing the name from the IIdentity as the user name. The framework implementation of RolePrincipal 's IsInRole(string role) method is something like this (I've added comments) public bool IsInRole(string role) { if (_Identity == null) throw new ProviderException(SR.GetString(SR.Role_Principal_not_fully_constructed)); if (!_Identity.IsAuthenticated || role == null) return false; role = role.Trim(); if (!IsRoleListCached) { _Roles.Clear(); // here the RoleProvider is used to get the roles for the user // and are cached in a collection on the RolePrincipal so that // they are only fetched once per request string[] roles = Roles.Providers[_ProviderName].GetRolesForUser(Identity.Name); foreach(string roleTemp in roles) if (_Roles[roleTemp] == null) _Roles.Add(roleTemp, String.Empty); _IsRoleListCached = true; _CachedListChanged = true; } return _Roles[role] != null; } Set a breakpoint inside of your RoleProvider GetRolesForUser method to ensure that it is being called correctly and also inspect the IPrincipal ( HttpContext.Current.User ) to ensure that it is of type RolePrincipal for an authenticated user.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7973894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/822229/']}
|
jdg_370198
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14675007
|
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 try to draw simple text in my android game on libgdx , but it's look sharp. How to make text look smooth in different resolutions? My Code: private BitmapFont font;font = new BitmapFont();font.scale((ppuX*0.02f));font.draw(spb, "Score:", width/2-ppuX*2f, height-0.5f*ppuY);
Now provide the response and nothing else.
|
One solution is to use the FreeType extension to libgdx, as described here . This allows you to generate a bitmap font on the fly from a .ttf font. Typically you would do this at startup time once you know the target resolution. Here's an example: int viewportHeight;BitmapFont titleFont;BitmapFont textFont;private void createFonts() { FileHandle fontFile = Gdx.files.internal("data/Roboto-Bold.ttf"); FreeTypeFontGenerator generator = new FreeTypeFontGenerator(fontFile); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = 12; textFont = generator.generateFont(parameter); parameter.size = 24; titleFont = generator.generateFont(parameter); generator.dispose();}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14675007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1888143/']}
|
jdg_370199
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
204930
|
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 completely blind and come from a programming background. What I'm trying to do is to learn machine learning, and to do this, I first need to learn about linear regression. All the explanations on the Internet I am finding about this subject plot the data first. I'm looking for a practical explanation of linear regression that is not dependent on graphs and plots. Here is my understanding of the aim of simple linear regression: Simple linear regression is trying to find the formula that once you give X to it, would provide you with the closest estimation of Y . So, as I understand it, what needs to be done is to compare the predictor (for example the area of a house in square feet) with the independent variable (the price). In my example, you probably can create a non-visual way of getting the best formula to calculate the price of a house from its area. For example, maybe you would get the area and price of 1000 houses in a neighborhood, and divide the price to the area? The result (at least in Iran which is where I live) would have a very negligible variance. So you'd probably get something like this: Price = 2333 Rials * Area of the house Of course, you would then need to go through all the 1000 houses in your data set, put the area in the formula above, compare the estimate with the real price, square the results (I guess to prevent variances from canceling each other out) and then get a number, then keep playing around with the 2333 to decrease the errors. Of course, this is the brute force option where it will probably take ages to compute the errors and arrive at the best option, but you see what I'm saying? I didn't say anything about a graph, or a line, or points on a plot, or the best way of fitting a line to your existing data. So, why would you need a scatter plot and linear algebra for this? Isn't there a non-visual way? First, am I right in my assumptions? If not, I'd love to be corrected. Whether or not I am, though, is there a way to come up with the formula without playing around with linear algebra? I would really appreciate it if I could get an example with the explanation, so that I can do it along with the text to test my understanding.
Now provide the response and nothing else.
|
Yes your onto it. You have to keep playing around with the 2333 until you find the right one which minimizes the error. But there's a mathematical way to find the "right" one. Let's call that number $\beta$. $E$, the sum of the squared errors (SSE) is a function of $\beta$ since for each choice of $\beta$ can calculate the amount each estimate is off, square it, and sum them together. What $\beta$ minimizes the total sum of the squared errors? This is just a calculus problem. Take the derivative of $E$ by $\beta$ and set it equal to zero. This gives an equation for $\beta$. Check the second derivative is positive to know that it's a minimium. Thus you get an equation for $\beta$ which minimizes the error. If you derive it this way, you will get $\beta$ as a summation. If you write out the linear algebra form of the estimate you will see that this is the same thing. Edit: Here's a link to some notes with this type of derivation. The math gets a little messy, but at it's core it's just a calculus problem.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/204930', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/110645/']}
|
jdg_370200
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2047349
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So, my friend show me prove that $1=-1$ by using this way: $$1=\sqrt{1}=\sqrt{(-1)\times(-1)}=\sqrt{-1}\times\sqrt{-1}=i\times i=i^2=-1$$ At first sight, I stated "No, $\sqrt{ab}=\sqrt{a}\times\sqrt{b}$ is valid only for $a,b\in\mathbb{R}$ and $a,b\geq0$" But, I remember that $\sqrt{-4}=\sqrt{4}\times\sqrt{-1}=2i$ which is true (I guess). Was my statement true? But, $\sqrt{ab}=\sqrt{a}\times\sqrt{b}$ is also valid if one of a or b is negative real number. Why is it not valid for a dan b both negative? If my statement was wrong, what is wrong with that prove?
Now provide the response and nothing else.
|
As you know, the rule $\sqrt{ab}=\sqrt a \sqrt b$ holds for some but not all combinations of $a$ and $b$. Explaining and remembering exactly which those combinations are is usually more trouble than it's worth, so usually the rule we remember is just It is a sufficient condition for $\sqrt{ab}$ to equal $\sqrt a\sqrt b$ that $a$ and $b$ are both non-negative reals. As you have noticed, this condition is not necessary , but that does not keep the rule from being useful. For the purpose of rejecting your friend's fake proof, even the above version is more than you need; all you need to say is The rule $\sqrt{ab}=\sqrt a\sqrt b$ does not always hold when we extend the $\sqrt{\phantom a}$ function to complex numbers. It is not your task to prove that the rule fails in the particular case $a=b=-1$ (thought doing so is a simple matter of computation); it is the guy who wants to prove something who has the responsibility for only using rules he knows apply in the context he's using them in. After you've pointed out that the rule has been stretched beyond the domain we know it to work for, it's up to him to figure out whether he can come up with an argument that it should be valid here.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2047349', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/379677/']}
|
jdg_370201
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34659695
|
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 importing some data with the foursquare api. My database contains multiple foursquare_id duplicates. Am I doing something wrong with the code here? I thought the way this is set up it will check the database for the column value of foursquare_id? Bar::firstOrCreate([ // do not check for these 2 below because they are mandatory 'foursquare_id' => $item['venue']['id'], 'name' => $item['venue']['name'], 'postalCode' => isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '', 'city' => isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '',]);
Now provide the response and nothing else.
|
That's right. You only receive the 'first' if all elements of your passed array exist in the row object. The alternative is using firstOrNew: $foo = Bar::firstOrNew(['foursquare_id' => $item['venue']['id']]); // find the object with this foursquare_id. Nothing found? Create a new one with the given foursquare_id$foo->name = $item['venue']['name'];$foo->postalCode = isset($item['venue']['location']['postalCode']) ? $item['venue']['location']['postalCode'] : '';$foo->city = isset($item['venue']['location']['city']) ? $item['venue']['location']['city'] : '';$foo->save();
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34659695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2294225/']}
|
jdg_370202
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54639
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently using nginx with the following ciphers: ssl_ciphers HIGH:!aNULL:!eNULL:!LOW:!ADH:!RC4:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS; I would like to maintain compatibility to older browsers, especially also older mobile browsers and therefore not completely disallow SHA1. How can I achieve that SHA256 is preferred over SHA1 for MAC (Message Authentication Code) and always used when possible. I can i.e. force SHA256 to be applied by adding SHA256:!SHA: to my ssl_ciphers string but this would also disallow SHA1 completely. With the ssl_cipher at the beginning it tends however to just use SHA1. Any recommendations? Update 29.12.2014 Thanks everybody for the constructive inputs and discussion. Even though I still think that the Mozilla page on Server side TLS overall covers the topic quite good - I would only recommend the Modern compatibility with the limitation that the DSS ciphers should be removed from it and explicitly disallowed (!DSS) as recommended in the comment by Anti-weakpasswords - thanks for spotting it. ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DSS:!DES:!RC4:!3DES:!MD5:!PSK Interestingly ssllabs did not alert or down rate for this... Further I prefer to use custom generated Diffie-Hellman parameters. Even though the standard ones are obviously considered safe. What are the OpenSSL standard Diffie-Hellman parameters (primes)? openssl dhparam -check -out /etc/ssl/private/dhparams.pem 2048 increase that to 4096 for paranoia and fun if you like.
Now provide the response and nothing else.
|
First, let's go over how cipher suite negotiation works, very briefly. For example, we can use the TLS 1.2 document RFC 5246 starting at section 7.4.1.2 to see, in the short short form: ClientHello: The client tells the server which cipher suites the client supports Now the server picks one I'll discuss how to control which one it picks next! ServerHello: The server tells the client which cipher suite it has chosen, or gives the client a failure message. Now, as to the actual selection. I've used the nginx ssl module documentation , the Qualys 2013 article on Configuring Apache, Nginx, and OpenSSL for Forward Secrecy , and the Hynek Hardening Your Web Server’s SSL Ciphers article for reference. The latter two cover both Apache and Nginx (as both use OpenSSL as a base). Essentially, you need to tell Nginx to use the order you select, and you need to select an order. To see what the results of that order would be, you can use the OpenSSL command line, e.g. openssl ciphers -v 'EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA256:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EDH+aRSA+AESGCM:EDH+aRSA+SHA256:EDH+aRSA:EECDH:!aNULL:!eNULL:!MEDIUM:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4:!SEED' NOTE: You may want to remove :!3DES from that string; 3-key triple-DES isn't efficient, but it is still secure in and of itself to more or less 112 bits of security, and is very, very common. Use the above command to determine which cipher suites will be most preferred and least preferred in your configuration, and change it until you like the results. The references I've given have their own strings; I amended it slightly to get the above example (removing RC4 and SEED, and putting every TLS 1.2 cipher suite above any 'SSLv3' cipher suite, for example). Then, for Nginx in particular, you would alter your configuration file to include something like: ssl_protocols TLSv1 TLSv1.1 TLSv1.2;ssl_prefer_server_ciphers on;ssl_ciphers "EECDH+ECDSA+AESGCM:EECDH+aRSA+AESGCM:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA256:EECDH+ECDSA+SHA384:EECDH+ECDSA+SHA256:EECDH+aRSA+SHA384:EDH+aRSA+AESGCM:EDH+aRSA+SHA256:EDH+aRSA:EECDH:!aNULL:!eNULL:!MEDIUM:!LOW:!3DES:!MD5:!EXP:!PSK:!SRP:!DSS:!RC4:!SEED"; Add in SSLv3 to ssl_protocols if you really insist on it. The ssl_prefer_server_ciphers will inform nginx to use the order we specify, and ignore the order the client presents their cipher list in. Now, if the only shared cipher suite between the ClientHello and the list OpenSSL ciphers -v ... gives is our least preferred cipher, that's of course what nginx will use. If nothing matches, then we send the client a failure notice. The ssl_ciphers command is the meat of the choice, here, as nginx will inform OpenSSL of our preferred cipher suite list. Please, please use the openssl ciphers -v command to see the results you get on your platform. Ideally, check it again after changing OpenSSL versions. Also, please read Scott Helme's article on Setting up HSTS (HTTP Strict Transport Security) in nginx , which will allows a host to enforce the use of HTTPS on the client side. Be sure to include the HSTS header inside the http block with the ssl listen statement. Edited to add: At least after this (if not before also), go to Qualys SSL Labs to see HTTPS security information and to Test Your Server that's been kept pretty well up to date for the last few years. Recommendations change regularly, and sometimes even frequently reverse themselves (RC4, for example, what nearly whiplash inducing). You can also even Test Your Browser !
|
{}
|
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/54639', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/43005/']}
|
jdg_370203
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
955207
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an assignment question Prove by either the Well Ordering Principle or induction that for all nonnegative integers $n$: $$\sum_{k=0}^n k^3 = \left(\frac{n(n+1)}{2}\right)^2.$$ I am able to solve this question using basic Induction, but not able to figure out how to do it by using Well Ordering Principle. Any Solutions or hints would be very helpful.Thanks in Advance
Now provide the response and nothing else.
|
Suppose that the statement is not true. Then the set $A=\left\{ n\in\mathbb{N}\mid\sum_{i=0}^{n}i^{3}\neq\left(\frac{n\left(n+1\right)}{2}\right)^{2}\right\} $is not empty. Since $\mathbb{N}$ is well-ordered set $A$ has a minimalelement $m$. That means that $\sum_{i=0}^{n}i^{3}=\left(\frac{n\left(n+1\right)}{2}\right)^{2}$is true for $n<m$ and is not true for $n=m$. From this you can deducea contradiction. (Start with $\sum_{i=0}^{m-1}i^{3}=\left(\frac{\left(m-1\right)m}{2}\right)^{2}$and prove on base of that $\sum_{i=0}^{m}i^{3}=\sum_{i=0}^{m-1}i^{3}+m^{3}=\left(\frac{m\left(m+1\right)}{2}\right)^{2}$) The conclusion is then that $A=\emptyset$ wich isexactly the statement to be proven.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/955207', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/180409/']}
|
jdg_370204
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54213601
|
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 is to show a progressbar while Axios is getting my requests. axios package has both onDownloadProgress and onUploadProgress to show a progressbar during download or upload, but no progress bar during get request. I've searched a lot of questions and articles but they are always about download/upload progress or for Vue.js and I fail to understand how to do it in React. I have the following code down below (which will not work because I'm not downloading). Ideally, I'd write it myself; but I'm willing to consider using axios-progress package if someone could explain me how I'd integrate the loadProgressBar() with my Axios request. request = () => { this.setState({error: null, results: []}) axios({ method: 'get', url: process.env.REACT_APP_API_LOCALS, responseType: 'json', onDownloadProgress: (progressEvent) => { var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); this.setState({ loading: percentCompleted }) }, }) .then( (response) => { console.log(response) this.setState({ results: response.data.results, error: null, totalPages: Math.ceil(response.data.count / response.data.results.length) }) } ) .catch( (error) => { this.setState({ loading: null, error: true }) } );}
Now provide the response and nothing else.
|
Here's what worked for me in React: const client = axios.create({ baseURL: 'http://localhost:10000/v1/client', timeout: 20000})let result = await client.get('/fetchMeSomething', { onDownloadProgress: progressEvent => { const total = parseFloat(progressEvent.currentTarget.responseHeaders['Content-Length']) const current = progressEvent.currentTarget.response.length let percentCompleted = Math.floor(current / total * 100) console.log('completed: ', percentCompleted) }}).then(res => { console.log("All DONE: ", res.headers) return res.data})
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54213601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10133180/']}
|
jdg_370205
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2718489
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering what the most effective way of preventing people from stealing my application (downloading a copy of the .apk online rather than buying it). I've spent a lot of time on one in particular (Droidbox) and won't be releasing Sync until I can guarantee that the people who are providing illegal copies of the pro version aren't able to. Anyone implemented this? I've tried checking my package signature verses an the signature of an unsigned copy but it appears to be the same - perhaps I'm doing something incorrectly here. I'm unsure whether people actually distribute the signed .apk in which case I don't think signature validation would work to begin with... Please note, this question is specific to Android Marketplace Applications - the difference being, application delivery is out of my hands and I have no way of linking between a legitimate purchase and an illegal download.
Now provide the response and nothing else.
|
Now there is the new Google App Licensing available. For deeper information read about it in the android developer blog . A short summary: Google provides a library that makes a inter process call to the market client on the phone. The market client will then ask the google servers if the signed in user has purchased the app and forward this answer to you. There should be a public key in you developer profile that you need to encrypt the connection to the google server to prevent spoofing of answers. You also provide a application and device unique id with the query to make it impossible to forward approved queries to another device and build something like an licensing proxy with one bought copy forwarding the IS LICENSED answers to other devices. At the moment this service looks secure enough to protect even the more valuable apps in the market. I will give it a try and maybe come back and leave some more informations after I used it a little bit. If your app is really popular like an EA game or something this wan't stop users from hacking it. To hack the app somebody has to buy it, then unzip the apk, and edit the bytecode of your app to think that the market send a correct answer. The new byte code can be packed into another apk and can be installed on every phone that allows side loading. To make this harder you can always try to obfuscate your apk and make your bytecode hard to understand.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2718489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/110762/']}
|
jdg_370206
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45671107
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've written a React app, using CSS transitions. But those transitions does not work correctly in some of the components. In my app , only the components who are moving upwards works well, those who are moving downwards moves instantly without animation. (I want them both moves with animation.) Here is the CSS I used there: div.canvas { position: absolute; top: 90px; left: 60px; width: 640px; height: 480px; border: 1px solid #999; background: white;}div.canvas-rect { position: relative; margin-left: 20px; margin-top: 10px; height: 20px; background: green; transition: all 1s linear; -moz-transition: all 1s linear; /* Firefox 4 */ -webkit-transition: all 1s linear; /* Safari 和 Chrome */ -o-transition: all 1s linear; /* Opera */} UPDATED: I also built a codepen.io project to show the problem. It has the complete code of this demo project. I've tried to add a log entry to componentDidUpdate , componentDidMount and componentWillUnmount methods to show whether these component are re-created or updated, it shows that they are all updated (not re-created, or removed) every second.
Now provide the response and nothing else.
|
Well, after I started a bounty because I also have this problem I finally found what seems to be the problem. When you are using absolute position (or relative, as in your case), if you re-render the whole list every time, React will re-order the elements in the DOM (as you said, the elements are not being recreated, just updated). But this creates the problem with the transitions... apparently, if you move an element while the transition is running then you end up cutting the animation. So, for cases in which you want to use position absolute, the key concept is to render the containers of your elements once (in this case, just divs) and only change the inner contents based on the new order. If you need to add more elements, just add them at the end. I modified your codepen so that it reflects what I am saying. My example is very dumb because I just created 4 ad-hoc divs, but it illustrates the idea: create as many containers as you need, but DO NOT use a map that recreates them every time, or your transitions will be cut. https://codepen.io/damianmr/pen/boEmmy?editors=0110 const ArrList = ({ arr}) => { return ( <div style={{position: 'relative'}}> <div className={`element element-${arr[0]} index-${arr[0]}`}>{arr[0]}</div> <div className={`element element-${arr[1]} index-${arr[1]}`}>{arr[1]}</div> <div className={`element element-${arr[2]} index-${arr[2]}`}>{arr[2]}</div> <div className={`element element-${arr[3]} index-${arr[3]}`}>{arr[3]}</div> </div> );} So, the problem is basically how you create a static list of containers and how you iterate through that list so that the first container renders the first element of your data, the second container the second element, etc. Hope that it helps, this problem was driving me crazy too! :)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45671107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1516794/']}
|
jdg_370207
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1849323
|
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 we prove that: $$\int_{0}^{1}\ln{x}\left({1\over \ln{x}}+{1\over 1-x}\right)^2\, dx =\color{blue}{\gamma-1}?\tag1$$ The only idea came to mind was this series $$\sum_{n=1}^{\infty}{1\over 2^k(1+x^{-1/2^k})}={x\over 1-x}-{1\over \ln{x}}\tag2$$ Or expanded $(1)$ $$\int_0^1 \left({1\over \ln x} + {2 \over 1-x}+{\ln x \over (1-x)^2} \right)\,dx=\gamma-1\tag3$$ $$\int_0^1 {\ln x \over (1-x)^2}\,dx=\sum_{n=0}^\infty (1+n)\int_0^1 x^n\ln x \,dx = \sum_{n=0}^\infty (1+n)\cdot{-1\over (1+n)^2}\tag4$$ But $(4)$ diverges! $\int {1\over 1-x} \, dx=-\ln(1-x)$ $\int_0^1 {2\over 1-x} \, dx$ also diverges $\int{1\over \ln x} dx = \ln(\ln x )+\ln x +{\ln^2 x\over 2\cdot2!}+{\ln^3 x \over 3\cdot 3!}+\cdots$ $\int_0^1 {1\over \ln x} \, dx$ diverges too. How do we go about integrating $(1)$? Help needed, thanks!
Now provide the response and nothing else.
|
$\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle} \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace} \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack} \newcommand{\dd}{\mathrm{d}} \newcommand{\ds}[1]{\displaystyle{#1}} \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,} \newcommand{\half}{{1 \over 2}} \newcommand{\ic}{\mathrm{i}} \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow} \newcommand{\Li}[1]{\,\mathrm{Li}} \newcommand{\ol}[1]{\overline{#1}} \newcommand{\pars}[1]{\left(\,{#1}\,\right)} \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\ul}[1]{\underline{#1}} \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,} \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}} \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$ The Question :$\ds{\quad\int_{0}^{1}\ln\pars{x}\bracks{{1 \over \ln\pars{x}} + {1\over 1-x}}^{2}\,\dd x =\color{blue}{\gamma - 1}\,?}$. \begin{align}&\color{#f00}{\int_{0}^{1}\ln\pars{x}\bracks{{1 \over \ln\pars{x}} + {1\over 1-x}}^{2}\,\dd x} =\int_{0}^{1}\bracks{{1 \over \ln\pars{x}} + {2 \over 1 - x} + {\ln\pars{x} \over \pars{1 - x}^{2}}}\,\dd x\end{align}When $\ds{x \lesssim 1}$, both $\ds{1 \over \ln\pars{x}}$ and$\ds{\ln\pars{x} \over \pars{1 - x}^{2}}$ are $\ds{\sim\,-\,{1 \over 1 - x}}$ such that the splitting of the original integral in three 'pieces' leads to divergent integrals albeit the sum of them converges. The above mentioned behaviour, when $\ds{x\lesssim 1}$, sugests the following splitting:\begin{align}&\color{#f00}{\int_{0}^{1}\ln\pars{x}\bracks{{1 \over \ln\pars{x}} + {1\over 1-x}}^{2}\,\dd x}\\[3mm] = &\\underbrace{\int_{0}^{1}\bracks{{1 \over \ln\pars{x}} + {1 \over 1 - x}}\,\dd x}_{\ds{J_{1}}}\ +\\underbrace{\int_{0}^{1}\bracks{{1 \over 1 - x} +{\ln\pars{x} \over \pars{1 - x}^{2} }}\,\dd x}_{\ds{J_{2}}}\ =\J_{1} + J_{2}\tag{1}\end{align} $\ds{\large J_{1} =\, ?}$. \begin{align}&\int_{0}^{1}\bracks{{1 \over \ln\pars{x}} + {1 \over 1 - x}}\,\dd x =\int_{0}^{1}\int_{0}^{\infty}\bracks{-x^{y} + \expo{-\pars{1 - x}y}}\,\dd y\,\dd x\\[3mm] = &\\int_{0}^{\infty}\int_{0}^{1}\bracks{-x^{y} + \expo{-\pars{1 - x}y}}\,\dd x\,\dd y =\int_{0}^{\infty}\bracks{-\,{1 \over y + 1} +\expo{-y}\,{\expo{y} - 1 \over y}}\,\dd y\\[3mm] = &\\lim_{\epsilon \to 0^{+}}\int_{\epsilon}^{\infty}\bracks{%-\,{1 \over y + 1} + {1 \over y} - {\expo{-y} \over y}}\,\dd y\\[3mm] = &\\lim_{\epsilon \to 0^{+}}\bracks{-\ln\pars{\epsilon \over 1 + \epsilon} +\ln\pars{\epsilon}\expo{-\epsilon} -\int_{\epsilon}^{\infty}\ln\pars{y}\expo{-y}\,\dd y} =-\,\lim_{\epsilon \to 0}\partiald{}{\epsilon}\int_{0}^{\infty}y^{\epsilon}\expo{-y}\,\dd y\\[3mm] = &\-\Gamma\,'\pars{1} = -\Gamma\pars{1}\Psi\pars{1}\end{align}\begin{equation}\fbox{$\ds{\J_{1} = \int_{0}^{1}\bracks{{1 \over \ln\pars{x}} + {1 \over 1 - x}}\,\dd x =\color{#f00}{\gamma}\ }$}\tag{2}\end{equation} $\ds{\large J_{2} =\, ?}$.Note that\begin{align}\int{\ln\pars{x} \over \pars{1 - x}^{2}}\,\dd x & =\int\ln\pars{x}\,\dd\pars{1 \over 1 - x} ={\ln\pars{x} \over 1 - x} - \int{1 \over 1 - x}\,{1 \over x}\,\dd x\\[3mm] & ={\ln\pars{x} \over 1 - x} - \int\pars{{1 \over 1 - x} + {1 \over x}}\,\dd x\\[3mm] \mbox{such that}\quad &\int\bracks{{1 \over 1 - x} +{\ln\pars{x} \over \pars{1 - x}^{2} }}\,\dd x ={\ln\pars{x} \over 1 - x} - \ln\pars{x}\\[3mm] \mbox{and}\quad &\left\lbrace\begin{array}{rcl}\ds{\lim_{x \to 1}\bracks{{\ln\pars{x} \over 1 - x} - \ln\pars{x}}} & \ds{=} &\ds{\color{#f00}{-1}}\\[2mm]\ds{\lim_{x \to 0^{+}}\bracks{{\ln\pars{x} \over 1 - x} - \ln\pars{x}}} & \ds{=} &\ds{\color{#f00}{0}}\end{array}\right. \\[3mm] \imp\quad & \fbox{$\ds{\ J_{2} = \int_{0}^{1}\bracks{{1 \over 1 - x} +{\ln\pars{x} \over \pars{1 - x}^{2} }}\,\dd x =\color{#f00}{-1} - \color{#f00}{0} = \color{#f00}{-1}\}$}\tag{3}\end{align} With $\pars{1}$, $\pars{2}$ and $\pars{3}$:$$\color{#f00}{\int_{0}^{1}\ln\pars{x}\bracks{{1 \over \ln\pars{x}} + {1\over 1-x}}^{2}\,\dd x} =J_{1} + J_{2} =\color{#f00}{\gamma - 1}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1849323', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/343408/']}
|
jdg_370208
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
59556
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
On my Debian-Testing -System, I want to completely conceal the home folders. That means, I not only want the data to be encrypted, but I also want to preclude determining any (or most) information from the encrypted data. For instance, also file names should be encrypted. But not being an expert for data protection, maybe also other file/folder attributes need to be encrypted to grant privacy. I considered ecryptfs to achieve this (Package ecryptfs-utils ) However, is this the right choice for my needs? I also would appreciate links to step-by-step instructions on the implementation of encrypted home-folders in Debian very much! [edit] I do a fresh install, therefore it's not necessary to migrate a previously unencrypted home folder.
Now provide the response and nothing else.
|
Ecryptfs stores each encrypted file in one file (the lower file, in ecryptfs terminology ). The directory structure of the lower files mirrors that of the payload files, although the file names are encrypted. The metadata (modification times, in particular) of the lower files also reveals that of the payload files. The size of the lower file is slightly larger than the size of the payload (with a fixed overhead for Ecryptfs's metadata)¹. If you're storing your own work, where the attacker would already know roughly what kinds of data you have (“I already know this is a source code tree, and I know these are spreadsheets, what I want to know is !”), none of that is a problem. But if you're storing directory trees that may be identified by their layout (directory structure, approximate sizes, dates), then Ecryptfs is not the right tool for you. Use encryption at the block device level. Linux provides this with dm-crypt . You can encrypt either the whole disk (except for a small area for the bootloader), or encrypt /home or some other partition. If you don't encrypt the whole disk, keep in mind that confidential information might end up in other places, especially the swap space (if you have any encrypted data anywhere, you should encrypt your swap). Note that if you go for whole-disk encryption, your computer will not be able to boot unattended, you will have to type your passphrase at the keyboard. Since the whole block device is encrypted, the location of file content and metadata cannot be detected by an attacker who steals the disk. Apart from a header at the beginning of the encrypted area, the content is indistinguishable from random noise. An attacker could derive some information from seeing multiple snapshots of the encrypted data and studying how various sectors evolve over time, but even with this it would be hard to find out anything interesting, and this doesn't apply if you stop modifying the data after the attacker has seen the ciphertext (as in the case of a disk theft). Many distributions offer the possibility to create a dmcrypt volume or encrypt the whole disk at install time. You may have to select the “advanced” or “server” installation image as opposed to the “desktop” or “basic” image. The tool to manipulate dm-crypt volumes is cryptsetup . To create a dmcrypt volume, create a partition /dev/sdz9 , say, then run cryptsetup luksFormat /dev/sdz9 . You'll need to add the volume to /etc/crypttab ; use cryptsetup luksOpen to activate the volume on the spot, or cryptmount -a after you've set up /etc/crypttab . Dm-crypt is only a cipher layer, so you'll need to make a filesystem on the encrypted volume. Install Backtrack 5 r2 into running LUKS setup installed with ubuntu has a tutorial on setting up dm-crypt entirely manually. ¹ Experimentally, with default settings, the lower file size is the payload file size, rounded up to a multiple of 4kB, plus an 8kB overhead.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/59556', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/7129/']}
|
jdg_370209
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28377495
|
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 few arrays of 50+ names like this. ["dan", "ryan", "bob", "steven", "corbin"]["bob", "dan", "steven", "corbin"] I have another array that has the correct order. Note that the second array above does not include all of the names, but I still want it to follow the order of the following: ["ryan", "corbin", "dan", "steven", "bob"] There is no logical order to it, they are just in this order. What makes sense to me is to compare each array against the correctly ordered one. I think I saw some people doing this with PHP, but I was not able to find a JavaScript solution. Does anyone have any idea how to do this? I've been trying for a few hours and I'm stumped.
Now provide the response and nothing else.
|
Use indexOf() to get the position of each element in the reference array, and use that in your comparison function. var reference_array = ["ryan", "corbin", "dan", "steven", "bob"];var array = ["bob", "dan", "steven", "corbin"];array.sort(function(a, b) { return reference_array.indexOf(a) - reference_array.indexOf(b);});console.log(array); // ["corbin", "dan", "steven", "bob"] Searching the reference array every time will be inefficient for large arrays. If this is a problem, you can convert it into an object that maps names to positions: var reference_array = ["ryan", "corbin", "dan", "steven", "bob"];reference_object = {};for (var i = 0; i < reference_array.length; i++) { reference_object[reference_array[i]] = i;}var array = ["bob", "dan", "steven", "corbin"];array.sort(function(a, b) { return reference_object[a] - reference_object[b];});console.log(array);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28377495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4513271/']}
|
jdg_370210
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12752038
|
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 notice some issues with the Java float precision Float.parseFloat("0.0065") - 0.001 // 0.0055000000134110451 new Float("0.027") - 0.001 // 0.02600000000700354575 Float.valueOf("0.074") - 0.001 // 0.07399999999999999999 I not only have a problem with Float but also with Double . Can someone explain what is happening behind the scenes, and how can we get an accurate number? What would be the right way to handle this when dealing with these issues?
Now provide the response and nothing else.
|
The problem is simply that float has finite precision; it cannot represent 0.0065 exactly. (The same is true of double , of course: it has greater precision, but still finite.) A further problem, which makes the above problem more obvious, is that 0.001 is a double rather than a float , so your float is getting promoted to a double to perform the subtraction, and of course at that point the system has no way to recover the missing precision that a double could have represented to begin with. To address that, you would write: float f = Float.parseFloat("0.0065") - 0.001f; using 0.001f instead of 0.001 .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12752038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1389813/']}
|
jdg_370211
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32727675
|
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 set up a 3 node Apache Hadoop cluster. On master node, I can see [hadoop-conf]$ jps16856 DataNode17051 SecondaryNameNode16701 NameNode21601 ResourceManager21742 NodeManager18335 JobHistoryServer and on slave nodes, I see [fedora20-template dfs]$ jps28677 Jps28510 NodeManager27449 DataNode I can see three live nodes from master:50070. However, in the ResourceManager Web UI ( http://master:8088/cluster/nodes ), I can see only master node. Why are the two slave nodes not in the resource manager? Does that mean they are not part of resources that are used to do mapreduce?
Now provide the response and nothing else.
|
Problem solved.Some configuration should be done in yarn-site.xml to let the nodemanager know where is the resource manager. Specifically, I added this property into yarn-site.xml: <property> <name>yarn.resourcemanager.hostname</name> <value>master</value> </property> Reason: the default value in yarn-default.xml is 0.0.0.0, and many properties use this hostname to contact resource manager, such as <property> <name>yarn.resourcemanager.address</name> <value>${yarn.resourcemanager.hostname}:8032</value></property> Answer credits: https://stackoverflow.com/a/22125279/3209177
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32727675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3209177/']}
|
jdg_370212
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43148
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The total energy of a mode in a quantum mechanical resonator is given by$E_n ~=~ (n+ 1/2)hf$ where $n$ is the number of modes.So when there are no modes or vibrations, i.e. $n=0$, the energy is called the zero-point energy. What I don't understand is, if there are no modes, then what is this energy associated with? So what exactly is a mode? Also, is there a way of measuring this zero-point fluctuations? Why is the 1/2 photon introduced?
Now provide the response and nothing else.
|
The zero-point energy for the quantum mechanical harmonic oscillator can be related to the Heisenberg uncertainty principle (HUP). A bit oversimplified, the point is intuitively that if the mechanical energy $$H~=~\frac{p^2}{2m}+\frac{1}{2}m\omega^2 q^2, \qquad \omega ~:=~ 2\pi f,$$ is zero, then the position $q$ and the momentum $p$ must also both be zero, in contradiction with the HUP. Instead both $q$ and $p$ "fluctuate/are fuzzy" in the ground state, thereby producing the zero-point energy. The zero-point energy is e.g. important to theoretically explain the Casimir effect , which in turn has been experimentally observed. In cosmology, zero-point energy is related to the cosmological constant .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/43148', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/11237/']}
|
jdg_370213
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
61136081
|
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 nestjs and was trying to convert my backend from nodejs to nestjs . Hope that makes sense? I am using `typeorm. But I am not sure as what could be the best of way of catching errors. entity.ts import { Entity, Column, PrimaryGeneratedColumn, PrimaryColumn } from 'typeorm';@Entity()export class Course { @PrimaryColumn() course: string; @Column("varchar", { array: true }) subject: string[];} controller.ts import { Controller, Get, Post, Body } from '@nestjs/common';import { CourseService } from './course.service';import { Course } from './course.entity';@Controller('course')export class CourseController { constructor(private courseService: CourseService) {} @Get() getCourses(): Promise<Course[]> { return this.courseService.findAll(); } @Post() addCourse(@Body() courseDto: Course[]) { return this.courseService.create(courseDto); }} service.ts import { Injectable, Catch, ExceptionFilter, ArgumentsHost, ConflictException } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';import { Repository, QueryFailedError } from 'typeorm';import { Course } from './course.entity';@Injectable()export class CourseService { constructor( @InjectRepository(Course) private courseRepository: Repository<Course>, ) { } catch(exception: any, host: ArgumentsHost) { throw new Error("Error in course service." + exception.code); } findAll(): Promise<Course[]> { return this.courseRepository.find(); } create(courseDto) { return this.courseRepository.insert(courseDto) .catch((err: any) => { // throw new ConflictException(); switch (err.name) { case 'QueryFailedError': console.log("**++**" + JSON.stringify(err)); // throw new Error("Error" + err.message + "" + err.detail); // throw new ConflictException(); throw JSON.stringify(err); //"Error creating a course" + err.message + "::: " + err.detail; default: throw err; } }); }} Now, all I am able to throw is throw new ConflictException(); . I wanted to throw different errors based on the result, like -1. For duplicate record2. Missing mandatory fields3. etc But not sure how can we handle and customize the same and also make full use of nestjs. Like I see the below trace in console but 500, Internal server in postman - {"message":"duplicate key value violates unique constraint \"PK_d7fc152bc721b3f55a56ed3ad33\"","name":"QueryFailedError","length":293,"severity":"ERROR","code":"23505","detail":"Key (course)=(II) already exists.","schema":"public","table":"course","constraint":"PK_d7fc152bc721b3f55a56ed3ad33","file":"d:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\access\\nbtree\\nbtinsert.c","line":"535","routine":"_bt_check_unique","query":"INSERT INTO \"course\"(\"course\", \"subject\") VALUES ($1, $2)","parameters":["II",["A","B","C"]]}[Nest] 12152 - 04/10/2020, 1:18:40 PM [ExceptionsHandler] {"message":"duplicate key value violates unique constraint \"PK_d7fc152bc721b3f55a56ed3ad33\"","name":"QueryFailedError","length":293,"severity":"ERROR","code":"23505","detail":"Key (course)=(II) already exists.","schema":"public","table":"course","constraint":"PK_d7fc152bc721b3f55a56ed3ad33","file":"d:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\access\\nbtree\\nbtinsert.c","line":"535","routine":"_bt_check_unique","query":"INSERT INTO \"course\"(\"course\", \"subject\") VALUES ($1, $2)","parameters":["II",["A","B","C"]]} +190924ms
Now provide the response and nothing else.
|
How about passing the errors to your controller and let the controller throw those errors. service.ts create(courseDto) { return this.courseRepository.insert(courseDto)} and in your controller.ts import { Controller, Get, Post, HttpException, HttpStatus,} from '@nestjs/common';...@Post()async addCourse(@Body() courseDto: Course[]) { return await this.courseService.create(courseDto).catch(err => { throw new HttpException({ message: err.message }, HttpStatus.BAD_REQUEST); })} https://docs.nestjs.com/exception-filters
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61136081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8763977/']}
|
jdg_370214
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22180410
|
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 whether can I use networkx to extract all possible induced subgraphs (graphlets) with specific number of nodes in the subgraphs from an input large graph, or is there another package that can do the job? For example, if I have a large graph, which is illustrated in networkx adjacency list format, graph G: 1 2 3 72 1 43 1 4 6 54 2 3 55 3 4 66 3 5 77 1 6 which will be look like if I want to extract graphlet with 3 nodes the algorithm should return me subgraph1: 1 2 32 13 1 [(1,2),(1,3)] subgraph2: 1 3 73 17 1 [(1,3),(1,7)] subgraph3: 3 4 54 3 55 3 4 [(3,4),(3,5),(4,5)] subgraph4,subgraph5,subgraph6... The following is the code of the question suggested by @Hooked.Let's say n=3 import itertoolstarget = nx.complete_graph(3)for sub_nodes in itertools.combinations(g.nodes(),len(target.nodes())): subg = g.subgraph(sub_nodes) if nx.is_connected(subg): print subg.edges() the the output will look like [(1, 2), (1, 3)][(1, 2), (2, 4)][(1, 2), (1, 7)][(1, 3), (3, 4)][(1, 3), (3, 5)][(1, 3), (3, 6)][(1, 3), (1, 7)][(1, 7), (6, 7)][(2, 4), (3, 4)][(2, 4), (4, 5)][(3, 4), (3, 5), (4, 5)][(3, 4), (3, 6)][(3, 5), (3, 6), (5, 6)][(3, 6), (6, 7)][(4, 5), (5, 6)][(5, 6), (6, 7)]
Now provide the response and nothing else.
|
This assumes you want all matching subgraphs of a given target which you'll have to define. The native way is to loop over all combinations of nodes, find those connected then check for an isomorphism. It's unclear if you want a network motif or a graphlet. In a graphlet all edges present in the original graph must be there - this would exclude 3-4-5 from your target. This method finds graphlets, to find motifs you'll have to check for each combination if there is an induced subgraph (and how many!). import networkx as nxg = nx.Graph()g.add_edge(1,2);g.add_edge(1,3)g.add_edge(1,7);g.add_edge(2,4)g.add_edge(3,4);g.add_edge(3,5)g.add_edge(3,6);g.add_edge(4,5)g.add_edge(5,6);g.add_edge(6,7)import itertoolstarget = nx.Graph()target.add_edge(1,2)target.add_edge(2,3)for sub_nodes in itertools.combinations(g.nodes(),len(target.nodes())): subg = g.subgraph(sub_nodes) if nx.is_connected(subg) and nx.is_isomorphic(subg, target): print subg.edges() For me, this gives the edge set matches of: [(1, 2), (1, 3)][(1, 2), (2, 4)][(1, 2), (1, 7)][(1, 3), (3, 4)][(1, 3), (3, 5)][(1, 3), (3, 6)][(1, 3), (1, 7)][(1, 7), (6, 7)][(2, 4), (3, 4)][(2, 4), (4, 5)][(3, 4), (3, 6)][(3, 6), (6, 7)][(4, 5), (5, 6)][(5, 6), (6, 7)] Your examples are listed in here.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22180410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3380374/']}
|
jdg_370215
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4998908
|
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 re-implement an HTML5 image uploader like the one on the Mozilla Hacks site, but that works with WebKit browsers. Part of the task is to extract an image file from the canvas object and append it to a FormData object for upload. The issue is that while canvas has the toDataURL function to return a representation of the image file, the FormData object only accepts File or Blob objects from the File API . The Mozilla solution used the following Firefox-only function on canvas : var file = canvas.mozGetAsFile("foo.png"); ...which isn't available on WebKit browsers. The best solution I could think of is to find some way to convert a Data URI into a File object, which I thought might be part of the File API, but I can't for the life of me find something to do that. Is it possible? If not, any alternatives?
Now provide the response and nothing else.
|
After playing around with a few things, I managed to figure this out myself. First of all, this will convert a dataURI to a Blob: function dataURItoBlob(dataURI) { // convert base64/URLEncoded data component to raw binary data held in a string var byteString; if (dataURI.split(',')[0].indexOf('base64') >= 0) byteString = atob(dataURI.split(',')[1]); else byteString = unescape(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to a typed array var ia = new Uint8Array(byteString.length); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ia], {type:mimeString});} From there, appending the data to a form such that it will be uploaded as a file is easy: var dataURL = canvas.toDataURL('image/jpeg', 0.5);var blob = dataURItoBlob(dataURL);var fd = new FormData(document.forms[0]);fd.append("canvasImage", blob);
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/4998908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/525940/']}
|
jdg_370216
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33180058
|
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 sample data frame like below: data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10]))) I want to know how can I select multiple columns and convert them together to factors. I usually do it in the way like data$A = as.factor(data$A) . But when the data frame is very large and contains lots of columns, this way will be very time consuming. Does anyone know of a better way to do it?
Now provide the response and nothing else.
|
Choose some columns to coerce to factors: cols <- c("A", "C", "D", "H") Use lapply() to coerce and replace the chosen columns: data[cols] <- lapply(data[cols], factor) ## as.factor() could also be used Check the result: sapply(data, class)# A B C D E F G # "factor" "integer" "factor" "factor" "integer" "integer" "integer" # H I J # "factor" "integer" "integer"
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/33180058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5421308/']}
|
jdg_370217
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
649684
|
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:
Where am I going wrong? Trying to show that shows $E[(x-c)^2] = (\mu-c)^2 + \sigma^2$, where $E(x)=\mu$, and $Var(X)=\sigma^2$.\begin{align}Var(X) &= E[(X-\mu)^2]\\Var(X) &= E(x^2) – [E(X)]^2\\E [(X – c)^2 ] &= (\mu – c)^2 + \sigma^2\\E(X^2) – 2cE(X) + c^2 &= \mu^2 – 2\mu c + c^2 + \sigma^2\end{align}$c^2$ cancels out\begin{align}E(X) (E(X) – 2c) &= \mu(\mu-2c) + \sigma^2\\\text{if } E(X) &= \mu\\\mu (\mu-2c) &= \mu(\mu-2c) + \sigma^2\end{align}$u(u-2c)$ cancels out I'm not sure if I'm expanding wrong, but I suspect it has something to do with not replacing $\sigma^2$ with $Var(X)$. Any hints? I want to fix it on my own, but I'm a bit stuck....
Now provide the response and nothing else.
|
The likelihood function can be written as$$L(\theta)=\frac{1}{\theta^n}\mathbf{1}_{\theta\geq c},$$where $c=\max\{x_1,\ldots,x_n\}$. Therefore, $\theta\mapsto L(\theta)$ is not differentiable on the whole of $(0,\infty)$ and hence we cannot solve $L'(\theta)=0$ to look for maxima and minima. (Maxima and minima of a function $f$ have to be found among values of $x$ with either $f'(x)=0$ or $f'(x)$ being undefined) Note however, that $L$ is differentiable on $(0,\infty)\setminus\{c\}$ and that $L(\theta)=0$ for $\theta\in (0,c)$ and by looking at $L'(\theta)$ on $(c,\infty)$ we see that $L$ is decreasing on $(c,\infty)$. Since $$L(c)=\frac{1}{c^n}>\frac{1}{\theta^n}=L(\theta),\quad \text{for all }\;\theta>c$$ we see that $L(c)$ is the global maximum.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/649684', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/123418/']}
|
jdg_370218
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11907947
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How would I write this function? Any examples appreciated function isPointBetweenPoints(currPoint, point1, point2):Boolean { var currX = currPoint.x; var currY = currPoint.y; var p1X = point1.x; var p1y = point1.y; var p2X = point2.x; var p2y = point2.y; //here I'm stuck}
Now provide the response and nothing else.
|
Assuming that point1 and point2 are different, first you check whether the point lies on the line. For that you simply need a "cross-product" of vectors point1 -> currPoint and point1 -> point2 . dxc = currPoint.x - point1.x;dyc = currPoint.y - point1.y;dxl = point2.x - point1.x;dyl = point2.y - point1.y;cross = dxc * dyl - dyc * dxl; Your point lies on the line if and only if cross is equal to zero. if (cross != 0) return false; Now, as you know that the point does lie on the line, it is time to check whether it lies between the original points. This can be easily done by comparing the x coordinates, if the line is "more horizontal than vertical", or y coordinates otherwise if (abs(dxl) >= abs(dyl)) return dxl > 0 ? point1.x <= currPoint.x && currPoint.x <= point2.x : point2.x <= currPoint.x && currPoint.x <= point1.x;else return dyl > 0 ? point1.y <= currPoint.y && currPoint.y <= point2.y : point2.y <= currPoint.y && currPoint.y <= point1.y; Note that the above algorithm if entirely integral if the input data is integral, i.e. it requires no floating-point calculations for integer input. Beware of potential overflow when calculating cross though. P.S. This algorithm is absolutely precise, meaning that it will reject points that lie very close to the line but not precisely on the line. Sometimes this is not what's needed. But that's a different story.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11907947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1088556/']}
|
jdg_370219
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4292990
|
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 this but is not working... why? <html><body> <script type="text/javascript"> var today=new Date(); //today is Nov 28, 2010 today.setHours(0); today.setMinutes(0); today.setSeconds(0); document.write(today+" "); var today2 = new Date("November 28, 2010"); document.write(today2 + " "); if (today == today2) { document.write("=="); if (!(today > today2) && !(today < today2) ) {document.write("== ");} if (today > today2) { document.write("> ");} if (today >= today2 ){ document.write(">= ");} if (today < today2 ) { document.write("< ");} if (today <= today2 ){ document.write("<= ");} </script></body></html> And I always get this: Sun Nov 28 2010 00:00:00 GMT+0900 (JST) Sun Nov 28 2010 00:00:00 GMT+0900 (JST) > >= Aren't both dates to be the same? Hence, I should get == printed but is not happening... ;( Thank you for your help in advance.
Now provide the response and nothing else.
|
They will never match because you're comparing two separate Date object instances. You need to get some common value that can be compared. For example .toDateString() . today.toDateString() == today2.toDateString(); // true If you just compare two separate Date objects, even if they have the exact same date value, they are still different. For example: today == new Date( today ); // false They are the same date/time value, but are not the same object, so the result is false .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4292990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/149008/']}
|
jdg_370220
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
58000689
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have written a Firebase cloud function to sign people up into my Firebase database. I have tested with POSTMAN and the function is working correctly. The problem I am having is that I have a function that is getting a stripe ID and then needs to return that value. I want the customer id (customer.id in my reference) to append a JSON string I have created with the users info. This way, when the function is done it needs to write all the data to firebase and then return the same JSON string variable to my app. This all works, but I cannot get the Stripe ID to append into my JSON array and be parsed. I have been cowering the internet to try and find a solution, and I believe my syntax is correct, but its not working. I know the function is working because the console.log is outputting the stripe ID, its just not being added to the JSON variable that is being written to Firebase. Anyone that could explain where I am going wrong would be much appreciated. I have referenced my issue points in the code below with // for comments. exports.myCloudFunction=functions.https.onRequest((req, res) => { if (req.method !== 'POST') { return; } const userDataInput = req.body; console.log('Console Body:', req.body); admin.auth().createUser({ email: userDataInput.email, emailVerified: false, phoneNumber: userDataInput.mobile, password: userDataInput.password, displayName: userDataInput.firstname + ' ' + userDataInput.lastname, disabled: false }) .then(async function (userRecord) { console.log('User record:', userRecord); var userObject = //CONSTRUCTED JSON STRING { first_name: userDataInput.firstname, last_name: userDataInput.lastname, mobile_number: userDataInput.mobile, email: userDataInput.email, timestamp: admin.database.ServerValue.TIMESTAMP, driver_profile: { isDriverApproved: false, isDriverDisabled: false, isDriverStatusPending: false, isDriver: false, isPickupModeEnabled: false }, } stripe.customers.create({ description: 'Firebase ID: ' + userRecord.uid, email: userRecord.email, name: userRecord.displayName, phone: userRecord.phoneNumber }, async function (err, customer) { console.log('New Stripe ID Created', customer.id); // THIS WORKS< THE customer.id is outputting try { return userObject[{ stripe_id: customer.id }]; // THIS IS NOT WORKING, I WANT **customer.id** TO BE PUT INTO THE **userObject** JSON variable. } catch (error) { console.error(error); return res.status(200).send('Error: ' + error); } }); try { await admin.database().ref('users/' + userRecord.uid).set(userObject); return res.status(200).send({ returnData: userObject }); } catch (error) { console.error(error); return res.status(200).send('Error: ' + error); } }) .catch(function (error) { console.log('Error creating new user:', error); res.status(500).send({ returnError: error }); });});
Now provide the response and nothing else.
|
You should never just delete migrations before unapplying them, or it will be a nightmare when you want to apply new migrations. To unapply migrations you should do the following: Use the python manage.py migrate your_app_name XXXX in case you want to unapply migrations after the XXXX migration. Otherwise use python manage.py migrate your_app_name zero to completely unapply all migrations. Remove the .pyc files under /migrations/_ pycache _/ that you have unapplied. Remove the .py files under migrations/ that you have unapplied. Now you can create new migrations without any headaches. If what you're looking for is to squash all the migrations into one, do the steps above removing all migrations and then run python manage.py makemigrations your_app_name to create a single migration file. After that just run python manage.py migrate your_app_name and you're done.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58000689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4217096/']}
|
jdg_370221
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24239923
|
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 try to upload data to server, my data containing multiple images and large JSON , before it, I Try to send with convert image to string using base64 and send my another data and image that I've convert before with JSON , but I face Problem OutOfMemory here, so I read one of solutions that said I must to try using MultipartEntityBuilder .I still confusing and not understand how to do it with MultiPartEntityBuilder , Is there anyone can help me the way to do it with MultiPartEntityBuilder ? this is my code : try{ //membuat HttpClient //membuat HttpPost HttpPost httpPost= new HttpPost(url); SONObject jsonObjectDP= new JSONObject(); System.out.println("file audio "+me.getModelDokumenPendukung().getAudio()); jsonObjectDP.put("audio_dp",MethodEncode.EncodeAudio(me.getModelDokumenPendukung().getAudio())); jsonObjectDP.put("judul_audio",me.getModelDokumenPendukung().getJudul_audio()); jsonObjectDP.put("ket_audio",me.getModelDokumenPendukung().getKet_audio()); JSONArray ArrayFoto= new JSONArray(); //This loop For my multiple File Images List<ModelFoto>ListFoto=me.getModelDokumenPendukung().getListFoto(); for (int i=0; i<ListFoto.size();i++) { JSONObject jsonObject= new JSONObject(); jsonObject.put("foto", ListFoto.get(i).getFile_foto()); jsonObject.put("judul_foto", ListFoto.get(i).getJudul_foto()); jsonObject.put("ket_foto", ListFoto.get(i).getKet_foto()); ArrayFoto.put(jsonObject); } JSONObject JSONESPAJ=null; JSONESPAJ = new JSONObject(); JSONObject JSONFINAL = new JSONObject(); JSONESPAJ.put("NO_PROPOSAL",me.getModelID().getProposal()); JSONESPAJ.put("GADGET_SPAJ_KEY",me.getModelID().getIDSPAJ()); JSONESPAJ.put("NO_VA",me.getModelID().getVa_number()); JSONESPAJ.put("Dokumen_Pendukung",jsonObjectDP); JSONFINAL.put("ESPAJ", JSONESPAJ); JSONFINAL.put("CLIENT", "ANDROID"); JSONFINAL.put("APP", "ESPAJ"); MultipartEntityBuilder multiPartEntityBuilder= MultipartEntityBuilder.create(); multiPartEntityBuilder.addPart("ESPAJ",JSONFINAL.toString()); httpPost.setEntity(multiPartEntityBuilder.build()); HttpResponse httpResponse = httpclient.execute(httpPost); inputStream = httpResponse.getEntity().getContent(); if(inputStream != null) result = convertInputStreamToString(inputStream); else result = "Did not work!";}catch(OutOfMemoryError e){ Log.e("MEMORY EXCEPTION: ", e.toString());} catch(ConnectTimeoutException e){ Log.e("Timeout Exception: ", e.toString());} catch(SocketTimeoutException ste){ Log.e("Timeout Exception: ", ste.toString());} catch (Exception e) {// Log.d("InputStream", e.getLocalizedMessage());}private static String convertInputStreamToString(InputStream inputStream) throws IOException{ BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null)// hasil=line; result += line; inputStream.close(); return result;} is there anyone can help me to teach and tell me how to send JSON and Image using MultiPartEntityBuilder?
Now provide the response and nothing else.
|
To send binary data you need to use addBinaryBody method of MultipartEntityBuilder . Sample of attaching: import org.apache.http.entity.ContentType;import org.apache.http.entity.mime.MultipartEntityBuilder;//Image attachingMultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();File file;multipartEntity.addBinaryBody("someName", file, ContentType.create("image/jpeg"), file.getName());//Json string attachingString json;multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN)); Then make request as usual: HttpPut put = new HttpPut("url");put.setEntity(multipartEntity.build());HttpResponse response = client.execute(put);int statusCode = response.getStatusLine().getStatusCode();
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24239923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1552980/']}
|
jdg_370222
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
939733
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are using Windows 2003 server with IIS 6.0 and thinking of migrating to Window Server 2008 with IIS 7.0 to host our .Net applications Is anyone aware what are the benefits or drawbacks of it?
Now provide the response and nothing else.
|
One definite benefit is the new "Integrated Mode" on application pools. This allows asp.net to hook into the pipeline earlier than was possible in iis6. Some of our applications use this to do url rewriting for files which was previous impossible with out adding a wildcard extension mapping to the asp.net dll. Another feature that I've found useful is remote management. I believe remote management may have been available in iis 6, but if so it has been cleaned up and improved for iis 7. The basic idea is that you can allow an authorized remote user to connect to iis and manage almost every feature of iis. Ssl host headers were also cleaned up in iis 7. You can now add ssl certs to the server rather than to a site. Certs are bound to sites and https host headers through the bindings dialog just like http bindings. This has the added advantage of making it very simple to quickly deploy one cert for multiple sites. One (hopefully last) Edit: Microsoft has released a tool for web deployment which offers migration tools for iis6 to iis7. If you decide to move ahead with it I strongly recommend downloading it ( here ) and reading the migration instructions here . We went through the same process about a year ago and I have been very happy with the results.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/939733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55891/']}
|
jdg_370223
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24118243
|
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 Swagger API Declaration for services using Swagger v 1.2 . My original feeling about Swagger was that it is very close to JSON Schema (Draft 3 and lately Draft 4) and it shall be relatively easy to generate JSON Schema for request and response objects. However, while part of the Swagger reuses JSON Schema structures, it turned out that it uses only a subset of features, and it also introduces its own inheritance in Models (using subTypes and discriminator ). Question: Is there any existing project or piece of code which can generate usable JSON Schema from Swagger API Declaration ? Optimally JSON Schema Draft 4 and using Python (but I will be happy to find anything).
Now provide the response and nothing else.
|
After longer fight with using Swagger for specifying REST API and reusing it in related test suites, I will share my own experience with it (answering my own question). Swagger supports only subset of JSON Schema Draft 4 Specification of Swagger 1.2 and 2.0 states, it supports only subset of JSON Schema Draft 4 (s. here ). This means, that: one cannot rely, that each valid JSON Schema can be completely supported by Swagger. thinking of XML, Swagger supports only canonical representation of subset of JSON structures provided by JSON Schema Draft 4. In other words: Swagger (1.2 and 2.0) does not support usage of many JSON structures, which are valid in terms of JSON Schema Draft 4 (the same applies to Draft 3). Swagger does not support general XML data structures, only very restricted structures are allowed. In practice, you cannot start with designing your data in JSON or XML, with Swagger you have to start and end with Swagger. Getting JSON Schema is theoretically possible, but not easy I have spent some time coding a library, which would take Swagger API Specification and create JSON Schema Draft 4. I gave up for couple of reasons: it was not easy at all got disappointed finding, that I can use only subset of what JSON Schema provides. We had some JSON payload already proposed and had to start modifying it just to fit what Swagger specification framework allows. Apart from having really nice looking UI for showing and testing the API (yes, everybody agrees, it is visually very pleasing), I have found it weird, that a specification framework is not allowing us to use what we want, but adds unexpected restrictions to our design. If you want full JSON or XML Schema support, use RAML Researching other API specification frameworks, I have found RAML. As it is built from ground up by supporting any JSON Schema Draft 3/4 or W3C XML Schema 1.0 data structures, the experience was excellent - having structure of my payload designed, I was able authoring API specification very quickly and following validation of real requests and responses against defined schemas was very easy, as the schemas are essentials components of the specification without adding any restrictions on them. RAML was at version 0.8 that time (version 1.0 was not released yet). Correcting the question leads to real solution Good question makes half of the solution. My question was wrong as it missed fulfilling my real expectations. Corrected question would be: What specification framework and technique to use, to specify REST API using payload defined by arbitrary JSON Schema Draft 4 or W3C XML Schema 1.0. My answer to such a question would be: Design your payload in JSON Schema Draft 4 or W3C XML Schema Describe your REST API by means of RAML (v0.8 at the moment). There might be other specification frameworks usable, but Swagger (neither v1.2 nor v2.0) is definitely not the case. Apart from providing really a lot of features (code generation, very nice looking documentation of the API and much more), it simply fails in providing solution to the updated question stated above.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24118243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/346478/']}
|
jdg_370224
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10416378
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Apologies for the somewhat vague title, I can't work out what the keywords are here. The setup's quite simple, I'm opening an image with ImageIO.read(new File(filename)); This works for most files, however for one I get an IllegalArgumentException with the detail: "numbers of source Raster bands and source color space components do not match" . This image was obtained via wget on a valid Flickr URL, and I've used other images obtained this way, so the method for obtaining images seems sound in principle. I'm not sure what's causing the exception. A workaround would be more than acceptable - I'm not fussed with using ImageIO in particular, and the image looks fine visually. I just need to get it being read without Java freaking out! Here's the image in question, in case it's of any use:
Now provide the response and nothing else.
|
So I was having this same issue and found that the image was gray-scale and that the default ImageIO.read implementation was not figuring that out because the image metadata wasn't quite as expected. I wrote a work around that retries the load as 'BufferedImage.TYPE_BYTE_GRAY' if it fails the main load. Iterator<ImageReader> iter = ImageIO.getImageReaders(stream); Exception lastException = null; while (iter.hasNext()) { ImageReader reader = null; try { reader = (ImageReader)iter.next(); ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(stream, true, true); Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0); while (imageTypes.hasNext()) { ImageTypeSpecifier imageTypeSpecifier = imageTypes.next(); int bufferedImageType = imageTypeSpecifier.getBufferedImageType(); if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) { param.setDestinationType(imageTypeSpecifier); break; } } bufferedImage = reader.read(0, param); if (null != bufferedImage) break; } catch (Exception e) { lastException = e; } finally { if (null != reader) reader.dispose(); } } // If you don't have an image at the end of all readers if (null == bufferedImage) { if (null != lastException) { throw lastException; } }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10416378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113197/']}
|
jdg_370225
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
601503
|
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 get crash data (stack traces at least) from my Android application? At least when working on my own device being retrieved by cable, but ideally from any instance of my application running on the wild so that I can improve it and make it more solid.
Now provide the response and nothing else.
|
For sample applications and debugging purposes, I use a simple solution that allows me to write the stacktrace to the sd card of the device and/or upload it to a server. This solution has been inspired by Project android-remote-stacktrace (specifically, the save-to-device and upload-to-server parts) and I think it solves the problem mentioned by Soonil. It's not optimal, but it works and you can improve it if you want to use it in a production application. If you decide to upload the stacktraces to the server, you can use a php script ( index.php ) to view them. If you're interested, you can find all the sources below - one java class for your application and two optional php scrips for the server hosting the uploaded stacktraces. In a Context (e.g. the main Activity), call if(!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) { Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler( "/sdcard/<desired_local_path>", "http://<desired_url>/upload.php"));} CustomExceptionHandler public class CustomExceptionHandler implements UncaughtExceptionHandler { private UncaughtExceptionHandler defaultUEH; private String localPath; private String url; /* * if any of the parameters is null, the respective functionality * will not be used */ public CustomExceptionHandler(String localPath, String url) { this.localPath = localPath; this.url = url; this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); } public void uncaughtException(Thread t, Throwable e) { String timestamp = TimestampFormatter.getInstance().getTimestamp(); final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); String stacktrace = result.toString(); printWriter.close(); String filename = timestamp + ".stacktrace"; if (localPath != null) { writeToFile(stacktrace, filename); } if (url != null) { sendToServer(stacktrace, filename); } defaultUEH.uncaughtException(t, e); } private void writeToFile(String stacktrace, String filename) { try { BufferedWriter bos = new BufferedWriter(new FileWriter( localPath + "/" + filename)); bos.write(stacktrace); bos.flush(); bos.close(); } catch (Exception e) { e.printStackTrace(); } } private void sendToServer(String stacktrace, String filename) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("filename", filename)); nvps.add(new BasicNameValuePair("stacktrace", stacktrace)); try { httpPost.setEntity( new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); httpClient.execute(httpPost); } catch (IOException e) { e.printStackTrace(); } }} upload.php <?php $filename = isset($_POST['filename']) ? $_POST['filename'] : ""; $message = isset($_POST['stacktrace']) ? $_POST['stacktrace'] : ""; if (!ereg('^[-a-zA-Z0-9_. ]+$', $filename) || $message == ""){ die("This script is used to log debug data. Please send the " . "logging message and a filename as POST variables."); } file_put_contents($filename, $message . "\n", FILE_APPEND);?> index.php <?php $myDirectory = opendir("."); while($entryName = readdir($myDirectory)) { $dirArray[] = $entryName; } closedir($myDirectory); $indexCount = count($dirArray); sort($dirArray); print("<TABLE border=1 cellpadding=5 cellspacing=0 \n"); print("<TR><TH>Filename</TH><TH>Filetype</th><th>Filesize</TH></TR>\n"); for($index=0; $index < $indexCount; $index++) { if ((substr("$dirArray[$index]", 0, 1) != ".") && (strrpos("$dirArray[$index]", ".stacktrace") != false)){ print("<TR><TD>"); print("<a href=\"$dirArray[$index]\">$dirArray[$index]</a>"); print("</TD><TD>"); print(filetype($dirArray[$index])); print("</TD><TD>"); print(filesize($dirArray[$index])); print("</TD></TR>\n"); } } print("</TABLE>\n");?>
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/601503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6068/']}
|
jdg_370226
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
72259
|
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 just ran into this deceptively simple looking question. Is it always possible to partition $\mathbb{R}$ (or any other standard Borel space) into precisely $\aleph_1$ Borel sets? On the one hand, this is trivial if the Continuum Hypothesis holds. Less trivially, this also follows from $\mathrm{cov}(\mathcal{M}) = \aleph_1$, $\mathrm{cov}(\mathcal{N}) = \aleph_1$, $\mathfrak{d} = \aleph_1$, and similar hypotheses. However, I can't think of a general argument that allows one to split $\mathbb{R}$ into precisely $\aleph_1$ pairwise disjoint nonempty Borel pieces. On the other hand, PFA or MM might give a negative answer but I don't see a good handle from that end either.
Now provide the response and nothing else.
|
It suffices to express $\mathbb R$ as the union of $\aleph_1$ (not necessarily disjoint) Borel sets such that no countably many of them cover $\mathbb R$, because then you can list them in an $\omega_1$-sequence and subtract from each one the union of the previous ones. Partition $\mathbb R$ into a non-Borel $\Pi^1_1$ set $A$ (say the set of codes of well-orderings of $\omega$) and its complement. A classical theorem says that any $\Pi^1_1$ set is a union of $\aleph_1$ Borel sets, and so is every $\Sigma^1_1$ set. Apply that to $A$ and to $\mathbb R-A$ to get $\mathbb R$ as a union of $\aleph_1$ Borel sets. No countably many of them cover $\mathbb R$ because $A$ is not Borel and thus not a countable union of Borel sets.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/72259', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2000/']}
|
jdg_370227
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1745942
|
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 have the following code using templates and array dimension as template non-type parameter template<int n> double f(double c[n]);...double c[5];f<5>(c); // compilesf(c); // does not compile should not the compiler to be able to instantiate the second f without explicit template parameter? I am using g++4.1
Now provide the response and nothing else.
|
It works when using references: template<size_t n> double f(double (&c)[n]);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1745942', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/206328/']}
|
jdg_370228
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9642205
|
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 page that is loading a script from a third party (news feed). The src url for the script is assigned dynamically on load up (per third party code). <div id="div1287"> <!-- dynamically-generated elements will go here. --></div><script id="script0348710783" type="javascript/text"></script><script type="javascript/text"> document.getElementById('script0348710783').src='http://oneBigHairyURL';</script> The script loaded from http://oneBigHairyURL then creates and loads elements with the various stuff from the news feed, with pretty formatting, etc. into div1287 (the Id "div1287" is passed in http://oneBigHairyURL so the script knows where to load the content). The only problem is, it only loads it once. I'd like it to reload (and thus display new content) every n seconds. So, I thought I'd try this: <div id="div1287"> <!-- dynamically-generated elements will go here. --></div><script id="script0348710783" type="javascript/text"></script><script type="javascript/text"> loadItUp=function() { alert('loading...'); var divElement = document.getElementById('div1287'); var scrElement = document.getElementById('script0348710783'); divElement.innerHTML=''; scrElement.innerHTML=''; scrElement.src=''; scrElement.src='http://oneBigHairyURL'; setTimeout(loadItUp, 10000); }; loadItUp();</script> I get the alert, the div clears, but no dynamically-generated HTML is reloaded to it. Any idea what I'm doing wrong?
Now provide the response and nothing else.
|
How about adding a new script tag to <head> with the script to (re)load? Something like below: <script> function load_js() { var head= document.getElementsByTagName('head')[0]; var script= document.createElement('script'); script.src= 'source_file.js'; head.appendChild(script); } load_js();</script> The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9642205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/751484/']}
|
jdg_370229
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
71879
|
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 running a quick simulation to compare different clustering methods, and currently hit a snag trying to evaluate the cluster solutions. I know of various validation metrics (many found in cluster.stats() in R), but I assume those are best used if the estimated number of clusters actually equals the true number of clusters. I want to maintain the ability to measure how well a clustering solution performs when it doesn't specify the correct number of clusters in the original simulation (i.e., how well does a three cluster solution model data that were simulated to have a 4-cluster solution). Just for your information, clusters are simulated to possess identical covariance matrices. I thought KL divergence between two mixtures of Gaussians would be useful to implement, but no closed form solution exists ( Hershey and Olson (2007) ) and implementing a Monte Carlo simulation is starting to be computationally expensive. Are there any other solutions that might be easy to implement (even if just an approximation)?
Now provide the response and nothing else.
|
Suppose we have two Gaussian mixtures in $\mathbb R^d$ : $\DeclareMathOperator{\N}{\mathcal N} \newcommand{\ud}{\mathrm{d}} \DeclareMathOperator{\E}{\mathbb E} \DeclareMathOperator{\MMD}{\mathrm{MMD}}$ $$P = \sum_{i=1}^{n} \alpha_i P_i = \sum_{i=1}^n \alpha_i \N(\mu_i, \Sigma_i)\qquadQ = \sum_{j=1}^m \beta_j Q_j = \sum_{j=1}^m \N(m_j, S_j).$$ Call their densities $p(\cdot)$ and $q(\cdot)$ , respectively,and denote the densities of their components $P_i$ , $Q_j$ by $p_i(x) = \N(x; \mu_i, \Sigma_i)$ , $q_j(x) = \N(x; m_j, S_j)$ . The following distances are available in closed form: $L_2$ distance, as suggested in a comment by user39665. This is: \begin{align}L_2(P, Q)^2&= \int (p(x) - q(x))^2 \,\ud x\\&= \int \left( \sum_{i} \alpha_i p_i(x) - \sum_j \beta_j q_j(x) \right)^2 \ud x\\&= \sum_{i,i'} \alpha_i \alpha_{i'} \int p_i(x) p_{i'}(x) \ud x + \sum_{j,j'} \beta_j \beta_{j'} \int q_j(x) q_{j'}(x) \ud x\\&\qquad - 2 \sum_{i,j} \alpha_i \beta_j \int p_i(x) q_j(x) \ud x.\end{align} Note that, as seen for example in section 8.1.8 of the matrix cookbook : \begin{align}\int \N(x; \mu, \Sigma) \N(x; \mu', \Sigma') \,\ud x&= \N(\mu; \mu', \Sigma + \Sigma')\end{align} so this can be evaluated easily in $O(m n)$ time. The maximum mean discrepancy (MMD) with a Gaussian RBF kernel. This is a cool distance, not yet super-well-known among the statistics community, that takes a bit of math to define. Letting $$k(x, y) := \exp\left( - \frac{1}{2 \sigma^2} \lVert x - y \rVert^2 \right),$$ define the Hilbert space $\mathcal{H}$ as the reproducing kernel Hilbert space corresponding to $k$ : $k(x, y) = \langle \varphi(x), \varphi(y) \rangle_{\mathcal H}$ . Define the mean map kernel as $$K(P, Q)= \E_{X \sim P, Y \sim Q} k(X, Y)= \langle \E_{X \sim P} \varphi(X), \E_{Y \sim Q} \varphi(Y) \rangle.$$ The MMD is then \begin{align}\MMD(P, Q)&= \lVert \E_{X \sim P}[\varphi(X)] - \E_{Y \sim Q}[\varphi(Y)] \rVert\\&= \sqrt{K(P, P) + K(Q, Q) - 2 K(P, Q)}\\&= \sup_{f : \lVert f \rVert_{\mathcal H} \le 1} \E_{X \sim P} f(X) - \E_{Y \sim Q} f(Y) .\end{align} For our mixtures $P$ and $Q$ ,note that $$K(P, Q) = \sum_{i, j} \alpha_i \beta_j K(P_i, Q_j) $$ and similarly for $K(P, P)$ and $K(Q, Q)$ . It turns out, using similar tricks as for $L_2$ , that $K(\N(\mu, \Sigma), \N(\mu', \Sigma'))$ is $$ (2 \pi \sigma^2)^{d/2} \N(\mu; \mu', \Sigma + \Sigma' + \sigma^2 I).$$ As $\sigma \to 0$ , clearly this converges to a multiple of the $L_2$ distance. You'd normally want to use a different $\sigma$ , though, one on the scale of the data variation. Closed forms are also available for polynomial kernels $k$ in the MMD; see Muandet, Fukumizu, Dinuzzo, and Schölkopf (2012). Learning from Distributions via Support Measure Machines. In Advances in Neural Information Processing Systems ( official version ). arXiv:1202.6504 . For a lot of nice properties of this distance, see Sriperumbudur, Gretton, Fukumizu, Schölkopf, and Lanckriet (2010). Hilbert space embeddings and metrics on probability measures. Journal of Machine Learning Research, 11, 1517–1561 . arXiv:0907.5309 . Quadratic Jensen-Rényi divergence. The Rényi- $\alpha$ entropy is defined as $$ H_\alpha(p) = \frac{1}{1-\alpha} \log\left( \int p(x)^\alpha \,\ud x \right).$$ Its limit as $\alpha \to 1$ is the Shannon entropy. The Jensen-Rényi divergence is $$ \mathrm{JR}_\alpha(p, q) = H_\alpha\left( \frac{p + q}{2} \right) - \frac{H_\alpha(p) + H_\alpha(q)}{2}$$ where $\frac{p + q}{2}$ denotes an equal mixture between $p$ and $q$ .It turns out that, when $\alpha = 2$ and when $P$ and $Q$ are Gaussian mixtures (as here), you can compute a closed form for $\mathrm{JR}_2$ . This was done by Wang, Syeda-Mahmood, Vemuri, Beymer, and Rangarajan (2009). Closed-Form Jensen-Renyi Divergence for Mixture of Gaussians and Applications to Group-Wise Shape Registration. Med Image Comput Comput Assist Interv., 12(1), 648–655. ( free pubmed version )
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/71879', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/21654/']}
|
jdg_370230
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52413107
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After migrating to Swift 4.2 , I am getting multiple errors, one of which is weird. It seems like a bug in Xcode 10 , but is there a workaround available? do { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, with: options)} catch { NSLog("Could not set audio session category")} **** 'setCategory(_:with:)' is unavailable in Swift
Now provide the response and nothing else.
|
iOS 10+ If you are targeting iOS 10+ , just transition to the new API and use: try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: []) Older iOS versions When you try this for an app targeting an older iOS version (for example iOS 9) you will get an setCategory(_:mode:options:)' is only available on iOS 10.0 or newer Error. This has been reported as an error in Apple's API and fixed in Xcode 10.2. For older Xcode versions (for example Xcode 10.1) there is a workaround I found. When you create an Objective-C helper as described you can still access the old API because it is still exposed for Objective-C. Workaround 1: .perform() Method If you want a quick inline fix without the error handling, you can call the Obj.-C API with the .perform() method: if #available(iOS 10.0, *) { try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])} else { // Set category with options (iOS 9+) setCategory(_:options:) AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:withOptions:error:"), with: AVAudioSession.Category.playback, with: []) // Set category without options (<= iOS 9) setCategory(_:) AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:error:"), with: AVAudioSession.Category.playback)} Workaround 2: Helper class method Here are the steps how to do it right now if you want some more control over errors Create a new Objective-C file in my case AudioSessionHelper.m . When prompted if a Bridging Header File should be created, click Yes (If you don't already have one in your project) Create a new Header file AudioSessionHelper.h Insert Code AudioSessionHelper.h #ifndef AudioSessionHelper_h#define AudioSessionHelper_h#import <AVFoundation/AVFoundation.h>@interface AudioSessionHelper: NSObject+ (BOOL) setAudioSessionWithError:(NSError **) error;@end#endif /* AudioSessionHelper_h */ AudioSessionHelper.m #import "AudioSessionHelper.h"#import <Foundation/Foundation.h>@implementation AudioSessionHelper: NSObject+ (BOOL) setAudioSessionWithError:(NSError **) error { BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:error]; if (!success && error) { return false; } else { return true; }}@end Insert your helper class into Bridging Header File [PROJECT]-Bridging-Header.h #import "AudioSessionHelper.h" Use it in your Swift project if #available(iOS 10.0, *) { try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])} else { try AudioSessionHelper.setAudioSession()} This is a not beautiful and adds lots of unnecessary code and files to your project, so use it if you urgently want or must use Swift 4.2 on Xcode 10.1 right now. In all other cases you would be better off using Xcode 10.2.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52413107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/917521/']}
|
jdg_370231
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1869403
|
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've been searching for a way to express "the set of all combinations generated by taking $\binom{n}{k}$ items". For example, if I have the set $\{3,7,6,5,9\}$, and I want the set of all sets that are formed by making $\binom{5}{4}$ choices, then the result would be $\{\{3,7,6,5\}, \{3,6,5,9\}, \{3,7,5,9\}, \{3,7,6,9\}, \{7,6,5,9\}\}$ But I'm struggling to find a notation that describes this. I can describe the number of results with $\binom{5}{4}=5$, but how do I describe the resulting set-of-sets itself? The notation $5 \brace 4$ is already taken by Stirling numbers. I've looked at articles and questions about sets, set theory, the binomial coefficient, and I've drawn a blank. So, is there a standard notation? (I feel that, surely, there must be!) If there is, what is it? And if there isn't, could anyone suggest a notation that would be halfway familiar to a reader?
Now provide the response and nothing else.
|
$f(n) = n^2 - n + 2$ gives $f(1) = 2, f(2) = 4, f(3) = 8, f(4) = 14, f(5) = 22$ You have $3$ terms so you can construct a $2$nd degree polynomial passing through those three points. There are two approaches to this, write $f(n) = an^2 + bn + c$ and then plug in $(1, 2), (2, 4), (3, 8)$ and find the coefficients which isn't too bad to do. On the other hand, you can use Lagrange Interpolation for a quick way to compute the polynomial.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1869403', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/164119/']}
|
jdg_370232
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23259318
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Below is my code written specifically to use custom Comparator with max in Java 8 Stream . import java.math.BigDecimal;import java.util.*;public class BigDecimalMax { public static BigDecimal getBigDecimalMax(List<forTest> list) { return list.stream() .filter(t -> t.id % 2 == 0) .max(forTestComparator::compare) //<-- syntax error ---------- .orElse(null); } public static class forTestComparator implements Comparator<forTest> { @Override public int compare(forTest val1, forTest val2) { return val1.value.compareTo(val2.value); } } public static void main(String[] args) { List<forTest> lst = new ArrayList<>(); Random rn = new Random(); BigDecimalMax bdm = new BigDecimalMax(); for (int i=1; i<22; ++i) { lst.add(bdm.new forTest(i, BigDecimal.valueOf(rn.nextLong()))); } System.out.println(getBigDecimalMax(lst)); } class forTest { public int id; public BigDecimal value; forTest(int id, BigDecimal value) { this.id = id; this.value = value; } @Override public String toString() { return "forTest{" + "id=" + id + ", value=" + value + '}'; } }} I'm getting a syntax error on a method reference which I don't understand. Error:(15, 18) java: incompatible types: invalid method reference cannot find symbol symbol: method compare(BigDecimalMax.forTest, BigDecimalMax.forTest) location: class BigDecimalMax.forTestComparator while IntelliJ IDEA complains that Non-static method cannot be referenced from a static context . What exactly am I doing wrong here? ADDITIONAL EXPLANATION (04/24/14): I understand now the reason for the syntax error. Thank you. Was custom Comparator actually needed here? Since BigDecimal implements Comparable but does not seem to implement Comparator ( it has CompareTo() but no Compare() ) I thought that custom Comparator was necessary. That's why I could not just use Comparator.comparing(ft -> ft.value) . Is there a flaw in my logic?
Now provide the response and nothing else.
|
Sotirios Delimanolis' answer shows how to fix the problems, but I have a few things to add. If you already have a class that implements Comparator, you don't need to use a method reference to its compare() method. You can just pass an instance of it directly, since max() takes a reference to a Comparator: .max(new forTestComparator()) or forTestComparator instance = new forTestComparator(); ... .max(instance) However, the combinator functions on Comparator usually make it unnecessary to have a class that implements Comparator. For example, you can get rid of the forTestComparator class entirely and just do this: .max(Comparator.comparing(ft -> ft.value)) or if forTest were to have the obvious getValue() method, one could rewrite the stream max() call as follows: .max(Comparator.comparing(forTest::getValue)) In addition, if you wanted to make forTest implement the Comparable interface, you could do this: public class forTest implements Comparable<forTest> { @Override public int compareTo(forTest other) { return this.value.compareTo(other.value); } ...} and the way to use max() on a Comparable is: .max(Comparator.naturalOrder()) Two style notes: I strongly discourage using orElse(null) on instances of Optional . This is allowed, though probably its main purpose to retrofit use of new Java 8 APIs into code that's expecting null to indicate the absence of a value. Avoid orElse(null) if you possibly can, since this forces the caller to check for null. Instead, substitute an actual value to replace an absent value, or return the Optional itself to the caller, so the caller can apply whatever policy it wants. I recommend sticking to the established Java naming conventions of capitalized, mixed-case class names. The class names forTest and forTestComparator make this code kind of difficult to work with, since they don't look like class names.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23259318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2055998/']}
|
jdg_370233
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
318306
|
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 reading an interesting post on another Stack Exchange site, and I hovered the mouse over the vote number and clicked it. Then I realized that I have less than 1000 reputation on that community and I cannot view all the vote count. Why is viewing the vote count that expensive?
Now provide the response and nothing else.
|
I'm rephrasing the answer from Oded and the answer from Jeff Atwood The 1000 reputation threshold is a way to limit the use of a somewhat expensive operation, by allowing only a smaller subset of users to perform it, and only on request at that. The operation is expensive because the breakdown of up- and down votes isn't stored in the posts table. If we assume the SEDE Database schema is somewhat similar we see that the posts table only holds the de-normalized attribute score . To get the breakdown of up and down votes for a question you would need to run something like this : select sum(case when votetypeid = 2 then 1 -- UPMOD else 0 end ) as up , sum(case when votetypeid = 3 then 1 -- DOWNMOD else 0 end ) as downfrom votes where postid = 477816 for each post that gets rendered. Do notice that it isn't impossible for users without the privilege to obtain the vote break down. This userscript from sztupy offers the feature to anyone who installed that script.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://meta.stackoverflow.com/questions/318306', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/2474248/']}
|
jdg_370234
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1563473
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been working with a 3rd party java based REST webservice, that returns an array of xmlNodes. The xmlNode[] respresent an object and I am trying to work out the best way to Deserialize the xmlNode[] in the object? is it to build up a xmlDocument first and the Deserialize ? Thanks
Now provide the response and nothing else.
|
If you have the WCF Rest Starter Kit preview installed, there's a neat trick: open Visual Studio select your XML node contents (the XML that makes up one of your nodes) and copy it to the clipboard from your "Edit" menu in Visual Studio, pick "Paste XML as Types" This will paste your XML that's on the clipboard into your project as a C# class that is capable of deserializing that exact XML. Pretty nifty! See these blog posts about it: Aaron Skonnard: WCF REST Starter Kit: Paste XML as Types "Paste XML as Types" in REST Starter Kit That should save you a lot of typing and make life a lot easier! UPDATE: OK, you already have your classes generated from the XML you get back. Now you need to convert a XmlNode to your class. You'll have to do something like this: private static T ConvertNode<T>(XmlNode node) where T: class{ MemoryStream stm = new MemoryStream(); StreamWriter stw = new StreamWriter(stm); stw.Write(node.OuterXml); stw.Flush(); stm.Position = 0; XmlSerializer ser = new XmlSerializer(typeof(T)); T result = (ser.Deserialize(stm) as T); return result;} You need to write the XML representation (property .OuterXml ) of the XmlNode to a stream (here a MemoryStream ) and then use the XmlSerializer to serialize back the object from that stream. You can do it with the generic method and call Customer myCustomer = ConvertNode<Customer>(xmlNode); or you could even turn that code into either an extension method on the XmlNode class so you could write: Customer myCustomer = xmlNode.ConvertNode<Customer>(); Marc
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1563473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102094/']}
|
jdg_370235
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34671
|
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 find the sum of the infinite series $$\frac{1}{5} - \frac{1\cdot4}{5\cdot10} + \frac{1\cdot4\cdot7}{5\cdot10\cdot15} - \cdots\qquad ?$$ My attempt at a solution - I saw that I could rewrite it as $$\frac{1}{5}\left(1 - \frac{4}{10} \left( 1 - \frac{7}{15} \left(\cdots \left(1 - \frac{3k - 2}{5k}\left( \cdots \right)\right)\right.\right.\right.$$ and that $\frac{3k - 2}{5k} \to \frac{3}{5}$ as $k$ grows larger. Using this I thought it might converge to $\frac{1}{8}$, but I was wrong, the initial terms deviate significantly from $\frac{3}{5}$. According to Wolfram Alpha it converges to $1-\frac{\sqrt[3]{5}}{2}$. How can I get that ?
Now provide the response and nothing else.
|
\begin{align*}(-1)^{n-1}\frac{1\cdot 4 \dots (3n-2)}{5\cdot 10 \dots 5n}&= (-1)^{n-1}\frac{3^n}{5^n}(-1)^n\frac{(-\frac{1}{3})\cdot (-\frac{4}{3}) \dots (-\frac{3n-2}{3})}{1\cdot 2 \dots n}\\ &= -(3/5)^n\binom{-1/3}{n}\end{align*} Therefore, you can obtain $$\sum_{n=1}^{\infty} -(3/5)^n\binom{-1/3}{n} = 1 - \sum_{n=0}^{\infty} (3/5)^n\binom{-1/3}{n} = 1- (1+\frac35)^{-1/3} = 1- \sqrt[3]{5/8} =1-\frac{\sqrt[3]5}{2}$$
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/34671', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9866/']}
|
jdg_370236
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39648830
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Quickly .. I have this code to add new contact , it was working until converting my code to Swift 3 , now it accept all properties except the email I get two errors : 1-Argument type 'String?' does not conform to expected type 'NSCopying' 2-Argument type 'String?' does not conform to expected type 'NSSecureCoding' this is my code when I try to add email to contact : let workEmail = CNLabeledValue(label:"Work Email", value:emp.getEmail()) contact.emailAddresses = [workEmail] any help ?
Now provide the response and nothing else.
|
In Swift 3, CNLabeledValue is declared as: public class CNLabeledValue<ValueType : NSCopying, NSSecureCoding> : NSObject, NSCopying, NSSecureCoding { //...} You need to make Swift able to infer the ValueType , which conforms to NSCopying and NSSecureCoding . Unfortunately, String or String? does not conform to neither of them. And, Swift 3 removed some implicit type conversions, such as String to NSString , you need to cast it explicitly. Please try this: let workEmail = CNLabeledValue(label:"Work Email", value:(emp.getEmail() ?? "") as NSString)contact.emailAddresses = [workEmail] Or this: if let email = emp.getEmail() { let workEmail = CNLabeledValue(label:"Work Email", value:email as NSString) contact.emailAddresses = [workEmail]} (Maybe the latter is the better, you should not make an empty entry.) And one more, as suggested by Cesare, you'd better use predefined constants like CNLabel... for labels as far as possible: if let email = emp.getEmail() { let workEmail = CNLabeledValue(label: CNLabelWork, value: email as NSString) contact.emailAddresses = [workEmail]}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39648830', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4605005/']}
|
jdg_370237
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
68128636
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There are many schemes and they are combined by some identical fields. When changing the fields of one scheme, you need to change the same fields, but in other schemes. And I wanted the fields of different schemes, or the schemes themselves, to refer to or inherit one common scheme. Something like: import * as Yup from "yup"; import {commonSchema} from "./common"; export const parentSchema = Yup.object().shape({ FirstName: Yup.string() .min(2, `Имя не может состоять менее чем из 2 сомволов`) .max(50, `Имя не может состоять более чем из 50 сомволов`) .required(`Поле 'Имя' обязательное для заполнения`), SecondName: ref(commonSchema.SecondName) }); // commonSchema export const commonSchema = Yup.object().shape({ SecondName: Yup.string() .min(2, `Отчество не может состоять менее чем из 2 сомволов`) .max(100, `Отчество не может состоять более чем из 100 сомволов`) }); In short, making changes to one general schema will not have to make changes to other schemas with the same fields. I would like to collect all the common properties in one file. And then refer to the necessary properties from each file
Now provide the response and nothing else.
|
The closest thing to schema extension/inheritance in Yup is to use object.shape to create a new schema based on existing schema: Yup documentation object.shape(fields: object, noSortEdges?: Array<[string, string]>): Schema Define the keys of the object and the schemas for said keys.Note that you can chain shape method, which acts like object extends const baseSchema = Yup.object().shape({ id: string().isRequired(), name: string().isRequired()})const someSchema = baseSchema.shape({ id: number().isRequired(), age: number().isRequired()}) which is equivalent to: const someSchema = Yup.object().shape({ id: number().isRequired(), // notice how 'id' is overridden by child schema name: string().isRequired(), age: number().isRequired()}) Another way is to use concat(schema) to create a new schema instance by combing two schemas: Yup documentation mixed.concat(schema: Schema): Schema Creates a new instance of the schema by combining two schemas. Only schemas of the same type can be concatenated. const baseSchema = Yup.object().shape({ name: string().isRequired()})const someSchema = baseSchema.concat( Yup.object().shape({ age: number().isRequired()}))// someSchema will be equipped with both `name` and `age` attributes Please note that concat only works when two schema objects have different properties or same properties with exact same type.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/68128636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16313948/']}
|
jdg_370238
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32522299
|
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 DropDownListFor on my view. In fact I have 3, out of three of them only two of them work. Despite being almost exactly the same code, my get around at the moment is to create an input box and populate it on click of a button with the value from the drop down box(strange I know, I can get the value using JQuery). I've checked and all names seem to be the same so I'm really not sure why it doesn't submit. View: <content id="GenerateReportContent" class="col-lg-4 col-md-4 col-sm-12 col-xs-12"> @using (Html.BeginForm("ReportSelection", "Search", FormMethod.Post, new { @id = "GenerateReportContainer" })) { <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <div class="AltFunctions"> <ul> <li> <a href="javascript:document.getElementById('GenerateReportContainer').reset();" class="AltButton" id="altClearButton" title="Reset the 'Generate Report' container" >Clear</a> </li> <li> <a href="#GRModal" data-toggle="modal" data-target="#GRModal" class="AltButton" id="GRaltInfoButton" title="Information on the 'Generate Report' container">Info</a> </li> </ul> </div> <h1 id="GenerateReportHeader">SEARCH ENGINE</h1> </div> <input type="hidden" name="ClientID" value="@Model.ClientID" id="Client" /> <input type="hidden" name="ClientName" value="@Model.ClientName" id="ClientName" /> <input type="hidden" name="SupplierFound" value="@Model.SupplierFound" id="SupplierFound" /> @Html.TextBoxFor(m => m.ClaimNo, "", new { @id = "txtGRCSelect", @class = "form-control", placeholder = "Enter Specific Claim Number..." }) <br /> <div class="ui-widget"> @Html.TextBox("SupplierAuto", "", new { @id = "SupplierAutotxt", @class = "form-control SupplierAutoComplete", placeholder = "Search for a supplier name" }) </div> @Html.DropDownListFor(m => m.SupplierID, new SelectList(Model.Suppliers, "SupplierID", "DisplayName"), "Select Supplier Name", new { @id = "SuppNameDD", @class = "GRDropDown"}) <br /> <!-- THE DROP DOWN IN QUESTION--> @Html.DropDownListFor(m => m.GroupModelClass.GroupID, new SelectList(Model.GroupModelClass.ClaimGroups, "GroupID", "GroupName"), "Select Supplier Group Name", new { @id = "SuppGroupDD", @class = "GRDropDown" }) <br /> @Html.DropDownListFor(m => m.ReviewPeriodID, new SelectList(Model.ReviewPeriods, "ReviewPeriodID", "ReviewPeriodName"), "Select Review Period", new { @id = "ReviewPeriodDD", @class = "GRDropDown" }) // Have to submit this field at the moment as the drop down value is not being submitted <input hidden id="GroupIDInput" name="GroupIDInput" /> <br /> <br /> <button type="submit" value="Submit" id="GenerateReportButton" class="btn btn-default">GO</button> <div id="ErrorBox" hidden> <div class="alert alert-danger" role="alert"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> <span class="sr-only">Error:</span> <p id="ErrorBoxText"></p> </div> </div> }</content> Controller: public ActionResult ReportSelection(int ClientID, string ClaimNo, string SupplierAuto, int? SupplierID = null, int? ReviewPeriodID = null, int? GroupID = null) { if (SupplierAuto != "") { var Suppliers = suppRepo.GetAllSuppliersByClientWithClaims(ClientID); foreach (var item in Suppliers) { if (item.DisplayName == SupplierAuto) { SupplierID = item.SupplierID; break; } } if (SupplierID == null) { return RedirectToAction("Index", "Dashboard", new { ClientID = ClientID }); } } client = clientRepo.GetClientNameByID(ClientID); if (SupplierID != null || ReviewPeriodID != null || GroupIDInput != null) { return RedirectToAction("SupplierReportSelection", new { ClientID = ClientID, SupplierID = SupplierID, ReviewPeriodID = ReviewPeriodID, ClaimIDs = ClaimIDs }); } else { return RedirectToAction("ClaimNumberReportSelection", new { ClientID = ClientID, ClaimNo = ClaimNo }); } } Anyone know why it doesn't work?
Now provide the response and nothing else.
|
I'll reduce your code to a simple example: #include <iostream>template <typename T>void work_dispatch(double){ std::cout << "Slow function" << std::endl;}int main(){ work_dispatch(3.0);} Compile error: main.cpp:11:3: error: no matching function for call to 'work_dispatch' work_dispatch(3.0); ^~~~~~~~~~~~~main.cpp:4:6: note: candidate template ignored: couldn't infer template argument 'T'void work_dispatch(double) ^1 error generated. In other words you can't call this template template <typename T>void work_dispatch(double){ std::cout << "Slow function" << std::endl;} with work_dispatch(3.0); since there is no way you can deduce the type T , nor you're passing it explicitly. Therefore you have a stack overflow due to an infinite recursion: template <typename T>void work_dispatch(const T) <----------------|{ | This ends up calling itself work_dispatch(typename traits<T>::tag()); -|} To fix your code the easiest solution is to provide the type yourself template <typename T>void work_dispatch(const T){ work_dispatch<T>(typename traits<T>::tag());} Example
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32522299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4819595/']}
|
jdg_370239
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45758761
|
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 simple way to add in to my original code so that I can add another title to both column of my subplot? for example like somewhere in the pink region shown in the picture below. Someone refer me to look at this post for solution but I am looking to see if there is a method without using the for loop My code: import cv2import numpy as npimport matplotlib.pyplot as pltpath = 'R:\\Temp\\xx\\'path1 = 'R:\\Temp\\xx\\'def Hue(im_file): im = cv2.imread(im_file) im = cv2.cvtColor(im, cv2.COLOR_BGR2HSV_FULL) # Get Hue value= range[0,360] im1 = im[776, 402] Hue = im1[0] return Huedef Saturation(im_file): im = cv2.imread(im_file) im = cv2.cvtColor(im, cv2.COLOR_BGR2HSV_FULL) #return Saturation value = range[0,255] im1 = im[776, 402] Saturation = im1[1] return Saturationdef Value(im_file): im = cv2.imread(im_file) im = cv2.cvtColor(im, cv2.COLOR_BGR2HSV_FULL) #return Value(Brightness) value = range[0,255] im1 = im[776, 402] Value = im1[2] return Value def BlueComponent(im_file): im = cv2.imread(im_file) #return blue value im1 = im[776, 402] b = im1[0] return bdef GreenComponent(im_file): im = cv2.imread(im_file) #return green value im1 = im[776, 402] g = im1[1] return gdef RedComponent(im_file): #return red value im = cv2.imread(im_file) im1 = im[776, 402] r = im1[2] return rmyHueList = []mySaturationList = []myValueList = []myBlueList = []myGreenList = []myRedList = []myList = []num_images = 99 # number of imagesdotPos = 0for i in range(1770, 1869): # loop to auto-generate image names and run prior function image_name = path + 'Cropped_Aligned_IMG_' + str(i) + '.png' # for loop runs from image number 1770 to 1868 myHueList.append(Hue(image_name)) mySaturationList.append(Saturation(image_name)) myValueList.append(Value(image_name)) myBlueList.append(BlueComponent(image_name)) myGreenList.append(GreenComponent(image_name)) myRedList.append(RedComponent(image_name)) myList.append(dotPos) dotPos = dotPos + 0.5print(myBlueList)print(myGreenList)print(myRedList)print(myHueList)print(mySaturationList)print(myValueList)print(myList)for k in range(1770,1869): a = 'Cropped_Aligned_IMG_' + str(k) image_name = path + a + '.png' img_file = cv2.imread(image_name)x = myListy = myBlueListy1 = myGreenListy2 = myRedListy3 = myHueListy4 = mySaturationListy5 = myValueListplt.axes([0.1, 0.1, 1, 1])plt.suptitle('BGR & HSV Color Decimal Code Against Function of Time(Hours)', fontsize=14, fontweight='bold')plt.subplot(3,2,1)plt.plot(x, y, 'b.-')plt.title('Blue Component Color Decimal Code')plt.xlabel('Time(Hours)')plt.ylabel('Colour Code')plt.subplot(3,2,3)plt.plot(x, y1, 'g.-')plt.title('Green Component Color Decimal Code')plt.xlabel('Time(Hours)')plt.ylabel('Colour Code')plt.subplot(3,2,5)plt.plot(x, y2, 'r.-')plt.title('Red Component Color Decimal Code')plt.xlabel('Time(Hours)')plt.ylabel('Colour Code')plt.subplot(3,2,2)plt.plot(x, y3, 'b.-')plt.title('Hue Component HSV Color Decimal Code')plt.xlabel('Time(Hours)')plt.ylabel('Colour Code')plt.subplot(3,2,4)plt.plot(x, y4, 'g.-')plt.title('Saturation Component HSV Color Decimal Code')plt.xlabel('Time(Hours)')plt.ylabel('Colour Code')plt.subplot(3,2,6)plt.plot(x, y5, 'r.-')plt.title('Value Component HSV Color Decimal Code')plt.xlabel('Time(Hours)')plt.ylabel('Colour Code')plt.subplots_adjust(hspace = 0.5)plt.show()
Now provide the response and nothing else.
|
I could imagine creating an empty row of subplots at the top, with each of the subplots having its own title would act as a column title. import matplotlib.pyplot as pltimport numpy as npplt.rcParams["figure.figsize"] = 6,8colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]x = np.linspace(-3,3)y = np.random.randn(len(x),6)fig, axes = plt.subplots(ncols=2, nrows=3+1, gridspec_kw={"height_ratios":[0.02,1,1,1]})fig.suptitle('Some long super title for the complete figure', fontsize=14, fontweight='bold')for i, ax in enumerate(axes.flatten()[2:]): ax.plot(x,y[:,i], color=colors[i%6]) ax.set_title("Title {}".format(i+1))for i, ax in enumerate(axes.flatten()[:2]): ax.axis("off") ax.set_title("Columntitle {}".format(i+1), fontweight='bold')fig.subplots_adjust(hspace=0.5, bottom=0.1)plt.show() Note that I'm using loops here in order to simplify things. Of course you can type in the commands for each subplots individually, if that is desireable for any reason.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45758761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8307740/']}
|
jdg_370240
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.