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 | 819467 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
hello currently i have a localy ntp server (chrony) and a ntp client (chrony), all are working but when i try to change ntp server time to say minus 6 years from current time. ntp client cannot sync with it, it will just say on syslog: Jan 9 17:29:11 localhost chronyd[9192]: System clock wrong by 6780812.328260 seconds, adjustment started ntp client (chrony) /etc/chrony.conf is on default configuration except that server is pointed to my local NTP server (chrony). Here is my config # Use public servers from the pool.ntp.org project.# Please consider joining the pool (http://www.pool.ntp.org/join.html).#server 0.centos.pool.ntp.org iburst#server 1.centos.pool.ntp.org iburst#server 2.centos.pool.ntp.org iburst#server 3.centos.pool.ntp.org iburstserver local.ntp.server iburst# Ignore stratum in source selection.stratumweight 0# Record the rate at which the system clock gains/losses time.driftfile /var/lib/chrony/drift# Enable kernel RTC synchronization.rtcsync# In first three updates step the system clock instead of slew# if the adjustment is larger than 10 seconds.makestep 10 3# Allow NTP client access from local network.#allow 192.168/16# Listen for commands only on localhost.bindcmdaddress 127.0.0.1bindcmdaddress ::1# Serve time even if not synchronized to any NTP server.#local stratum 10keyfile /etc/chrony.keys# Specify the key used as password for chronyc.commandkey 1# Generate command key if missing.generatecommandkey# Disable logging of client accesses.noclientlog# Send a message to syslog if a clock adjustment is larger than 0.5 seconds.logchange 0.5logdir /var/log/chrony#log measurements statistics tracking I do not know it wont sync, i've read that it will take longer time, but i've let my machine sit for 1 day and still ntp client didn't not have the same time as the ntp server (not synchronized). Any ideas? am tryin not to restart the chronyd service and just let it auto-sync the time Note that "local.ntp.server" is define on my /etc/hosts. Also, NTP server and NTP client are not using ntpd service but it is using chronyd. And this kind of setup is an isolated one
Now provide the response and nothing else.
| Your problem seems to be that you're trying to accomplish a six year time change by skewing the clock, and giving up after one day . If the skew algorithm drifts the clock by as much as one percent - which is quite a lot - it will take six hundred years to skew the clock that much. Even if the clock stands completely still , six years will need to elapse to step it back by six years. The only way to achieve a six-year backwards time drift in less than six years elapsed is to run the clock backwards , and I don't think anything will react well to that. To do it in one day would mean running the clock backwards at slightly more than two thousand times the real-time rate! My feeling is that running NTP servers that lie is a very bad idea, but if you insist on doing this, and you suddenly skew the server by any significant amount, you will need to forcibly alter the client clocks before they have any chance of syncing. This is most easily done by ensuring that the clients forcibly reset their clocks from the server at boot time (with ntpd , this is done with ntpdate at boot time; I don't know about chrony) and rebooting the clients. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/819467', 'https://serverfault.com', 'https://serverfault.com/users/212105/']} | jdg_76341 |
stackexchange | llm_judgeable_groundtruth_similarity | 17371157 |
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 teaching myself c++ for the last couple days to prepare for my freshman year as a CS major. I'm on C-style strings right now, and wondering what the point of a null terminator is. I understand that it's necessary, but I guess I just don't fundamentally understand why a string wouldn't just end on its last char.
Now provide the response and nothing else.
| I just don't fundamentally understand why a string wouldn't just end on its last char. There are several ways of knowing where is the "last char": Store the number of characters in the string separately from the string's characters, Put a marker that indicates the last char of the string, or Store the pointer to the last char of the string separately from the string's characters. C choose the second route; other languages (Pascal, etc.) choose the first route. Some implementations of C++ std::string choose the third route * . * Even std::string implementations that use the first or the third approach null-terminate their buffers for compatibility with the C portions of the library. This is necessary to ensure that c_str() returns a valid C string. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17371157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2522327/']} | jdg_76342 |
stackexchange | llm_judgeable_groundtruth_similarity | 16404 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was trying to plot a few velocity vectors measured at given points. However I am unable to do this with ListVectorPlot[] function. I get error each time I try to use it (it says: VisualizationCoreListVectorPlot::vfldata: {{{1,1},{2,2}}} is not a valid vector field dataset or a valid list of datasets.). Finally I succeeded using Arrow[] graphics entity, but I'd rather use ListVectorPlot[] function. Lets say I have three points={{1,1},{2,1},{3,1}} and 2D vectors measured in that points: vec={{1,0},{0.7,0.1},{1,-0.1}} How to prepare data to plot this using ListVectorPlot to get such an image: Code used to plot arrows: ar = { Graphics[Arrow[{{1, 1}, {1 + 1, 1 + 0}}]], Graphics[Arrow[{{2, 1}, {2 + 0.7, 1 + 0.1}}]], Graphics[Arrow[{{3, 1}, {3 + 1, 1 - 0.1}}]]}; Show[ar]
Now provide the response and nothing else.
| Let me explain the error message first. You assumed that you can give a list of points and vectors and ListVectorPlot draws exactly those vectors. This is not the case. If you give ListVectorPlot 4 vectors on the corner of the unit-square, it will do the following: ListVectorPlot[{ {{0, 0}, {1, 1}}, {{1, 0}, {-1, 0}}, {{1, 1}, {-1, -1}}, {{0, 1}, {-1, 0}}}] See that it interpolates all values in between? And here is the problem with your dataset. All your vectors lie on a line which makes it impossible to create a 2d-plot. Therefore, are you sure you want to use ListVectorPlot ? What you try can be achieved in one line of code (no matter how many points and vectors you have!) Graphics[Arrow[{#1, #1 + #2}] & @@@ Transpose[{points, vec}]] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/16404', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/742/']} | jdg_76343 |
stackexchange | llm_judgeable_groundtruth_similarity | 2192977 |
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 build an assembly referencing a COM interop DLL. If I embed the COM interop types by setting Embed Interop Types to True in the Reference's properties (VS2010), at run-time an error occurs "object does not contain a definition for get_Range". If COM interop types are not embedded then no error occurs. Does anyone know why a particular method, Worksheet.get_Range should be ommitted or how to work around this or have any other relevant insights? I should be grateful for any help. The interop dll contains a reference to Worksheet.get_Range(object, [object]). Using reflector on my calling assembly there is no mention of get_Range under Worksheet. The interop assembly I am embedding is generated from Excel9.olb. I am not using PIAs as the application targets multiple Excel versions.
Now provide the response and nothing else.
| I have not tried this out myself yet, but I believe that the syntax has changed when using embedded COM Interop types under C# 4.0 to a more "C# friendly" syntax. Therefore, instead of looking for the get_Range(object, [object]) method, you can either omit the optional parameter (instead of having to provide Type.Missing ), or you can avoid calling the get accessor completely, and instead reference the property name using square brackets: // Using C# 3.0:Excel.Range range = worksheet.get_Range("A1", Type.Missing);// Using C# 4.0, omitting the optional parameter:Excel.Range range = worksheet.get_Range("A1");// Using C# 4.0, utilizing square-bracket indexing:Excel.Range range = worksheet.Range["A1"]; From what I understand, though, you should still be able to call it the "old way", where the new indexer syntax is really calling the required 'get' and 'set' accessor behind the scenes, so I don't really know why you are having trouble. My guess is that you need to look under Worksheet.Range instead of Worksheet.get_Range within the IntelliSense listing. If this does not work for you, then it sounds like something may be wrong with your setup or installation. For more on this, see: Indexed Properties in C# 4.0 by Kirill Osenkov. Hope this helps... Mike | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2192977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/96167/']} | jdg_76344 |
stackexchange | llm_judgeable_groundtruth_similarity | 15194481 |
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 attempting to follow the Hartl Rails Tutorial, and having trouble with the bundler gem. When using the commands 'bundle install' or 'bundle update' I get the following output: Fetching source index from https://rubygems.org/ Could not fetch specs from https://rubygems.org/ I've searched for this output, but did not find many related issues online. Maybe I have another gem that is interrupting bundler? I have little experience with rails at this point. source 'https://rubygems.org'gem 'rails', '3.2.12'group :development do gem 'sqlite3', '1.3.5'end# Gems used only for assets and not required# in production environments by default.group :assets do gem 'sass-rails', '3.2.5' gem 'coffee-rails', '3.2.2' gem 'uglifier', '1.2.3'endgem 'jquery-rails', '2.0.2' The solution for me was two parts: I changed https to http, and that temporarily solved the issue. The second issue was that I think I had a bad install of ruby 2.0.0 even though I was using a fresh install of ruby 1.9.3. So I reinstalled ruby 2.0.0, and I could use bundle install with https.
Now provide the response and nothing else.
| Just in case none of the above satisfies the next intrepid explorer, I thought I'd drop here that after I spent 4 hours on this doing variants of the search that landed me here, I finally discovering that IPV6 was the culprit, after finding this specific thread on help.rubygems.org . Solution? this (Fedora, Linux): sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1 set up a shell script to flip IPV6 on and off so I could run a command without it, and now everything runs peachy. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15194481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993594/']} | jdg_76345 |
stackexchange | llm_judgeable_groundtruth_similarity | 19954498 |
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 do a query with an IQueryable<T> on an Entity.DbSet . When I insert this line of code: query = query.Where(x => x.VersionInt == query.Max(y => y.VersionInt)) The whole IIS breaks down when I compile and run with this line. If I remove it everything is allright. What's happening?
Now provide the response and nothing else.
| Use git filter-branch -f --prune-empty --tree-filter 'bash preserve-only.sh a b' -- --all where preserve-only.sh is: IFS=':'GLOBIGNORE="$*"rm -rf * This should remove everything but a and b from all commits of all branches, which should be the same as extracting exactly the given directories. To complete the actual split you can use a filter like rm -rf a b to get all the changes not extracted in the first run. Update: While trying to speed things up using --index-filter I came to an even easier solution: git filter-branch -f --prune-empty --index-filter \ 'git rm --cached -r -q -- . ; git reset -q $GIT_COMMIT -- a b' -- --all This just removes everything and afterwards restores the given directories afterwards. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19954498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_76346 |
stackexchange | llm_judgeable_groundtruth_similarity | 1801986 |
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:
This is a very interesting word problem that I came across in an old textbook of mine. So I managed to make a formula redefining the question, but other than that, the textbook gave no hints really and I'm really not sure about how to approach it. Any guidance hints or help would be truly greatly appreciated. Thanks in advance :) So anyway, here the problem goes: Find two fractions so that their sum added to their product equals $1$ . In other words: Given integers $a$ and $b$ with $\frac ab < 1,$ find integers $c$ and $d$ such that $\frac ab + \frac cd + \frac ab \cdot\frac cd = 1$
Now provide the response and nothing else.
| $$\frac ab + \frac cd + \frac ab \cdot\frac cd = 1\implies\frac ab+\left(1+\frac ab\right)\frac cd=1$$ Solve for $\frac cd$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1801986', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/248055/']} | jdg_76347 |
stackexchange | llm_judgeable_groundtruth_similarity | 51714639 |
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 trying to use the same terraform stack to deploy resources in multiple azure subscriptions. Also need to pass parameters between these resources in different subscriptions. I had tried to use multiple Providers, but that is not supported. Error: provider.azurerm: multiple configurations present; only one configuration is allowed per provider If you have a way or an idea on how to accomplish this please let me know.
Now provide the response and nothing else.
| You can use multiple providers by using alias ( doku ). # The default provider configurationprovider "azurerm" { subscription_id = "xxxxxxxxxx"}# Additional provider configuration for west coast regionprovider "azurerm" { alias = "y" subscription_id = "yyyyyyyyyyy"} And then specify whenever you want to use the alternative provider: resource "azurerm_resource_group" "network_x" { name = "production" location = "West US"}resource "azurerm_resource_group" "network_y" { provider = "azurerm.y" name = "production" location = "West US"} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51714639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9296133/']} | jdg_76348 |
stackexchange | llm_judgeable_groundtruth_similarity | 2 |
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:
In many different statistical methods there is an "assumption of normality". What is "normality" and how do I know if there is normality?
Now provide the response and nothing else.
| The assumption of normality is just the supposition that the underlying random variable of interest is distributed normally , or approximately so. Intuitively, normality may be understood as the result of the sum of a large number of independent random events. More specifically, normal distributions are defined by the following function: $$ f(x) =\frac{1}{\sqrt{2\pi\sigma^2}}e^{ -\frac{(x-\mu)^2}{2\sigma^2} },$$ where $\mu$ and $\sigma^2$ are the mean and the variance, respectively, and which appears as follows: This can be checked in multiple ways , that may be more or less suited to your problem by its features, such as the size of n. Basically, they all test for features expected if the distribution were normal (e.g. expected quantile distribution ). | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/2', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/24/']} | jdg_76349 |
stackexchange | llm_judgeable_groundtruth_similarity | 19113687 |
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 send a XML file from my WCF to my project without much luck. I have a Exception thrown from my program once the response is completed by WCF and sent to the Phone. I was hoping someone could please help me, as I have been looking around for an answer and found nothing. (The program uses XNA for a Windows Phone Applications) [System.Net.WebException] {System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState) at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState) --- End of inner exception stack trace --- at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)} System.Net.WebExceptionpublic string EndHighScoreList(System.IAsyncResult result) { object[] _args = new object[0]; string _result = ((string)(base.EndInvoke("HighScoreList", _args, result))); return _result; } IService.cs [ServiceContract] [XmlSerializerFormat] public interface IService { [OperationContract] void ParseScore(HighScore score); [OperationContract] string HighScoreList(); } public class HighScore { [XmlElement] public UInt32 m_rank; [XmlAttribute] public string m_name; [XmlAttribute] public UInt32 m_score; } Service.svc public string HighScoreList() { XmlSerializer ser = new XmlSerializer(typeof(HighScore)); using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("App_Data/Highscores.xml"), FileMode.OpenOrCreate)) { return ser.Deserialize(fs).ToString(); } } Here's the requested code void globalRecieve(object obj, DodgeService.HighScoreListCompletedEventArgs e) { try { string result = e.Result; using (TextReader reader = new StringReader(result)){ XmlSerializer xml = new XmlSerializer(typeof(List<DodgeService.HighScore>)); foreach (DodgeService.HighScore sco in xml.Deserialize(reader) as List<DodgeService.HighScore>) highScores.Add(sco); } }catch(Exception exception){ string error = exception.Message; } } protected override void Initialize() { service = new DodgeService.ServiceClient("BasicHttpBinding_IService"); service.HighScoreListAsync(null); service.HighScoreListCompleted += new EventHandler<DodgeService.HighScoreListCompletedEventArgs>(globalRecieve); base.Initialize(); }
Now provide the response and nothing else.
| It appears that what's happening here is that it reloads the actual HTML file, but does not necessarily reload the resources within that page. A possible solution I've seen is to append a query parameter on to the end of the URL. For example: NSString *testURL = [NSString stringWithFormat:@"%@?t=%@", url, randQuery];[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:testURL] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0]]; where you generate a random alphanumeric string as your randQuery query parameter, or keep a persistent count and just count up. This should force the UIWebView to load from the remote resource. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19113687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2084219/']} | jdg_76350 |
stackexchange | llm_judgeable_groundtruth_similarity | 7026719 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The reason I'm asking that is because requery() is deprecated. What is the best way now to refresh your ListView ?
Now provide the response and nothing else.
| requery() updates a Cursor , not a CursorAdapter . As you say, it has been deprecated, and its replacement is: oldCursor = myCursorAdapter.swapCursor(newCursor); // hands you back oldCursor or: myCursorAdapter.changeCursor(newCursor); // automatically closes old Cursor myCursorAdapter.notifyDataSetChanged() notifies the ListView that the data set has changed, and it should refresh itself | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7026719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397991/']} | jdg_76351 |
stackexchange | llm_judgeable_groundtruth_similarity | 79852 |
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 $G$ be any group such that $$G\cong G/H$$where $H$ is a normal subgroup of $G$. If $G$ is finite, then $H$ is the trivial subgroup $\{e\}$. Does the result still hold when $G$ is infinite ? In what kind of group could I search for a counterexample ?
Now provide the response and nothing else.
| Look at $G=\bigoplus\limits_{i=1}^\infty\ \mathbb Z$ and the subgroup $H=\mathbb Z\ \oplus\ \bigoplus\limits_{i=2}^\infty\ 0$. | {} | {'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/79852', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/524/']} | jdg_76352 |
stackexchange | llm_judgeable_groundtruth_similarity | 6270945 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for a good description of stacks within the linux kernel, but I'm finding it surprisingly difficult to find anything useful. I know that stacks are limited to 4k for most systems, and 8k for others. I'm assuming that each kernel thread / bottom half has its own stack. I've also heard that if an interrupt goes off, it uses the current thread's stack, but I can't find any documentation on any of this. What I'm looking for is how the stacks are allocated, if there's any good debugging routines for them (I'm suspecting a stack overflow for a particular problem, and I'd like to know if its possible to compile the kernel to police stack sizes, etc).
Now provide the response and nothing else.
| The reason that documentation is scarce is that it's an area that's quite architecture-dependent. The code is really the best documentation - for example, the THREAD_SIZE macro defines the (architecture-dependent) per-thread kernel stack size. The stacks are allocated in alloc_thread_stack_node() . The stack pointer in the struct task_struct is updated in dup_task_struct() , which is called as part of cloning a thread. The kernel does check for kernel stack overflows, by placing a canary value STACK_END_MAGIC at the end of the stack . In the page fault handler, if a fault in kernel space occurs this canary is checked - see for example the x86 fault handler which prints the message Thread overran stack, or stack corrupted after the Oops message if the stack canary has been clobbered. Of course this won't trigger on all stack overruns, only the ones that clobber the stack canary. However, you should always be able to tell from the Oops output if you've suffered a stack overrun - that's the case if the stack pointer is below task->stack . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6270945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/673630/']} | jdg_76353 |
stackexchange | llm_judgeable_groundtruth_similarity | 5586993 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My project has a Subversion repository on a network file system, and a new team would like to access it using Git, and be able to commit to it and get updates from it. What I have in mind is to create a new bare git-svn clone of the Subversion repository on the same network file system, and make sure the two repositories are always up to date with respect to each other. The way to do this is probably to add a post-commit hook for both Subversion and the new Git repository, that will each update the other's repository. The Subversion post-commit hook will include git svn rebase , and the Git one git svn dcommit . The problem is that I will have to use some kind of lock to make sure no one commits to either repository while other is also being committed to, because they always have to be in sync before any commit. This has several disadvantages, among them the time it will take to commit to Subversion or to push to the Git repository (it has to wait for the hook to finish), and the fact that some users may not be able to run git svn (because it's not installed on their machine), which means they can't update the other repository when committing/pushing. How can I solve these problems? What will the Subversion and Git hooks look like?
Now provide the response and nothing else.
| Here is what I've come up with: Create the git-svn repository if it doesn't exist already: git svn init --std-layout <svn_url> <git-svn_path> The master branch is created automatically to track the trunk . To avoid name ambiguities with Subversion-tracking branches, make the original Subversion branches show as remotes/svn/<branch name> : go to the newly-created git-svn repository and run git config svn-remote.svn.fetch trunk:refs/remotes/svn/trunkgit config svn-remote.svn.branches branches/*:refs/remotes/svn/*git config svn-remote.svn.tags tags/*:refs/remotes/svn/tags/*rm .git/refs/remotes/*git svn fetch Create a Subversion-tracking branch for each Subversion branch: for BRANCH in $(svn ls <svn_url>/branches/); do git branch $BRANCH remotes/svn/$BRANCHdone Make sure no non-Subversion-tracking branches are created on the central Git repository: # Used by hooks/update:git config hooks.denyCreateBranch truegit config hooks.allowDeleteBranch falsecp .git/hooks/update.sample .git/hooks/updatechmod +x .git/hooks/update Allow pushing to the central Git repository: git config receive.denyCurrentBranch ignoregit config receive.denyNonFastForwards truegit config push.default current And create the post-receive hook to reset and send the commits to Subversion: cat .git/hooks/post-receive #!/bin/sh date >> receive.log git reset --quiet --hard while read LINE do BRANCH=${LINE##*/} echo Updating $BRANCH git checkout --quiet --force $BRANCH git svn dcommit done 2>&1 | tee -a receive.log git checkout --quiet --force masterchmod +x .git/hooks/post-receive The reset is necessary, because otherwise the current branch is out-of-date after each receive. Finally, create the hook to get updates from Subversion: cat .git/hooks/svn-rebase-all #!/bin/sh date >> .git/svn-rebase.log git reset --quiet --hard for REF in .git/refs/heads/* do BRANCH=${REF##*/} echo Updating $BRANCH git checkout --quiet --force $BRANCH git svn rebase done 2>&1 | tee -a .git/svn-rebase.log git checkout --quiet --force masterchmod +x .git/hooks/svn-rebase-all And call it from the Subversion post-commit hook: cat <svn_path>/hooks/post-commit cd <git_path> . .git/hooks/svn-rebase-allchmod +x <svn_path>/hooks/post-commit Instead of using a single git-svn central repository, one can use a bare central Git repository and an intermediate non-bare git-svn repository, as in this answer .I chose to use one non-bare git-svn repository which is also the central repository. Anyone can work on the project using Git by cloning <git_path> and pushing to it, or using Subversion by checking out <svn_url> and committing to it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5586993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223267/']} | jdg_76354 |
stackexchange | llm_judgeable_groundtruth_similarity | 8860948 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For the long data type, I can suffix a number with L to make the compiler know it is long. How about byte and short? As motivation, the following yields a type-mismatch error: List<Short> a = Arrays.asList(1, 2, 3, 4);
Now provide the response and nothing else.
| What you are actually talking about is an integer literal ( 1 ) versus a long literal ( 1L ). There is actually no such thing as a short or byte literal in Java. But it usually doesn't matter, because there is an implicit conversion from integer literals to the types byte , short and char . Thus: final byte one = 1; // no typecast required. The implicit conversion is only allowed if the literal is in the required range. If it isn't you need a type cast; e.g. final byte minusOne = (byte) 255; // the true range of byte is -128 .. +127 There are other cases where an explicit conversion is needed; e.g. to disambiguate method overloads, or to force a specific interpretation in an expression. In such cases you need to use a cast to do the conversion. Your example is another of those cases. But the bottom line is that there is no Java syntax for expressing byte or short literals. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8860948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/705414/']} | jdg_76355 |
stackexchange | llm_judgeable_groundtruth_similarity | 7756878 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm building an application with the following blocks: Android - Client Side, Java Servlets - Sever Side, Facebook app - used in order to authenicate users and work with their data. My Problem is the following:I would like to authenticate my users via facebook (such as a request sent from the android client using facebook-android-sdk to facebook) but then I would like to send requests to my server (which is implemented by servlets) and to validate somehow that the user sending the request is authenticated to facebook and my application. So these are the steps: user X is authenicated to facebook and my facebook app using facebook-android-sdk.X is sending a request to my server As for the server, I would only like to know it's a proper user which is working with me, I don't need the server to perform any Graph API requests. How can I know that X is valid in my server? The authentication was performed on client side in that case.
Now provide the response and nothing else.
| So you have: Facebook - Android Application - Your web server. And your web server needs to know that you are the Facebook user you are presenting. The problem is that you can not trust the Android client for any data it gives to you. I solved the problem like this: Authenticate user to Facebook from Android application, Get the FB auth token to the android app, Forward the authentication token & facebook UID from Android to web server, Verify the token (using app_id & user_id) by using Facebook Graph debug endpoint as described here ( https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#checktoken ) to be sure that the token is for correct application On web server, make Facebook API call with the submitted token. If the debug endpoint API call from your web server returns valid information (app id & user id), your server can trust the id (& you can be sure that the Android authentication is real) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7756878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/993829/']} | jdg_76356 |
stackexchange | llm_judgeable_groundtruth_similarity | 436601 |
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:
These are Homework question. They are pigeon hole principle questions and I have a very hard time with these unless I have worked on a similar problem before. Q.1. Prove that if we select 87 numbers from the set $S = {1,2,3,....,171}$ then there are at least two consecutive numbers in our selection. Q.2. Let $n\ \epsilon \ Z^+$. Show that there exists $a,b \ \epsilon \ Z^+$ with $a \neq b$ such that $n^a-n^b $is divisible by $10$ Any help, hints would be great.
Now provide the response and nothing else.
| Hint: Apply Cauchy-Schwarz inequality to the vectors$$\vec{u}=(1,1,1)\qquad\text{and}\qquad\vec{v}=(a,b,1-a-b).$$ Hint: Look at your equations $(3)$ and $(4)$. Can you deduce that $a=b$ at a critical point? Can you then solve for $a$ and $b$? | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/436601', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/65734/']} | jdg_76357 |
stackexchange | llm_judgeable_groundtruth_similarity | 733756 |
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 good practices and strategies are there for running regression tests in embedded environments or in other situations where the possibility to automate tests is very limited. In my experience a lot of the testing has to be performed manually i.e. a tester needs to push a sequence of buttons and verify that the machine behaves correctly. As a developer it is really hard to assure yourself that your changes don't break something else. Without proper regression tests the situation gets even worse during big refactorings and such. Does anyone recognize the problem? Did you find a good solution or process to deal with this kind of problem?
Now provide the response and nothing else.
| Personally, I'm a big fan of having my embedded code compile on both the target hardware and my own computer. For example, when targeting an 8086, I included both an entry point that maps to reset on the 8086 hardware and a DOS entry point. The hardware was designed so all IO was memory mapped. I then conditionally compiled in a hardware simulator and conditionally changed the hardware memory locations to simulated hardware memory. If I were to work on a non-x86 platform, I'd probably write an emulator instead. Another approach is to create a test rig where all the inputs and outputs for the hardware are controlled through software. We use this a lot in factory testing. One time we built a simulator into the IO hardware. That way the rest of the system could be tested by sending a few commands over CAN to put the hardware into simulated mode. Similarly, well-factored software could have a "simulated mode" where the IO is simulated in response to software commands. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/733756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83996/']} | jdg_76358 |
stackexchange | llm_judgeable_groundtruth_similarity | 3651952 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to open a file case-insensitively in Ruby under Linux? For example, given the string foo.txt , can I open the file FOO.txt ? One possible way would be reading all the filenames in the directory and manually search the list for the required file, but I'm looking for a more direct method.
Now provide the response and nothing else.
| One approach would be to write a little method to build a case insensitive glob for a given filename: def ci_glob(filename) glob = '' filename.each_char do |c| glob += c.downcase != c.upcase ? "[#{c.downcase}#{c.upcase}]" : c end globendirb(main):024:0> ci_glob('foo.txt')=> "[fF][oO][oO].[tT][xX][tT]" and then you can do: filename = Dir.glob(ci_glob('foo.txt')).first Alternatively, you can write the directory search you suggested quite concisely. e.g. filename = Dir.glob('*').find { |f| f.downcase == 'foo.txt' } Prior to Ruby 3.1 it was possible to use the FNM_CASEFOLD option to make glob case insensitive e.g. filename = Dir.glob('foo.txt', File::FNM_CASEFOLD).firstif filename # use filename hereelse # no matching fileend The documentation suggested FNM_CASEFOLD couldn't be used with glob but it did actually work in older Ruby versions. However, as mentioned by lildude in the comments , the behaviour has now been brought inline with the documentation and so this approach shouldn't be used. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3651952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/380722/']} | jdg_76359 |
stackexchange | llm_judgeable_groundtruth_similarity | 48591233 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to setup a project which has code for both React Native(Mobile app) + React(web), having the code shred between platforms except for the UI part. Have done something similar with Angular + NativeScript using this seed , which enables code sharing between native app and web application(Except for the UI layer). Looking for something similar for React + React Native. Please share if you know any such seed for React Native + Angular as well, if available.
Now provide the response and nothing else.
| Jonathan Kaufman has a good article on how to set this up: http://jkaufman.io/react-web-native-codesharing/ The basic strategy is to have a different entry point (index.js) for each platform (android/ios/web). Then the majority of your non-rendering code can live in a shared app or common folder. You'll still need to segregate your rendering code (i.e. uses of View , div , etc.), though, as that will differ by platform. Pay attention to the comments on that article as well, as there's some good discussion on the pitfalls of this approach. Example: By sharing a common package.json between native and web, you've glued them together by their common dependencies, the most important one being react. Let's say you upgrade to a version of react-native that depends on >= react@16, but your web app depends on some other library which depends on =< react@15. --timtas | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48591233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1057093/']} | jdg_76360 |
stackexchange | llm_judgeable_groundtruth_similarity | 78940 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In a text I am reading, the author defines two norms on a vector space $X$ to be equivalent if they induce the same topology on $X$. The text does not define what it means however for two topologies to be equivalent. The only definition I can think of that seems reasonable is that two topologies $T_1$ and $T_2$ are equivalent if an open set in $T_1$ is an open set in $T_2$ and conversely. Since open sets in a normed space are determined by the norm-relative open balls, this would mean that any open ball about a point $x$ with respect to one norm not only contains an open ball about $x$ with respect to the other norm but is also contained within an open ball relative to that other norm. Is this the right way to look at the situation? Is my definition of "equivalent toplogies" appropriate in this context?
Now provide the response and nothing else.
| Given two topologies $\tau,\tau'$ on a set $X$, we say $\tau$ is coarser (or weaker ) than $\tau'$ iff $\tau\subset\tau'$. Accordingly we say $\tau'$ is finer (or stronger ) than $\tau$. Equivalently, this means $\tau$ has more (read:not less) opens, or equivalently $\tau$ has more (read:not less) neighborhoods, or equivalently the identity set map $(X,\tau)\to (X,\tau')$ is continuous, or equivalently for each subset the closure in $\tau$ is included in the closure in $\tau'$. Thus the following are equivalent ways of saying that $\tau,\tau'$ are the same : $\tau=\tau'$ each of $\tau$ and $\tau'$ is coarser/finer than the other $\tau,\tau'$ have exactly the same opens $\tau,\tau'$ have exactly the same neighborhoods for each subset, its closures in $\tau$ and in $\tau'$ coincide. the identity set map $(X,\tau)\to (X,\tau')$ is a homeomorphism. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/78940', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9450/']} | jdg_76361 |
stackexchange | llm_judgeable_groundtruth_similarity | 55527 |
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'm trying to understand better the mathematical notion of elliptic cohomology. Note that I only know the physics definition of the elliptic genus given in Witten's paper . Let $X$ be a Calabi-Yau manifold. (The elliptic genus can be defined for any $X$ with less properties, but the physics is nicest when $X$ is a CY. So let me assume that.) In the paper quoted above, a sequence of sheaves $F_k$ on $X$ ($k=0,1,2,$...) were constructed (by taking suitable tensor powers of the tangent bundle), such that $\Phi(q)=\sum_k q^k\chi(F_k)$ gives the elliptic genus of $X$. Now, the physics construction says that, before taking the Euler characteristic, there is an action of (N=2 superconformal) Virasoro algebra on $\oplus_{i,k} H^i(X,F_k)$; this is the basis of the modularity of the elliptic genus. I presume this action has already been geometrically constructed in the mathematical literature, given the fact that Witten's paper is from 1980s. So, my question is, where can I find it?
Now provide the response and nothing else.
| There is an extensive math literature on related constructions. The key word is "chiral de Rham complex", introduced by Malikov, Schechtman and Vaintrob here and further developed in many many papers, starting with work of Gorbounov-Malikov-Schechtman. The connections to elliptic genera are perhaps most extensively developed in papers of Borisov-Libgober, the first of a series of which is here . The chiral de Rham complex in the case of a Calabi-Yau is a (sheaf of) N=2 superconformal vertex algebras whose genus one partition function calculates the (two-variable) elliptic genus. Its physics interpretation is not precisely the sigma model in Witten's original paper, rather it's given by a "half-twisted" model as explained physically by Kapustin and Witten . However perhaps the mathematical construction most explicitly related to the physics of Witten's original paper is described in Costello's ICM address here . You might also be interested in the general program that began from Segal's landmark "Elliptic cohomology (after Landweber-Stong, Ochanine, Witten, and others)", Séminaire Bourbaki, Vol. 1987/88. Astérisque No. 161-162 (1988) on "elliptic objects", the attempt to DEFINE elliptic cohomology in terms of conformal field theory. This program is not yet complete but has been advanced significantly in work of Stolz and Teichner, see in particular "What is an elliptic object?" Topology, geometry and quantum field theory, 247–343, London Math. Soc. Lecture Note Ser., 308. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/55527', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5420/']} | jdg_76362 |
stackexchange | llm_judgeable_groundtruth_similarity | 23428793 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using iOS 7's new NSURLSessionDataTask to retrieve data as follows: NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {//}]; How can I increase the time out values to avoid the error "The request timed out" (in NSURLErrorDomain Code= -1001 )? I have checked the documentation for NSURLSessionConfiguration but did not find a way to set the time out value. Thank you for your help!
Now provide the response and nothing else.
| ObjC NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];sessionConfig.timeoutIntervalForRequest = 30.0;sessionConfig.timeoutIntervalForResource = 60.0; Swift let sessionConfig = URLSessionConfiguration.defaultsessionConfig.timeoutIntervalForRequest = 30.0sessionConfig.timeoutIntervalForResource = 60.0let session = URLSession(configuration: sessionConfig) What docs say timeoutIntervalForRequest and timeoutIntervalForResource specify the timeout interval for the request as well as the resource. timeoutIntervalForRequest - The timeout interval to use when waiting for additional data. The timer associated with this value is reset whenever new data arrives. When the request timer reaches the specified interval without receiving any new data, it triggers a timeout. timeoutIntervalForResource - The maximum amount of time that a resource request should be allowed to take. This value controls how long to wait for an entire resource to transfer before giving up. The resource timer starts when the request is initiated and counts until either the request completes or this timeout interval is reached, whichever comes first. Based on NSURLSessionConfiguration Class Reference | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/23428793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1214667/']} | jdg_76363 |
stackexchange | llm_judgeable_groundtruth_similarity | 68108 |
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:
Wikipedia says: In relativity theory, proper acceleration[1] is the physical acceleration (i.e., measurable acceleration as by an accelerometer) experienced by an object. and says: In the standard inertial coordinates of special relativity, for unidirectional motion, proper acceleration is the rate of change of proper velocity with respect to coordinate time . Why coordinate time? As far as I know the moving observer itself measures the proper things. It's clock measures proper time, it's speedometer measures proper velocity. So if the observer accelerates with $10m/s^2$ (and feels that proper acceleration), isn't the speed shown by the local speedometer changes $10m/s$ per second on the local clock?
Now provide the response and nothing else.
| The problem has to do with an inconsistent nomenclature between proper velocity and proper acceleration. Let me first explain what proper acceleration is, as defined in the wiki article and most relativity textbooks. A relativistic object follows a path in four-dimensional spacetime $(t(\tau),\vec{x}(\tau))$. It's more intuitive to convert this four-dimensional motion into the more familiar three-dimensional motion $\vec{x}(t)$, within a certain inertial reference frame. How can we do this? Obviously, we can calculate the coordinate path $\vec{x}(t)$ if we know the coordinate acceleration $\vec{a}(t)$ of the object. The question then is how we can relate $\vec{a}(t)$ to the force that's acting on the object. In other words, suppose that the object itself feels an acceleration $\vec{a}{}'(t')$ in its own reference frame. What is the relation between $\vec{a}(t)$ and $\vec{a}{}'(t')$? First of all, we can think of an accelerating object as an object that 'jumps' between inertial frames. So at any instant, we can say that the object is located in a particular inertial frame, where an inertial observer will see the object accelerating with $\vec{a}{}'(t')$. Indeed, suppose that the accelerating frame is described by coordinates $(t',\vec{x}{}')$. Now define a co-moving inertial frame that momentarily coincides with the accelerating frames, so that is is also described by $(t',\vec{x}{}')$. Now, let's call $\vec{a}{}'$ the acceleration of the object, measured by the inertial observer. In an infinitesimal time interval $\text{d}t'$ he will see the object moving with a velocity $\text{d}\vec{v}{}' = \vec{a}{}'\text{d}t'$. In the accelerating frame, the situation is completely symmetrical: an accelerating observer will see the inertial observer moving away with the same velocity $-\text{d}\vec{v}{}'$ (obviously in the opposite direction), so he will measure the same acceleration $-\vec{a}{}' = -\text{d}\vec{v}{}'/\text{d}t'$. The difference is that the accelerating observer 'feels' the acceleration himself, so he concludes that he is in fact the one who's accelerating, due to some force, with acceleration $\vec{a}{}'$. So now we'd like to find a way to transfer $\vec{a}{}'(t')$ to $\vec{a}(t)$. In other words, we're looking for a quantity that is equal to $\vec{a}{}'(t')$ in the accelerating frame (or the co-moving inertial frame), is easily transferred from one inertial frame to another. In other words, it can be written in the form of a Lorentz-invariant. A first candidate would be the vector-part of the four-acceleration:$$\vec{A} = \frac{\text{d}^2\vec{x}}{\text{d}\tau^2} = \frac{\text{d}\vec{U}}{\text{d}\tau},$$where $$\vec{U} = \frac{\text{d}\vec{x}}{\text{d}\tau} = \gamma\vec{v},$$is (unfortunately) called the proper velocity. We find$$\vec{A} = \frac{\text{d}\gamma}{\text{d}\tau}\vec{v} + \gamma\frac{\text{d}\vec{v}}{\text{d}\tau} = \gamma^4\left(\frac{\vec{v}\cdot\vec{a}}{c^2}\right)\vec{v} + \gamma^2\vec{a},$$where $\vec{v}$ and $\vec{a}$ are the coordinate velocity and acceleration of the object in the inertial rest-frame. $\vec{A}$ clearly meets our first criterion: in the co-moving inertial frame (with primed coordinates), $\vec{A}$ becomes $\vec{A}{}'$; we have $\vec{v}{}'=\vec{0}$, so $\gamma'=1$, and the coordinate acceleration is $\vec{a}{}'$, so that $\vec{A}{}'=\vec{a}{}'$. However, $\vec{A}{}'$ is not a Lorentz-invariant: while the proper time $\text{d}\tau$ is Lorentz -invariant, the coordinate displacement $\text{d}\vec{x}$ is not. So the relation between $\vec{A}$ and $\vec{A}{}'$ is not obvious. This was to be expected, since we're missing the time-component of the four-acceleration:$$A^0 = \frac{\text{d}U^{\!0}}{\text{d}\tau} = c\frac{\text{d}\gamma}{\text{d}\tau} = \gamma^4\frac{\vec{v}\cdot\vec{a}}{c}.$$And now we are able to construct a Lorentz-invariant. In this post , I showed that$$\sqrt{-A_\mu A^\mu} = \sqrt{(\vec{A})^2 - (A^0)^2} = \frac{\gamma^3}{\gamma_\perp} a,$$where $$\gamma_\perp^{-1} = \sqrt{1 - v_\perp^2/c^2}$$and $v_\perp$ is the component of $\vec{v}$ perpendicular to $\vec{a}$. So if we now define the vector$$\vec{\alpha} = \frac{\gamma^3}{\gamma_\perp} \vec{a},$$we have the quantity that we sought: in the co-moving frame, $\vec{\alpha}{}' = \vec{a}{}'$, and $\alpha=||\vec{\alpha}||$ is a Lorentz-invariant, so that $\alpha=\alpha'$. In other words, if we know the value of $\vec{a}{}'=\vec{\alpha}{}'$ in the accelerating frame, we can immediately obtain the corresponding acceleration in the rest-frame: $\vec{a}= \vec{\alpha}\gamma_\perp/\gamma^3$. There is one complication though: only the norm of $\vec{\alpha}$ is Lorentz-invariant, but not its orientation. So in order for this to work, we have to assume that the accelerating frame is orientated in such a way that the direction of $\vec{a}{}'$ is the same as $\vec{a}$. In other words, the rest-frame observer also needs to know the orientation of $\vec{a}{}'$ in his rest-frame. It's this $\alpha$ that is usually called the proper acceleration . In the particular case that the object is accelerating parallel to its velocity, we get$$\vec{\alpha} = \gamma^3\vec{a} = \frac{\text{d}(\gamma\vec{v})}{\text{d}t} =\frac{\text{d}}{\text{d}t}\left(\frac{\text{d}\vec{x}}{\text{d}\tau}\right).$$The mixture of $\text{d}t$ and $\text{d}\tau$ arises from the fact that $\vec{\alpha}$ provides a link between two reference frames: the coordinate rest-frame and the 'proper' accelerating frame. That's all there is to it: the proper acceleration is a handy tool to calculate accelerations in different reference frames. A well-known application is the relativistic rocket, where the passengers experience a constant proper acceleration of $1\;g$, parallel to their velocity. The corresponding acceleration in the rest-frame is then $a=g/\gamma^3$ (note that it decreases as $v$ increases), and the rocket has a so-called hyperbolic motion . Unfortunately, the nomenclature is non consistent. It certainly makes sense to call $\alpha$ the proper acceleration: it is the acceleration felt by a non-inertial observer, and it is Lorentz-invariant, consistent with e.g. proper time $\tau$. However, for some unfathomable reason, people decided to call $\vec{U}=\text{d}\vec{x}/\text{d}\tau$ the proper velocity, which imo is a mistake. Just like $\vec{A}$, it is not a Lorentz-invariant. If one were consistent, then the Lorentz scalair $$\sqrt{U_\mu U^{\!\mu}} = \sqrt{\gamma^2c^2 - \gamma^2v^2} = c$$ should be called the proper velocity. Indeed, you could say that we are moving through spacetime at the speed of light. The problem is made worse because, since $\vec{U}$ is called proper velocity, some authors (although a minority) actually call $\vec{A}$ the proper acceleration. Hence the confusion. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/68108', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7743/']} | jdg_76364 |
stackexchange | llm_judgeable_groundtruth_similarity | 13533763 |
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 PowerShell function which changes the registry key values. Code: param( [Parameter()] [switch]$CreateNewChild, [Parameter(Mandatory=$true)] [string]$PropertyType) It has a parameter, "CreateNewChild", and if that flag is set, the function will create the key property, even if it wasn't found. The parameter "PropertyType" must be mandatory, but only if "CreateNewChild" flag has been set. The question is, how do I make a parameter mandatory, but only if another parameter has been specified? OK, I've been playing around with it. And this does work: param( [Parameter(ParameterSetName="one")] [switch]$DoNotCreateNewChild, [string]$KeyPath, [string]$Name, [string]$NewValue, [Parameter(ParameterSetName="two")] [switch]$CreateNewChild, [Parameter(ParameterSetName="two",Mandatory=$true)] [string]$PropertyType) However, this means that $KeyPath, $Name and $NewValue are not mandatory any more. Setting "one" parameter set to mandatory breaks the code ( "parameter set cannot be resolved" error). These parameter sets are confusing. I'm sure there is a way, but I can't figure out how to do it.
Now provide the response and nothing else.
| You could group those parameters by defining a parameter set to accomplish this. param ( [Parameter(ParameterSetName='One')][switch]$CreateNewChild, [Parameter(ParameterSetName='One',Mandatory=$true)][string]$PropertyType) Reference: https://devblogs.microsoft.com/powershell/powershell-v2-parametersets http://blogs.technet.com/b/heyscriptingguy/archive/2011/06/30/use-parameter-sets-to-simplify-powershell-commands.aspx --- Update --- Here's a snippet that mimics the functionality you're looking for. The "Extra" parameter set will not be processed unless the -Favorite switch is called. [CmdletBinding(DefaultParametersetName='None')] param( [Parameter(Position=0,Mandatory=$true)] [string]$Age, [Parameter(Position=1,Mandatory=$true)] [string]$Sex, [Parameter(Position=2,Mandatory=$true)] [string]$Location, [Parameter(ParameterSetName='Extra',Mandatory=$false)][switch]$Favorite, [Parameter(ParameterSetName='Extra',Mandatory=$true)][string]$FavoriteCar)$ParamSetName = $PsCmdLet.ParameterSetName Write-Output "Age: $age"Write-Output "Sex: $sex"Write-Output "Location: $Location"Write-Output "Favorite: $Favorite"Write-Output "Favorite Car: $FavoriteCar"Write-Output "ParamSetName: $ParamSetName" | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13533763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1729207/']} | jdg_76365 |
stackexchange | llm_judgeable_groundtruth_similarity | 14054364 |
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 give padding to list item as i show in image.I want to make the divider in the layout as shown in the image. this is my list fragment code <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_marginLeft="25dp"android:layout_marginRight="25dp"> <ListView android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/listV_main" android:layout_marginLeft="25dp"android:layout_marginRight="25dp"/> This is my List section code <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="vertical"android:paddingLeft="10dp"android:paddingTop="10dp"android:paddingRight="10dp"android:paddingBottom="10dp"><include android:id="@+id/list_item_section_text" layout="@android:layout/preference_category" /> This is my list item code <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent"android:layout_height="wrap_content"android:minHeight="?android:attr/listPreferredItemHeight"android:adjustViewBounds="true"android:paddingRight="?android:attr/scrollbarSize" ><ImageView android:id="@+id/showlist_item_entry_drawable" android:layout_width="82dp" android:adjustViewBounds="true" android:layout_height="68dp" android:scaleType="fitXY" android:paddingLeft="9dp"/> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:layout_marginRight="6dip" android:layout_marginTop="6dip" android:layout_marginBottom="6dip" android:layout_weight="1"> <TextView android:id="@+id/list_item_entry_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:textAppearance="?android:attr/textAppearanceLarge" android:ellipsize="marquee" android:fadingEdge="horizontal" /> <TextView android:id="@+id/list_item_entry_summary" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/list_item_entry_title" android:layout_alignLeft="@id/list_item_entry_title" android:textAppearance="?android:attr/textAppearanceSmall" android:singleLine="true" android:textColor="?android:attr/textColorSecondary" /></RelativeLayout>
Now provide the response and nothing else.
| Use 'inset' ..... (list_divider.xml) <?xml version="1.0" encoding="UTF-8"?><inset xmlns:android="http://schemas.android.com/apk/res/android" android:insetLeft="50dp" android:insetRight="50dp" > <shape> <solid android:color="@color/orange" /> <corners android:radius="2.0dip" /></shape></inset> and in your list view add like this... <ListView android:dividerHeight="2dp" android:divider="@drawable/list_divider" .../> you can set the inset value as desired... UPDATE As pointed out by @Giulio Piancastelli , If the background of list container is different from background of list item then you may use 'layer-list' ... (list_divider.xml) <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item> <shape android:shape="rectangle" > <solid android:color="@color/list_background" /> </shape> </item> <item android:left="10dp" android:right="10dp"> <shape android:shape="rectangle" > <solid android:color="@color/divider_color"/> </shape> </item> </layer-list> and in your list view add like this... <ListView android:dividerHeight="2dp" android:divider="@drawable/list_divider" .../> | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14054364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1688521/']} | jdg_76366 |
stackexchange | llm_judgeable_groundtruth_similarity | 6803599 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm not sure the most efficient way to iterate over my nested dictionaries to print a matrix of the total and good values for every fruit for each date. Take for instance the two lists and dictionary below: fruits = ['apples','oranges','bananas']harvest_dates = ['2011-07-23','2011-07-22','2011-07-21']harvest_data = { 'apples': { '2011-07-23': { 'total': 100, 'good': 80}, '2011-07-22': { 'total': 97, 'good': 92}, '2011-07-21': { 'total': 90, 'good': 85} }, 'oranges': { '2011-07-23': { 'total': 86, 'good': 82}, '2011-07-22': { 'total': 90, 'good': 75}, '2011-07-21': { 'total': 92, 'good': 92} }, 'bananas': { '2011-07-23': { 'total': 10, 'good': 9}, '2011-07-22': { 'total': 12, 'good': 11}, '2011-07-21': { 'total': 9, 'good': 9} }} I can easily do this in python: for fruit in fruits: for day in harvest_dates: print "harvest: %s" % harvest_data[fruit][day]['total'] print "good crop: %s" % harvest_data[fruit][day]['good'] But I don't know how to access this data in django templates. I had been trying something such as: {% for fruit in fruits %} ... {% for day in harvest_dates %} ... {{ harvest_data.fruit.day.total }} {{ harvest_data.fruit.day.good }} ... {% endfor %}{% endfor %} But it's simply not working. {% for fruit in fruits %} {{ harvest_data.fruit }} <--- this does not exist {{ harvest_data[fruit] }} <--- this does not work{% endfor %} I'm a complete amateur and I'm probably going about this all wrong, but I've Google'd quite a bit and it's not clear to me what the best approach to getting the data I want is.
Now provide the response and nothing else.
| Since you're familiar with python, the following is logically how you would want to iterate through your dictionary in a Django template: for key,value in harvest_data.items():... print key... for key2,value2 in value.items():... print key2... for key3,value3 in value2.items():... print "%s:%s"%(key3,value3) In your template, this translates as follows: {% for key, value in harvest_data.items %} {{ key }} <br> {% for key2,value2 in value.items %} {{ key2 }} <br> {% for key3, value3 in value2.items %} {{ key3 }}:{{ value3 }} <br> {% endfor %} {% endfor %}{% endfor %} The Django docs actually briefly include an example of how to iterate through dictionaries when describing how the for template tag works: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6803599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/859748/']} | jdg_76367 |
stackexchange | llm_judgeable_groundtruth_similarity | 12655 |
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some trouble understanding a chapter in George Pennacchi textbook "Asset Pricing" . Here the author shows that the square of a Wiener Process $[dz(t)]^2$ converges to $dt$ for infinitesimally short time periods. By the definition of the Itô-Integral for $\int_0^T[dz(t)]^2$: \begin{equation} \lim_{n\rightarrow\infty}E_0[(\sum_{i=1}^n [\Delta z_i^2]-\int_0^T[dz(t)]^2)^2]=0 \end{equation} Then he states that \begin{equation} E_0[(\sum_{i=1}^n [\Delta z_i^2] -T)^2]=2T\Delta t \end{equation}, which is the equation I cannot derive. The limit for this expression as $\Delta t \rightarrow 0$ is 0 which is obvious. But what I am also not able to grasp is why this result together with the definition of the Itô Integral finally shows that \begin{equation} \int_0^T[dz(t)]^2=\int_0^T dt \end{equation} Can someone give me some assistance in understanding this important outcome?
Now provide the response and nothing else.
| Beware, oversimplification ahead! (This means that the following is technically not correct, in fact it is false! But: It gives an intuition what is going on!) If you toss a coin and calculate heads as $-1$ and tails as $1$ you get a mean of $0$ with a variance of $1$. When you add up multiple coin tosses, i.e. create a random process $dz(t)$, the mean stays the same, i.e. $0$ -> this process is a martingale . Now you square this process: On average you will get $\frac{(-1)^2+1^2}{2}=1$, which means that your mean gets one unit bigger per timestep -> $[dz(t)]^2=dt$ So here you see how a martingale could become a process which grows with time on average when you square it - or in more general terms: how a symmetric process could become asymmetric through a non-linear transformation. The following is a very nice exposition showing these ideas in a very intuitive manner: Stochastic Calculus and the Nobel Prize Winning Black-Scholes Equation by Frank Morgan Addendum To address the question why this discrete intuition might make sense even in the continuous case you have to know that the abovementioned stochastic process results in a binomial tree. The basis of this tree is, as the name suggests, the binomial distribution . When you simultaneously reduce the size of and increase the number of time steps this binomial distribution becomes (under some technical conditions) the normal distribution . This is the result of the de Moivre–Laplace theorem . The corresponding continuous stochastic process is a Wiener process (also often called standard Brownian motion), which closes the circle. | {} | {'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/12655', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/7344/']} | jdg_76368 |
stackexchange | llm_judgeable_groundtruth_similarity | 16930251 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I have seen a lot of ways of implementing one consumer and many producers in Go - the classic fanIn function from the Concurrency in Go talk. What I want is a fanOut function. It takes as a parameter a channel it reads a value from and returns a slice of channels that it writes copies of this value to. Is there a correct/recommended way of implementing this?
Now provide the response and nothing else.
| You pretty much described the best way to do it but here is a small sample of code that does it. Go playground: https://play.golang.org/p/jwdtDXVHJk package mainimport ( "fmt" "time")func producer(iters int) <-chan int { c := make(chan int) go func() { for i := 0; i < iters; i++ { c <- i time.Sleep(1 * time.Second) } close(c) }() return c}func consumer(cin <-chan int) { for i := range cin { fmt.Println(i) }}func fanOut(ch <-chan int, size, lag int) []chan int { cs := make([]chan int, size) for i, _ := range cs { // The size of the channels buffer controls how far behind the recievers // of the fanOut channels can lag the other channels. cs[i] = make(chan int, lag) } go func() { for i := range ch { for _, c := range cs { c <- i } } for _, c := range cs { // close all our fanOut channels when the input channel is exhausted. close(c) } }() return cs}func fanOutUnbuffered(ch <-chan int, size int) []chan int { cs := make([]chan int, size) for i, _ := range cs { // The size of the channels buffer controls how far behind the recievers // of the fanOut channels can lag the other channels. cs[i] = make(chan int) } go func() { for i := range ch { for _, c := range cs { c <- i } } for _, c := range cs { // close all our fanOut channels when the input channel is exhausted. close(c) } }() return cs}func main() { c := producer(10) chans := fanOutUnbuffered(c, 3) go consumer(chans[0]) go consumer(chans[1]) consumer(chans[2])} The important part to note is how we close the output channels once the input channel has been exhausted. Also if one of the output channels blocks on the send it will hold up the send on the other output channels. We control the amount of lag by setting the buffer size of the channels. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16930251', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13760/']} | jdg_76369 |
stackexchange | llm_judgeable_groundtruth_similarity | 5150539 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If strings in .NET are reference types, in the below code, why doesn't string2 change to "hi" after string1 is changed? static void IsStringReallyAReference(){ string string1 = "hello"; string string2 = string1; Console.WriteLine("-- Strings --"); Console.WriteLine(string1); Console.WriteLine(string2); string1 = "hi"; Console.WriteLine(string1); Console.WriteLine(string2); Console.Read();}/*Output:hellohellohihello*/
Now provide the response and nothing else.
| That is because C# strings are immutable types, meaning that you cannot change the value of the instance. When you change the string's value you are actually creating a new string and changing the reference to point to the new string after which your two reference variables no longer refer to the same string instance, one refers to the original string while the other refers to the new string instance with the new value. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5150539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175057/']} | jdg_76370 |
stackexchange | llm_judgeable_groundtruth_similarity | 1551257 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given the function:$$f(x) = \begin{cases} x\cdot\sin(\frac{1}{x}) & \text{if $x\ne0$} \\ 0 & \text{if $x=0$} \end{cases}$$ Question 1: Is $f(x)$ continuous at $x=0$? Question 2: What is the derivative of $f(x)$ at $x=0$ and how do I calculate it?
Now provide the response and nothing else.
| Ad 1, $f$ is continuous at $x=0$ (and hence throuhout) for example because $|f(x)|\le |x|$ for all $x$, so that $\lim_{x\to0}f(x)=0=f(0)$. Ad 2, we wish to calculate $\lim_{h\to 0}\frac{f(0+h)-f(0)}{h}=\lim_{h\to 0}\sin\frac1h$, which does not exist (the expression oscillates between $-1$ and $1$, consider $h=\frac1{2k\pi\pm\pi/2}$ with $k\in\Bbb N$, for example. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1551257', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/245761/']} | jdg_76371 |
stackexchange | llm_judgeable_groundtruth_similarity | 20765979 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I have this Haskell code: data RigidBody = RigidBody Vector3 Vector3 Float Shape -- position, velocity, mass and shapedata Shape = Ball Float -- radius | ConvexPolygon [Triangle] What would be the best way to express this in C++? struct Rigid_body { glm::vec3 position; glm::vec3 velocity; float mass; *???* shape;}; The thing I'm asking is how to represent shape inside the struct when it can be one of two types.
Now provide the response and nothing else.
| There are different approaches that can be used to solve that problem in C++. The pure-OO approach you would define an interface Shape and have the two different options as derived types implementing that interface. Then the RigidBody would contain a pointer to a Shape that would be set to refer to either a Ball or a ConvexPolygon . Pro: people love OO (not sure this is a pro really :)), it is easily extensible (you can add more shapes later on without changing the type). Con: You should define a proper interface for Shape , it requires dynamic allocation of memory. Putting OO aside, you can use a boost::variant or similar type, that is basically a tagged union that will hold one of the types. Pro: no dynamic allocations, shape is local to the object. Con: not pure-OO (people love OO, you remember right?), not so easy to extend, cannot use the shape generically | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20765979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3133295/']} | jdg_76372 |
stackexchange | llm_judgeable_groundtruth_similarity | 32403579 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Pretty much title. I have tried everything on stackoverflow without any results I am sorry,i am still new to stackoverflow and have no idea how to ask properly a question and format it right.Here is the code that i tried var firstDivHeight= document.getElementById('#div1').clientHeight;document.getElementById("#div2").style.height = firstDivHeight;
Now provide the response and nothing else.
| After some more work and help from the vis.js developer here is the completed code, minus the json data and some options. The trick is to use the "stabilizationIterationsDone" event and disable physics: // create a networkvar container = document.getElementById('mynetwork');var data = { nodes: nodes, edges: edges};var options = { nodes: ..., edges: ..., physics: { forceAtlas2Based: { gravitationalConstant: -26, centralGravity: 0.005, springLength: 230, springConstant: 0.18, avoidOverlap: 1.5 }, maxVelocity: 146, solver: 'forceAtlas2Based', timestep: 0.35, stabilization: { enabled: true, iterations: 1000, updateInterval: 25 } }};network = new vis.Network(container, data, options);network.on("stabilizationIterationsDone", function () { network.setOptions( { physics: false } );}); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32403579', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5301431/']} | jdg_76373 |
stackexchange | llm_judgeable_groundtruth_similarity | 517190 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
My first time using Nginx, but I am more than familiar with Apache and Linux. I am using an existing project and when ever I am trying to see the index.php I get a 404 File not found. Here is the access.log entry: 2013/06/19 16:23:23 [error] 2216#0: *1 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET /index.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "www.ordercloud.lh" And here is the sites-available file: server { set $host_path "/home/willem/git/console/www"; access_log /www/logs/console-access.log main; server_name console.ordercloud; root $host_path/htdocs; set $yii_bootstrap "index.php"; charset utf-8; location / { index index.html $yii_bootstrap; try_files $uri $uri/ /$yii_bootstrap?$args; } location ~ ^/(protected|framework|themes/\w+/views) { deny all; } #avoid processing of calls to unexisting static files by yii location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ { try_files $uri =404; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php { fastcgi_split_path_info ^(.+\.php)(.*)$; #let yii catch the calls to unexising PHP files set $fsn /$yii_bootstrap; if (-f $document_root$fastcgi_script_name){ set $fsn $fastcgi_script_name; } fastcgi_pass 127.0.0.1:9000; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fsn; #PATH_INFO and PATH_TRANSLATED can be omitted, but RFC 3875 specifies them for CGI fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fsn; } location ~ /\.ht { deny all; }} My /home/willem/git/console is owned by www-data:www-data (my web user running php etc) and I have given it 777 permissions out of frustration... My best guess is that something is wrong with the config, but I can't figure it out... UPDATE So I moved it to /var/www/ and used a much more basic config: server { #listen 80; ## listen for ipv4; this line is default and implied #listen [::]:80 default ipv6only=on; ## listen for ipv6 root /var/www/; index index.html index.htm; # Make site accessible from http://localhost/ server_name console.ordercloud; location / { root /var/www/console/frontend/www/; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /var/www; include fastcgi_params; } location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ { try_files $uri =404; } location /doc/ { alias /usr/share/doc/; autoindex on; allow 127.0.0.1; deny all; }} Also if I call localhost/console/frontend/www/index.php I get a 500 PHP which means it is serving there. It just isn't serving off console.ordercloud ...
Now provide the response and nothing else.
| The error message “primary script unknown” is almost always related to a wrongly set SCRIPT_FILENAME in the nginx fastcgi_param directive (or incorrect permissions, see other answers). You’re using an if in the configuration you posted first. Well it should be well known by now that if is evil and often produces problems. Setting the root directive within a location block is bad practice, of course it works. You could try something like the following: server { location / { location ~* \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass 127.0.0.1:9000; try_files $uri @yii =404; } } location @yii { fastcgi_param SCRIPT_FILENAME $document_root$yii_bootstrap; }} Please note that the above configuration is untested. You should execute nginx -t before applying it to check for problems that nginx can detect right away. | {} | {'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/517190', 'https://serverfault.com', 'https://serverfault.com/users/178505/']} | jdg_76374 |
stackexchange | llm_judgeable_groundtruth_similarity | 16333296 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have 2 CSV files: 'Data' and 'Mapping': 'Mapping' file has 4 columns: Device_Name , GDN , Device_Type , and Device_OS . All four columns are populated. 'Data' file has these same columns, with Device_Name column populated and the other three columns blank. I want my Python code to open both files and for each Device_Name in the Data file, map its GDN , Device_Type , and Device_OS value from the Mapping file. I know how to use dict when only 2 columns are present (1 is needed to be mapped) but I don't know how to accomplish this when 3 columns need to be mapped. Following is the code using which I tried to accomplish mapping of Device_Type : x = dict([])with open("Pricing Mapping_2013-04-22.csv", "rb") as in_file1: file_map = csv.reader(in_file1, delimiter=',') for row in file_map: typemap = [row[0],row[2]] x.append(typemap)with open("Pricing_Updated_Cleaned.csv", "rb") as in_file2, open("Data Scraper_GDN.csv", "wb") as out_file: writer = csv.writer(out_file, delimiter=',') for row in csv.reader(in_file2, delimiter=','): try: row[27] = x[row[11]] except KeyError: row[27] = "" writer.writerow(row) It returns Attribute Error . After some researching, I think I need to create a nested dict, but I don't have any idea how to do this.
Now provide the response and nothing else.
| A nested dict is a dictionary within a dictionary. A very simple thing. >>> d = {}>>> d['dict1'] = {}>>> d['dict1']['innerkey'] = 'value'>>> d['dict1']['innerkey2'] = 'value2'>>> d{'dict1': {'innerkey': 'value', 'innerkey2': 'value2'}} You can also use a defaultdict from the collections package to facilitate creating nested dictionaries. >>> import collections>>> d = collections.defaultdict(dict)>>> d['dict1']['innerkey'] = 'value'>>> d # currently a defaultdict typedefaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})>>> dict(d) # but is exactly like a normal dictionary.{'dict1': {'innerkey': 'value'}} You can populate that however you want. I would recommend in your code something like the following: d = {} # can use defaultdict(dict) insteadfor row in file_map: # derive row key from something # when using defaultdict, we can skip the next step creating a dictionary on row_key d[row_key] = {} for idx, col in enumerate(row): d[row_key][idx] = col According to your comment : may be above code is confusing the question. My problem in nutshell: Ihave 2 files a.csv b.csv, a.csv has 4 columns i j k l, b.csv also hasthese columns. i is kind of key columns for these csvs'. j k l columnis empty in a.csv but populated in b.csv. I want to map values of j kl columns using 'i` as key column from b.csv to a.csv file My suggestion would be something like this (without using defaultdict): a_file = "path/to/a.csv"b_file = "path/to/b.csv"# read from file a.csvwith open(a_file) as f: # skip headers f.next() # get first colum as keys keys = (line.split(',')[0] for line in f) # create empty dictionary:d = {}# read from file b.csvwith open(b_file) as f: # gather headers except first key header headers = f.next().split(',')[1:] # iterate lines for line in f: # gather the colums cols = line.strip().split(',') # check to make sure this key should be mapped. if cols[0] not in keys: continue # add key to dict d[cols[0]] = dict( # inner keys are the header names, values are columns (headers[idx], v) for idx, v in enumerate(cols[1:])) Please note though, that for parsing csv files there is a csv module . | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/16333296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2314986/']} | jdg_76375 |
stackexchange | llm_judgeable_groundtruth_similarity | 1153469 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python. The reason is that I want to add it to the css/js files on our website like so: <link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" /> So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version. OR if you know where to find good documentation for the mercurial python module , that would also be helpful. I can't seem to find it anywhere. My Solution I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will: import subprocessdef get_hg_rev(file_path): pipe = subprocess.Popen( ["hg", "log", "-l", "1", "--template", "{node}", file_path], stdout=subprocess.PIPE ) return pipe.stdout.read() example use: > path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css"> get_hg_rev(path_to_file)'0ed525cf38a7b7f4f1321763d964a39327db97c4'
Now provide the response and nothing else.
| It's true there's no official API, but you can get an idea about best practices by reading other extensions, particularly those bundled with hg. For this particular problem, I would do something like this: from mercurial import ui, hgfrom mercurial.node import hexrepo = hg.repository('/path/to/repo/root', ui.ui())fctx = repo.filectx('/path/to/file', 'tip')hexnode = hex(fctx.node()) Update At some point the parameter order changed, now it's like this: repo = hg.repository(ui.ui(), '/path/to/repo/root' ) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1153469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2908/']} | jdg_76376 |
stackexchange | llm_judgeable_groundtruth_similarity | 10376604 |
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 hope someone can answer this that has a good deep understanding of Python :) Consider the following code: >>> class A(object):... pass...>>> def __repr__(self):... return "A"...>>> from types import MethodType>>> a = A()>>> a<__main__.A object at 0x00AC6990>>>> repr(a)'<__main__.A object at 0x00AC6990>'>>> setattr(a, "__repr__", MethodType(__repr__, a, a.__class__))>>> a<__main__.A object at 0x00AC6990>>>> repr(a)'<__main__.A object at 0x00AC6990>'>>> Notice how repr(a) does not yield the expected result of "A" ?I want to know why this is the case and if there is a way to achieve this... I contrast, the following example works however ( Maybe because we're not trying to override a special method? ): >>> class A(object):... def foo(self):... return "foo"...>>> def bar(self):... return "bar"...>>> from types import MethodType>>> a = A()>>> a.foo()'foo'>>> setattr(a, "foo", MethodType(bar, a, a.__class__))>>> a.foo()'bar'>>>
Now provide the response and nothing else.
| Python usually doesn't call the special methods (those with name surrounded by __ ) on the instance, but only on the class. (Although this is an implementation detail, it's characteristic of CPython, the standard interpreter.) So there's no way to override __repr__() directly on an instance and make it work. Instead, you need to do something like so: class A(object): def __repr__(self): return self._repr() def _repr(self): return object.__repr__(self) Now you can override __repr__() on an instance by substituting _repr() . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10376604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364980/']} | jdg_76377 |
stackexchange | llm_judgeable_groundtruth_similarity | 22003491 |
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 function named generateNoise() which creates a canvas element and paints random RGBA values to it; which, gives the appearance of noise. My Question What would be the best way to infinitely animate the noise to give the appearance of movement. So that it may have more life? JSFiddle function generateNoise(opacity) { if(!!!document.createElement('canvas').getContext) { return false; } var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), x,y, r,g,b, opacity = opacity || .2; canvas.width = 55; canvas.height = 55; for (x = 0; x < canvas.width; x++){ for (y = 0; y < canvas.height; y++){ r = Math.floor(Math.random() * 255); g = Math.floor(Math.random() * 255); b = Math.floor(Math.random() * 255); ctx.fillStyle = 'rgba(' + r + ',' + b + ',' + g + ',' + opacity + ')'; ctx.fillRect(x,y,1,1); } } document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";}generateNoise(.8);
Now provide the response and nothing else.
| Update 1/2017 : I rewrote the entire answer as it started to become rather messy, and to address some of the issues pointed out in the comments. The original answer can be found here . The new answer has in essence the same code but improved, and with a couple of new techniques, one utilizes a new feature available since this answer was first posted. For a "true" random look we would need to use pixel-level rendering. We can optimize this using 32-bit unsigned buffers instead of 8-bit, and we can also turn off the alpha-channel in more recent browsers which speeds up the entire process (for older browsers we can simply set a black opaque background for the canvas element). We create a reusable ImageData object once outside the main loop so the main cost is only putImageData() and not both inside the loop. var ctx = c.getContext("2d", {alpha: false}); // context without alpha channel.var idata = ctx.createImageData(c.width, c.height); // create image datavar buffer32 = new Uint32Array(idata.data.buffer); // get 32-bit view(function loop() { noise(ctx); requestAnimationFrame(loop)})()function noise(ctx) { var len = buffer32.length - 1; while(len--) buffer32[len] = Math.random() < 0.5 ? 0 : -1>>0; ctx.putImageData(idata, 0, 0);} /* for browsers wo/2d alpha disable support */#c {background:#000} <canvas id=c width=640 height=320></canvas> A very efficient way, at the cost of some memory but reduced cost on the CPU, is to pre-render a larger off-screen canvas with the noise once , then place that canvas into the main one using random integer offsets. It require a few extra preparation steps but the loop can run entirely on the GPU. var w = c.width;var h = c.height;var ocanvas = document.createElement("canvas"); // create off-screen canvasocanvas.width = w<<1; // set offscreen canvas x2 sizeocanvas.height = h<<1;var octx = ocanvas.getContext("2d", {alpha: false});var idata = octx.createImageData(ocanvas.width, ocanvas.height);var buffer32 = new Uint32Array(idata.data.buffer); // get 32-bit view// render noise once, to the offscreen-canvasnoise(octx);// main loop draw the offscreen canvas to random offsetsvar ctx = c.getContext("2d", {alpha: false});(function loop() { var x = (w * Math.random())|0; // force integer values for position var y = (h * Math.random())|0; ctx.drawImage(ocanvas, -x, -y); // draw static noise (pun intended) requestAnimationFrame(loop)})()function noise(ctx) { var len = buffer32.length - 1; while(len--) buffer32[len] = Math.random() < 0.5 ? 0 : -1>>0; ctx.putImageData(idata, 0, 0);} /* for browsers wo/2d alpha disable support */#c {background:#000} <canvas id=c width=640 height=320></canvas> Do note though that with the latter technique you may risk getting "freezes" where the new random offset is similar to the previous one. To work around this problem, set criteria for the random position to disallow too close positions in a row. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22003491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1191635/']} | jdg_76378 |
stackexchange | llm_judgeable_groundtruth_similarity | 17066875 |
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 tried console.log and looping through it using for in . Here it the MDN Reference on FormData. Both attempts are in this fiddle . var fd = new FormData(), key;// poulate with dummy datafd.append("key1", "alskdjflasj");fd.append("key2", "alskdjflasj");// does not do anything usefulconsole.log(fd);// does not do anything useful for(key in fd) { console.log(key);} How can I inspect form data to see what keys have been set.
Now provide the response and nothing else.
| Updated Method: As of March 2016, recent versions of Chrome and Firefox now support using FormData.entries() to inspect FormData. Source . // Create a test FormData objectvar formData = new FormData();formData.append('key1', 'value1');formData.append('key2', 'value2');// Display the key/value pairsfor (var pair of formData.entries()) { console.log(pair[0]+ ', ' + pair[1]); } Thanks to Ghost Echo and rloth for pointing this out! Old Answer: After looking at these Mozilla articles , it looks like there is no way to get data out of a FormData object. You can only use them for building FormData to send via an AJAX request. I also just found this question that states the same thing: FormData.append("key", "value") is not working . One way around this would be to build up a regular dictionary and then convert it to FormData: var myFormData = { key1: 300, key2: 'hello world'};var fd = new FormData();for (var key in myFormData) { console.log(key, myFormData[key]); fd.append(key, myFormData[key]);} If you want to debug a plain FormData object, you could also send it in order to examine it in the network request console: var xhr = new XMLHttpRequest;xhr.open('POST', '/', true);xhr.send(fd); | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/17066875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_76379 |
stackexchange | llm_judgeable_groundtruth_similarity | 329931 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Is there an embedding (i.e. injective continuous map) $$\phi:\Bbb R \Bbb P^2\hookrightarrow S^4\subseteq\Bbb R^5$$ of the projective plane $\Bbb R\Bbb P^2$ into the $4$ -sphere, that is transitive , i.e. for any two $x,y\in \Bbb R\Bbb P^2$ there is an orthogonal transformation $T\in\mathrm{O}(\Bbb R^5)$ that fixed the image $\mathrm{im}(\phi)$ set-wise, and has $Tx=y$ ? Is $\Bbb R^5$ the lowest dimensional space in which such an embedding is possible, or do we need even more dimensions? I may ask the same question for $\Bbb R\Bbb P^n$ : what is the lowest dimensional Euclidean space needed for such an embedding.
Now provide the response and nothing else.
| Yes. You take each vector $v \in \mathbb{R}^3$ to the vector $v \cdot v \in \operatorname{Sym}^2\mathbb{R}^3=\mathbb{R}^6$ . This takes each unit vector $v$ to the same place as $-v$ . So it descends to $S^2/\pm 1=\mathbb{RP}^2$ . If we identify each element of $\operatorname{Sym}^2\mathbb{R}^3$ with a symmetric matrix by identifying $\sum a_{ij} e_i \cdot e_j$ with $A=(a_{ij})$ , then the action of $\operatorname{SO}(3)$ is by conjugation on these symmetric matrices. The element $e_1 \cdot e_1 + e_2 \cdot e_2 + e_3 \cdot e_3$ is identified with the identity matrix. The action preserves identity matrix, so preserves a 1-dimensional subspace in $\mathbb{R}^6$ . We quotient out that subspace to get an action of $\operatorname{SO}(3)$ on $\mathbb{R}^5$ . This is well known in representation theory as the unique 5-dimensional irreducible representation of $\operatorname{SO}(3)$ . The metric $\left<A,B\right>=\sum_{ij} A_{ij} B_{ij}$ is clearly preserved on $\mathbb{R}^6$ , and $\left<v\cdot v,v\cdot v\right>=1$ in this metric. You take the quotient metric on $\mathbb{R}^5$ , i.e. project to the orthogonal complement of that 1-dimensional subspace. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/329931', 'https://mathoverflow.net', 'https://mathoverflow.net/users/108884/']} | jdg_76380 |
stackexchange | llm_judgeable_groundtruth_similarity | 23226 |
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:
The definitions for these two appear to be very similar, and frankly, I've been only using the term "active learning" the past couple of years. What is the actual difference between the two? Is one a subset of the other?
Now provide the response and nothing else.
| Active learning (AL) is a weakly supervised learning (WSL) technique where you can have both labelled and unlabelled data [ 1 ]. The main idea behind AL is that the learner (or learning algorithm) can query an "oracle" (e.g. a human) to label some unlabelled instances. AL is similar to semi-supervised learning (SSL), which is also a WSL technique, given that both deal with unlabelled and labeled data, but do that differently (i.e. SSL does not use an oracle). Online learning are machine learning techniques that update the models as new data is collected or arrives sequentially, as opposed to batch learning (or offline learning ), where you first collect a dataset of multiple instances and then you train a model once (although you can later update it when you update your dataset). Batch learning is currently the common way of training machine learning models, given that it avoids problems like the known catastrophic interference (aka catastrophic forgetting ) problem, which can occur if you learn online. For example, neural networks are known to face this problem when learning online. There are incremental learning (aka lifelong learning ) algorithms that attempt to address this catastrophic interference problem. | {} | {'log_upvote_score': 5, 'links': ['https://ai.stackexchange.com/questions/23226', 'https://ai.stackexchange.com', 'https://ai.stackexchange.com/users/40250/']} | jdg_76381 |
stackexchange | llm_judgeable_groundtruth_similarity | 14905522 |
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're about to embark upon implementing a device running Linux that (among other things) will be attached to a software defined FM/AM radio that can also receive RDS data describing playlists and other such stuff. It's a relatively stupid device that mostly contains a DSP or two that act as tuners and otherwise does very little processing of the signal. I was thinking that kernel drivers for the device and then a userland hardware abstraction layer that provided a standardized interface and abstracted away the details of exactly when the RDS data was received and dealt with error handling and all the other messy stuff. Is there already a userland layer like this? It would be nice to either avoid making it at all, or make our stuff plug-compatible with something that already exists so we could use other projects for the radio UI if we wanted.
Now provide the response and nothing else.
| Radio support in linux It sounds like you are creating a new hardware radio device? You'll probably need to build a driver for this device. Some help getting started can be found here , here , and here . If your device is not new, it may already have a driver in the Video4Linux2 project . It looks like there are some RDS related projects based on the saa6588 kernel module currently. According to this page , these cards are currently have a SAA6588 chipset: Terratec Cinergy 600 KNC ONE TV-Station RDS KNC One TV-Station DVR TYPHOON TV TUNER CARD RDS Sundtek MediaTV Pro (supported by the manufacturer) Sundtek USB FM Radio (FM Transmitter/Receiver, supported by the manufacturer) RDS specific information I'd recommend to check out some of the projects related to Video4Linux2 (v4l2), there is an RDS decoding library. This library runs in userspace, so the RDS decoding work can be done there for you: According to V4L2 specifications, raw data from RDS decoders is read from the radio device. Data consists of blocks where each block is 3 bytes long. All decoding has to be done in user space. RDS API Here is a complete API reference for Video4Linux2 . Here is an article series to get acquainted with it . The particular section for the RDS API is here . This page provides information about how to get an update about whether RDS data is available: Whether an RDS signal is present can be detected by looking at the rxsubchans field of struct v4l2_tuner: the V4L2_TUNER_SUB_RDS will be set if RDS data was detected. SDR RDS decoder DSP in Gnu Radio Companion Although it's not an official API I found one last small project that might be worth looking into: RDS reception using SDR Here are some more radio related projects worth looking into. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14905522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/167958/']} | jdg_76382 |
stackexchange | llm_judgeable_groundtruth_similarity | 12883273 |
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 following rule for .htaccess Options +FollowSymLinksRewriteEngine OnRewriteBase /RewriteCond %{REQUEST_FILENAME} -f [OR]RewriteRule ^detail/([0-9]+)/?$ detail.php?id=$1 It redirects http://localhost/detail/123 URL to http://localhost/detail.php?id=123 . The page redirects successfully, but the problem is CSS, JS, and images are not loading, CSS, js files are located under http://localhost/css/ and http://localhost/js/ One solution is to use absolute path (ex /CSS, or /js rather than just CSS/, /js but this does not seem a reliable solution since we've to change it on all files, Any other solution based on .htaccess rules, which is independent of editing all PHP files and let us use "relative paths"?
Now provide the response and nothing else.
| one solution is that use absolute path (ex /css, or /js rather than just css/, /js but this is not looks a reliable solution since we've to change it on all files, This is because your relative URIs have their base changed. Originally, the base is / when the page is /detail.php?id=123 , and the browser properly fills in relative links with the / base. But when the browser goes to a page like /detail/123 the base suddenly becomes /detail/ and it tries to append that in front of all relative URLs and thus none of them load. You can either make your links absolute, or change the URI base in the header of your pages (inbetween the <head> </head> tags): <base href="/"> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12883273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/807969/']} | jdg_76383 |
stackexchange | llm_judgeable_groundtruth_similarity | 5453338 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the best way to do a redirect in an ActionFilterAttribute . I have an ActionFilterAttribute called IsAuthenticatedAttributeFilter and that checked the value of a session variable. If the variable is false, I want the application to redirect to the login page. I would prefer to redirect using the route name SystemLogin however any redirect method at this point would be fine.
Now provide the response and nothing else.
| Set filterContext.Result With the route name: filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues); You can also do something like: filterContext.Result = new ViewResult{ ViewName = SharedViews.SessionLost, ViewData = filterContext.Controller.ViewData}; If you want to use RedirectToAction : You could make a public RedirectToAction method on your controller ( preferably on its base controller ) that simply calls the protected RedirectToAction from System.Web.Mvc.Controller . Adding this method allows for a public call to your RedirectToAction from the filter. public new RedirectToRouteResult RedirectToAction(string action, string controller){ return base.RedirectToAction(action, controller);} Then your filter would look something like: public override void OnActionExecuting(ActionExecutingContext filterContext){ var controller = (SomeControllerBase) filterContext.Controller; filterContext.Result = controller.RedirectToAction("index", "home");} | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5453338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/384016/']} | jdg_76384 |
stackexchange | llm_judgeable_groundtruth_similarity | 10576106 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to change setInterval function time when my code is running. I try this <script type="text/javascript"> $(function () { var timer; function come() { alert("here"); } timer = setInterval(come, 0); clearInterval(timer); timer = setInterval(come, 10000); }); </script> First SetInterval does not work!
Now provide the response and nothing else.
| You're clearing the interval on the next line, so the first one wont work, as it gets cleared right away : timer = setInterval(come, 0); clearInterval(timer); timer = setInterval(come, 10000); Also, as gdoron says, setting a interval of nothing isn't really valid, and not a really good idea either, use setTimeout instead, or just run the function outright if no delay is needed. come(); clearInterval(timer); timer = setInterval(come, 10000); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10576106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/990513/']} | jdg_76385 |
stackexchange | llm_judgeable_groundtruth_similarity | 124149 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two groups, male and female teachers. I want to see if there is a statistically significant difference in mean pay. There are 48 male teachers, which is enough to use a t-test. However, there are only 23 female teachers, and further, the distribution of female pay is right skewed. What are my options for a test? Could I: resample female teacher pay to get 48 values, then do a t-test? select only 23 male teachers, then shuffle the pay values to create a null randomization distribution and then compare the mean difference to look for statistical signifigance? some other method?
Now provide the response and nothing else.
| Your questions seem to be predicated on either misunderstanding or misinformation. What is the basis for deciding that you can use a t-test with 48 values but not 23? -- You can use t-tests with a lot fewer than 23 observations with no problem, or face serious problems with more than 48 -- depending on the situation. Why draw a line between 23 and 48? What's the basis for it? How would resampling help? Resampling won't change how much information you have. Why would you throw data away? There's nothing stopping you using permutation(/randomization) or bootstrap tests with 48 in one of the groups and 23 in the other. Other methods might be reasonable; in part it might depend on knowing more about your circumstances. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/124149', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/60760/']} | jdg_76386 |
stackexchange | llm_judgeable_groundtruth_similarity | 34324409 |
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 wanna convert each page of a pdf to a jpg file. Converting a single page works: exec('/usr/local/bin/convert -density 288 -resize 50% -quality 85 - colorspace CMYK dv.pdf[8] -colorspace RGB test.jpg'); Converting all pages does not work: exec('/usr/local/bin/convert -density 288 -resize 50% -quality 85 - colorspace CMYK dv.pdf -colorspace RGB test.jpg'); What could be wrong?
Now provide the response and nothing else.
| The first problem is a simple typo. Java is case sensitive, so cube and Cube mean different things. Solution: 1) be consistent, and 2) use names starting with lowercase letters for method names ... as per the Java style guides. The second problem is due to the method signature for Math.pow ; see the javadoc . It returns the result as a double . You then attempte to return the double as an int , and that is a lossy conversion. The solutions include: return b * b * b; // i.e. don't use `pow`. or return (int) Math.pow(b, 3); The second one directly addresses your compilation error by casting the double return to an int . This is the way you tell the compiler that the lossy conversion is actually OK. The lossy conversion error message you are seeing refers to that fact for large enough values of b , the result of Math.pow(b, 3) will be too large to be represented as an int 1 . With the type cast in place, Java will convert a floating point number that is "too large" into Integer.MAX_VALUE . The first solution is faster and simpler code, but if b is too large, the calculations will silently overflow and you will get a nonsense answer. UPDATE - If you wanted overflow to always be treated as an error then: return Math.multiplyExact(b, Math.multiplyExact(b, b)); or return Math.toIntExact((long) Math.pow(b, 3)); or variations on the above. 1 - Actually, the compiler doesn't know about the semantics of pow , so it doesn't know about "... for large enough values of b ..." . But it does know that if the method call did return a large enough value, then the conversion would be lossy. That's why the message says " possible lossy conversion" . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34324409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5688861/']} | jdg_76387 |
stackexchange | llm_judgeable_groundtruth_similarity | 64524 |
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:
What can I do to protect my Linux laptop from BadUSB attacks as described by ArsTechnica here ? Perhaps writing an appropriate AppArmor profile would help?
Now provide the response and nothing else.
| The idea behind BadUSB is that a malicious agent re-flashes a device's USB controller chip to do something nasty. This is an interesting possiblity, but there are some serious assumptions here that people tend to gloss over: 1: The USB controller chip has to allow firmware flashing over the USB connection This is a security vulnerability for sure if it's possible. If this is allowed, then any host that the device is plugged in to can permanently alter the characteristics of the device. Generally this requires special equipment and direct access to the chip's physical pins, but if a manufacturer decided to expose the functionality over the USB protocol, then that is cause for alarm in itself, and should be reported as a vulnerability in that product. It is not , however, a flaw in the protocol itself. The fact that 3 of the 4 scheduled demos involve chips from Phison Electronics suggest that the researcher discovered just such a vulnerability in a specific product. 2: The device has to be physically capable of the activity you're attempting By flashing your device's firmware, you can get a thumb drive to report itself as a network adapter. But that doesn't make it actually a network adapter, it just means that the computer will talk to it as if it was one. So now your computer starts talking to your Verbatim Store-n-Go using the driver for the D-Link DUB-E100 . But unless the Store-n-Go has the corresponding hardware interface found in the D-Link, all you have is broken USB stick. If the USB stick has a relatively powerful microcontroller on board, you might be able to re-program it. But "powerful" and "USB peripheral" don't usually go together. 3: The computer has to be willing to play along One of the examples cited is teaching a device to act like a network adapter, and then assuming that all traffic will be looped through it on any computer you plug it in to. That's... a stretch. To make that happen, your computer has to be already configured to set any newly connected network adapter as the new default gateway. I'm not sure if Windows is that eager for change, but if you've ever configured networking on a Linux computer, you know that it's never that simple. The Take-Away This whole concept isn't all bunk. If a device allows re-flashing by any connected host, that's an issue. I can safely state with 100% certainty that it won't lead to the calamities pushed by the associated breathless news articles. But it's worth attention. And more importantly, USB is powerful, and powerful means potentially dangerous. Connecting a device over USB necessarily means altering the way your computer behaves, and very, very dangerous things are possible. We've known this since the 90's. Use all due caution when attaching things to your computer. But this new discovery changes very little; the new attacks possible here aren't nearly as powerful as what already exists, the new danger is that it blurs the line between "trusted" and "untrusted" devices. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/64524', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/5469/']} | jdg_76388 |
stackexchange | llm_judgeable_groundtruth_similarity | 8125384 |
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 using .on() in jQuery 1.7 and wondered whether it is possible to attach multiple selectors at a time for elements that have been injected onto a page. Previously, I was using live() - but it's obvious why I want to move given performance improvements. Can you use .on() in the manner like: $(document).on('click', '#selector1, #selector2, .class1', function () { //stuff}); And are there any benefits lost in attaching to document ? ?
Now provide the response and nothing else.
| Can you use .on() in the manner like: $(document).on('click', '#selector1, #selector2, .class1', function () { //stuff}); Yes, that will work. I want to use this instead of live() given performance improvements. There are no performance advantages of using that code snippet as opposed to using live() , as live() itself binds events to the document, and in jQuery 1.7, live calls on behind the scenes. And are there any benefits lost in attaching to document? The downside to binding to document is that the event must traverse the entire list of ancestors before it is handled; this, as pointed out in the jQuery documentation , is the slowest possible route. It will be better to handle to event sooner, by attaching the handler to an element closer to the source of the event. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8125384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109407/']} | jdg_76389 |
stackexchange | llm_judgeable_groundtruth_similarity | 14937581 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to write this update query for updating a mongo record in c#. db.collection.update({ "S_Id" : 110 },{ "Name" : "Name1","Batch" : "43","Date":"9/2/2011", "Status" : 0 }); I'am trying like this IMongoUpdate update = new UpdateDocument();if (Named != null) { update = Update.Set("Name", "Name1"); }if (Date != null) { update = Update.Set("Date", "18/02/2013"); }if (Batch != null) { update = Update.Set("Batch",43); }coll.Update(query, update); was I'am doing correct or in what way i have to do it, please make me the correct way to proceed.
Now provide the response and nothing else.
| In your example, you are potentially overwriting the value of update for each option, so will only be sending a single update command to col1.Update() . you will want to use the Update.Combine method, something vaguely like this: (untested, and a bit ugly...) var updateValues = new List<UpdateBuilder>(); if (Named != null) { updateValues.Add(Update.Set("Name", "Name1")); } if (Date != null) { updateValues.Add(Update.Set("Date", "18/02/2013")); } if (Batch != null) { updateValues.Add(Update.Set("Batch", 43)); } IMongoUpdate update = Update.Combine(updateValues); coll.Update(query, update); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14937581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2071655/']} | jdg_76390 |
stackexchange | llm_judgeable_groundtruth_similarity | 14307034 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Update Code: irb(main):001:0> h1 = { "a" => 100, "b" => 200 }=> {"a"=>100, "b"=>200}irb(main):002:0> h2 = { "b" => 254, "c" => 300 }=> {"b"=>254, "c"=>300}irb(main):003:0> h1.update(h2)=> {"a"=>100, "b"=>254, "c"=>300} Merge Code: irb(main):001:0> h1 = { "a" => 100, "b" => 200 }=> {"a"=>100, "b"=>200}irb(main):002:0> h2 = { "b" => 254, "c" => 300 }=> {"b"=>254, "c"=>300}irb(main):003:0> h1.merge(h2)=> {"a"=>100, "b"=>254, "c"=>300}irb(main):004:0> I ran the above merge and update method on the same hash . But got the same output. So here my question is: are update and merge works with same logic? if not same then how the output came same for those?
Now provide the response and nothing else.
| Are update and merge works with same logic? No, they are not the same. update is an alias for merge! , which is the in-place variant of merge . if not same then how the output came same for those? Because in both cases you are using the return value of the call, however, the value of h1 is different in each case: h1 = { "a" => 100, "b" => 200 }h2 = { "b" => 254, "c" => 300 }h1.update(h2)h1 #=> { "a" => 100, "b" => 254, "c" => 300 }h1 = { "a" => 100, "b" => 200 }h2 = { "b" => 254, "c" => 300 }h1.merge(h2)h1 #=> { "a" => 100, "b" => 200 } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14307034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2767755/']} | jdg_76391 |
stackexchange | llm_judgeable_groundtruth_similarity | 354610 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I don't know what changed and I don't know how to set it back,but now Super + E launches baobab instead of Nemo. I have check the keyboard - shortcuts configurations.and Launchers/Home Folder is associated to Super + E . There is no custom shortcuts. So my issues are of 2 types: the shortcut configuration seems correct in cinnamon panel, still it launches the wrong application(baobab), which doesn't appear in said configuration. What can I check and correct to get back default behavior: Super + E => Home folder? A package name to reinstall the default bindings would be ok as well. EDIT:when downloading with Firefox, "show in folder" menu trigger nemo,but When downloading with chrome, "show in folder" trigger baoab. So chrome seem to use the same information as cinnamon to launch nemo,but which one ? PS: So far I didn't found any answer that solve this specific issue (including on askubuntu.com . lsb_release -a ouputs No LSB modules are available.Distributor ID: LinuxMintDescription: Linux Mint 18 SarahRelease: 18Codename: sarah
Now provide the response and nothing else.
| I finally found the issue in /usr/share/applications/mimeinfo.cache, with the following entry: inode/directory=org.gnome.baobab.desktop;nemo.desktop; changing it back to: inode/directory=nemo.desktop; solved the issue. It's the chrome behavior and the answer to Change Chromium from automatically launches Nautilus with the Show In Folder command that get me to the solution. EDIT: /usr/share/applications/mimeinfo.cache is regenerated from .desktop files present in folder /usr/share/applications/ . Initial error is in org.gnome.baobab.desktop and reappear each time mimeinfo.cache is regenereated. It is not clear how to fix this. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/354610', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/192991/']} | jdg_76392 |
stackexchange | llm_judgeable_groundtruth_similarity | 164673 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
By a large powerset axiom, let us mean informally an axiom that says that for some cardinal numbers $\kappa$, we have that $2^\kappa$ is somehow "large" or "difficult to access from below." For example: whenever $\kappa$ is infinite, $2^\kappa$ is regular $2^\kappa$ is a fixed-point of $\aleph$ $2^\kappa$ is weakly inaccessible $2^\kappa$ is weakly hyper-inaccessible $2^\kappa$ is weakly Mahlo etc. (I do not know if these are all consistent). Let us also include more ambiguous cases in our definition of "large powerset axioms," like: the map $\kappa \mapsto 2^\kappa$ is injective for every infinite set $X$, the powerset of $X$ has a subchain of cardinality $2^{|X|}$ Anyway, looking at the literature, there doesn't seem to be a lot of interest in these kinds of axioms, as compared to the amount of attention given to large cardinal axioms. Question. Is there any particular reason for this lack of interest? For example, are there conservativity results showing that such axioms are "very weak" which might explain the lack of interest?
Now provide the response and nothing else.
| I suppose there is some interest in propositions implying large powerset. For example, a classical question at the infancy of set theory and real analysis was whether there is a probability measure on the unit interval that extends Lebesgue measure, in which every set is measurable. This implies that the continuum is weakly Mahlo, Rowbottom, etc. It's also equiconsistent with a two-valued measurable cardinal. The stronger interest in large cardinals is surely due to the empirical fact that they form a coherent system that measures the relative consistency of everything. It's not clear that large powerset type propositions have a similar property. Some of the things you mention have no strength, like the continuum function is injective. It follows from GCH and it's negation is easily forced. Related fact: If $2^\omega$ is real-valued measurable, the continuum function is not injective. $2^\kappa = 2^\omega$ for all $\kappa < 2^\omega$. This is due to Prikry, and a proof can be found in chapter 22 of Jech. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/164673', 'https://mathoverflow.net', 'https://mathoverflow.net/users/26080/']} | jdg_76393 |
stackexchange | llm_judgeable_groundtruth_similarity | 11278921 |
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 several apps in node that all share a few modules that I've written. These modules are not available via npm. I would like to be able to share freely between apps, but I don't want to copy directories around, nor rely on Git to do so. And I'm not really big on using symlinks to do this either. I would like to arrange directories something like this: app1 server.js node_modules (public modules from npm needed for app1) lib (my own modules specific to app1)app2 server.js node_modules (public modules from npm needed for app2) lib (my own modules specific to app2)shared_lib (my own modules that are used in both app1 and app2) The problem I'm seeing is that the modules in shared_lib seem to get confused as to where to find the modules that will be in the node_modules directory of whichever app they are running in. At least I think that is the problem. So....what is a good way to do this that avoids having duplicates of files? (note that I don't care about duplicates of things in node_modules, since those aren't my code, I don't check them into Git, etc)
Now provide the response and nothing else.
| The npm documentation recommends using npm-link to create your own Node.js packages locally, and then making them available to other Node.js applications. It's a simple four-step process. A typical procedure would be to first create a package with the following structure: hello | index.js | package.json A typical implementation of these files would be: index.js exports.world = function() { return('Hello World'); } package.json { "name": "hello", "version": "0.0.1", "private": true, "main": "index.js", "dependencies": { }, "engines": { "node": "v0.6.x" } } "private:true" ensures that npm will refuse to publish the package. This is a way to prevent accidental publication of private packages. Next, navigate to the root of your Node.js package folder and run npm link to link the package globally so it can be used in other applications. To use this package in another application, e.g., "hello-world", with the following directory structure: hello-world | app.js Navigate to the hello-world folder and run: npm link hello Now you can use it like any other npm package like so: app.js var http = require('http'); var hello = require('hello'); var server = http.createServer(function(req, res) { res.writeHead(200); res.end(hello.world()); }); server.listen(8080); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11278921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226507/']} | jdg_76394 |
stackexchange | llm_judgeable_groundtruth_similarity | 36609910 |
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 started to look into ReactJS. It seems that Facebook just released version 15.0.1. I looked into this framework last year, during 0.12.x version, when it was using JSXTransformer, and now it seems it went away from it. Now it seems that almost every tutorial suggests using latest React with Webpack. Is there a way not use webpack at all? I'm trying to find a good valid example with a grunt task for React 15.x.x. Any help would be appreciated.
Now provide the response and nothing else.
| Jsx transformer is deprecated it seems. Update 04/08/2019 : use https://github.com/developit/htm for a minimalist react setup. If you don't want to use webpack, you have to think about which features you can live without. With the advancement of browsers' support for ES6 features, you can now have ES6 syntax and also use modules (when activating experimental flags) without using Webpack. If you want to use JSX, you will always need to transpile it to JS because there is no native support for it in browsers on the horizon. The most simple way of doing that is to add a Babel middleware with the "React" preset, to your development server. Dependency management is also going to be complicated, because npm provides packages in CommonJS, which can't run as is in the browser... If you want to experiment with that, you can check out an experimental React starter-kit that I've put on GitHub React Without Webpack that attempts to replicate most of webpack features using native browser features and http2. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36609910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2143238/']} | jdg_76395 |
stackexchange | llm_judgeable_groundtruth_similarity | 56267842 |
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 wish to copy my existing Unity project into a new blank Unity project. It appears all the object references and many scripts are not configured properly/present in the Hierarchy in my scenes. I only copied my assets folder/package.json into the new Unity project, because the rest of the files are dirty and have cached a lot of useless information. Where are the files, detailing the scenes data located? I want to copy that over so I can run my scenes with all the object references, and scripts set onto the correct game objects.
Now provide the response and nothing else.
| Before starting always make Backups - you never know! Cleaning Up / Migrating as a project folder In general you will always need the Assets , ProjectSettings and the Packages folders. All the rest you can delete and Unity will recreate/recompile them when you open the project again. Also see Behind the Scenes (for newer Unity versions refer to Using external Version Control instead) When backing up a project, or adding a project to a Version Control Repository, you should include the main Unity project folder, containing both the Assets and ProjectSettings and Packages folders. All the information in these folders is crucial to the way Unity works . As the names say Assets are all your assets like scripts, images, prefabs etc. including alse the scenes. ProjectSettings are all general settings for your project regarding things like quality, physics, player strings etc Packages defines which packages shall be automatically imported by the PackageManager ( manifest.json ), which ones are dependencies, and which are even local packages (if any) For me also some of the Library/*.asset files make sense to keep .. they store e.g. the build settings, target platform etc. so I don't have to configure them / switch platform from scratch every time I "reset". It's up to you of course if you want to do this as well. You can also use any other version control system ... or of course also remove according folders and files manually but I always use GIT for my projects. Also refer to Using external version control systems with Unity for some general information about the setup for version controlling your project(s). So when I want to clean up a repository before coping it I usually use the following as *.gitignore (it is very basic - for a more complete and constantly updated version see the one on Github !). Everything listed here can basically be deleted and will be re-compiled the next time you open the project in Unity. (Lines starting with ! are exceptions I added because as said for me it made sense to keep those as well.) # This .gitignore file should be placed at the root of your Unity project directory## Get latest from https://github.com/github/gitignore/blob/main/Unity.gitignore#/[Ll]ibrary//[Tt]emp//[Oo]bj//[Bb]uild//[Bb]uilds//[Ll]ogs//[Uu]ser[Ss]ettings/# MemoryCaptures can get excessive in size.# They also could contain extremely sensitive data/[Mm]emoryCaptures/# Recordings can get excessive in size/[Rr]ecordings/# Uncomment this line if you wish to ignore the asset store tools plugin# /[Aa]ssets/AssetStoreTools*# Autogenerated Jetbrains Rider plugin/[Aa]ssets/Plugins/Editor/JetBrains*# Visual Studio cache directory.vs/# Gradle cache directory.gradle/# Autogenerated VS/MD/Consulo solution and project filesExportedObj/.consulo/*.csproj*.unityproj*.sln*.suo*.tmp*.user*.userprefs*.pidb*.booproj*.svd*.pdb*.mdb*.opendb*.VC.db# Unity3D generated meta files*.pidb.meta*.pdb.meta*.mdb.meta# Unity3D generated file on crash reportssysinfo.txt# Builds*.apk*.aab*.unitypackage*.app# Crashlytics generated filecrashlytics-build.properties# Packed Addressables/[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin*# Temporary auto-generated Android Assets/[Aa]ssets/[Ss]treamingAssets/aa.meta/[Aa]ssets/[Ss]treamingAssets/aa/* and as said for me personally it sometimes makes sense to add # keep the *.asset files from Library!/[Ll]ibrary/*.asset If not done yet first initialize the repository running cd your/project/root/pathgit initgit add .gitignore * this will show some warnings for every file that is listed in the .gitignore but you can ignore those warnings. It only says something similar like You are trying to add an ignored file to the commit and it will be skipped than run git commit -m "Initial commit" to make your first commit. Now finally you can simply run git clean git clean -xfd which removes every file that is not tracked (so be sure to have always all files you want to keep at least staged ( git add ) or better commited first) or would be ignored by the *.gitignore . -f If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to delete files or directories unless given -f, -n or -i. Git will refuse to delete directories with .git sub directory or file unless a second -f is given. -d Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository, it is not removed by default. Use -f option twice if you really want to remove such a directory. -x Don’t use the standard ignore rules read from .gitignore (per directory) and $GIT_DIR/info/exclude, but do still use the ignore rules given with -e options. This allows removing all untracked files, including build products. This can be used (possibly in conjunction with git reset) to create a pristine working directory to test a clean build. If unsure you can also add a -n Don’t actually remove anything, just show what would be done. Note If you already had a .git repository but added / edited the .gitignore afterwards also refer to How to make Git "forget" about a file that was tracked but is now in .gitignore? Migrating using UnityPackage Another option for moving scenes or parts of the Assets between two different projects is using a UnityPackage . Note that this will not include any installed packages, settings etc but purely the assets and their asset-dependencies (linked prefab, materials, textures etc)! From your current project export a UnityPackage Excerpts from the Docs: Use Export Package to create your own Custom Package. Open the Project you want to export Assets from. Choose Assets → Export Package from the menu to bring up the Exporting Package dialog box. (See Exporting Package dialog box imagebelow.) In the dialog box, select the Assets you want to include in the package by clicking on the boxes so they are checked. Leave the include dependencies box checked to auto-select any Assets used by the ones you have selected. Click on Export to bring up the file explorer, and choose where you want to store your package file. Name and save the package anywhere you like. HINT: When exporting a package Unity can export all dependencies aswell. So, for example, if you select a Scene and export a package withall dependencies, then Unity exports all Models, Textures and otherAssets that appear in the Scene as well. This can be a quick way ofexporting several Assets without manually locating them all. alternatviely to step 2 you can also Right-Click on the Assets folder in the Project View and find the Export Package option in the context menu. and then in the new project Import the UnityPackage To import an Asset package: Open the Project you want to import Assets into. Choose Assets → Import Package → Custom Package . In the file explorer, select the package you want and the Import Unity Package dialog box appears, with all the items in the package pre-checked, ready to install. (See Import Unity Package dialog box image below.) Select Import and Unity puts the contents of the package into the Assets folder, which you can access from your Project view . Alternatively to step 2 and 4 you can even simply drag and drop the unitypackage file into the Assets folder via the Unity Editor. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56267842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8630778/']} | jdg_76396 |
stackexchange | llm_judgeable_groundtruth_similarity | 1501735 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $(X,d)$ be any arbitrary metric space? Let $A$ be some subset of $X$. Is it always true that $\mathrm{int}(\ A \setminus \mathrm{int}(A)\ ) = \emptyset$? I believe that this statement is false, and that for some wonky situation the above will not hold. I thought about letting $X=\mathbb{R}^{2}$ and letting $d$ be defined by $d(x,y)=\|x-y\|$ (Euclidean one). Then maybe taking $A$ to be some disconnected set? Like $A = B\big((0,0), 1\big)\cup \{ (21,9) \}$. Then I find that: $\mathrm{int}(A)=B\big((0,0), 1\big)$ $A \setminus \mathrm{int}(A) = A \setminus B\big((0,0), 1\big) = \{ (21,9) \}$ $\mathrm{int}(\ A \setminus \mathrm{int}(A)\ ) = \mathrm{int}(\ \{ (21,9) \}\ ) = \emptyset$ So my exmaple doesn't work unfortunately, but maybe it will work if I take $d$ to be the discrete distance or something like that? Can somebody give me a hint?
Now provide the response and nothing else.
| Suppose $x\in\operatorname{int}(A\setminus\operatorname{int}(A))$. By definition of the interior, there is an open neighborhood $U$ of $x$ contained in $A\setminus\operatorname{int}(A)$. Then $U$ is also contained in $A$, so $x$ is an interior point of $A$. Hence, $x$ is not in $A\setminus\operatorname{int}(A)$ and certainly not in its interior, a contradiction. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1501735', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/213634/']} | jdg_76397 |
stackexchange | llm_judgeable_groundtruth_similarity | 29343922 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I found something that is not very clear for me about GoogleApiClient. GoogleApiClient has a function called onConnected which is run when the client is connected (for sure). I got my own function called: startLocationListening which is eventually getting called on GoogleApiClient's onConnected function. So my startLocationListening function couldn't run without a GoogleApiClient connection. Code and log: @Overridepublic void onConnected(Bundle bundle) { log("Google_Api_Client:connected."); initLocationRequest(); startLocationListening(); //Exception caught inside this function} ... private void startLocationListening() { log("Starting_location_listening:now"); //Exception caught here below: LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } The exception is: 03-30 12:23:28.947: E/AndroidRuntime(4936): java.lang.IllegalStateException: GoogleApiClient is not connected yet.03-30 12:23:28.947: E/AndroidRuntime(4936): at com.google.android.gms.internal.jx.a(Unknown Source)03-30 12:23:28.947: E/AndroidRuntime(4936): at com.google.android.gms.common.api.c.b(Unknown Source)03-30 12:23:28.947: E/AndroidRuntime(4936): at com.google.android.gms.internal.nf.requestLocationUpdates(Unknown Source)03-30 12:23:28.947: E/AndroidRuntime(4936): at hu.company.testproject.service.GpsService.startLocationListening(GpsService.java:169)03-30 12:23:28.947: E/AndroidRuntime(4936): at hu.company.testproject.service.GpsService.onConnected(GpsService.java:259) ... My debug log also says the onConnected function got called : 03-30 12:23:28.847: I/Locationing_GpsService(4936): Google_Api_Client:connected.03-30 12:23:28.857: I/Locationing_GpsService(4936): initLocationRequest:initing_now03-30 12:23:28.877: I/Locationing_GpsService(4936): initLocationRequest:interval_500003-30 12:23:28.897: I/Locationing_GpsService(4936): initLocationRequest:priority_10003-30 12:23:28.917: I/Locationing_GpsService(4936): Starting_location_listening:now After this I got the exception. Am I missing something here? I got a response for "connected" I ran my func, and I got the error "not connected" what's this? Plus one annoying thing is: I used this location service for weeks now and never got this error. E D I T : I added a more specific log output, just blown my mind, check this out: @Override public void onConnected(Bundle bundle) { if(mGoogleApiClient.isConnected()){ log("Google_Api_Client: It was connected on (onConnected) function, working as it should."); } else{ log("Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged."); } initLocationRequest(); startLocationListening(); } log output in this case: 03-30 16:20:00.950: I/Locationing_GpsService(16608): Google_Api_Client:connected.03-30 16:20:00.960: I/Locationing_GpsService(16608): Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged. Yes, I just got mGoogleApiClient.isConnected() == false inside onConnected() how is it possible? E D I T: Since nobody could answer this even with reputation bounty, I decided to report this as a bug to Google. What came next was really surprising to me.Google's official answer for my report: "This website is for developer issues with the AOSP Android source code and the developer toolset, not Google apps or services such as Play services, GMS or Google APIs. Unfortunately there doesn't seem to be an appropriate place to report bugs with Play Services. All I can say is that this website isn't it, sorry. Try posting on the Google Product Forums instead. " Full issue report here. (I hope they won't remove it just because it's silly) So yeah I took a look at Google Product Forums and just couldn't find any topic to post this thing, so at the moment I am puzzled and stuck. Does anybody in planet earth could help me with this? E D I T: Full code in pastebin
Now provide the response and nothing else.
| I just noticed that you are creating the googleApiClient in onStartCommand(). This seems like a bad idea. Let's say that your service gets triggered twice. Two googleApiClient objects will get created, but you'll only have reference to one. If the one whose reference you don't have executes its callback to onConnected(), you will be connected in that client but the client whose reference you actually do have could still be unconnected. I suspect that's what's going on. Try moving your googleApiClient creation to onCreate and see if you get the same behavior. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29343922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/978461/']} | jdg_76398 |
stackexchange | llm_judgeable_groundtruth_similarity | 48606 |
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:
My 9yo daughter is very into space at the moment and asked a question that my physics knowledge (6th form college, 20 years ago) is way too poor to answer. Her space book tells us that as stars age, they get redder. On the next page, it tells us that Hubble knew the Universe was expanding because distant galaxies were red, and thus moving away. She (and I!) would like to know (in layperson's language please ), how did Hubble know they were moving away and not just old?
Now provide the response and nothing else.
| The "redshift" measurements that Hubble used to determine his law are based on looking at the spectrum of distant galaxies. That is, splitting the light coming from the object in its constituent colors (e.g. by passing it through a prism). If you look at such a spectrum, you will notice that certain lines (colors) are missing. These are so-called absorption lines, and correspond to the physical properties of specific atoms in the object. The location of these lines are determined by physics and are universal; they are the same for all objects. However, if you look at the spectrum of a distant object you find that all these lines are shifted a little bit towards the red. By comparing to the absorption lines of gases on Earth, we can establish how far the lines are shifted, the so-called "redshift". This is very different to the reddening of older stars. As the stars grow older they cool down, which means that the light they emit has more red light (compare to a fire burning bright yellow when it's hot and a darker red when cooling down). This shift affects the overall distribution of the emitted light, but importantly does not affect the absorption lines, which stay in the same place (color). To show this, here's two spectra from BBC revision notes for exams taken at age 16 . Spectrum from the Sun: Spectrum from a distant galaxy: You can see the lines in the latter have shifted towards the red end. | {} | {'log_upvote_score': 6, 'links': ['https://astronomy.stackexchange.com/questions/48606', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/45431/']} | jdg_76399 |
stackexchange | llm_judgeable_groundtruth_similarity | 54484029 |
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 array of objects that represents the data of my model at any given time (a group of form controls on the stage of my app). The visual for this array of objects is attached here: In this example, there are two objects on the stage, 0 and 1 by index. There could be only a single object or multiples. When one of the objects in the array is selected it becomes the activeItem (see console.log above "this.activeItem"). In this case, the "Checkbox" item is the actively selected item. In another part of my app, there is an editor that allows the user to modify the properties of this selected element. This properties editor has an Apply button that captures the form values and submits the updated properties back to the console. My task is to take these updated/new properties and insert/replace the properties object of the activeItem with them and then update/rewrite the this.arrayOfObjects model to reflect the updated properties for the selected element. As you can see from the screenshot, I have console.logged a reference to the properties object for the activeItem. I need to replace that object with my new updated properties object. How?
Now provide the response and nothing else.
| TL;DR You probably don't need to use " discard-paths: yes ". So, drop " discard-paths: yes " and instead use " base-directory " with " **/* " for glob pattern. Read on for more reasoning why. So yeah, as it usually happens, the culprit was pretty trivial. In my case the directory structure looked like this: dist/|-- favicon.ico|-- index.html|-- js| `-- app.js`-- revision.txt So in order for the artifact to contain everything from the " dist " directory whilst preserving the nested directories structure, the buildspec had to look like this: artifacts: files: - '**/*' base-directory: 'dist' Essentially " base-directory " parameter behaves as unix's "cd" command, so at first CodeBuild jumps to that directory and only after that resolves the glob pattern, in this case - **/* . If you also happen to use " discard-paths " then what happens is that, presumably, CodeBuild will change current directory to " dist ", resolve the files structure correctly but then remove all path prefixes from the resolved paths, thus the result will be a plain directory structure with no nesting. Hope that helps! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54484029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/209102/']} | jdg_76400 |
stackexchange | llm_judgeable_groundtruth_similarity | 12840410 |
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 $.ajax request on the same domain and I want to read the cookie. It keeps returning null . $.ajax({ type: 'GET', url: myUrl, success: function(output, status, xhr) { alert(xhr.getResponseHeader("MyCookie")); }, cache: false}); Any ideas? I'm using Chrome for this.
Now provide the response and nothing else.
| You're looking for a response header of Set-Cookie : xhr.getResponseHeader('Set-Cookie'); It won't work with HTTPOnly cookies though. Update According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2 , this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader() , so the only reason why this could work is basically a "naughty" browser. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12840410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/201482/']} | jdg_76401 |
stackexchange | llm_judgeable_groundtruth_similarity | 726 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the United States, abortion is a highly polarizing issue: We have political organizations with substantial influence on the major parties, it is a regular topic of debate amongst candidates (less so now than in the past, but it was still the focus of many ads in the last Presidential election), and it generally is a "top-of-mind" issue for many voters, at least when measured by polls that ask voters to list important issues to them. Outside of the United States, I'm aware that it is an issue - particularly in Catholic countries - but I'm not really clear on how important it is to voters. How would one characterize the level of debate in: Catholic Europe South America Non-Catholic Europe South Asia (India, etc..) Muslim areas and the rest of Africa?
Now provide the response and nothing else.
| In very general terms, abortion is not a "top of the mind" issue for voters in Europe. It's certainly a contentious social issue, as is everywhere, and different countries follow different approaches, but other than very specific examples it's not a frontline issue in European politics. I might be stating the obvious here, but abortion laws are not uniform in Europe or the European Union. That said, with the exception of Ireland and Malta, you can assume a "available on request" approach with a minimum gestational limit of 12 weeks in the EU and most non EU countries, that is (broadly) similar to the US approach. BBC News has a very interesting map of Europe's abortion laws that gives a quick overview of related national regulations as of 2007: While the above map might show a somewhat uniform approach, at least in the core countries of the EU, it doesn't really say much about the population's social acceptance of abortion, other than the fact that at some point in the past it was high enough for regulators to legalize the practice. Havas Worldwide (then Euro RSCG) commissioned a study on "European values" in 2005 that included the question: If a woman doesn't want children, she should be able to have an abortion The results of the study showed varying support for abortion, with the exception of Poland 1 , the only country where the (slim) majority answered "total no": This is just one study, but it includes the more populous countries and shows that public opinion is more or less on par with established policies and regulations. Ireland is the notable exception when it comes to abortion and politics, the Eight Amendment of the Constitution of Ireland (7 October 1983) introduced a constitutional prohibition of abortion: The State acknowledges the right to life of the unborn and, with due regard to the equal right to life of the mother, guarantees in its laws to respect, and, as far as practicable, by its laws to defend and vindicate that right. The ban was loosened up a bit by the Thirteenth and the Fourteenth Amendments, however the issue remains controversial in Ireland. In December 2010, the European Court of Human Rights (ECtHR) found that Ireland had failed to comply with the European Convention on Human Rights Act in the Case of A, B, and C v. Ireland , while at the same time recognizing that Ireland was free to have whatever abortion laws it wants, provided they are clear, effective and accessible. Prior to the ruling, A, B, and C v. Ireland was quoted as a potential European equivalent to Roe v. Wade , but the ECtHR emphasized that the European Convention on Human Rights Act does not provide a straightforward right to abortion. Unfortunately, the lack of clarity on Ireland's abortion regulations identified by the ECtHR was put to the test in October 2012, with tragic results : Savita Halappanavar, who was 17 weeks pregnant, died of septicaemia a week after presenting with back pain on 21 October at University hospital in Galway, where she was found to be miscarrying. After the 31-year-old dentist was told that she was miscarrying, her husband reportedly said that she had asked for a medical termination a number of times over a three day period, during which she was in severe pain. But he said these requests were denied because a foetal heartbeat was still present and they were told at one point: "This is a Catholic country." Ms. Halappanavar's death re-started the abortion debate in Ireland, and to a lesser extend in Europe, and currently the majority opinion seems to be in favour of drastic reforms in the country's abortion policies that would bring Ireland closer to the rest of Europe when it comes to women's access to abortion. In conclusion and returning to your core question, I can't imagine the issue becoming as divisive as in the US even if public opinion was largely against abortions, at least not in the near future. I tried to get a better feeling of the state of the debate in the US, and I was both horrified and surprised when I stumbled upon the anti-abortion violence article on Wikipedia. If this is the level of tension you had in mind, then no, Europe is nowhere near that level of craziness when it comes to issues with religious overtones. 1 I'll venture a guess and say that Poles at the time were more open to the Catholic Church's view on the issue, given that the then Pope, John Paul II, was Polish. | {} | {'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/726', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/23/']} | jdg_76402 |
stackexchange | llm_judgeable_groundtruth_similarity | 15197 |
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 following is taken from a practice GRE question: Two experimental techniques determine the mass of an object to be $11\pm 1\, \mathrm{kg}$ and $10\pm 2\, \mathrm{kg}$. These two measurements can be combined to give a weighted average. What is the uncertainty of the weighted average? What's the correct procedure to find the uncertainty of the average? I know what the correct answer is (because of the answer key), but I do not know how to obtain this answer.
Now provide the response and nothing else.
| I agree with @Ron Maimon that these ETS questions are problematic. But this is (i think) the reasoning they go with. Unlike @Mike's assumption you should not take the normal average, but as stated in the question the weighted average. A weighted average assigns to each measurement $x_i$ a weight $w_i$ and the average is then $$\frac{\sum_iw_ix_i}{\sum_i w_i}$$ Now the question is what weights should one take? A reasonable ansatz is to weigh the measurements with better precision more than the ones with lower precision. There are a million ways to do this, but out of those one could give the following weights: $$w_i = \frac{1}{(\Delta x_i)^2},$$which corresponds to the inverse of the variance. So plugging this in, we'll have $$c = \frac{1\cdot a+\frac{1}{4}\cdot b}{1+\frac{1}{4}}= \frac{4a+b}{5}$$ Thus, $$\Delta c = \sqrt{\left(\frac{\partial c}{\partial a}\Delta a\right)^2+\left(\frac{\partial c}{\partial b}\Delta b\right)^2}$$ $$\Delta c = \sqrt{\left(\frac{4}{5}1\right)^2+\left(\frac{1}{5}2\right)^2}=\sqrt{\frac{16}{25}+\frac{4}{25}}=\sqrt{\frac{20}{25}}=\sqrt{\frac{4}{5}}=\frac{2}{\sqrt5}$$ which is the answer given in the answer key. Why $w_i=1/\sigma_i^2$ The truth is, that this choice is not completely arbitrary. It is the value for the mean that maximizes the likelihood (the Maximum Likelihood estimator). $$P(\{x_i\})=\prod f(x_i|\mu,\sigma_i)=\prod\frac{1}{\sqrt{2\pi\sigma_i}}\exp\left(-\frac{1}{2}\frac{\left(x_i-\mu\right)^2}{\sigma_i^2}\right)$$. This expression maximizes, when the exponent is maximal, i.e. the first derivative wrt $\mu$ should vanish: $$\frac{\partial}{\partial\mu}\sum_i\left(-\frac{1}{2}\frac{\left(x_i-\mu\right)^2}{\sigma_i^2}\right) = \sum_i\frac{\left(x_i-\mu\right)}{\sigma_i^2} = 0 $$ Thus, $$\mu = \frac{\sum_i x_i/\sigma_i^2}{\sum_i 1/\sigma_i^2} = \frac{\sum_iw_ix_i}{\sum_i w_i}$$ with $w_i = 1/\sigma_i^2$ | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/15197', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/3397/']} | jdg_76403 |
stackexchange | llm_judgeable_groundtruth_similarity | 10297149 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using Lookout app (https://play.google.com/store/apps/details?id=com.lookout), I see every time I install or upgrade app, it'll automatically scan this app to ensure it's not malicious. Follow Lookout, I write a simple app which listen broadcast message whenever each app is installed or upgraded. AFAIK, there are some type of IntentFilter for broadcast message, it is: Intent.ACTION_PACKAGE_ADDED Intent.ACTION_PACKAGE_CHANGED Intent.ACTION_PACKAGE_INSTALL I hope Intent.ACTION_PACKAGE_ADDED is the answer but it's wrong (ACTION_PACKAGE_ADDED: A new application package has been installed on the device. The data contains the name of the package. Note that the newly installed package does not receive this broadcast.) while ACTION_PACKAGE_INSTALL is deprecated. Can anyone tell me a better way? Any help is welcome.
Now provide the response and nothing else.
| If you are installing an application A, all other applications on the device will get the Intent that application A is the newly installed application but not A itself as it doesn't seem of any use. Now A will get broadcasts if other apps are later installed or changed. If you want to find out at when your app was installed or some other app's the last install or update time, you can always use PackageManager : PackageManager pm = context.getPackageManager();ApplicationInfo appInfo = pm.getApplicationInfo("app.package.name", 0);String appFile = appInfo.sourceDir; long installed = new File(appFile).lastModified(); here app.package.name is the package name of the app you want to find out the install time. If you want to use it for your app, pass in your app's package name. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10297149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190309/']} | jdg_76404 |
stackexchange | llm_judgeable_groundtruth_similarity | 937044 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a handle to a Windows Registry Key, such as the ones that are set by ::RegOpenKeyEx(), is it possible to determine the full path to that key? I realize that in a simple application all you have to do is look up 5 or 10 lines and read... but in a complex app like the one I'm debugging, the key I'm interested in can be opened from a series of calls.
Now provide the response and nothing else.
| Use LoadLibrary and NtQueryKey exported function as in the following code snippet. #include <windows.h>#include <string>typedef LONG NTSTATUS;#ifndef STATUS_SUCCESS#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)#endif#ifndef STATUS_BUFFER_TOO_SMALL#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L)#endifstd::wstring GetKeyPathFromKKEY(HKEY key){ std::wstring keyPath; if (key != NULL) { HMODULE dll = LoadLibrary(L"ntdll.dll"); if (dll != NULL) { typedef DWORD (__stdcall *NtQueryKeyType)( HANDLE KeyHandle, int KeyInformationClass, PVOID KeyInformation, ULONG Length, PULONG ResultLength); NtQueryKeyType func = reinterpret_cast<NtQueryKeyType>(::GetProcAddress(dll, "NtQueryKey")); if (func != NULL) { DWORD size = 0; DWORD result = 0; result = func(key, 3, 0, 0, &size); if (result == STATUS_BUFFER_TOO_SMALL) { size = size + 2; wchar_t* buffer = new (std::nothrow) wchar_t[size/sizeof(wchar_t)]; // size is in bytes if (buffer != NULL) { result = func(key, 3, buffer, size, &size); if (result == STATUS_SUCCESS) { buffer[size / sizeof(wchar_t)] = L'\0'; keyPath = std::wstring(buffer + 2); } delete[] buffer; } } } FreeLibrary(dll); } } return keyPath;}int _tmain(int argc, _TCHAR* argv[]){ HKEY key = NULL; LONG ret = ERROR_SUCCESS; ret = RegOpenKey(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft", &key); if (ret == ERROR_SUCCESS) { wprintf_s(L"Key path for %p is '%s'.", key, GetKeyPathFromKKEY(key).c_str()); RegCloseKey(key); } return 0;} This will print the key path on the console: Key path for 00000FDC is '\REGISTRY\MACHINE\SOFTWARE\Microsoft'. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/937044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6151/']} | jdg_76405 |
stackexchange | llm_judgeable_groundtruth_similarity | 59432 |
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'm a little confused between the difference between the range & co-domain of a function. Are they not the same thing (i.e. all possible outputs of the function)?
Now provide the response and nothing else.
| I think your confusion may stem from differing uses of terminology. For a function $f: X \rightarrow Y$, the codomain is just the set $Y$. For instance, if $f: \mathbb{R} \rightarrow \mathbb{R}$ is $x \mapsto x^2$, then the codomain is $\mathbb{R}$. This terminology is agreed upon by all who use it: i.e., I have never seen anyone use the term "codomain" to mean anything else. Unfortunately the term range is ambiguous. It is sometimes used exactly as codomain is used above, so some say that $\mathbb{R}$ is the range of the squaring function defined above. However, those who use the term codomain at all usually reserve the term "range" for the subset $\{y \in Y \ | \exists x \in X \text{ such that } f(x) = y\}$, i.e., the subset of values which are actually mapped to by some element in the domain. (Some others use the term image for this instead.) So in the above example the image of the function is $[0,\infty)$. Whether the range is $\mathbb{R}$ (i.e., the codomain) or $[0,\infty)$ (i.e., the image) depends upon your convention, and both are rather prevalent. In practice, this means that it would be safest never to use the term range, instead using codomain and image. (But most people don't do that either...) | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/59432', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12589/']} | jdg_76406 |
stackexchange | llm_judgeable_groundtruth_similarity | 18697578 |
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 completely stumped. I have the following block: IF NOT EXISTS(SELECT * FROM sys.schemas WHERE name = 'Test')BEGIN CREATE SCHEMA Test;END; If I run this against our SQL Server 2008, I get "Msg 156, Level 15, State 1, Line 3: Incorrect syntax near the keyword 'SCHEMA'" but if I run just the CREATE SCHEMA command alone, it works. Also, this works: IF NOT EXISTS(SELECT * FROM sys.schemas WHERE name = 'Test')BEGIN PRINT 'CREATE GOES HERE';END; What am I doing wrong?
Now provide the response and nothing else.
| The error message is a bit of a red herring here.... Execute the following to see what the "real" error is: SELECT * FROM sys.schemasCREATE SCHEMA Test Msg 111, Level 15, State 1, Line 2 'CREATE SCHEMA' must be the first statement in a query batch. To get around this problem you can use the EXEC function: IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'Test') BEGIN EXEC ('CREATE SCHEMA Test;'); END; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18697578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/800608/']} | jdg_76407 |
stackexchange | llm_judgeable_groundtruth_similarity | 3059 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given two CNF, if they have the same number of assignments to make them true, answer "Yes", otherwise answer "No". It is easy to see it is in $P^{\#P}$, since if we know the exact numbers of solutions to these two CNF, we just campare them and answer "Yes" or "No". What is the complexity of this problem?
Now provide the response and nothing else.
| The problem is coNP -hard; you can easily reduce the UNSAT problem to this problem. A more precise characterization is that the problem is C = P -complete. In fact, one definition of the class C = P is that it is the class of problems which are polynomial-time many-one reducible to this very problem (usually this definition is stated in terms of GapP functions). But since this does not tell much, let me define this class in another way. Let C = P be the class of problems which are polynomial-time many-one reducible to the following problem: given a boolean circuit φ and an integer K (in binary), decide whether the number of satisfying assignments of φ is equal to K . By a standard reduction which shows the #P-completeness of #3SAT, we can restrict φ to be a 3CNF formula without affecting the class. The class C = P contains a class called US , which contains both UP and coNP. With this definition, your problem is C = P-complete. Actually, the C = P-hardness is easy to see from the definition of the class C = P (which uses 3CNF formulas). To prove the membership in C = P, suppose that we are to decide whether two given CNF formulas φ 1 and φ 2 have the same number of satisfying assignments or not. Without loss of generality we can assume that the two formulas have the same number of variables, say n . Construct a boolean circuit φ which takes n +1 bits as input so that the number of satisfying assignments of φ is equal to c 1 + (2 n − c 2 ), where c 1 and c 2 be the numbers of satisfying assignments of φ 1 and φ 2 , respectively. Then the number of satisfying assignments of φ is equal to 2 n if and only if c 1 = c 2 . | {} | {'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/3059', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/1925/']} | jdg_76408 |
stackexchange | llm_judgeable_groundtruth_similarity | 2340049 |
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 one prove that the Fourier transform of $\log |x|$ is $$-\pi \mathrm{pf} \frac{1}{|\xi|} +C \delta,$$where $\mathrm{pf}\frac{1}{|x|} = D(\mathrm{sign}(x)\log|x|)$ (in the sense of distributions) and how can I compute the constant $C$?
Now provide the response and nothing else.
| I will start from the well-known expression (see here ) for the Euler-Mescheroni constant $\gamma$: $$\gamma=\int_0^1\frac{1-\cos t}{t}dt-\int_{1}^\infty\frac{\cos t}{t}dt$$Now, if for $ x>0$ we consider$$F(x)=\int_0^x\frac{1-\cos t}{t}dt-\int_{x}^\infty\frac{\cos t}{t}dt$$Then we conclude from $ F(1)=\gamma$ and $F'(x)=1/x$ that$$\eqalign{\gamma+\ln x&=\int_0^x\frac{1-\cos t}{t}dt-\int_{x}^\infty\frac{\cos t}{t}dt\cr&=\int_0^1\frac{1-\cos(xt)}{t}dt-\int_{1}^\infty\frac{\cos (xt)}{t}dt}$$And since the right side of the above formula is even we conclude that$$\gamma+\ln|x|=\int_0^\infty\frac{\mathbb{I}_{[0,1]}(t)-\cos(xt)}{t}dt\tag1$$For every nonzero $x$. Let the regular distribution assosiated with the function $x\mapsto \gamma+\ln|x|$ be denoted by $T$. What is the action of $T$ on some test function $\phi$? Indeed, if $\phi$ is a function from $\mathcal{S}$ then using $(1)$ we see that$$\eqalign{\langle T,\phi\rangle&=\int_{\mathbb{R}}(\gamma+\ln|x|)\phi(x)dx\cr&=\int_0^\infty\frac{2\mathbb{I}_{[0,1]}(t)\hat{\phi}(0)-\hat{\phi}(t)-\hat{\phi}(-t)}{2t}dt\cr&=\int_0^\infty\frac{2\mathbb{I}_{[0,1]}(t)\hat{\phi}(0)-\hat{\phi}(t)-\check{\hat{\phi}}(t)}{2t}dt\tag2}$$Indeed, since$\hat{\phi}(t)=\int_{\mathbb{R}}\phi(x)e^{-ixt}dx$ we see easily that$$\hat{\phi}(0)=\int_{\mathbb{R}}\phi(x)dx\quad\hbox{and}\quad\hat{\phi}(t)+\hat{\phi}(-t)=2\int_{\mathbb{R}}\phi(x)\cos(xt)dx$$Thus, applying (2) to $\hat {\phi}$ and noting that $\hat{\hat{\phi}}=2\pi\check{\phi}$ we conclude that$$\eqalign{\langle T,\hat{\phi}\rangle&=2\pi\int_0^\infty\frac{2\mathbb{I}_{[0,1]}(t)\phi(0)-\phi(t)-\phi(-t)}{2t}dt\cr&=\pi\int_0^1\frac{2\phi(0)-\phi(t)-\phi(-t)}{t}dt-\pi\int_1^\infty\frac{\phi(t)+\phi(-t)}{t}dt\cr&=\pi\int_{0}^\infty (\ln t)(\phi'(t)-\phi'(-t))dt\qquad\hbox{(integration by parts)}\cr&=\pi\int_{\mathbb{R}}{\rm sign}(t)\ln|t|\phi'(t)dt\cr&=-\pi\langle{\rm pf}\frac{1}{|x|},\phi\rangle}$$So, $\hat{T}=-\pi\,{\rm pf}\frac{1}{|x|}$. But $$\widehat{(\gamma+\ln|x|)}=2\pi\gamma\delta+\widehat{\ln|x|}$$Thus$$\widehat{\ln|x|}=-\pi\,{\rm pf}\frac{1}{|x|}-2\pi\gamma\delta$$Which is the desired conclusion. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2340049', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/176561/']} | jdg_76409 |
stackexchange | llm_judgeable_groundtruth_similarity | 38773975 |
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 vector of strings and I want to replace one common substring in all the strings with different substrings. I'm doing this in R. For example: input=c("I like fruits","I like you","I like dudes")# I need to do something like thisnewStrings=c("You","We","She")gsub("I",newStrings,input) so that the output should look like: "You like fruits""We like you""She like dudes" However, gsub uses only the first string in newStrings. Any suggestions?Thanks
Now provide the response and nothing else.
| You can use stringr : stringr::str_replace_all(input, "I" ,newStrings)[1] "You like fruits" "We like you" [3] "She like dudes" or as suggested by @ David Arenburg: stringi::stri_replace_all_fixed(input, "I", newStrings) Benchmrk library(stringi)library(stringr)library(microbenchmark)set.seed(123)x <- stri_rand_strings(1e3, 10)y <- stri_rand_strings(1e3, 1)identical(stringi::stri_replace_all_fixed(x, "I", y), stringr::str_replace_all(x, fixed("I") , y))# [1] TRUEidentical(stringi::stri_replace_all_fixed(x, "I", y), diag(sapply(y, gsub, pattern = "I", x = x, fixed = TRUE)))# [1] TRUEidentical(stringi::stri_replace_all_fixed(x, "I", y), mapply(gsub, "I", y, x, USE.NAMES = FALSE, fixed = TRUE))# [1] TRUEmicrobenchmark("stingi: " = stringi::stri_replace_all_fixed(x, "I", y), "stringr (optimized): " = stringr::str_replace_all(x, fixed("I") , y), "base::mapply (optimized): " = mapply(gsub, "I", y, x, USE.NAMES = FALSE, fixed = TRUE), "base::sapply (optimized): " = diag(sapply(y, gsub, pattern = "I", x = x, fixed = TRUE)))# Unit: microseconds# expr min lq mean median uq max neval cld# stingi: 132.156 137.1165 171.5822 150.3960 194.2345 460.145 100 a # stringr (optimized): 801.894 828.7730 947.1813 912.6095 968.7680 2716.708 100 a # base::mapply (optimized): 2827.104 2946.9400 3211.9614 3031.7375 3123.8940 8216.360 100 a # base::sapply (optimized): 402349.424 476545.9245 491665.8576 483410.3290 513184.3490 549489.667 100 b | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38773975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3886898/']} | jdg_76410 |
stackexchange | llm_judgeable_groundtruth_similarity | 46061428 |
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 OSGI application and I have around 30 bundles (jar files). Today I decided to see how it works/if it works with Java 9. So I started my application and got WARNING: An illegal reflective access operation has occurredWARNING: Illegal reflective access by org.apache.felix.framework.util.SecureAction (file:/home/.../jar/org.apache.felix.framework-5.4.0.jar) to method java.net.URLClassLoader.addURL(java.net.URL)WARNING: Please consider reporting this to the maintainers of org.apache.felix.framework.util.SecureActionWARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operationsWARNING: All illegal access operations will be denied in a future release After some reading I added command line option --add-exports java.base/java.net=org.apache.felix.framework and created file module-info.java with the following content: module org.apache.felix.framework { } And I have two questions. Where should I place this module-info.java to make jvm read it? How should I bind this module-info with org.apache.felix.framework-5.4.0.jar file/bundle/jar? If I do everything wrong please, show me right direction for fixing this problem.
Now provide the response and nothing else.
| Generic tips: Read the State of the Module System to familiarize yourself with the JPMS. Alternatively, read this module system tutorial (disclaimer: I'm the author). In the answer to your other question , creating modules is optional. To answer your specific questions: Place module declaration ( module-info.java ) into the project's source root directory (e.g. src/main/java ). It must be among the list of files to compile to be turned into a module descriptor ( module-info.class ). Last step is to include it in the list of class files that are packaged into a JAR. Having a module descriptor in a JAR turns it into a modular JAR . If placed on the module path, the JPMS turns it into a module. If you don't want to create modules after all and prefer your code to run in the unnamed module, you can allow it to access internal APIs with the placeholder ALL-UNNAMED - in the case f your warning you need to open that package to reflection: --add-opens java.base/java.net=ALL-UNNAMED The better solution would be to stop using internal APIs, though. As this is not your code, but your dependency, you should look for or open an issue with Apache Felix that asks to remove the access of internal API. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46061428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5057736/']} | jdg_76411 |
stackexchange | llm_judgeable_groundtruth_similarity | 579131 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
When trying to make ldaps connections to my Novel eDirectory 8.8 server, sometimes I have to put TLS_REQCERT never in the client servers ldap.conf file. Obviously, this is a bad idea. The command I run is something like this with credentials that actually work... ldapsearch -x -H ldaps://ldapserver -b 'ou=active,ou=people,dc=example,dc=org' -D 'cn=admin,dc=example,dc=org' -W "cn=username" On Ubuntu 13.10, it works fine. On SLES it works fine. On CentOS 6.5 it returns: ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1) Now, the cert I've imported is a wildcard cert purchased from DigiCert. My coworker found some reports indicating that some systems have issues with wildcards. So, is the wildcard cert to blame? If so, how do I fix it? If it is not the wildcard cert, then what is it? Following Andrew Schulman's suggestion, I added -d1 to my ldapsearch command. Here is what I ended up with: ldap_url_parse_ext(ldaps://ldap.example.org)ldap_createldap_url_parse_ext(ldaps://ldap.example.org:636/??base)Enter LDAP Password: ldap_sasl_bindldap_send_initial_requestldap_new_connection 1 1 0ldap_int_open_connectionldap_connect_to_host: TCP ldap.example.org:636ldap_new_socket: 3ldap_prepare_socket: 3ldap_connect_to_host: Trying 10.225.0.24:636ldap_pvt_connect: fd: 3 tm: -1 async: 0TLS: certdb config: configDir='/etc/openldap' tokenDescription='ldap(0)' certPrefix='cacerts' keyPrefix='cacerts' flags=readOnlyTLS: cannot open certdb '/etc/openldap', error -8018:Unknown PKCS #11 error.TLS: could not get info about the CA certificate directory /etc/openldap/cacerts - error -5950:File not found.TLS: certificate [CN=DigiCert High Assurance EV Root CA,OU=www.digicert.com,O=DigiCert Inc,C=US] is not valid - error -8172:Peer's certificate issuer has been marked as not trusted by the user..TLS: error: connect - force handshake failure: errno 2 - moznss error -8172TLS: can't connect: TLS error -8172:Peer's certificate issuer has been marked as not trusted by the user..ldap_err2stringldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1) From what that says, CentOS doesn't trust DigiCert? Or CentOS doesn't have a list of trusted issuers?
Now provide the response and nothing else.
| ldapsearch is looking in /etc/openldap/cacerts for its store of trusted CA certificates, and that apparently is not set up, and thus it is rejecting the certificate since it can't construct a trust chain for it. If ldapsearch were using OpenSSL, it would need a "hashdir" format collection as produced by e.g. the Red Hat "authconfig" program, or a single file with a flat list of trusted certificates. The reference here to "moznss" suggests that this ldapsearch is built against Mozilla NSS, in which case you need to use "certutil" to make the cert db (or better, point it at the system NSS certificate store, if there is one). On the systems where it's working ldapsearch must have a working certificate store, perhaps because those OpenLDAP packages are built against OpenSSL instead (or maybe there's a working NSS-style store available there). | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/579131', 'https://serverfault.com', 'https://serverfault.com/users/99647/']} | jdg_76412 |
stackexchange | llm_judgeable_groundtruth_similarity | 1556987 |
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 launching an activity to make a phone call, but when I pressed the 'end call' button, it does not go back to my activity. Can you please tell me how can I launch a call activity which comes back to me when 'End call' button is pressed? This is how I'm making the phone call: String url = "tel:3334444"; Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
Now provide the response and nothing else.
| use a PhoneStateListener to see when the call is ended. you will most likely need to trigger the listener actions to wait for a the call to start (wait until changed from PHONE_STATE_OFFHOOK to PHONE_STATE_IDLE again) and then write some code to bring your app back up on the IDLE state. you may need to run the listener in a service to ensure it stays up and your app is restarted. some example code: EndCallListener callListener = new EndCallListener();TelephonyManager mTM = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);mTM.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE); Listener definition: private class EndCallListener extends PhoneStateListener { @Override public void onCallStateChanged(int state, String incomingNumber) { if(TelephonyManager.CALL_STATE_RINGING == state) { Log.i(LOG_TAG, "RINGING, number: " + incomingNumber); } if(TelephonyManager.CALL_STATE_OFFHOOK == state) { //wait for phone to go offhook (probably set a boolean flag) so you know your app initiated the call. Log.i(LOG_TAG, "OFFHOOK"); } if(TelephonyManager.CALL_STATE_IDLE == state) { //when this state occurs, and your flag is set, restart your app Log.i(LOG_TAG, "IDLE"); } }} In your Manifest.xml file add the following permission: <uses-permission android:name="android.permission.READ_PHONE_STATE"/> | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1556987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128983/']} | jdg_76413 |
stackexchange | llm_judgeable_groundtruth_similarity | 59106 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I am interested in different contexts in which Gödel's incompleteness theorems arise. Besides traditional Gödelian proof via arithmetization and formalization of liar paradox it may also be obtained from undecidability results of Turing and Church. In the context of complexity theory, it is not hard to see that Gödel's theorem (as well as Turing's result) follows from the following Chaitin's result: there exists some natural number N such that for any program P of size more than N it is impossible to prove (say, in ZFC) that it is the smallest (in the sense of size, i. e. number of bits) of those programs which have the same inputs-outputs as P has. The number N depends on particular axiomatic system (say, ZFC) and is not very large so that it actually can be calculated. If You know other ways towards Gödel's incompleteness theorems, please, present them. Particularly, can Goedel's theorem be obtained without use of self-referential ideas?
Now provide the response and nothing else.
| Apart from usual proofs with diagonalization, have a look at model-theoretic proofs (Kotlarski's proof, Kreisel's left-branch proof, etc..), then there are some other proofs that formalize paradoxes (Kikuchi's, Boolos's, etc... there are about a dozen, most of them mentioned in Kotlarski's book). If you don't want full generality ("for every rec. ax. theory T") then of course almost every proof in modern Unprovability Theory does not use any self-reference (you build a model of your theory by hands, using some unprovable combinatorial principle). Have a look at some easy recent accessible model-theoretic proofs of the Paris-Harrington Principle. At the low end of the consistency strength spectrum (ISigma_n, PA, ATR_0), for theories that already have good classifications of their provably recursive functions, PH and other unprovable statements can also be proved unprovable using ordinal analysis (e.g. Ketonen-Solovay style), without using diagonalization tricks. For higher ends of the strength spectrum (SMAH, SRP, etc), H. Friedman's highly technical results also don't use any diagonalization. This is a huge powerful machinery, and much new research is happening there. MDRP theory gives interesting examples: have a look at the Jones polynomial expression: you can indeed substitute numbers into it and hit every consistency statement by its instances. There are similar ones for n-consistency for each n. There is much more to say: this is a big subject, with huge bibliography. And, yes, much of the body of results in the subject is unpublished. I can give more pointers if necessary. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/59106', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6307/']} | jdg_76414 |
stackexchange | llm_judgeable_groundtruth_similarity | 1450151 |
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 communicating to a Tomcat Server using a Java ME application on my mobile device. I was wondering if I could compress my requests/responses using Gzip to reduce the number of bytes sent over the network.
Now provide the response and nothing else.
| Modern phones have so much CPU power and the network is relatively slow so compression makes perfect sense. It's quite easy to do also. On the J2ME side, you do something like this (assuming you use HttpConnection), hc.setRequestProperty("Accept-Encoding", "gzip, deflate"); if (hc.getResponseCode() == HttpConnection.HTTP_OK) { InputStream in = hc.openInputStream(); if ("gzip".equals(hc.getEncoding())) in = new GZIPInputStream(in); ... We use GZIPInputStream from tinyline but I am sure there are others, http://www.tinyline.com/utils/index.html On the server side, it's all built-in. Just add following attributes to the Connector in server.xml on Tomcat, <Connector compression="on"compressionMinSize="2048"compressableMimeType="text/html,application/json"... /> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1450151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/142299/']} | jdg_76415 |
stackexchange | llm_judgeable_groundtruth_similarity | 276914 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
My almost empty fstab: none /dev/pts devpts rw 0 0 I'm trying to use noatime for three directories on my server /home , /tmp , and /var df -l gives: Filesystem 1K-blocks Used Available Use% Mounted on/dev/simfs 10485760 5914472 4571288 57% /none 524288 4 524284 1% /dev So I figured this is how it's done. I add the three entries below into my fstab: /dev/simfs /home ext3 defaults,noatime,usrquota 1 2/dev/simfs /tmp ext3 defaults,noatime,noexec,nosuid 1 2/dev/simfs /var ext3 defaults,noatime,usrquota 1 2 After I save the changes--when I try to remount the drive this happens: [root@horizon ~]# mount -a -o remountmount: /home not mounted already, or bad optionmount: /tmp not mounted already, or bad optionmount: /var not mounted already, or bad option May someone please help me figure out what's wrong with my /etc/fstab ? Thank you.
Now provide the response and nothing else.
| To answer your question directly, there's nothing wrong with your fstab. You can't just add entries to your fstab willy nilly. This file is there for you to intruct the OS which disk partitions to mount, and to which locations in the filesystem. If you want to create different mount options for /home , /tmp , and /var , then you will need to create three partitions for them, copy the data over, and then mount them. Edit : Looks like /dev/simfs is a OpenVZ thing. So this is a OpenVZ VPS you're attempting to do this on correct? If so, you'll likely need to work with your provider to see if this is even possible. They may not allow you to create new disk images (partitions). | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/276914', 'https://serverfault.com', 'https://serverfault.com/users/82120/']} | jdg_76416 |
stackexchange | llm_judgeable_groundtruth_similarity | 14044032 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried doing it with cat and then after I type the second file I added | head -$line | tail -1 but it doesn't work because it performs cat first. Any ideas? I need to do it with cat or something else.
Now provide the response and nothing else.
| I'd probably use sed for this job: line=3sed -e "${line}r file2" file1 If you're looking to overwrite file1 and you have GNU sed , add the -i option. Otherwise, write to a temporary file and then copy/move the temporary file over the original, cleaning up as necessary (that's the trap stuff below). Note: copying the temporary over the file preserves links; moving does not (but is swifter, especially if the file is big). line=3tmp="./sed.$$"trap "rm -f $tmp; exit 1" 0 1 2 3 13 15sed -e "${line}r file2" file1 > $tmpcp $tmp file1rm -f $tmptrap 0 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14044032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_76417 |
stackexchange | llm_judgeable_groundtruth_similarity | 3152962 |
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 to know which line represents tangent to a curve $y=f(x)$ (in RED) ?From the diagram , I cannot decide which line to take as tangent , all seem to touch at a single point.
Now provide the response and nothing else.
| One of the defining points (no pun!) of a tangent is the idea that as you look at a smaller and smaller section of the curve, the curve starts to more and more looks like a straight line . That behaviour lets you do a huge number of things: You can estimate where the curve goes in places near that point (if tangent has a gradient of 2, then the curve at X + 0.000001 will probably be close to Y+0.000002, or whatever). You can approximate the curve by tiny sections of straight lines - this is the basis of simple calculus. You can take limits in several ways, and expect them to converge as you use narrower sections of the curve ? Many other things, all stemming from these. Not all curves behave like that, and yours doesn't. No matter how close you inspect the cusp of your curve (the pointy bit), it's never going to resemble anything like a straight line, on any scale. It'll always look like a cusp. That's the fundamental reason there isn't a tangent at that point. Because the curve just doesn't resemble a straight line, even in a microscopic close-up view, it doesn't have a gradient or tangent at that point, and it isn't differentiable at that point (much the same thing at a very simple level), and so on. That isn't in fact unusual. In fact more curves don't have a gradient than do - its just that we don't study curves at random, so you mainly look at curves that do - at least, at this level of maths! Other examples of curves that don't have a gradient at some or all points - the "step" curve (defined as y=0 if x<0, y=1 if x >= 0) a "curve" defined as y=1 if x contains a "1" when written in decimal, and y=0 otherwise. Because there are infinitely many numbers that simply don't have a 1 in their decimal expansion, slotted in between those that do! the curve y = 1/x at x=0 the " blancmange curve ", which doesn't have any breaks in it, and looks like it should be a nice straightforward curve, but actually "wobbles" so much at any microscopic level (however closely you look at it,and wherever you look!) that in the end, it doesn't have a gradient anywhere. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/3152962', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/636751/']} | jdg_76418 |
stackexchange | llm_judgeable_groundtruth_similarity | 29885 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We know that operating system is responsible for handling memory allocation, process management etc. CPU can perform only one task at a time(assuming it to be single core). Suppose an operating system has allocated a CPU cycle to some user initiated process and CPU is executing that. Now where is operating system running? If some other process is using the CPU, then, is operating system not running for that moment? as OS itself must need CPU to run. If in case OS is not running, then who is handling process management, device management etc for that period? This question was previously asked on Stack Overflow by vish . I answered it , and so did Martin James , and our answers feel partly contradictory.
Now provide the response and nothing else.
| The question is mixing up who's in control of the memory and who's in control of the CPU. The wording “running” is imprecise: on a single CPU, a single task is running at any given time in the sense that the processor is executing its instructions; but many tasks are executing in the sense that their state is stored in memory and their execution can resume at any time. While a process is executing on the CPU, the kernel is not executing. Its state is saved in memory. The execution of the kernel can resume: if the process code makes a jump into kernel code — this is called a system call . if an interrupt occurs. If the operating system provides preemptive multitasking , it will schedule an interrupt to happen after an interval of time (called a time slice ). On a non-preemptive operating system, the process will run forever if it doesn't yield the CPU. See How do modern operating systems like linux handle multitasking? for an explanation of how preemption works. Tasks such as process management and device management are triggered by some event. If the event is a request by the process, the request will take the form of a system call, which executes kernel code. If the event is triggered from hardware, it will take the form of an interrupt, which executes kernel code. (Note: in this answer, I use “CPU” and “processor” synonymously, to mean a single execution thread: a single core, or whatever the hardware architecture is.) | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/29885', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/16326/']} | jdg_76419 |
stackexchange | llm_judgeable_groundtruth_similarity | 2341890 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to understand the Scala quicksort example from Wikipedia. How could the sample be disassembled step by step and what does all the syntactic sugar involved mean? def qsort: List[Int] => List[Int] = { case Nil => Nil case pivot :: tail => val (smaller, rest) = tail.partition(_ < pivot) qsort(smaller) ::: pivot :: qsort(rest)} As much as I can gather at this stage qsort is a function that takes no parameters and returns a new Function1[List[Int],List[Int]] that implements quicksort through usage of pattern matching, list manipulation and recursive calls. But I can't quite figure out where the pivot comes from, and how exactly the pattern matching syntax works in this case. UPDATE: Thanks everyone for the great explanations! I just wanted to share another example of quicksort implementation which I have discovered in the Scala by Example by Martin Odersky . Although based around arrays instead of lists and less of a show-off in terms of varios Scala features I personally find it much less convoluted than its Wikipedia counterpart, and just so much more clear and to the point expression of the underlying algorithm: def sort(xs: Array[Int]): Array[Int] = { if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat( sort(xs filter (pivot >)), xs filter (pivot ==), sort(xs filter (pivot <))) }}
Now provide the response and nothing else.
| def qsort: List[Int] => List[Int] = { case Nil => Nil case pivot :: tail => val (smaller, rest) = tail.partition(_ < pivot) qsort(smaller) ::: pivot :: qsort(rest) } Let's rewrite that. First, replace the function literal with an instance of Function1 : def qsort: List[Int] => List[Int] = new Function1[List[Int], List[Int]] { def apply(input: List[Int]): List[Int] = input match { case Nil => Nil case pivot :: tail => val (smaller, rest) = tail.partition(_ < pivot) qsort(smaller) ::: pivot :: qsort(rest) }} Next, I'm going to replace the pattern match with equivalent if / else statements. Note that they are equivalent , not the same. The bytecode for pattern matches are more optimized. For instance, the second if and the exception throwing below do not exist, because the compile knows the second match will always happen if the first fails. def qsort: List[Int] => List[Int] = new Function1[List[Int], List[Int]] { def apply(input: List[Int]): List[Int] = if (input == Nil) { Nil } else if (input.isInstanceOf[::[_]] && scala.collection.immutable.::.unapply(input.asInstanceOf[::[Int]]) != None) { val unapplyResult = scala.collection.immutable.::.unapply(input.asInstanceOf[::[Int]]).get val pivot = unapplyResult._1 val tail = unapplyResult._2 val (smaller, rest) = tail.partition(_ < pivot) qsort(smaller) ::: pivot :: qsort(rest) } else { throw new scala.MatchError(input) }} Actually, val (smaller, rest) is pattern match as well, so Let's decompose it as well: def qsort: List[Int] => List[Int] = new Function1[List[Int], List[Int]] { def apply(input: List[Int]): List[Int] = if (input == Nil) { Nil } else if (input.isInstanceOf[::[_]] && scala.collection.immutable.::.unapply(input.asInstanceOf[::[Int]]) != None) { val unapplyResult0 = scala.collection.immutable.::.unapply(input.asInstanceOf[::[Int]]).get val pivot = unapplyResult0._1 val tail = unapplyResult0._2 val tmp0 = tail.partition(_ < pivot) if (Tuple2.unapply(tmp0) == None) throw new scala.MatchError(tmp0) val unapplyResult1 = Tuple2.unapply(tmp0).get val smaller = unapplyResult1._1 val rest = unapplyResult1._2 qsort(smaller) ::: pivot :: qsort(rest) } else { throw new scala.MatchError(input) }} Obviously, this is highly unoptmized. Even worse, there are some function calls being done more than once, which doesn't happen in the original. Unfortunately, to fix that would require some structural changes to the code. There's still some syntactic sugar here. There is an anonymous function being passed to partition, and there is the syntactic sugar for calling functions. Rewriting those yields the following: def qsort: List[Int] => List[Int] = new Function1[List[Int], List[Int]] { def apply(input: List[Int]): List[Int] = if (input == Nil) { Nil } else if (input.isInstanceOf[::[_]] && scala.collection.immutable.::.unapply(input.asInstanceOf[::[Int]]) != None) { val unapplyResult0 = scala.collection.immutable.::.unapply(input.asInstanceOf[::[Int]]).get val pivot = unapplyResult0._1 val tail = unapplyResult0._2 val func0 = new Function1[Int, Boolean] { def apply(input: Int): Boolean = input < pivot } val tmp0 = tail.partition(func0) if (Tuple2.unapply(tmp0) == None) throw new scala.MatchError(tmp0) val unapplyResult1 = Tuple2.unapply(tmp0).get val smaller = unapplyResult1._1 val rest = unapplyResult1._2 qsort.apply(smaller) ::: pivot :: qsort.apply(rest) } else { throw new scala.MatchError(input) }} For once, the extensive explanations about each syntactic sugar and how it works are being done by others. :-) I hope this complements their answers. Just as a final note, the following two lines are equivalent: qsort(smaller) ::: pivot :: qsort(rest) qsort(rest).::(pivot).:::(qsort(smaller)) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2341890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22088/']} | jdg_76420 |
stackexchange | llm_judgeable_groundtruth_similarity | 244384 |
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:
Im trying to read Data Output Registers of X,Y,Z So far I've been able to: Send a START - flag 0x08 = START condition transmitted.Send 0x3C - flag 0x18 = SLA+W transmitted, ACK received.//For configuring HMC5883L Control Register A & BSend 0x02 data byte - flag 0x28 = Data byte transmitted, ACK received.Send 0x00 data byte - flag 0x28 = Data byte transmitted, Ack Received.Send a Repeat Start - flag 0x10 = Repeat Start condition transmitted.Send 0x3D - flag 0x40 = SLA+R transmitted, ACK received.Start > SLA+W > Configure Control Register A & B > Repeat Start > SLA+R > ?? I'm stuck on what to do after sending a SLA+R, I've tried sending a 0x03 (MSB register for Output X). I keep getting a repeated fixed value like (0,10,10,18 - repeat). My main question would be how do I correctly read the memory address of the slave at 0x03 followed by 0x04, 0x05, 0x06, 0x07, 0x08 successfully? In the data sheet it is mentioned: When one or more of the output registers are read, new data cannot be placed in any of the output data registers until all six data output registers are read. To minimize the communication between the master and this device, the address pointer updated automatically without master intervention. The register pointer will be incremented by 1 automatically after the current register has been read successfully. The address pointer value itself cannot be read via the I2C bus. Any attempt to read an invalid address location returns 0’s, and any write to an invalid address location or an undefined bit within a valid address location is ignored by this device. To move the address pointer to a random register location, first issue a “write” to that register location with no data byte following the commend. For example, to move the address pointer to register 10, send 0x3C 0x0A. Any help would be appreciated, thanks in advance!
Now provide the response and nothing else.
| In general, when you're looking at the bit representation of data in memory, you only have two options: Use a pointer to the variable, and "lie" as to what it is pointing to: Note @erebos' and @Lundin's comments below: while you'll often see something like the following, it is NOT strictly conformant C. That "lie" could bite you... volatile float f;volatile uint32_t *p = (volatile uint32_t *)&f; // Take the address of f and cast it....if (*p!=0xFFFFFFFFu) { printf("%f", f);} // if Use a union structure to change its interpretation depending on what field you acccess: typedef union FloatAs32 { volatile float f; volatile uint32_t i; // "Overlays" other fields in union} FloatAs32;FloatAs32 f;...if (f.i!=0xFFFFFFFFu) { // Access 'i' field printf("%f", f.f); // Access 'f' field} // if I say "in general", because you may also have the opportunity to rely on the encoding of the float to get what you want. I'll need to check my references, but it may be that you can test for NaN , which is a special representation of floats to indicate (literally) "Not a Number" (such as sqrt(-1); ) Your test if (f==0xFFFFFFFF) tries to compare the interpreted value of the float against that number. You want to compare against the uninterpreted value. Edit I checked my sources, and I was right. If the "Exponent" field is all 1 s, and the "Mantissa" field is not all 0 s (which matches your case in general, but not specifically all F s), then the float is interpreted as a NaN . Note that the "Sign" bit is used to distinguish between a "Quiet" NaN (can be propagated through calculations) and a "Signalling" NaN (can cause exceptions). Luckily, a "Sign" bit of 1 (as in your case) is a QNaN . That means that you can simply use the isnan(f) function and it will return true for your special case - and other cases too. Does your device produce a NaN at any time? Perhaps to indicate an error condition? If so, you shouldn't use this suggestion. If not... that's your call. Edit #2 @dwelch made a good point in the comments about using volatile . The compiler could keep its values in registers rather than memory, so neither example above would have worked. Adding volatile tells the compiler to always read and write the values to memory rather than caching them. I've modified my examples to take this into account. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/244384', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/115838/']} | jdg_76421 |
stackexchange | llm_judgeable_groundtruth_similarity | 2541467 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the real reason for that limitation? Is it just work that had to be done? Is it conceptually hard? Is it impossible? Sure, one couldn't use the type parameters in fields, because they are allways read-write. But that can't be the answer, can it? The reason for this question is that I'm writing an article on variance support in C# 4, and I feel that I should explain why it is restricted to delegates and interfaces. Just to inverse the onus of proof. Update: Eric asked about an example. What about this (don't know if that makes sense, yet :-)) public class Lookup<out T> where T : Animal { public T Find(string name) { Animal a = _cache.FindAnimalByName(name); return a as T; }}var findReptiles = new Lookup<Reptile>();Lookup<Animal> findAnimals = findReptiles; The reason for having that in one class could be the cache that is held in the class itself. And please don't name your different type pets the same! BTW, this brings me to optional type parameters in C# 5.0 :-) Update 2: I'm not claiming the CLR and C# should allow this. Just trying to understand what led to that it doesnt.
Now provide the response and nothing else.
| First off, as Tomas says, it is not supported in the CLR. Second, how would that work? Suppose you have class C<out T>{ ... how are you planning on using T in here? ... } T can only be used in output positions. As you note, the class cannot have any field of type T because the field could be written to. The class cannot have any methods that take a T, because those are logically writes. Suppose you had this feature -- how would you take advantage of it? This would be useful for immutable classes if we could, say, make it legal to have a readonly field of type T; that way we'd massively cut down on the likelihood that it be improperly written to. But it's quite difficult to come up with other scenarios that permit variance in a typesafe manner. If you have such a scenario, I'd love to see it. That would be points towards someday getting this implemented in the CLR. UPDATE: See Why isn't there generic variance for classes in C# 4.0? for more on this question. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2541467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11562/']} | jdg_76422 |
stackexchange | llm_judgeable_groundtruth_similarity | 11720585 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
2011-12-01T00:43:51.251871+05:18 Dec 01 2011 00:41:32 KOC-TEJ-AMEX-ASA-5510-6 : %ASA-4-106023: Deny icmp src TCS:172.26.40.1 dst AMEX:172.26.40.187 (type 5, code 0) by access-group "TCS_access_in" [0x953d065b, 0x0] Need to extract 2011-12-01T00:43:51.251871+05:18 My code create view standardLogTime asextract regex /(\d{4}\-\d{2}\-\d+\w+\:\d{2}\:\d+\.\d+\+\d+\:\d+)/ on D.text as testValuefrom Document D; -- Extracting standard log generation time. create view standardLogTime asextract regex /\d{4}(-\d{2}){2}T(\d{2}:){2}\d{2}\.\d+?\+\d{2}:\d{2}/ on D.text as testValuefrom Document D;output view standardLogTime; -- Extracting incoming request Date. create view dateView asextract regex /(\s+\w+\s\d+\s\d{4})/ on Date.text as testDate from Document Date; --output view dateView; -- Extracting incoming request Time. create view timeView asextract regex /\s+(\d{1,2}\:\d{1,2}\:\d{1,2})/ on Time.textas requestTime from Document Time; --output view timeView; -- Extracting the firewall device name. create view deviceName as extract regex /(\w+\-\w+\-\w+\-\w+\-\d+\-\d+)/ on Device.text as deviceName from Document Device; --output view deviceName; create view combinedView asextract pattern (<S.testValue>) (<D.testDate>) (<T.requestTime>) (<Div.deviceName>)return group 0 as logTime and group 1 as date and group 2 as time and group 3 as deviceName from standardLogTime S,dateView D ,timeView T,deviceName Div; output view combinedView;*/
Now provide the response and nothing else.
| While the value returned by Type.FullName and the C# type identifier sometimes happen to be the same, this is not guaranteed. Keep in mind that Type.FullName returns the same value regardless of what CLI language it is called from, be it C#, VB.NET, Oxygene or anything else. For multidimensional and jagged arrays, C# syntax lists the indices in the order they are written later on, while reflection syntax returns something that matches the logical structure of the array. And a (C#) string[,][,,][,,,] is, after all, a value of type string , thereof a 4-dimensional array (i.e. string[,,,] ), thereof a 3-dimensional array (i.e. string[,,,][,,] ) and thereof a 2-dimensional array (i.e. string[,,,][,,][,] ). Rather than relying on the reflection syntax name returned by FullName , you might want to examine the properties of the Type class when analyzing types. Information such as the number of dimensions or the generic arguments can be retrieved from there. When constructing types, you can also use methods such as MakeArrayType or MakeGenericType to create complex types at runtime without constructing a string that contains the ingredients for the new types. Some of the contents of this answer was pointed out by Marc Gravell - thank you! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11720585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1340260/']} | jdg_76423 |
stackexchange | llm_judgeable_groundtruth_similarity | 486333 |
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:
The definition of direct limits is: I'm trying to see how this definition works in the stalks: The index $I$ is the open sets containing $x$ under the inclusion and the restrictions $\rho_{UV}:\mathcal F(U)\to \mathcal F(V)$ are the $f_{ik}$. The $f_i$ are the maps where $s\in \mathcal F(U)$, $s\mapsto s_x\in \mathcal F_x$ I hope I'm right by now, I continue... Then, In order prove the definition of direct limit is equivalent with the definition of $\mathcal F_x$, I have to demonstrate the diagram commutes using the definition of $\mathcal F_x$ using equivalence classes: I'm struggling to prove the commutativity of the inner triangle $(f_j\circ f_{ij}=f_i)$, I need help in this part. Thanks a lot
Now provide the response and nothing else.
| One way is: If $r=(-5)^{1/4}$, so that the splitting field is $L=\mathbb Q(r,i)$, then $Gal(L/\mathbb Q(i))$ is the cyclic group $C_4$, acting via $r\to i^k r$ ($k\in\mathbb Z$ mod 4). To see it: it is certainly a subgroup of this group; if it's a proper subgroup then $r^2$ is fixed, i.e. $r^2\in\mathbb Q(i)$. But that's not possible: $-5=(a+ib)^2$ has evidently no rational solutions. From this we get that $Gal(L/\mathbb Q)$ is $r\mapsto ri^k$, $i\mapsto\pm i$, which is the dihedral group. [edited to become a 'pure Galois' proof] | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/486333', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42912/']} | jdg_76424 |
stackexchange | llm_judgeable_groundtruth_similarity | 116429 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've read Steve McConnell's "Code Complete" and one of items in checklist for requirements is: "Is the definition of success included? Of failure?". Why is this important? Can you write any examples of those definitions? Can anybody provide examples of good requirements specification?
Now provide the response and nothing else.
| Why it's important? Can you write any examples of those definitions? When you specify a requirement, it's important that it meets certain qualities, such as cohesiveness (only address a single thing), complete (does not lack any information needed to fulfill the desired outcome), traceable (it is documented and can be tracked through design, implementation, and maintenance in both directions), up-to-date, feasible (it can actually be implemented), unambiguous (multiple people reading it will have the same idea of the desired outcome), and verifiable (it can be tested and easily seen whether the requirement is complete). Defining success or failure criteria for a requirement allows it to be complete, traceable, feasible, unambiguous, and verifiable. How can you know if the requirement can be met now or in the future? How can you know when you have implemented the feature or aspect of the system? How can you point to specific modules at any level that implement the requirement, either in a representation of the design or the implementation? This is somewhat related to the concept of "definition of done" in the agile community , as well. Can anybody provide examples of good requirements specification? You can find a lot of information about requirements, including examples, in Karl Wiegers' Software Requirements and More About Software Requirements: Thorny Issues and Practical Advice . In addition, Wiegers' site Process Impact provides a number of goodies , such as sample documents and templates. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/116429', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/15135/']} | jdg_76425 |
stackexchange | llm_judgeable_groundtruth_similarity | 30038475 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing a Rails 4 app that will expose an API for a mobile app that's yet to be developed. Users will authenticate using an e-mail and password from the mobile app. While I've found quite a bit of information on the topic. It's hard to discern what's dated or non-optimal. I've read about HTTP Basic Auth, which doesn't seem too secure, and HTTP Token-based Auth, but I'm not sure on how to couple that with regular e-mail and password authentication (I'm using Devise by the way). I'd just like to know what's the current best practice on how to implement this, so I'll be sure to be going the right way.
Now provide the response and nothing else.
| The important point, from a security perspective, is to exchange the user's email and password for a token once, and then use that token for subsequent requests. This is because: You don't want the client app to be responsible for holding onto the user's password, where a bug or attack could cause it to be leaked; and A server-issued token gives you (and your users) the ability to expire a token if necessary, e.g. to lock out a stolen device or block a misbehaving API client. There are many ways to accomplish this with varying levels of complexity. Here is a tutorial that is very recent and has a thorough walkthrough for creating an API in Rails with token-based authentication (not using Devise, but still relevant to understand the concepts): https://labs.kollegorna.se/blog/2015/04/build-an-api-now/ | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30038475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2201664/']} | jdg_76426 |
stackexchange | llm_judgeable_groundtruth_similarity | 9614622 |
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 jQuery, there are .hide() and .show() methods which sets the CSS display: none setting. Is there an equivalent function which would set the visibility: hidden setting? I know I can use .css() but I prefer some function like .hide() or so. Thanks.
Now provide the response and nothing else.
| You could make your own plugins. jQuery.fn.visible = function() { return this.css('visibility', 'visible');};jQuery.fn.invisible = function() { return this.css('visibility', 'hidden');};jQuery.fn.visibilityToggle = function() { return this.css('visibility', function(i, visibility) { return (visibility == 'visible') ? 'hidden' : 'visible'; });}; If you want to overload the original jQuery toggle() , which I don't recommend... !(function($) { var toggle = $.fn.toggle; $.fn.toggle = function() { var args = $.makeArray(arguments), lastArg = args.pop(); if (lastArg == 'visibility') { return this.visibilityToggle(); } return toggle.apply(this, arguments); };})(jQuery); jsFiddle . | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/9614622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684229/']} | jdg_76427 |
stackexchange | llm_judgeable_groundtruth_similarity | 10319643 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm a bit confused about how and when to use beginBackgroundTaskWithExpirationHandler . Apple shows in their examples to use it in applicationDidEnterBackground delegate, to get more time to complete some important task, usually a network transaction. When looking on my app, it seems like most of my network stuff is important, and when one is started I would like to complete it if the user pressed the home button. So is it accepted/good practice to wrap every network transaction (and I'm not talking about downloading big chunk of data, it mostly some short xml) with beginBackgroundTaskWithExpirationHandler to be on the safe side?
Now provide the response and nothing else.
| If you want your network transaction to continue in the background, then you'll need to wrap it in a background task. It's also very important that you call endBackgroundTask when you're finished - otherwise the app will be killed after its allotted time has expired. Mine tend look something like this: - (void) doUpdate { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [self beginBackgroundUpdateTask]; NSURLResponse * response = nil; NSError * error = nil; NSData * responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error]; // Do something with the result [self endBackgroundUpdateTask]; });}- (void) beginBackgroundUpdateTask{ self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ [self endBackgroundUpdateTask]; }];}- (void) endBackgroundUpdateTask{ [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask]; self.backgroundUpdateTask = UIBackgroundTaskInvalid;} I have a UIBackgroundTaskIdentifier property for each background task Equivalent code in Swift func doUpdate () { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let taskID = beginBackgroundUpdateTask() var response: URLResponse?, error: NSError?, request: NSURLRequest? let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error) // Do something with the result endBackgroundUpdateTask(taskID) })}func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier { return UIApplication.shared.beginBackgroundTask(expirationHandler: ({}))}func endBackgroundUpdateTask(taskID: UIBackgroundTaskIdentifier) { UIApplication.shared.endBackgroundTask(taskID)} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10319643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/954267/']} | jdg_76428 |
stackexchange | llm_judgeable_groundtruth_similarity | 199472 |
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 AIX (but this happens on HP-UX as well), I have GNU ls in my pathand it is also aliased as ls . When I use xargs, it instead uses the standard Unix ls instead of thealias. For example ( flocate is a function which finds the exact path ofthe search subject): flocate mirrorvg | xargs ls -lhls: illegal option -- husage: ls [-1ACFHLNRSabcdefgiklmnopqrstuxEUX] [File...]ls -lh /usr/sbin/mirrorvg-r-xr-x--- 1 root system 37K apr 3 2014 /usr/sbin/mirrorvg* Why doesn't xargs use the ls alias?
Now provide the response and nothing else.
| The command xargs is only able to run commands, not aliases. GNU parallel, however, is able to run functions: The command must be an executable, a script, a composedcommand, or a function. If it is a function you need to export-f the function first. An alias will, however, not work (seewhy http://www.perlmonks.org/index.pl?node_id=484296). So I would recommend either: Giving xargs the full path to the version of ls you want to use (or an unambiguous name, perhaps gls depending on how it was installed on your system) or, if your shell allows it, Defining ls as a function ( function ls { gls "$@"; }; export -f ls in bash) and using GNU parallel instead of xargs ( parallel -j1 if you would like to use a single CPU). | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/199472', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/80389/']} | jdg_76429 |
stackexchange | llm_judgeable_groundtruth_similarity | 17180673 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this code to initialize map from into to unique_ptr. auto a = unique_ptr<A>(new A());map<int, unique_ptr<A>> m;m[1] = move(a); Can I use uniform initialize this? I tried map<int, unique_ptr<A>> m {{1, unique_ptr<A>(new A())}}; But I got an error. Some part of error message is In instantiation of 'std::_Rb_tree_node<_Val>::_Rb_tree_node(_Args&& ...) [with _Args = {const std::pair<const int, std::unique_ptr<A, std::default_delete<A> > >&}; _Val = std::pair<const int, std::unique_ptr<A> >]': ... In file included from /opt/local/include/gcc48/c++/memory:81:0, from smart_pointer_map.cpp:3: /opt/local/include/gcc48/c++/bits/unique_ptr.h:273:7: error: declared here unique_ptr(const unique_ptr&) = delete; ^
Now provide the response and nothing else.
| unique_ptr is movable, but not copyable. initializer_list requires copyable types; you can't move something out of an initializer_list . Unfortunately, I believe what you want to do isn't possible. Incidentally, it would be more helpful to know which specific error you got. Otherwise, we have to guess whether you did something wrong and what, or whether what you want to do isn't implemented in your compiler, or is simply not supported in the language. (This is most helpful along with minimal reproduction code.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17180673', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260127/']} | jdg_76430 |
stackexchange | llm_judgeable_groundtruth_similarity | 24775451 |
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 creating a Android Wear app that has an touch area. The user is suppose to be able to move it's finger in all directions over the screen (Think touchpad on your laptop). However the back swipe makes this a bit problematic. Any help with getting around this issue would be a great help. How to disable the android wear back swipe? /Jakob
Now provide the response and nothing else.
| There is an attribute in window style to disable this behavior: <style name="AppTheme" parent="@android:style/Theme.DeviceDefault.Light"> <item name="android:windowSwipeToDismiss">false</item></style> Once you disable it you have to provide other way of exiting your app. There is a DismissOverlayView class (listed here https://developer.android.com/training/wearables/apps/layouts.html#UiLibrary ) that you should use instead. Basically it provides an overlay that will show a red button with cross after a long press. Clicking the red button will exit your app. Here is a video from Google I/O 2014 with some bookmarked moments: https://www.youtube.com/watch?v=sha_w3_5c2c#t=1390 <- disabling android:windowSwipeToDismiss https://www.youtube.com/watch?v=sha_w3_5c2c#t=1505 <- Java code for DismissOverlayView You can also check another video called: Fullscreen apps for Android Wear : https://www.youtube.com/watch?v=naf_WbtFAlY | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24775451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3825965/']} | jdg_76431 |
stackexchange | llm_judgeable_groundtruth_similarity | 29076255 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a database full of user user entered Barcode numbers of variious lengths. How can I validate these barcode values to determine if the are correct format, ie, length and check digit? using php
Now provide the response and nothing else.
| here you go: function isValidBarcode($barcode) { //checks validity of: GTIN-8, GTIN-12, GTIN-13, GTIN-14, GSIN, SSCC //see: http://www.gs1.org/how-calculate-check-digit-manually $barcode = (string) $barcode; //we accept only digits if (!preg_match("/^[0-9]+$/", $barcode)) { return false; } //check valid lengths: $l = strlen($barcode); if(!in_array($l, [8,12,13,14,17,18])) return false; //get check digit $check = substr($barcode, -1); $barcode = substr($barcode, 0, -1); $sum_even = $sum_odd = 0; $even = true; while(strlen($barcode)>0) { $digit = substr($barcode, -1); if($even) $sum_even += 3 * $digit; else $sum_odd += $digit; $even = !$even; $barcode = substr($barcode, 0, -1); } $sum = $sum_even + $sum_odd; $sum_rounded_up = ceil($sum/10) * 10; return ($check == ($sum_rounded_up - $sum)); } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29076255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4676202/']} | jdg_76432 |
stackexchange | llm_judgeable_groundtruth_similarity | 42599 |
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created three different models using deep learning for multi-class classification and each model gave me a different accuracy and loss value. The results of the testing model as the following: First Model: Accuracy: 98.1% Loss: 0.1882 Second Model: Accuracy: 98.5% Loss: 0.0997 Third Model: Accuracy: 99.1% Loss: 0.2544 My questions are: What is the relationship between the loss and accuracy values? Why the loss of the third model is the higher even though the accuracy is higher?
Now provide the response and nothing else.
| There is no relationship between these two metrics. Loss can be seen as a distance between the true values of the problem and the values predicted by the model. Greater the loss is, more huge is the errors you made on the data. Accuracy can be seen as the number of error you made on the data. That means: a low accuracy and huge loss means you made huge errors on a lot of data a low accuracy but low loss means you made little errors on a lot of data a great accuracy with low loss means you made low errors on a few data (best case) your situation: a great accuracy but a huge loss, means you made huge errors on a few data. For you case, the third model can correctly predict more examples, but on those where it was wrong, it made more errors (the distance between true value and predicted values is more huge). NOTE: Don't forget that low or huge loss is a subjective metric, which depends on the problem and the data. It's a distance between the true value of the prediction, and the prediction made by the model. It depends also on the loss you use. Think: If your data are between 0 and 1, a loss of 0.5 is huge, but if your data are between 0 and 255, an error of 0.5 is low. Maybe think of cancer detection, and probability of detecting a cancer. Maybe an error of 0.1 is huge for this problem, whereas an error f 0.1 for image classification is fine. | {} | {'log_upvote_score': 6, 'links': ['https://datascience.stackexchange.com/questions/42599', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/51129/']} | jdg_76433 |
stackexchange | llm_judgeable_groundtruth_similarity | 22031 |
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
(This isn't a "maintenance & repair" question, I hope you'll forgive me.) When powerful electric cars (such as, but not only, the Tesla) can accelerate from zero to ludicrous in half a jiffy, and can do regenerative braking, then why do they still use "old school" mechanical disc brakes? Does acceleration ability not equate deceleration ability? Is the brake construction mandated by law (I know, this depends on location, but seems to be the case for all brands anyhow)? Or is it a safety feature (no power=no braking, oops)?
Now provide the response and nothing else.
| It's not so much that the motors can't brake like mad. It's as you hint at yourself that any auto-mobile that is required to be fully road legal needs two completely separate systems for braking, in case one of them fails. It's why even the most automated gas-fuelled cars still had a hand-brake type system. It originates from the perceived unreliability of hard to maintain systems, such as hidden cables or liquid braking systems, so that there was a way to stop the vehicle, be it slower, if one of them fails. | {} | {'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/22031', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/6473/']} | jdg_76434 |
stackexchange | llm_judgeable_groundtruth_similarity | 50014088 |
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 basic inheritance situation with an overloaded method in the super class. public class Person { private String name; private int dob; private String gender; public Person(String theName, int birth, String sex){ name = theName; dob = birth; gender = sex; } public void work(){ getWorkDetail(this); } public void getWorkDetail(Employee e){ System.out.println("This person is an Employee"); } public void getWorkDetail(Person p){ System.out.println("This person is not an Employee"); }} The following Employee class extends the Person class above: public class Employee extends Person { String department; double salary; public Employee(String theName, int birth, String sex){ super(theName, birth, sex); department = "Not assigned"; salary = 30000; }} The main method simply creates an Employee object (both static and dynamic type) and calls .work() on it: public static void main(String[] args){ Employee e1 = new Employee("Manager1", 1976, "Female"); e1.work();} This ends up printing This person is not an Employee Looking through this I had thought that since both the static and dynamic type of the object e1 is Employee it would call the overloaded method in Person that takes an Employee as a parameter. Since I am clearly wrong about this I opened a debugger assuming the reference to "this" at the line getWorkDetail(this) in the Person class must have morphed to it's super class. However this is not what I found. Clearly at this point in the code this is an Employee object, however it still chose to execute the overloaded method getWorkDetail(Person p) . Can anyone explain this behavior?
Now provide the response and nothing else.
| Unlike method overrides, method overloads are linked based on the static type. And in this case, getWorkDetail(this) in Person only knows about the Person type. Method overloading is not designed to provide dynamic runtime behavior. To take advantage of dynamic binding, you may need to redesign your code to override the methods, instead: public static void main(String[] args) throws IOException { new Employee("Manager1", 1976, "Female").getWorkDetail(); new Person("Manager1", 1976, "Female").getWorkDetail();} And modify behavior based on implementing classes. Of course, you can overload methods, as long as you take care of overriding the overloaded methods too, if required. class Person { private String name; private int dob; private String gender; public Person(String theName, int birth, String sex) { name = theName; dob = birth; gender = sex; } public void getWorkDetail() { System.out.println("This person is not an Employee"); }}class Employee extends Person { String department; double salary; public Employee(String theName, int birth, String sex) { super(theName, birth, sex); department = "Not assigned"; salary = 30000; } public void getWorkDetail() { System.out.println("This person is an Employee"); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50014088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6735965/']} | jdg_76435 |
stackexchange | llm_judgeable_groundtruth_similarity | 51109159 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on an app using the latest version of NativeScript with Angular. I have added most of the pro-ui plugins to my project and added the Firbase plugin. When I run “tns run android” I get the error: “D8: Cannot fit requested classes in a single dex file. Try supplying a main-dex list.” Also, it takes over 5 minutes to build. I have been doing some searching but I cannot find what is causing this problem. Does anyone know what is wrong?
Now provide the response and nothing else.
| After much trial and error I have finally come to a solution. All other answers I've read have said that the multiDexEnabled property must be set to true in the android project's build.gradle file. I wasn't sure how to do this for NativeScript though since the platforms folder is not committed to version control and can be potentially overwritten. However, in your_project_root/app/App_resources/Android there are two files, settings.gradle and settings.json . settings.gradle is used to generate your projects's build.gradle file from the properties you set in settings.json . So, to the defaultConfig string template in settings.gradle I added: if(__multiDexEnabled__) { multiDexEnabled = __multiDexEnabled__} And to the JSON object defined in settings.json I added: "multiDexEnabled": true After that I deleted my project's platforms folder and ran: > tns platforms add android> tns run android And my app started up on my phone with no problems. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51109159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/515377/']} | jdg_76436 |
stackexchange | llm_judgeable_groundtruth_similarity | 215931 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use apropos so that I would look for all man pages starting with system . I try: apropos ^systemapropos "^system" but these seem to return lines that don't start with system, but where system occurs somewhere in the line. Any ideas? Edit As per comment below, the above actually works but it matches against several compoments: - cmd name - cmd description - cmd one liner. So when I searched for system, I got a line like this: tapset::task_time (3stap) - systemtap task_time tapset Which makes sense because the description starts with system. One way to get really just the lines starting with "system" would be: apropos "" | grep "^system"
Now provide the response and nothing else.
| Running apropos '^system' works for me, returning the list of man pages where either the page name itself starts with system or the one line description starts with system. For example, the output on Debian (jessie) includes: system-config-printer (1) - configure a CUPS serversigset (3) - System V signal API I know of no clean way to tell apropros to search only in page names or in the one-line description, but there's always grep : apropos system | grep -- '^system' # page namesapropos system | grep -- '- system' # descriptions Either of these can be encapsulated in a shell function such as this: apro() { apropos "$1" | grep -- "^$1"; } | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/215931', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/77271/']} | jdg_76437 |
stackexchange | llm_judgeable_groundtruth_similarity | 257124 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $x_1 \cdots x_n$ be real numbers $x_i>1$ such that $$\frac{1}{x_1} + \cdots + \frac{1}{x_n} = 1$$ Is it true that the matrix $$\left[\begin{matrix}x_1-1 & -1 & \cdots & -1 \\-1 & x_2-1 & \cdots & -1 \\\vdots & \vdots & \ddots & -1 \\-1 & -1 & \cdots & x_n-1\end{matrix}\right]$$ has rank $n-1$? Is there a simple proof?
Now provide the response and nothing else.
| Yes, it's true. Here's a very elementary proof, using $\text{rk}(M) = n-\dim (\ker M)$. We have $M_{ij} = x_i\delta_{ij} - 1$, so $v \in \ker M$ becomes\begin{align*}&\sum_{j=1}^n (x_i\delta_{ij} - 1)v_j = 0 ~,~\forall~i\\\Rightarrow& v_j = \frac{1}{x_j}\sum_{i=1}^n v_i~.\end{align*}So the kernel is one-dimensional (determined by the arbitrary constant $K = \sum_i v_i$). The constraint you get from summing the above over $j$ is satisfied identically due to your condition $\sum_j 1/x_j = 1$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/257124', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4873/']} | jdg_76438 |
stackexchange | llm_judgeable_groundtruth_similarity | 28838530 |
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 Spring Boot (1.2.1.RELEASE) application that serves OAuth2 (2.0.6.RELEASE) authorization and resource server in one application instance. It uses custom UserDetailsService implementation that makes use of MongoTemplate to search users in MongoDB. Authentication with grant_type=password on /oauth/token works like a charm, as well as authorization with Authorization: Bearer {token} header while calling for specific resources. Now I want to add simple OAuth confirm dialog to the server, so I can authenticate and authorize e.g. Swagger UI calls in api-docs for protected resources. Here is what I did so far: @Configuration@SessionAttributes("authorizationRequest")class OAuth2ServerConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/login").setViewName("login"); registry.addViewController("/oauth/confirm_access").setViewName("authorize"); } @Configuration @Order(2) protected static class LoginConfig extends WebSecurityConfigurerAdapter implements ApplicationEventPublisherAware { @Autowired UserDetailsService userDetailsService @Autowired PasswordEncoder passwordEncoder ApplicationEventPublisher applicationEventPublisher @Bean DaoAuthenticationProvider daoAuthenticationProvider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider() provider.passwordEncoder = passwordEncoder provider.userDetailsService = userDetailsService return provider } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.parentAuthenticationManager(authenticationManagerBean()) .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()) } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { //return super.authenticationManagerBean() ProviderManager providerManager = new ProviderManager([daoAuthenticationProvider()], super.authenticationManagerBean()) providerManager.setAuthenticationEventPublisher(new DefaultAuthenticationEventPublisher(applicationEventPublisher)) return providerManager } @Bean public PasswordEncoder passwordEncoder() { new BCryptPasswordEncoder(5) } } @Configuration @EnableResourceServer protected static class ResourceServer extends ResourceServerConfigurerAdapter { @Value('${oauth.resourceId}') private String resourceId @Autowired @Qualifier('authenticationManagerBean') private AuthenticationManager authenticationManager @Override public void configure(HttpSecurity http) throws Exception { http.setSharedObject(AuthenticationManager.class, authenticationManager) http.csrf().disable() http.httpBasic().disable() http.formLogin().loginPage("/login").permitAll() //http.authenticationProvider(daoAuthenticationProvider()) http.anonymous().and() .authorizeRequests() .antMatchers('/login/**').permitAll() .antMatchers('/uaa/register/**').permitAll() .antMatchers('/uaa/activate/**').permitAll() .antMatchers('/uaa/password/**').permitAll() .antMatchers('/uaa/account/**').hasAuthority('ADMIN') .antMatchers('/api-docs/**').permitAll() .antMatchers('/admin/**').hasAuthority('SUPERADMIN') .anyRequest().authenticated() //http.sessionManagement().sessionCreationPolicy(STATELESS) } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(resourceId) resources.authenticationManager(authenticationManager) } } @Configuration @EnableAuthorizationServer protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter { @Value('${oauth.clientId}') private String clientId @Value('${oauth.secret:}') private String secret @Value('${oauth.resourceId}') private String resourceId @Autowired @Qualifier('authenticationManagerBean') private AuthenticationManager authenticationManager @Bean public JwtAccessTokenConverter accessTokenConverter() { return new JwtAccessTokenConverter(); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.checkTokenAccess("permitAll()") oauthServer.allowFormAuthenticationForClients() } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .accessTokenConverter(accessTokenConverter()) } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient(clientId) .secret(secret) .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit") .authorities("USER", "ADMIN") .scopes("read", "write", "trust") .resourceIds(resourceId) } }} Main problem is that I cannot make both (web login form and OAuth2 authorization token in header) running. If ResourceServer gets higher priority, then OAuth2 token authorization works, but I can't login using web form. On the other hand if I set the higher priority to LoginConfig class, then OAuth2 token authorization stops working. Case study: Login form works, OAuth2 token authorization does not I figured out that in that case the problem is caused by non-registered OAuth2AuthenticationProcessingFilter . I tried to registered it manually in ResourceServer.configure(HttpSecurity http) method, but it didn't work - I could see the filter on FilterChain list, but it didn't get triggered. It wasn't good way to fix it, because there is a lot of other magic done during the ResourceServer initialization so I moved to the second case. Case study: Login form does not work, OAuth2 token authorization works In that case the main problem is that by default UsernamePasswordAuthenticationFilter cannot find a properly configured AuthenticationProvider instance (in ProviderManager ). When I tried to add it manually by: http.authenticationProvide(daoAuthenticationProvider()) it gets one, but in this case there is no AuthenticationEventPublisher defined and successful authentication cannot be published to other components. And in fact in the next iteration it gets replaced by AnonymousAuthenticationToken . That's why I tried to define manually AuthenticationManager instance with DaoAuthenticationProvider inside: @Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception { //return super.authenticationManagerBean() ProviderManager providerManager = new ProviderManager([daoAuthenticationProvider()], super.authenticationManagerBean()) providerManager.setAuthenticationEventPublisher(new DefaultAuthenticationEventPublisher(applicationEventPublisher)) return providerManager} I thought it will work, but there is a different problem with providing AuthenticationManager instance to registered filters. It turns out that each filter has authenticationManager injected manually using sharedObjects component: authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); The problem here is that you are not guaranteed to have a proper instance set, because there is a simple HashMap ( check it on GitHub ) used to store specific shared object and it can be change any time. I tried to set it in: http.setSharedObject(AuthenticationManager.class, authenticationManager) but before I get to the place where it is being read, it's already replaced by default implementation. I checked it with the debugger and it looks like that for each new filter there is a new instance of authentication manager. My question is: am I doing it correctly? How can I set up authorization server with the resources server integrated in one application with login form (OAuth2 dialog) working? Maybe it can be done in a different and much easier way. I would be thankful for any help.
Now provide the response and nothing else.
| Here is the solution to the problem. Take a look at this exemplary Groovy class: @Configuration@EnableResourceServerclass ResourceServer extends ResourceServerConfigurerAdapter { @Value('${oauth.resourceId}') private String resourceId @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable() http.httpBasic().disable() http.requestMatchers().antMatchers('/admin/**', '/uaa/**') .and().authorizeRequests() .antMatchers('/uaa/authenticated/**').authenticated() .antMatchers('/uaa/register/**').permitAll() .antMatchers('/uaa/activate/**').permitAll() .antMatchers('/uaa/password/**').permitAll() .antMatchers('/uaa/auth/**').permitAll() .antMatchers('/uaa/account/**').hasAuthority('ADMIN') .antMatchers('/admin/**').hasAuthority('ADMIN') .anyRequest().authenticated() http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(resourceId); }} Basically, to run OAuth2.0 authentication parallel with web form authentication, you have to put http.requestMatchers().antMatchers('/path/1/**', '/path/2/**') to configuration class. My previous configuration missed this important part so only OAuth2.0 took a part in authentication process. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28838530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2194470/']} | jdg_76439 |
stackexchange | llm_judgeable_groundtruth_similarity | 41474829 |
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 Foo: def __getitem__(self, item): print('getitem', item) if item == 6: raise IndexError return item**2 def __len__(self): print('len') return 3class Bar: def __iter__(self): print('iter') return iter([3, 5, 42, 69]) def __len__(self): print('len') return 3 Demo: >>> list(Foo())lengetitem 0getitem 1getitem 2getitem 3getitem 4getitem 5getitem 6[0, 1, 4, 9, 16, 25]>>> list(Bar())iterlen[3, 5, 42, 69] Why does list call __len__ ? It doesn't seem to use the result for anything obvious. A for loop doesn't do it. This isn't mentioned anywhere in the iterator protocol , which just talks about __iter__ and __next__ . Is this Python reserving space for the list in advance, or something clever like that? (CPython 3.6.0 on Linux)
Now provide the response and nothing else.
| See the Rationale section from PEP 424 that introduced __length_hint__ and offers insight on the motivation: Being able to pre-allocate lists based on the expected size, as estimated by __length_hint__ , can be a significant optimization. CPython has been observed to run some code faster than PyPy, purely because of this optimization being present. In addition to that, the documentation for object.__length_hint__ verifies the fact that this is purely an optimization feature: Called to implement operator.length_hint() . Should return an estimated length for the object (which may be greater or less than the actual length). The length must be an integer >= 0 . This method is purely an optimization and is never required for correctness . So __length_hint__ is here because it can result in some nice optimizations. PyObject_LengthHint , first tries to get a value from object.__len__ (if it is defined) and then tries to see if object.__length_hint__ is available. If neither is there, it returns a default value of 8 for lists. listextend , which is called from list_init as Eli stated in his answer, was modified according to this PEP to offer this optimization for anything that defines either a __len__ or a __length_hint__ . list isn't the only one that benefits from this, of course, bytes objects do : >>> bytes(Foo())lengetitem 0...b'\x00\x01\x04\t\x10\x19' so do bytearray objects but, only when you extend them : >>> bytearray().extend(Foo())lengetitem 0... and tuple objects which create an intermediary sequence to populate themselves: >>> tuple(Foo())lengetitem 0...(0, 1, 4, 9, 16, 25) If anybody is wandering why exactly 'iter' is printed before 'len' in class Bar and not after as happens with class Foo : This is because if the object in hand defines an __iter__ Python will first call it to get the iterator , thereby running the print('iter') too. The same doesn't happen if it falls back to using __getitem__ . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41474829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/674039/']} | jdg_76440 |
Subsets and Splits