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 | 31418376 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to slice a string in Go. Possible values can contain Latin chars and/or Arabic/Chinese chars. In the following example, the slice annotation [:1] for the Arabic string alphabet is returning a non-expected value/character. package main import "fmt" func main() { a := "a" fmt.Println(a[:1]) // works b := "ذ" fmt.Println(b[:1]) // does not work fmt.Println(b[:2]) // works fmt.Println(len(a) == len(b)) // false } http://play.golang.org/p/R-JxaxbfNL
Now provide the response and nothing else.
| First of all, you should really read about strings, bytes and runes in Go . And here is how you can achieve what you want: Go playground (I was not able to properly paste arabic symbols, but if Chinese works, arabic should work too). s := "abcdefghijklmnop" fmt.Println(s[2:9]) s = "维基百科:关于中文维基百科" fmt.Println(string([]rune(s)[2:9])) The output is: cdefghi百科:关于中文 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31418376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1566161/']} | jdg_77641 |
stackexchange | llm_judgeable_groundtruth_similarity | 21046282 |
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 having issues with a pod called DCIntrospect-ARC which should only work in DEBUG mode. It checks if the DEBUG macro is defined before running. However, it is not defined in the CocoaPods target and even though I am running in debug mode in Xcode it fails to run because the DEBUG macro is not defined. I can define the DEBUG macro in the podspec using s.xcconfig = { "GCC_PREPROCESSOR_DEFINITIONS" => '$(inherited) DEBUG=1' } but this defined DEBUG for all build configurations and not only the DEBUG configuration. Is this a CocoaPods issue? Shouldn't the DEBUG macro generally be defined for Pods? Can I work around this in the Podspec file and declare the DEBUG macro in the Debug build configuration only?
Now provide the response and nothing else.
| you can use the post_install hook in Podfile. This hook allows you to make any last changes to the generated Xcode project before it is written to disk, or any other tasks you might want to perform. http://guides.cocoapods.org/syntax/podfile.html#post_install post_install do |installer_representation| installer_representation.pods_project.targets.each do |target| target.build_configurations.each do |config| if config.name != 'Release' config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)', 'DEBUG=1'] end end endend | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21046282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1280966/']} | jdg_77642 |
stackexchange | llm_judgeable_groundtruth_similarity | 18161127 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Before starting, I'm a big fan of AutoFixture, I'm still in the curve of learning how to use the tool. So thanks for having developed Autofixture Mr Ploeh and all the contributors. So let's start with my question. According to AutoFixture/AutoMoq ignores injected instance/frozen mock The interesting part of the above link is given this code Mock<ISettings> settingsMock = new Mock<ISettings>();settingsMock.Setup(s => s.Get(settingKey)).Returns(xmlString);ISettings settings = settingsMock.Object;fixture.Inject(settings); To which Mark answer it can be rewritten to fixture.Freeze<Mock<ISettings>>() .Setup(s => s.Get(settingKey)).Returns(xmlString); It looks like a syntaxic sugar, using Freeze method is a way to write in fluent interface the creation of the mock, the configuration, and the injection in autofixture container. After doing some research on the web, there're actually a functional difference between Freeze and Inject. I found this question: https://github.com/AutoFixture/AutoFixture/issues/59 which point the answer to How can I Freeze a null instance in AutoFixture The author of the link above describe Freeze method as the following: Internally, Freeze creates an instance of the requested type (e.g. IPayPalConfiguration) and then injects it so it will always return that instance when you request it again I understand that when we do var customer = fixture.Freeze<Order>(); it will always use the same instance of Order whenever our code request an Order type. But what if I specify in Freeze constructor that I want it to use a specific instance ? Here's a little code example: [Fact]public void MethodeName(){ var fixture = new Fixture().Customize(new AutoMoqCustomization()); fixture.Freeze<OrderLine>(new OrderLine("Foo")); var order = fixture.Create<Order>();}public class Order{ private readonly OrderLine _line; public Order(OrderLine line) { _line = line; }}public class OrderLine{ private readonly string _name; public OrderLine(string name) { _name = name; }} Shouldn't the name of OrderLine be equal to "Foo" instead of namefe48163a-d5a0-49a5-b349-7b11ba5f804b ? The documentation of Freeze method say: <typeparam name="T">The type to freeze.</typeparam><param name="fixture">The fixture.</param><param name="seed">Any data that adds additional information when creating the anonymous object. Hypothetically, this value might be the value being frozen, but this is not likely.</param> why is the author not sure when the value is returned ? If I specify, my instance in the constructor of Freeze, I'm expecting autofixture to use this instance ? then Please notice that the isn't likely to be used as the frozen value, unless you've customized to do this. If you wish to inject a specific value into the Fixture, you should use the method instead.` It seems like I have to customize the seed parameter. Can anyone clarify ? The solution pointed by documentation is to use Inject method. And indeed, it works in my code example with OrderLine. I'm looking for your help to understand the difference between Freeze, Inject, and also Register which, according to the source code, is just called by Inject method but it takes a lambda.
Now provide the response and nothing else.
| Register and Inject Once upon a time, there was no Inject and no Freeze ; Register ruled the code. Back then, there was a Register overload defined thusly: public static void Register<T>(this IFixture fixture, T item) However, it had to share the API with this close relative: public static void Register<T>(this IFixture fixture, Func<T> creator) The creator of AutoFixture thought that this was good, but alas: users were stricken with confusion. Most grievously, a user could write: fixture.Register(() => universe.LightUp()); but also fixture.Register(universe.LightUp); which means the exact same thing, because universe.LightUp is a reference to a method, and thus matches a delegate. However, that syntax looks like a property reference, so if LightUp had been a property instead of a method, the first overload would be selected by the compiler. This caused much confusion, so the Register<T>(this IFixture fixture, T item) overload was renamed to Inject<T>(this IFixture fixture, T item) . Freeze Freeze has a different history. A long time ago, when I still used AutoFixture in an imperative way, I noticed that I repeatedly wrote code like this: var foo = fixture.Create<Foo>();fixture.Inject(foo); So I decided that this was a concept and named it Freeze . The Freeze method is only shorthand for those two lines of code. I'm looking for your help to understand the difference between Freeze, Inject, and also Register which, according to the source code, is just called by Inject method but it takes a lambda In general, it shouldn't be too hard to distinguish between Inject and Register , since their signatures don't collide. Thus, if you try to accomplish a goal with one of those two methods, and your code compiles, you probably chose the right version. This would also be the case for Freeze if it wasn't for the overload used in the OP: [EditorBrowsable(EditorBrowsableState.Never)]public static T Freeze<T>(this IFixture fixture, T seed) Notice that this overload actually has EditorBrowsableState.Never , because it always confuses people. However, despite that, apparently people still find that overload, so I think it should be moved in AutoFixture 4 . It's one of those features that exist because it was easy to implement... | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18161127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717058/']} | jdg_77643 |
stackexchange | llm_judgeable_groundtruth_similarity | 61780339 |
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 updated my app to 9 version.Everything is alright but I've problemwith strictTemplates set to true.For instance this code loaded$: Observable<boolean>[loaded]="loaded$ | async"@Input() loaded!: boolean; I've got the error Type 'boolean | null' is not assignable to type 'boolean'. This fix the error @Input() loaded!: boolean | null; But I cant see the point someone acn explain me, please?
Now provide the response and nothing else.
| The reason is because the async pipes return signature is something like <T>(input$: Observable<T>): T | null always, because it returns null to the template while it's awaiting a response from an asynchronous call. More about this here: https://angular.io/guide/template-typecheck#strict-null-checks You can do what you've done and allow null, or if you know it will never be null, use a non null assertion operator: [loaded]="(loaded$ | async)!" or disable type checking here: [loaded]="$any(loaded$ | async)" or for this particular case you could probably do something like this: [loaded]="(loaded$ | async) || false" | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/61780339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3887366/']} | jdg_77644 |
stackexchange | llm_judgeable_groundtruth_similarity | 191218 |
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 have a virtual box running with CentOS. I have attached a new virtual disk to the existing CentOS VM and I'm now trying to install GRUB on this newly attached disk. Later, I will bring up a second VM with a newly prepared bootable hard disk with a custom root filesystem and kernel. I have tried the following steps: Attached a new virtual disk to the existing working CentOS machine. Created a new partition with fdisk /dev/sdb . While partitioning, I chose the options primary partition, partition number 1 and other default options. Formatted the disk with mkfs.ext3 /dev/sdb1 . Mounted the disk to /media/new_drive . Installed GRUB grub-install /dev/sdb1 --root-directory=/media/new_drive/ . After this, the second VM with the newly prepared hard disk didn't boot; I got the error: could not read from the boot medium . It seems the MBR is not updated after grub-install , but I can see GRUB installed under /boot/grub on the new drive. But the worst thing is, it has corrupted my existing CentOS GRUB: The CentOS VM hangs showing a black screen with the only text being GRUB . Why does grub-install /dev/sdb1 not modify the MBR of sdb1? Is this not the right way to install GRUB on new drive?
Now provide the response and nothing else.
| I'm not a grub2 expert (sorry) but try adding --skip-fs-probe to your grub-install line, I have found this prevents creation of /boot/grub/device.map which can cause booting to a grub prompt. I think that without this parameter grub-install, instead of doing what you tell it, thinks it is cleverer than you, and may do something different. Another thing is to be sure you are using the right grub-install (i.e. for grub2 and not for original grub). This isn't a problem if you are inside Centos but with SystemRecoveryCD both versions are available and so you have to use grub2-install . I learned the hard way... And as @wurtel pointed out (kudos), you should specify a drive not a partition. Grub2 installs in sector 0 of the whole disk drive, and this 'stub' is what runs at boot time, but it needs to know whereabouts on the disk it should install the files for the next stage of booting - this is what the --root-directory parameter is for. (I think.) Reading man grub-install and googling I see that --root-directory is not really meant to be used for grub2 versions 1.99++, though it does work in my experience. You are meant to use --boot-directory and refer to the actual boot directory, so this would give you: grub-install /dev/sdb --skip-fs-probe --boot-directory=/media/new_drive/boot | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/191218', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/106741/']} | jdg_77645 |
stackexchange | llm_judgeable_groundtruth_similarity | 4347815 |
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 $(\sigma_i)_{i \geq 1}$ be i.i.d. random variables with Exponential distribution of parameter $\lambda$ , representing the waiting time between consecutive events . The arrival time of these events (from a $t=0$ origin) is: $$\tau_n = \sigma_1 + \sigma_2 + ... + \sigma_n$$ The number of those events happening between time $t_0=k$ and $t_1=k+1$ is: $$M_k :=\sum_{\quad j \geq 1 \\ k \leq \tau_j < k+1} 1$$ Is it true that $(M_k)$ , counting the number of events happening in a time-window $[k, k+1[$ , has a Poisson distribution? It seems true intuitively, but I would like to find a source / proof. NB: I have aleady read Link between Poisson and Exponential distribution and Relationship between Poisson and exponential distribution which may be linked, but it's not the same question. I wonder if the reciprocal is also true: let's say we have consecutive events with arrival times of $(\tau_i)_{i \geq 1}$ , such that the number $M_k$ of events happening between $[k, k+1]$ is a Poisson distribution of parameter $\lambda$ , for each integer $k$ . Can we conclude that $\sigma_i = \tau_i - \tau_{i-1}$ has an exponential distribution?
Now provide the response and nothing else.
| Let $(\sigma_i)$ be an i.i.d. sequence of exponentially distributed waiting times: $$\mathbb P(\sigma_i\in[t,t+dt])=\lambda\,e^{-\lambda t}\,dt$$ and define $\tau_n:=\sum_{i=1}^n\sigma_i$ to be the time of the $n$ -th jump. The jump process is defined as $$N_t=\sum_{n=1}^\infty 1_{\{\tau_n\le t\}}\,.$$ The distribution of $N_t$ is obtained from \begin{align}&\mathbb P(N_t= k)\\&=\mathbb P\left(\tau_k\le t<\tau_{k+1} \right)=\mathbb P\left(\sigma_1+...+\sigma_k\le t<\sigma_1+...+\sigma_{k+1} \right)\\&=\mathbb P\Big(\sigma_1\le t,\sigma_2\le t-\sigma_1,...,\sigma_k\le t-\sigma_1-...-\sigma_{k-1},t-\sigma_1-...-\sigma_{k} <\sigma_{k+1} \Big)\\ \tag{1}&=\int_0^t\int_0^{t-s_1}...\int_0^{t-s_1-...-s_{k-1}}\int_{t-s_1-...-s_k}^\infty\lambda^{k+1}e^{-\lambda s_1-...-\lambda s_{k+1}}\,ds_{k+1}\,...ds_1\,.\end{align} The $ds_{k+1}$ -integral is \begin{align}\lambda^ke^{-\lambda s_1-...-\lambda s_k}\,e^{-\lambda t+\lambda s_1+...+\lambda s_k}=\lambda^ke^{-\lambda t}\,.\end{align} The $ds_k$ -integral is \begin{align}\lambda^k e^{-\lambda t}\big(t-s_1-...-s_{k-1}\big)\,.\end{align} The $ds_{k-1}$ -integral is $$\lambda^k e^{-\lambda t}\big(t-s_1-...-s_{k-2}\big)^2-\lambda^k e^{-\lambda t}\frac{(t-s_1-...-s_{k-2})^2}{2}=\lambda^k e^{-\lambda t}\frac{(t-s_1-...-s_{k-2})^2}{2}\,.$$ And so forth. This shows that (1) is $$\mathbb P(N_t=k)=\lambda^ke^{-\lambda t}\frac{t^k}{k!}\,$$ which is the well-known Poisson distribution with parameter $\lambda\, t$ . Conversely, when we start with a Poisson process $N_t$ then itsfirst jump time has an exponential distribution function: \begin{align}\mathbb P(\tau_1\le t)=\mathbb P(N_t\ge 1)=\sum_{k=1}^\infty\frac{(\lambda t)^k}{k!}\,e^{-\lambda t}=\Big(\underbrace{\sum_{k=0}^\infty\frac{(\lambda t)^k}{k!}}_{\displaystyle e^{\lambda t}}-1\Big)\,e^{-\lambda t}=1-e^{-\lambda t}\,.\end{align} To find the distribution of $\sigma_2=\tau_2-\tau_1$ we look at the joint distribution of $\tau_1$ and $\tau_2$ first: for $t_1\le t_2\,,$ \begin{align}&\mathbb P(t_1<\tau_1,\tau_2\le t_2)=\mathbb P(N_{t_1}<1,N_{t_2}\ge 2)=\mathbb P(N_{t_1}=0)-\mathbb P(N_{t_1}=0,N_{t_2}\le 1)\\\tag{2}&\stackrel{(*)}{=}e^{-\lambda t_1}-e^{-\lambda t_1}\big(1+\lambda(t_2-t_1)\big)\,e^{-\lambda (t_2-t_1)}=e^{-\lambda t_1}-e^{-\lambda t_2}-\lambda(t_2-t_1)\,e^{-\lambda t_2}\,.\end{align} In (*) we have used the independence of $N_{t_2}-N_{t_1}$ and $N_{t_1}\,.$ Therefore, \begin{align}&\mathbb P(\tau_1\le t_1,\tau_2\le t_2)=\mathbb P(\tau_2\le t_2)-\mathbb P(t_1<\tau_1,\tau_2\le t_2)\\&\stackrel{(2)}{=} \mathbb P(N_{t_2}\ge 2)-e^{-\lambda t_1}+e^{-\lambda t_2}+\lambda(t_2-t_1)\,e^{-\lambda t_2}\\&=\sum_{k=2}^\infty\frac{(\lambda t_2)^k}{k!}\,e^{-\lambda t_2}-e^{-\lambda t_1}+e^{-\lambda t_2}+\lambda(t_2-t_1)\,e^{-\lambda t_2}\\&=1-e^{-\lambda t_2}-\lambda t_2\,e^{-\lambda t_2}-e^{-\lambda t_1}+e^{-\lambda t_2}+\lambda(t_2-t_1)\,e^{-\lambda t_2}\\&=1-\lambda t_2\,e^{-\lambda t_2}-e^{-\lambda t_1}+\lambda(t_2-t_1)\,e^{-\lambda t_2}\,.\end{align} Consequently, $$\tag{3}\mathbb P\Big(\tau_1\in[t_1,t_1+dt],\tau_2\in[t_2,t_2+dt]\Big)=\lambda^2e^{-\lambda t_2}1_{\{t_1\le t_2\}}\,dt_1\,dt_2\,.$$ It follows that $\sigma_2$ has an exponential distribution: \begin{align}&\mathbb P(\sigma_2\le t)=\mathbb P(\tau_2\le t+\tau_1)=\int_0^\infty\int_{t_1}^{t+t_1}\lambda^2e^{-\lambda t_2} \,dt_2\,dt_1=\lambda \int_0^\infty e^{-\lambda t_1}-e^{-\lambda(t+t_1)}\,dt_1\\&=1-e^{-\lambda t}\,.\end{align} The remaining task is now to show this for all $\sigma_n$ . I suspect that the joint distribution of $\tau_{n-1}$ and $\tau_n$ is also given by (3). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4347815', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/109021/']} | jdg_77646 |
stackexchange | llm_judgeable_groundtruth_similarity | 116121 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Should I keep project filesm like Eclipse's .project, .classpath, .settings, under version control (e.g. Subversion, GitHub, CVS, Mercurial, etc)?
Now provide the response and nothing else.
| You do want to keep in version control any portable setting files , meaning: Any file which has no absolute path in it. That includes: .project, .classpath ( if no absolute path used , which is possible with the use of IDE variables, or user environment variables) IDE settings (which is where i disagree strongly with the 'accepted' answer). Those settings often includes static code analysis rules which are vitally important to enforce consistently for any user loading this project into his/her workspace. IDE specific settings recommandations must be written in a big README file (and versionned as well of course). Rule of thumb for me: You must be able to load a project into a workspace and have in it everything you need to properly set it up in your IDE and get going in minutes. No additional documentation, wiki pages to read or what not. Load it up, set it up, go. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/116121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18722/']} | jdg_77647 |
stackexchange | llm_judgeable_groundtruth_similarity | 42827222 |
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 looked through every question like this here and tried to apply the stated fixes with no success. I'm using the wordpress:4.7.3-php7.0-fpm-alpine docker image with a separate nginx container in front of it. When I curl wordpress I get: File not found. When I check the wordpress container logs, I get: 127.0.0.1 - 16/Mar/2017:06:26:24 +0000 "GET /index.php" 404127.0.0.1 - 16/Mar/2017:06:31:27 +0000 "GET /index.php" 404127.0.0.1 - 16/Mar/2017:06:32:16 +0000 "GET /index.php" 404127.0.0.1 - 16/Mar/2017:06:37:17 +0000 "GET /index.php" 404127.0.0.1 - 16/Mar/2017:06:39:09 +0000 "GET /index.php" 404 The actual nginx error is: 2017/03/16 06:26:24 [error] 17#17: *1 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 10.128.0.7, server: k8wp, request: "GET / HTTP/1.0", upstream: "fastcgi://127.0.0.1:9000" I'm using php 7 /var/www/html # php-fpm -vPHP 7.0.16 (fpm-fcgi) (built: Mar 3 2017 23:07:56)Copyright (c) 1997-2017 The PHP GroupZend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies with Zend OPcache v7.0.16, Copyright (c) 1999-2017, by Zend Technologies My nginx config is server { root /app; # Add index.php to the list if you are using PHP index index.php index.html index.htm index.nginx-debian.html; server_name _localhost; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { try_files $uri =404; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }} I'm running nginx as the user www-data : user www-data; According to /usr/local/etc/php-fpm.d/www.conf the user and group are uncommented and set to www-data
Now provide the response and nothing else.
| The error indicates that your SCRIPT_FILENAME is incorrect. Your comment: in the wordpress container it's at /var/www/html/index.php in the nginx container it's at /app suggests that nginx and php-fpm are seeing a different document root. In which case, use: fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42827222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3176550/']} | jdg_77648 |
stackexchange | llm_judgeable_groundtruth_similarity | 2752909 |
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:
There is a linear homogeneous ODE (let's pick a second order one, but it can be in any order): \begin{align*}af'' + bf' + cf = 0\end{align*} We know, that \begin{align*}f(t)=e^{\lambda t}\end{align*} is a solution, and we need to find two $\lambda$'s, so the general solution is (if $\lambda$'s are real and distinct): \begin{align*}f(t)=c_1e^{\lambda _1 t} + c_2e^{\lambda _2 t}\end{align*} My question is, why do the only solution is in the form of summed exponentials? What is the proof, that there is no other solution in some other form, a non-exponential one? (I understand, that if $f_1$ and $f_2$ are solutions, then $c_1f_1+c_2f_2$ is a solution too, but I don't understand, why $f_*$ have to be exponential)
Now provide the response and nothing else.
| There is a linear homogeneous ODE (let's pick a second order one, but it can be in any order): Since you only took the second order case as an example, I'll elaborate on the more general case. You can show that the solutions to an $n$-th order linear ODE form a vector space with dimension at most $n$; such a space is spanned by (at most) $n$ linearly independent functions. Plugging $e^{\lambda t}$ into an $n$-th order, linear, homogeneous ODE with constant coefficients will result in an $n$-th degree polynomial which has exactly $n$ (possibly complex) solutions, if we take the multiplicities into account. If the $r$ distinct roots are $\lambda_1 , \ldots , \lambda_r$ with respective multiplicities $m_1,\ldots,m_r$ (and thus we have $m_1+\ldots+m_r=n$), then you can show that for all $i$ with $1 \le i \le r$, the functions $e^{\lambda_i},te^{\lambda_i},\ldots,t^{m_i}e^{\lambda_i}$ are solutions to the ODE; there are in total $n$ such functions. The $n$ functions from above are linearly independent and thus span an $n$-dimensional vector space so this contains all the solutions to the ODE; in other words: any solution will be a linear combination of these exponential functions above. This argument is a bit indirect in the sense that it doesn't provide a direct intuition as to why the solutions have to be exponential, but it does show that there cannot be any other : all the solutions are in this vector space which is spanned by the "exponentials" (including those of the form $t^ke^{\lambda t}$ which technically aren't exponentials). See for example here (Theorem 8.3) or here (Theorem 4.1). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2752909', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/555997/']} | jdg_77649 |
stackexchange | llm_judgeable_groundtruth_similarity | 357997 |
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 Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class. Suppose that you want create a subclass of OptionParser that overrides only a single method (for example exit() ). In Java you can write something like this: new OptionParser () { public void exit() { // body of the method }}; This piece of code creates a anonymous class that extends OptionParser and override only the exit() method. There is a similar idiom in Python? Which idiom is used in these circumstances?
Now provide the response and nothing else.
| You can use the type(name, bases, dict) builtin function to create classes on the fly. For example: op = type("MyOptionParser", (OptionParser,object), {"foo": lambda self: "foo" })op().foo() Since OptionParser isn't a new-style class, you have to explicitly include object in the list of base classes. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/357997', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36131/']} | jdg_77650 |
stackexchange | llm_judgeable_groundtruth_similarity | 39327954 |
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 customize the path of the reset email blade template in Laravel 5.3? The template used is: vendor/laravel/framework/src/Illuminate/Notifications/resources/views/email.blade.php I'd like to build my own. Also, how to change the text of this email predefined in: vendor/laravel/framework/src/Illuminate/Auth/Notifications/ResetPassword.php public function toMail(){ return (new MailMessage) ->line([ 'You are receiving this email because we received a password reset request for your account.', 'Click the button below to reset your password:', ]) ->action('Reset Password', url('password/reset', $this->token)) ->line('If you did not request a password reset, no further action is required.');}
Now provide the response and nothing else.
| To change template you should use artisan command php artisan vendor:publish it will create blade templates in your resources/views/vendor directory. To change text of email you should override the sendPasswordResetNotification method on your User model. This is described here https://laravel.com/docs/5.3/passwords in Reset Email Customization section. You must add new method to your User model. public function sendPasswordResetNotification($token){ $this->notify(new ResetPasswordNotification($token));} and use your own class for notification instead ResetPasswordNotification. UPDATED : for @lewis4u request Step by step instruction: To create a new Notification class, you must use this command line php artisan make:notification MyResetPassword . It will make a new Notification Class 'MyResetPassword' at app/Notifications directory. add use App\Notifications\MyResetPassword; to your User model add new method to your User model. public function sendPasswordResetNotification($token){ $this->notify(new MyResetPassword($token));} run php artisan command php artisan vendor:publish --tag=laravel-notifications After running this command, the mail notification templates will be located in the resources/views/vendor/notifications directory. Edit your MyResetPassword class method toMail() if you want to. It's described here https://laravel.com/docs/5.3/notifications Edit your email blade template if you want to. It's resources/views/vendor/notifications/email.blade.php Bonus: Laracast video: https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/9 PS: Thanks @Garric15 for suggestion about php artisan make:notification | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39327954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094611/']} | jdg_77651 |
stackexchange | llm_judgeable_groundtruth_similarity | 654820 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A friend of mine gave me the following problem: Find all functions $f:[0,1]\to[0,1]$, which are one-to-one and onto and satisfy the following functional relation:$$f\big(2x-f(x)\big)=x, \tag{1}$$for all $x\in [0,1]$. Clearly, the identity function $f(x)=x$ is one such function. Also, as $f$ is a bijection $f^{-1}$ exists, and by $(1)$ we have$$f^{-1}(x)=2x-f(x), \tag{2}$$but I have no idea that how should I continue. It will be great if someone can give me some hints. Thanks in advance.
Now provide the response and nothing else.
| In the formulation of the question the function $f$ is one-to-one and onto. Below two proofs are presented. The first one requires the one-to-one and assumption, while the second one does not. First answer requiring that $f$ is one-to-one. Clearly, $f$ is also onto, as an arbitrary $x\in[0,1]$, is the image of $2x-f(x)$, and since$f$ is one-to-one and onto, $f$ possesses an inverse $f^{-1}:[0,1]\to [0,1]$. The functional relation $f\big(2x-f(x)\big)=x$, implies$$f(x)-x=x-f^{-1}(x). \tag{1}$$We shall show that $f(x)=x$. Assume not. Then $$f(x_0)-x_0\ne 0,$$for some $x_0\in(0,1)$. Let's assume that $f(x_0)-x_0=a>0$. Then $(1)$ implies that$$f(x_0)-x_0=x_0-f^{-1}(x_0)=f^{-1}(x_0)-f^{-2}(x_0)=\cdots=f^{-k}(x_0)-f^{-(k+1)}(x_0),$$for every $k\in\mathbb N$, where $f^{-k}$ is $f^{-1}\circ\cdots\circ f^{-1}$ $k$ times.But this means that $$f^{-1}(x_0)=x_0-a,\,\,f^{-2}(x_0)=x_0-2a,\ldots,f^{-k}(x_0)=x_0-ka,$$which means that $\lim_{k\to\infty}f^{-k}(x_0)=-\infty$. A contradiction, $f^{-k}(x_0)\in [0,1]$. We would reach to a contradiction even if we had assumed that $a<0$. Second answer not requiring that $f$ is one-to-one. As $f\big(2x - f(x)\big) = x,\,$ for all $x \in \left[ {0,1} \right]$, then$$0 \le 2x - f(x) \le 1 \quad \Longrightarrow\quad 2x - 1 \le f(x) \le 2x,\,\,\,\text{for all $x \in \left[ {0,1} \right]$.}$$Replacing in the above $x$ with $2x - f(x)$ we obtain\begin{align}2\big( {2x - f(x)} \big) - 1 \le f\big( {2x - f(x)} \big) \le 2\big( {2x - f(x)} \big),\end{align}or\begin{align}2\big( {2x - f(x)} \big) - 1 \le x \le 2\big( {2x - f(x)} \big)\end{align}which implies that$$\frac{3x-1}{2}\le f(x) \le \frac{3x}{2}.$$Repetition of this process produces the following inequalities$$x+\frac{x-1}{n}\le f(x)\le x+\frac{x}{n},\,\,\,\text{for all $x \in \left[ {0,1} \right]\,\,$ and $\,\,n\in\mathbb N$,}$$and therefore$$f(x)=x ,\,\,\,\text{for all $x \in \left[ {0,1} \right]$.}$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/654820', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/123824/']} | jdg_77652 |
stackexchange | llm_judgeable_groundtruth_similarity | 12684509 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As I stated on the title, I'm currently feeling pretty uncomfortable of basic understanding of them. As far as I know, mod_wsgi implemented WSGI specification which can be run under Apache web server. It was coded in C language. Another one, werkzeug is a kind of toolkit which have useful utilities.I also reviewed werkzeug can run simple service which is implemented within its sources(make_server in serving.py). I aware that werkzeug has useful features and simple server feature. What I want to know it the below. When using Flask like framework based on werkzeug under Apache web server, what does mod_wsgi do exactly? werkzeug has also basic http server functionality which is don't need to be supported mod_wsgi. Can anyone explain the differences between mod_wsgi and werkzeug ? mod_wsgi and werkzeug has duplicated features from the perspective of web server.
Now provide the response and nothing else.
| WSGI stands for Web Server Gateway Interface, (mostly) defined by PEP 333 at http://www.python.org/dev/peps/pep-0333/ . It is an effort by the Python community to establish a standard mechanism for web servers to speak to Python applications. In theory, any wsgi compliant server (or extension to an existing web server) should be able to load and run any wsgi compliant application. werkzeug is a web application framework which can run under a compliant WSGI server, such as Apache+mod_wsgi. It also contains a built-in development server that you can use for development. WSGI can be very confusing at first, but it is actually pretty simple. The WSGI spec requires that your python application do the following: define a callable named application said callable should accept 2 parametes: ( environ , start_response ) environ is a dictionary of environment variables start_response is a callable that needs called to start the response Once application is called, then it handles the request, builds the output, and: calls start_response('200 OK', Headers) return [content] A simple WSGI app might look like this: def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] It is strongly suggested that you use an existing WSGI framework, as there are a lot of details involved in parsing HTTP requests, handling file uploads, encoding characters, etc... Take a look at Bottle, Flask, werkzeug, AppStruct, etc... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12684509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1713464/']} | jdg_77653 |
stackexchange | llm_judgeable_groundtruth_similarity | 15247614 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi I am just learning to work with Entity Framework Code First and I can not seem to understand something.I have created three models based on a tutorial: public class Course{ public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments{ get; set; }}public class Enrollment{ public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public decimal? Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; }}public class Student{ public int StudentID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; }} My problem is that I do not understand what the properties with virtual do.If I check the database there is no column crate for each of the properties , only for the others. So what happens when you create a property with the virtual keyword?
Now provide the response and nothing else.
| It is used to manage lazy loading and change tracking . EF will generate proxy types on runtime, which are dynamically generated types that inherit from your POCO classes and add all the EF stuff to manage lazy loading / change tracking in the overridden virtual properties . So virtual is not a "magic keyword" here, virtual is here so your POCOs can be inherited with additional EF-related code at runtime. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15247614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1981274/']} | jdg_77654 |
stackexchange | llm_judgeable_groundtruth_similarity | 8417270 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to push a new item onto an observableArray , but only if the item is not already present. Is there any "find" function or recommended pattern for achieving this in KnockoutJS? I've noticed that the remove function on an observableArray can receive a function for passing in a condition. I almost want the same functionality, but to only push it if the condition passed in is or is not true.
Now provide the response and nothing else.
| An observableArray exposes an indexOf function (wrapper to ko.utils.arrayIndexOf ). This allows you to do: if (myObservableArray.indexOf(itemToAdd) < 0) { myObservableArray.push(itemToAdd);} If the two are not actually a reference to the same object and you want to run custom comparison logic, then you can use ko.utils.arrayFirst like: var match = ko.utils.arrayFirst(myObservableArray(), function(item) { return itemToAdd.id === item.id;});if (!match) { myObservableArray.push(itemToAdd);} | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8417270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/306098/']} | jdg_77655 |
stackexchange | llm_judgeable_groundtruth_similarity | 59529 |
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:
The nations of the UK are independent nations that share resources with each other, and sometimes a feeling of oneness and fraternity is seen among the good people of that land. Emotions are subjective. Would the rest of the UK have anything "real" to lose if Scotland exits the UK?
Now provide the response and nothing else.
| The Scottish government's 2013 white paper on independence - Scotland's Future - sets out a number of tangible assets that, the paper argues, Scotland would be entitled to a proportion of based on population share. For example, an independent Scotland would seek to take ownership of a share of the United Kingdom's overseas properties, e.g. embassies & consulates: Scotland will be entitled to a fair share of the UK's extensiveoverseas properties (or a share of their value) allowing us to useexisting premises for some overseas posts. For example, the ForeignOffice owns or leases almost 5,000 properties overseas [source] . Theestimated value of this estate is around £1.9 billion. Based on apopulation share (our actual share will be a matter for negotiation)Scotland would be entitled to around £150 million allowing us toestablish ourselves quickly and for little initial cost in ourpriority countries. Chapter 6 - International Relations and Defence The paper also argues that Scotland would be entitled to £7.8 billion of the UK's existing defence assets - based on a population-share proportion of the 2007 valuation of ~£93 billion performed by the Ministry of Defence. It even splits out what particular assets Scotland would seek from the UK, including, amongst others, "one aviation unit operating six helicopters", "a Quick Reaction Alert (QRA) squadron incorporating a minimum of 12 Typhoon jets", "two frigates from the Royal Navy's current fleet" and so on. Other assets mentioned in the report that an independent Scotland would seek to inherit include BBC Scotland, "assets that are not related directly to particular services, suchas the UK’s public shareholdings in banks", "bespoke IT software", and so on. Page 21 of the report does mention that Scotland may choose to offset its share of national debt against these assets. There are also implications for the United Kingdom's nuclear deterrent - Trident. The white paper makes clear that an independent Scotland would no longer accept Trident being based at the ports of Faslane & Coulport: The Scottish Government is committed to securing the completewithdrawal of Trident from an independent Scotland as quickly as canbe both safely and responsibly achieved. As the rest of the UK has no bases outside of Scotland suitable for Trident, this would present a significant problem for the Westminster government. Indeed, it has been proposed more recently that Scotland should fund its defence by leasing the bases out while a replacement is constructed - something which would almost certainly prove to be extremely expensive for the UK taxpayer. In a worst case scenario, the loss of the UK's nuclear deterrent would lead to a further reduction in its international standing. For example, the UK would become the only permanent member of the UN Security Council without nuclear capabilities. | {} | {'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/59529', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/34768/']} | jdg_77656 |
stackexchange | llm_judgeable_groundtruth_similarity | 1362903 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have developed an console application in C# .net which creates a new excel & performs some operations in it [Interop]. I have added Interop.Microsoft.Office.Interop.Excel.dll as reference in my project The code works fine on XP & in Vista too. But if i keep my exe in one of the folder then it gives me excception Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C0 00-000000000046} failed due to the following error: 80090006. Unhandled Exception: System.Exception: Unhandled exception during execution ---> System.NullReferenceException: Object reference not set to an instance of an object. Anyone has any idea whether this could be possible because of stricter policies which might have been set on any folder. I am asking this because, if i copy this exe to another folder, the exe works perfectly. The piece of code where execption is thrown is, /* Create spreadsheet update data */InteropExcel.Workbook oWorkbook = null;InteropExcel.Worksheet oWorkSheet = null;InteropExcel.ApplicationClass appExcel = null;try{ // Probable at this line appExcel = new InteropExcel.ApplicationClass(); oWorkbook = (InteropExcel.Workbook)appExcel.Workbooks.Add(true); oWorkSheet = (InteropExcel.Worksheet)oWorkbook.ActiveSheet; // ... I am also not able to handle it even i have written this code in try-catch block. Can anyone suggest any solution for it? Thanks, Amit
Now provide the response and nothing else.
| Take a look at this MS Support article on how to achieve this: HOW TO: Use ASP.NET to Protect File Types . It involves setting up IIS to forward those requests to ASP.NET and then setting up your web.config to block the desired file types, such as: (nb this works for your dev machine and before IIS7 - be sure to see below) <system.web> <httpHandlers> <add verb="*" path="*.ini" type="System.Web.HttpForbiddenHandler" /> </httpHandlers></system.web> According to the httpHandlers Element page , the following extensions are forbidden by default as of .NET 2.0 (.ini is not one of them): *.asax, *.ascx, *.master, *.skin, *.browser, *.sitemap, *.config, *.cs, *.csproj, *.vb, *.vbproj, *.webinfo, *.licx, *.resx, *.resources, *.mdb, *.vjsproj, *.java, *.jsl, *.ldb, *.dsdgm, *.ssdgm, *.lsad, *.ssmap, *.cd, *.dsprototype, *.lsaprototype, *.sdm, *.sdmDocument, *.mdf, *.ldf EDIT: this applies to IIS versions prior to IIS 7.0. IIS 7.0 adds an additional operating mode, called Integrated Mode (default for ASP.NET), which requires handlers to be placed in <system.webServer>/<handlers> instead of <system.web>/<httpHandlers> . I added some more info and links to @awe's answer on this page, check it out for more details. IMPORTANT! for IIS 7.0 or later As specified in the edit you need to place the <add> element in a different place and the rule needs a name too - if you dont specify a name you will get a 500 Internal Error when restarting <system.webServer> <handlers> <add name="IgnoreIni" verb="*" path="*.ini" type="System.Web.HttpForbiddenHandler" /> </handlers> </system.webServer> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1362903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_77657 |
stackexchange | llm_judgeable_groundtruth_similarity | 3753 |
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:
A common and oft repeated belief regarding options volatility is that implied volatility increases due to people bidding up a contract, usually related to anticipation of the outcome of an expected event. After the event, volatility drops because more people are selling the contracts. But I have noticed contracts with ZERO volume with an increase in IV, and after the event those same contracts with ZERO volume now are quoted at lower prices after IV has dropped. The only market participants that are "bidding up" or "bidding down" are the market makers, and they never fill each other, just change their quotes. The fallacy is that nobody is interested in those contracts therefore IV should not increase. The market makers' computers simply change their bid and ask because the IV has changed, not the other way around. Is there a more comprehensive options volatility study I can read that more accurately addresses change in volatility? I have reservations about what is commonly said about volatility vs what I see in the market. On these illiquid contracts, perhaps the long standing idea of implied volatility is simply of no use here, and if people really think these contracts are worth what they are, then the portion of the contract's price that is based on IV should be spread out amongst the other variables, mainly theta.
Now provide the response and nothing else.
| The way market makers mark their volatility curves is by using models which 'fill in the gaps', i.e. they will make a price for a given option even if they do not believe this option is going to get a lot of volume. They are still willing to go long/short because they have a strategy to hedge their overall position (i.e. by managing their greeks and expiries). So they make some assumption on what the overall vol curve is (as function of time / strike), and also of how the ATM vol relates to perhaps some more liquid underlier (for example they will use the vol for a sector index as a proxy to vol for a single underlier). Therefore, the price (and therefore the implied vol) may change even when there are no transactions, just because some of assumptions or market parameters have changed. If the implied vol increases for one particular option, it may be not because demand for that option has gone up, but just because demand for other options (which are considered related) has gone up. | {} | {'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/3753', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/1453/']} | jdg_77658 |
stackexchange | llm_judgeable_groundtruth_similarity | 7770569 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Big O Notation Arrays vs. Linked List insertions: According to academic literature for arrays it is constant O(1) and for Linked Lists it is linear O(n). An array only takes one multiplication and addition. A linked list which is not laid out in contiguous memory requires traversal. This question is, does O(1) and O(n) accurately describe indexing/search costs for arrays and linked lists respectively?
Now provide the response and nothing else.
| O(1) accurately describes inserting at the end of the array. However, if you're inserting into the middle of an array, you have to shift all the elements after that element, so the complexity for insertion in that case is O(n) for arrays. End appending also discounts the case where you'd have to resize an array if it's full. For linked list, you have to traverse the list to do middle insertions, so that's O(n) . You don't have to shift elements down though. There's a nice chart on wikipedia with this: http://en.wikipedia.org/wiki/Linked_list#Linked_lists_vs._dynamic_arrays Linked list Array Dynamic array Balanced treeIndexing Θ(n) Θ(1) Θ(1) Θ(log n)Insert/delete at beginning Θ(1) N/A Θ(n) Θ(log n)Insert/delete at end Θ(1) N/A Θ(1) amortized Θ(log n)Insert/delete in middle search time + Θ(1) N/A Θ(n) Θ(log n)Wasted space (average) Θ(n) 0 Θ(n)[2] Θ(n) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7770569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_77659 |
stackexchange | llm_judgeable_groundtruth_similarity | 1337504 |
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:
It is well know that: $$\int x^k \text{d}x = \begin{cases}\displaystyle\frac{x^{k+1}}{k+1} + c & k \neq -1\\\\\log|x| + c & k = -1\end{cases}$$ My guess is: $$\lim_{k\to -1}\frac{x^{k+1}}{k+1} = \log|x| ???$$ Apparently, this limit goes to infinity when $x>0$. Having said that, is there something that "join" monomial to logarithm? I mean, why the integral of a monomial is a monomial except for the case $k=-1$? Addition I know very well that this is because $$\frac{\text{d}}{\text{d}x} \log(x) = \lim_{h \to 0^+} \frac{\log(x+h)-\log(x)}{h} = \frac{1}{x}.$$ Anyway, the scheme "integral of monomial is a monomial" is somehow broken. What is the "deep" reason for this situation?
Now provide the response and nothing else.
| The usual way to define truth is due to Tarski. Given a structure $M$ (i.e. a set with operations and relations), we recursively define $M \models \phi$, meaning $\phi$ is true in $M$. For concreteness, let's consider the natural numbers $N = (\mathbb N, +, \times, 0, 1, <)$: $N \models a + b = c$ if it the output of the binary function $+$ on input $(a,b)$ is $c$. Similarly for $N \models a \times b = c$. $N \models a < b$ if $(a,b)$ is in the set $\mathord< \mathbin{\subseteq} \mathbb N^2$. $N \models \phi \land \psi$ if $N \models \phi$ and $N \models \psi$ and $N \models \phi \lor \psi$ if $N \models \phi$ or $N \models \psi$. $N \models \neg \phi$ if it is not the case that $N \models \phi$. $N \models \exists x \phi(x)$ if there is some $a \in \mathbb N$ so that $N \models \phi(a)$ and $N \models \forall x \phi(x)$ if for all $a \in \mathbb N$ we have $N \models \phi(a)$. In other words, truth is defined exactly how you would expect; symbols in the language correspond to certain constants, functions, and relations in the structure and truth is based upon that connection. Provability, on the other hand, isn't a property of structures. Instead, it's a property of theories. If $T$ is a theory, meaning a set of sentences in some fixed language, then we can define a provability relation $T \vdash \phi$. There are many ways to do the details here to match with our intuitive notion of provability. But the important things are that the provability relation should be closed under valid inference rules (e.g. if $T \vdash \phi$ and $T \vdash \phi \rightarrow \psi$, then $T \vdash \psi$), that the axioms of $T$ are provable (if $\phi \in T$ then $T \vdash \phi$), and that logical validities (statements true in any structure) are provable. We can now ask about how provability and truth relate. Any definition of provability worth a damn will be sound . This means that if $M$ is a model of $T$ (i.e. every axiom of $T$ is true in $M$, when interpreted appropriately), then $T \vdash \phi$ implies $M \models \phi$. In other other words, if we have proved something, then we know it is true. Moreover, as Gödel showed, first-order logic is complete . This means that if every model $M$ of $T$ has $M \models \phi$, then $T \vdash \phi$. On a final note, it's very common to see people refer to truth without indicating a structure they are working in or refer to provability without indicating a theory they are working from. In the former situation, it's usually clear what structure is implicitly being used. For instance, the statement "17 is prime" is referring to the natural numbers, and can be translated to a formal statement something like $N \models \forall x < 17\, \exists y \le 17 \ (x \times y = 17 \rightarrow x = 1)$. In the latter situation, when referring to provability, some implicit background of commonly accepted mathematics is assumed. When we say that the intermediate value theorem is provable, we mean that there is a proof of the IVT from some commonly accepted basic principles. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1337504', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51370/']} | jdg_77660 |
stackexchange | llm_judgeable_groundtruth_similarity | 123649 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
While doing work on propositional logic (namely, proving the Generalized De Morgan's Laws), I found myself wondering why precisely an infinite conjunction or disjunction are not permitted, due to the fact that in predicate logic (also a finitary logic), quantification over domains of discourse with infinite size are allowed. Using the definition of the existential and universal quantifiers as:$ \exists( x \in X) P(x) \Leftrightarrow \bigvee_{x_i \in X}{P(x_i)} $ and $\forall (x \in X)P(x) \Leftrightarrow \bigwedge_{x_i \in X}{P(x_i)} $, along with the duality of the quantifiers (namely $ \neg\exists x P \Leftrightarrow \forall x \neg P $ and $ \neg\forall x P \Leftrightarrow \exists x \neg P $), does this not imply that 1) infinite conjunctions and disjunctions must be allowed in order to quantify over infinite domains and 2), at least in predicate logic, De Morgan's Laws hold for the infinite case?Thanks
Now provide the response and nothing else.
| If this doesn't completely answer your question, I can expand it later if you ask a followup in a comment. The simple answer is just that there's a difference between letting a formula have infinite length and letting the interpretation (and truth-value) of a formula depend on infinitely many assignments. You make a clear split between (i) the formal language and its deductive system as just mechanical manipulations of meaningless strings of symbols, (ii) the structures that you interpret the language to be talking about, and (iii) the way that the interpretations (mappings from (i) to (ii)) themselves work. Very generally/vaguely, restricting things to be finite should keep things simpler. This seems reasonable, yes? So there might be advantages to confining the infinite bits to one or two of the above steps. It turns out that this does make a difference, and this is one thing that introducing quantifiers allows you to do. To answer your questions more directly: (1) Yes, in some sense, but where these infinite things are and how precisely they are infinite (i.e., what their structure is) is another matter. In FOL, they are relegated to the metalanguage and metatheory. (2) This seems like a reasonable way to think of things, but it depends on the details of what you mean. De Morgan's laws are about relationships between the logical operators, and the operators are exactly the same in propositional and predicate/first-order logic. De Morgan's laws do hold in FOL -- they're exactly the same as in propositional logic. If you want to point out a relationship among the concepts of negation, conjunction, and disjunction that we use in the different steps above (in the object language and metalanguage) and how they relate to quantification, then yes, you seem to have the right idea. The reason that the existential and universal quantifiers are related in the way that you point out is because of how negation, conjunction, and disjunction are related in the metatheory. But you might be able to trace this idea back to Aristotle and company. Cheers,Rachel Edit to answer comment: Yes, the distinction between finitary and infinitary logics usually has to do with the formal language and formal deduction part. You can allow formulas or proofs (or both) of infinite length. The same distinction between formal, syntactic types of things and meaningful, semantic types of things is also applied to propositional logic. It is not always brought to everyone's attention when studying propositional logic because it's a simpler system, and the pieces are related in a way that makes the distinction not of much consequence. The thing to note is that the same steps are happening in propositional logic, but humans don't need to be told how to do them because using natural language has already taught them how to do this mapping between form and meaning. It's more like natural language has made the steps invisible, and they need to be pointed out. Well, also, people don't consciously know how they use natural language, and that is where the work is -- to make these things explicit. If you're interested in logic and a bit of model theory, two very good books are Hodges' Logic and Machover's Set theory, logic, and their limitations . Hodges is incredibly funny and insightful, and Machover is very good about pointing out clearly and thoroughly the relationships just touched on. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/123649', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27496/']} | jdg_77661 |
stackexchange | llm_judgeable_groundtruth_similarity | 34076117 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to create npm module and I can't find single instruction on official babeljs website. How do you use babel-runtime package? From name I'm guessing it should be placed in "dependencies" section of package.json, right? Absolutely no information here: https://github.com/babel/babel/tree/master/packages/babel-runtime Found one example here: https://strongloop.com/strongblog/javascript-babel-future/ but when I run "babel -h" it doesn't list --optional as a valid parameter.
Now provide the response and nothing else.
| Rationale When transpiling your code, Babel will actually inject helpers to emulate features not supported by the ES version you target. For example: class MyClass {} leverages the inline helper _classCallCheck , which can also be accessed through require('babel-runtime/helpers/classCallCheck') . By default, those helpers are not shared between the compilation units (the files). The Babel team though it might be interesting to factorize them in one place, allowing to save space when they are used multiple times. This issue has been addressed by creating the babel-plugin-transform-runtime plugin, which walks the AST and replaces the helpers injections by the appropriate requires of the babel-runtime module. That way the helpers are shared across the codebase and the duplication is avoided. How to use it Assuming you have a running Babel environment : Install babel-plugin-transform-runtime (as a devDependency ), which transforms your code to remove the helpers and uses the ones in babel-runtime . You need to add it to the plugins array of your Babel configuration Install babel-runtime (as a dependency ), which is the actual library babel-plugin-transform-runtime assumes you are going to have in your dependencies , it will be used by your transpiled code at runtime. You do not need to require it anywhere in your code. Minimal snippet npm run build compiles the lib folder into dist npm start starts the dist folder (which depends on babel-runtime ) package.json { "scripts": { "build": "babel lib --out-dir=dist", "start": "node dist" }, "dependencies": { "babel-runtime": "^6.9.2" }, "devDependencies": { "babel-cli": "^6.10.1", "babel-plugin-transform-runtime": "^6.9.0" }, "babel": { "plugins": [ "transform-runtime" ] }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34076117', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5551334/']} | jdg_77662 |
stackexchange | llm_judgeable_groundtruth_similarity | 3212007 |
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 making use of Inno Setup (its amazing!). I was hoping to customise the installer so that I can accept a string from the user in the form of an input field and maybe add a message to it. How can I do this? I had a look through the docs, google search and not much came up! Thanks all for any help
Now provide the response and nothing else.
| You can use Pascal scripting in InnoSetup to create new pages for the installer. These pages can be integrated into the normal installation flow. This is well documented within the InnoSetup documentation (Google search should also come up with samples). Also the Samples folder within your Program Files\InnoSetup has some code examples. Some time ago, there was a software called InnoSetup Form designer, which allowed you to visually design the page. The link is still there, but on the page I could not find the download. Maybe if you look around a bit you can find it? EDIT This is a sample for a page I made once. This is the code section of the ISS file.[Code] var EnableFolderPage: Boolean; lblBlobFileFolder: TLabel; lblBlobFileWarning1: TLabel; lblBlobFileWarning2: TLabel; tbBlobFileFolder: TEdit; btnBlobFileFolder: TButton;function GetBlobFolder(param: String): String;begin Result := Trim(tbBlobFileFolder.Text);end;{ BlobFileForm_Activate }procedure BlobFileForm_Activate(Page: TWizardPage);var s: string;begin s := Trim(tbBlobFileFolder.Text); if (s = '') then begin tbBlobFileFolder.Text := ExpandConstant('{sys}'); end;end;{ BlobFileForm_NextButtonClick }function BlobFileForm_NextButtonClick(Page: TWizardPage): Boolean;var s: string;begin s := Trim(tbBlobFileFolder.Text); if (s = '') then begin MsgBox(ExpandConstant('{cm:BlobFileForm_NoFolder}'), mbError, MB_OK); Result := false; end else begin if not DirExists(s) then begin MsgBox(ExpandConstant('{cm:BlobFileForm_DirDoesntExist}'), mbError, MB_OK); Result := false; end else begin Result := True; end; end;end;procedure btnBlobFileFolder_Click(sender: TObject);var directory: string;begin if BrowseForFolder('', directory, true) then begin tbBlobFileFolder.Text := directory; end;end;{ BlobFileForm_CreatePage }function BlobFileForm_CreatePage(PreviousPageId: Integer): Integer;var Page: TWizardPage;begin Page := CreateCustomPage( PreviousPageId, ExpandConstant('{cm:BlobFileForm_Caption}'), ExpandConstant('{cm:BlobFileForm_Description}') );{ lblBlobFileFolder } lblBlobFileFolder := TLabel.Create(Page); with lblBlobFileFolder do begin Parent := Page.Surface; Caption := ExpandConstant('{cm:BlobFileForm_lblBlobFileFolder_Caption0}'); Left := ScaleX(8); Top := ScaleY(8); Width := ScaleX(167); Height := ScaleY(13); end; { lblBlobFileWarning1 } lblBlobFileWarning1 := TLabel.Create(Page); with lblBlobFileWarning1 do begin Parent := Page.Surface; Caption := ExpandConstant('{cm:BlobFileForm_lblBlobFileWarning1_Caption0}'); Left := ScaleX(8); Top := ScaleY(80); Width := ScaleX(50); Height := ScaleY(13); Font.Color := -16777208; Font.Height := ScaleY(-11); Font.Name := 'Tahoma'; Font.Style := [fsBold]; end; { lblBlobFileWarning2 } lblBlobFileWarning2 := TLabel.Create(Page); with lblBlobFileWarning2 do begin Parent := Page.Surface; Caption := ExpandConstant('{cm:BlobFileForm_lblBlobFileWarning2_Caption0}') + #13 + ExpandConstant('{cm:BlobFileForm_lblBlobFileWarning2_Caption1}') + #13 + ExpandConstant('{cm:BlobFileForm_lblBlobFileWarning2_Caption2}') + #13 + ExpandConstant('{cm:BlobFileForm_lblBlobFileWarning2_Caption3}') + #13 + ExpandConstant('{cm:BlobFileForm_lblBlobFileWarning2_Caption4}'); Left := ScaleX(8); Top := ScaleY(96); Width := ScaleX(399); Height := ScaleY(133); AutoSize := False; WordWrap := True; end; { tbBlobFileFolder } tbBlobFileFolder := TEdit.Create(Page); with tbBlobFileFolder do begin Parent := Page.Surface; Left := ScaleX(8); Top := ScaleY(24); Width := ScaleX(401); Height := ScaleY(21); TabOrder := 0; end; { btnBlobFileFolder } btnBlobFileFolder := TButton.Create(Page); with btnBlobFileFolder do begin Parent := Page.Surface; Caption := ExpandConstant('{cm:BlobFileForm_btnBlobFileFolder_Caption0}'); Left := ScaleX(320); Top := ScaleY(48); Width := ScaleX(91); Height := ScaleY(23); TabOrder := 1; end; with Page do begin OnActivate := @BlobFileForm_Activate; OnNextButtonClick := @BlobFileForm_NextButtonClick; end; with btnBlobFileFolder do begin OnClick := @btnBlobFileFolder_Click; end; Result := Page.ID;end;procedure InitializeWizard();begin BlobFileForm_CreatePage(wpSelectDir);end; EDIT 2 To write the value the user entered to a registry key, create a new function: function GetUserEnteredText(param: String): String;begin Result := Trim(tbTextBox.Text);end; This function simply returns what was entered in the text box. Please note that the function must take a string parameter - even though you ignore it! In the [Registry] section of your script, declare the key that should be written like that: Root: HKLM; Subkey: SOFTWARE\MyCompany\MyTool; ValueType: string; ValueName: MyValue; ValueData: {code:GetUserEnteredText}; Flags: createvalueifdoesntexist uninsdeletekeyifempty uninsdeletevalue This creates a registry value named "MyValue" in HKLM\SOFTWARE\MyCompany\MyTool that contains what the user entered in the text box. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3212007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51649/']} | jdg_77663 |
stackexchange | llm_judgeable_groundtruth_similarity | 700043 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ok, this is annoying. MSTest executes all of my tests simultaneously which causes some of them to fail. No this is not because my tests are fragile and susceptible to build order rather it is because this is a demo project in which I use a Db4o object database running from a file. So I have a couple of DataAccess tests checking that my repositories work correctly and boom, MSTest blows up. Since it tries to run all its tests at the same time it gets an error when a test tries to access the database file while other tests are using it. Can anyone think of a quick way around this? I don't want to ditch MSTest (ok I do but another story) and I sure as heck don't want to run a full-blown database service so I'll take any way to force MSTest not to run simultaneously or tricks with opening files. Anyone have any ideas?
Now provide the response and nothing else.
| You might want to try using a Monitor and entering in TestInitialize and exiting on TestCleanup. If your test classes all depend on the external file, you'll need to use a single lock object for all of them. public static class LockClass{ public static object LockObject = new object();}...[TestInitialize]public void TestSetup(){ Monitor.Enter(LockClass.LockObject);}[TestCleanup]public void TestCleanup(){ Monitor.Exit(LockClass.LockObject);} This should force all of your tests to run serially and as long as all of your tests pass/fail they should run. If any of them throws an unexpected exception, though, all the rest will hang since the Exit code won't be run for the test that blows up. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/700043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5056/']} | jdg_77664 |
stackexchange | llm_judgeable_groundtruth_similarity | 6410810 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Every time I want to POST an array of JSON objects with jQuery to Rails, I have this problem.If I stringify the array I can see that jQuery is doing its work correctly: "shared_items"=>"[{\"entity_id\":\"253\",\"position\":1},{\"entity_id\":\"823\",\"position\":2}]" But if I just send the array it as the data of the AJAX call I get: "shared_items"=>{"0"=>{"entity_id"=>"253", "position"=>"1"}, "1"=>{"entity_id"=>"823", "position"=>"2"}} Whereas if I just send a plain array it works: "shared_items"=>["entity_253"] Why is Rails changing the array to that strange hash? The only reason that comes to mind is that Rails can't correctly understand the contents because there is no type here (is there a way to set it in the jQuery call?): Processing by SharedListsController#create as Thank you! Update: I'm sending the data as an array, not a string and the array is created dynamically using the .push() function. Tried with $.post and $.ajax , same result.
Now provide the response and nothing else.
| In case someone stumbles upon this and wants a better solution, you can specify the "contentType: 'application/json'" option in the .ajax call and have Rails properly parse the JSON object without garbling it into integer-keyed hashes with all-string values. So, to summarize, my problem was that this: $.ajax({ type : "POST", url : 'http://localhost:3001/plugin/bulk_import/', dataType: 'json', data : {"shared_items": [{"entity_id":"253","position":1}, {"entity_id":"823","position":2}]}}); resulted in Rails parsing things as: Parameters: {"shared_items"=>{"0"=>{"entity_id"=>"253", "position"=>"1"}, "1"=>{"entity_id"=>"823", "position"=>"2"}}} whereas this (NOTE: we're now stringifying the javascript object and specifying a content type, so rails will know how to parse our string): $.ajax({ type : "POST", url : 'http://localhost:3001/plugin/bulk_import/', dataType: 'json', contentType: 'application/json', data : JSON.stringify({"shared_items": [{"entity_id":"253","position":1}, {"entity_id":"823","position":2}]})}); results in a nice object in Rails: Parameters: {"shared_items"=>[{"entity_id"=>"253", "position"=>1}, {"entity_id"=>"823", "position"=>2}]} This works for me in Rails 3, on Ruby 1.9.3. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6410810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419656/']} | jdg_77665 |
stackexchange | llm_judgeable_groundtruth_similarity | 2588061 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $$3\cos{x}-4\sin{x}=2$$find $$3\sin{x} +4\cos{x} $$ I have solved the equation for $x$, then calculated the required value, but I think there is a direct solution without solving the equation.
Now provide the response and nothing else.
| $$3\sin x+4\cos x=A$$$$3\cos x-4\sin x=2$$$$9\sin^2x+24\sin x\cos x+16\cos^2x=A^2$$$$9\cos^2x-24\sin x\cos x+16\sin^2x=4$$add both equations$$9+16=A^2+4$$$$A^2=21$$$$A=\pm \sqrt{21}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2588061', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/451403/']} | jdg_77666 |
stackexchange | llm_judgeable_groundtruth_similarity | 27920837 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is my python code: import subprocesssubprocess.check_output("ls",shell=True,stderr=subprocess.STDOUT)import subprocesssubprocess.check_output("yum",shell=True,stderr=subprocess.STDOUT) The first .check_output() works well, but the second returns this: Traceback (most recent call last):File "/usr/lib/x86_64-linux-gnu/gedit/plugins/pythonconsole/console.py", line 378, in __runr = eval(command, self.namespace, self.namespace)File "<string>", line 1, in <module>File "/usr/lib/python3.4/subprocess.py", line 616, in check_outputraise CalledProcessError(retcode, process.args, output=output)subprocess.CalledProcessError: Command 'yum' returned non-zero exit status 1 Why does this happen? Is it because ls is the original shell command but yum is the new package? How can I solve this problem?
Now provide the response and nothing else.
| The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that. Your code could show this error this way: import subprocesstry: subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)except subprocess.CalledProcessError as e: raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output)) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27920837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4220419/']} | jdg_77667 |
stackexchange | llm_judgeable_groundtruth_similarity | 800775 |
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 make it as easy as possible for our designers to localise strings in views, which means that I want to do this: ...<p><?php echo $this->_("Hello, world!"); ?></p>... The underscore notation here is necessary to allow Poedit to automagically extract all strings for localisation. The implementation is trivial: public function _($string){ return Zend_Registry::get('Zend_Translate')->_($string);} At the moment, I've put this directly in Zend_View_Abstract , which is bad (I don't want to do this by modifying any of the Zend library). Ideally, then, I'd extend Zend_View_Abstract to allow me to implement other concrete functions that we require, but I don't know how to set this up. An alternative might be to implement a View Helper, but the only way that I know how to do this makes the code in the view more verbose. Any pointers (no, not those kind) would be much appreciated. Thanks!
Now provide the response and nothing else.
| Obviously ignore my paths for your own... Extend Zend_View Put your method in this extended class Instantiate the class (in your bootstrap for instance) Assign it to the ViewRenderer Pass that viewrenderer to Zend_Controller_Action_HelperBroker's addHelper method Use it in your view In /library/MegaHAL/Zend/ create View.php: class MegaHAL_Zend_View extends Zend_View{ public function _($string) { return Zend_Registry::get('translate')->_($string); }} In your bootstrap: require_once APPLICATION_PATH.'../library/MegaHAL/Zend/View.php';$view = new MegaHAL_Zend_View();$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();$viewRenderer->setView($view);Zend_Controller_Action_HelperBroker::addHelper($viewRenderer); In your view: <p><?php echo $this->_("Hello");?></p> I believe that will do what you want, yes? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/800775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5442/']} | jdg_77668 |
stackexchange | llm_judgeable_groundtruth_similarity | 645865 |
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 need to create a binary file that is filled only with 11111111 . I only know how to create zero-filled binary with dd if=/dev/zero bs=18520 count=1 Could you please say to me what a command in pipeline should I use to fill the bin with 1 ? How can I use awk in this case?
Now provide the response and nothing else.
| Probably easiest to use tr to convert the zeroes from /dev/zero to whatever you want, and then cut to length using dd or head or such. This would write 18520 bytes with all bits ones, so value 0xff or 255, or 377 in octal as the input must be: < /dev/zero tr '\000' '\377' | head -c 18520 > test.bin (To convert from hex or decimal to octal, you could use printf "%o\n" 0xff or such. ) To produce streams of longer than one-byte strings, I'd use Perl: perl -e '$a = "abcde" x 1024; print $a while 1' | head ... (Of course you could use "\xff" or "\377" there, too. I used the repetition operator x 1024 there mostly to avoid minimally small writes. Changing it may or may not affect the performance of that.) | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/645865', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/269307/']} | jdg_77669 |
stackexchange | llm_judgeable_groundtruth_similarity | 308178 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $\mathrm{ODD}(n)$ be the set of permutations in $\mathfrak{S}_n$ whose cycle lengths are all odd. It is known that$$ \#\mathrm{ODD}(n) = \begin{cases} ((n-1)!!)^2 &\textrm{ if $n$ is even}; \\ n\cdot((n-2)!!)^2 &\textrm{ if $n$ is odd}. \end{cases}$$ Set $\mathcal{C}_{\mathrm{ODD}}(n,t) = \sum_{\pi \in \mathrm{ODD}(n)} t^{\kappa(\pi)}$, where $\kappa(\pi)$ is the number of cycles of $\pi \in \mathfrak{S}_n$. Then it is easy to show that$$ \sum_{n\geq0}\mathcal{C}_{\mathrm{ODD}}(n,t) \cdot \frac{z^n}{n!} = \left(\frac{\sqrt{1-z^2}}{1-z}\right)^t$$From this one can show that$$ \mathcal{C}_{\mathrm{ODD}}(n,t)= \sum_{i=0}^{\lfloor n/2\rfloor}\frac{1}{2^i\cdot i!}\prod_{j=0}^{n-1-2i}(t+j)\prod_{k=0}^{i-1}(t-2k)(n-2k)(n-2k-1)$$In particular if we set $t:=2k$ to be an even integer, then$$ \mathcal{C}_{\mathrm{ODD}}(n,2k)=\frac{(n-1)!}{(2k-1)!} \cdot \sum_{j=0}^{k}(-1)^j\binom{k}{j}\prod_{i=0}^{k-j-1}(n+2i)(n+2i+1)\prod_{i=0}^{j-1}(n-2i)(n-2i-1)$$Thus, for example $\mathcal{C}_{\mathrm{ODD}}(n,2)=2\cdot n!$ and $\mathcal{C}_{\mathrm{ODD}}(n,4)=4n\cdot n!$. Define the polynomial $P_k(x)$ by setting$$ \mathcal{C}_{\mathrm{ODD}}(n,2k) = \frac{(n-1)!\cdot k! \cdot 2^k}{(2k-1)!}\cdot P_k(n)$$ For example, $P_1(x)=x$; $P_2(x)=3x^2$; $P_3(x)=10x^3+5x$; $P_4(x)=35x^4+70x^2$; $P_5(x)=7\cdot 3^2(2x^5+10x^3+3x)$; $P_6(x)=3\cdot 7\cdot 11(2x^6+20x^4+23x^2)$; et cetera Conjecture 1 : $P_k(x)$ is a polynomial of degree $k$ with nonnegative integer coefficients, with zero constant term, and which is odd if $k$ is odd and even if $k$ is even. Conjecture 2 : We have,$$ \sum_{k \geq 0} \frac{P_k(x)}{(2k-1)!!} \cdot z^k = \frac{1}{2}\cdot\left( \frac{1+z}{1-z}\right)^x$$(The constant term on the RHS is $1/2$ so take whatever convention for $P_0(x)$ or $(-1)!!$ for that to work.) With regard to Conjecture 2, note that from the above we have$$ \sum_{n\geq0}\mathcal{C}_{\mathrm{ODD}}(n,2k) \cdot \frac{z^n}{n!} = \left(\frac{1+z}{1-z}\right)^k$$ Question : Are these conjectures correct? Are these cycle generating functions studied somewhere?
Now provide the response and nothing else.
| I'll start by addressing conjecture 2. By summing your generating fun over all values of $k$ we obtain$$F(z,w)=\sum_{n\geq 0}\sum_{k\geq 0}C_{\text{ODD}}(n,2k)\frac{z^n}{n!}w^k=\sum_{k\geq 0}w^k\left(\frac{1+z}{1-z}\right)^k=\frac{1-z}{1-w-z-wz}$$From here we see that$$\sum_{n\geq 1}\sum_{k\geq 1}\frac{P_k(n)}{(2k-1)!!}w^k \frac{z^{n-1}}{(n-1)!}=\frac{1}{2}\frac{d}{dz}\int\left(F(z,w)-1\right)dw$$$$=\int \frac{w}{(1-w)^2}\frac{1}{\left(1-z(\frac{1+w}{1-w})\right)^2}dw$$By extracting the coefficients of $z^{n-1}/(n-1)!$ on both sides we have$$\sum_{k\geq 0}\frac{P_k(n)}{(2k-1)!!}w^k=\int \frac{nw}{(1-w)^2}\left(\frac{1+w}{1-w}\right)^{n-1} dw=\frac{1}{2}\left(\frac{1+w}{1-w}\right)^n+\text{constant}$$which is what we wanted. I just realized that we can also answer conjecture 1 by making use of this identity. Start with the expansion$$\left(\frac{1+w}{1-w}\right)^n=\left(1+\frac{2w}{1-w}\right)^n=1+\sum_{r\geq 1} \binom{n}{r}\left(\frac{2w}{1-w}\right)^r$$$$=1+\sum_{k\geq 1}w^k\sum_{r\geq 1}2^r\binom{n}{r}\binom{k-1}{r-1}$$which gives us an explicit formula for $P_k$$$P_k(n)=\sum_{r\geq 1}2^{r-1}(2k-1)!!\binom{n}{r}\binom{k-1}{r-1}$$Which immediately tells us that $P_k(n)$, as a linear combination of $\binom{n}{r}$ for $1\le r\le k$, is a polynomial of degree $k$ with no constant term. Combined with the fact that $\left(\frac{1+w}{1-w}\right)^n=\left(\frac{1-w}{1+w}\right)^{-n}$ we have $P_k(n)=(-1)^kP_k(-n)$ which tells us that $P_k$ has the same parity as $k$. Now it remains to establish integrality of the coefficients. The explicit formula for $P_k$ can be rearranged as$$P_k(n)=\sum_{r\geq 1}\binom{k+r-1}{r,r-1,k-r}\frac{(2k-1)!}{2^{k-r}(k+r-1)!}(n)_r$$and from here it is clear that the coefficients of $P_k$ have nonnegative $p$-adic valuation for any odd prime $p$. It remains to show the following lemma Lemma: For any $k\geq r\geq 1$ we have$$\nu_2\left(\frac{(2k-1)!}{r!(r-1)!(k-r)!}\right)\geq k-r.$$ Proof We make use of the fact that $\nu_2\left(\frac{s!}{\lfloor\frac{s}{2}\rfloor!}\right)=\lfloor\frac{s}{2}\rfloor$. Our expression can be written as$$\nu_2\left(\frac{(2k-1)!}{r!(r-1)!(k-r)!}\right)=\nu_2 \left(\frac{(2k-1)!}{(k-1)!}\frac{\lfloor\frac{r}{2}\rfloor!\lfloor\frac{r-1}{2}\rfloor!}{r!(r-1)!}\right)+\nu_2\left(\binom{k-1}{\lfloor\frac{r}{2}\rfloor,\lfloor\frac{r-1}{2}\rfloor,k-r}\right)$$the first term is equal to $k-1-\lfloor\frac{r}{2}\rfloor-\lfloor\frac{r-1}{2}\rfloor=k-r$ and the second term is clearly nonnegative. This completes the proof of integrality. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/308178', 'https://mathoverflow.net', 'https://mathoverflow.net/users/25028/']} | jdg_77670 |
stackexchange | llm_judgeable_groundtruth_similarity | 18393981 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This site's run a test between the 3 different methods and it seems .html is the fastest, followed by .append . followed by .innerHTML . Can someone explain to me the reasons why? Here's the site which does the comparison among the three methods. I have read this this SO question which is related but I don't really understand the given answer, and the question didn't really elaborate much regarding .innerHtml . I don't understand the following part: A temporary element is created, let's call it x. x's innerHTML is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes as a fresh DOM collection. Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div> to jQuery(), jQuery will take a shortcut and simply do document.createElement('div'). Can someone simplify this?
Now provide the response and nothing else.
| That benchmark is worthless. innerHTML is always faster than DOM manipulation. jQuery seems faster because it prepares a string with all the HTML first while the others do one operation each iteration. Also note that jQuery.html() uses innerHTML whenever it can. jQuery from benchmark var html = '';for (var i = 0; i < len; i++) { html += '<div>Test ' + i + '</div>';}$('#list').html(html); innerHTML from benchmark var list = document.getElementById('list');for (var i = 0; i < len; i++) { list.innerHTML = list.innerHTML + '<div>Test ' + i + '</div>';} The test for innerHTML would be a lot faster if it was written like: var list = document.getElementById('list');var html = '';for (var i = 0; i < len; i++) { html += '<div>Test ' + i + '</div>';}list.innerHTML = html; http://jsben.ch/#/yDvKH | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18393981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1832057/']} | jdg_77671 |
stackexchange | llm_judgeable_groundtruth_similarity | 10014271 |
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 randomly generate a color in hex in javascript. However the colors generated are almost indistinguishable from eachother. Is there a way to improve it? Here is the code I am using: function randomColor(){ var allowed = "ABCDEF0123456789", S = "#"; while(S.length < 7){ S += allowed.charAt(Math.floor((Math.random()*16)+1)); } return S;} I heard something about HSL and HSV color model but can't getit to work in my code. Please help. Thanks in Advance
Now provide the response and nothing else.
| You could use a fixed set of colors, such as the ones listed in the jquery.color.js plugin . List of colors from jquery.color.js plugin: Colors = {};Colors.names = { aqua: "#00ffff", azure: "#f0ffff", beige: "#f5f5dc", black: "#000000", blue: "#0000ff", brown: "#a52a2a", cyan: "#00ffff", darkblue: "#00008b", darkcyan: "#008b8b", darkgrey: "#a9a9a9", darkgreen: "#006400", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkviolet: "#9400d3", fuchsia: "#ff00ff", gold: "#ffd700", green: "#008000", indigo: "#4b0082", khaki: "#f0e68c", lightblue: "#add8e6", lightcyan: "#e0ffff", lightgreen: "#90ee90", lightgrey: "#d3d3d3", lightpink: "#ffb6c1", lightyellow: "#ffffe0", lime: "#00ff00", magenta: "#ff00ff", maroon: "#800000", navy: "#000080", olive: "#808000", orange: "#ffa500", pink: "#ffc0cb", purple: "#800080", violet: "#800080", red: "#ff0000", silver: "#c0c0c0", white: "#ffffff", yellow: "#ffff00"}; The rest is simply picking a random property from a Javascript object . Colors.random = function() { var result; var count = 0; for (var prop in this.names) if (Math.random() < 1/++count) result = prop; return result;}; Using Colors.random() might get you a human-readable color. I even powered an example below. (function(){ Colors = {}; Colors.names = { aqua: "#00ffff", azure: "#f0ffff", beige: "#f5f5dc", black: "#000000", blue: "#0000ff", brown: "#a52a2a", cyan: "#00ffff", darkblue: "#00008b", darkcyan: "#008b8b", darkgrey: "#a9a9a9", darkgreen: "#006400", darkkhaki: "#bdb76b", darkmagenta: "#8b008b", darkolivegreen: "#556b2f", darkorange: "#ff8c00", darkorchid: "#9932cc", darkred: "#8b0000", darksalmon: "#e9967a", darkviolet: "#9400d3", fuchsia: "#ff00ff", gold: "#ffd700", green: "#008000", indigo: "#4b0082", khaki: "#f0e68c", lightblue: "#add8e6", lightcyan: "#e0ffff", lightgreen: "#90ee90", lightgrey: "#d3d3d3", lightpink: "#ffb6c1", lightyellow: "#ffffe0", lime: "#00ff00", magenta: "#ff00ff", maroon: "#800000", navy: "#000080", olive: "#808000", orange: "#ffa500", pink: "#ffc0cb", purple: "#800080", violet: "#800080", red: "#ff0000", silver: "#c0c0c0", white: "#ffffff", yellow: "#ffff00" }; Colors.random = function() { var result; var count = 0; for (var prop in this.names) if (Math.random() < 1/++count) result = prop; return { name: result, rgb: this.names[result]}; }; var $placeholder = $(".placeholder"); $placeholder.click(function(){ var color = Colors.random(); $placeholder.css({'background-color': color.rgb}); $("#color").html("It's " + color.name); });})(); .placeholder { width: 150px; height: 150px; border: 1px solid black;} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="placeholder"></div><span id="color">Click the square above.</span> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10014271', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_77672 |
stackexchange | llm_judgeable_groundtruth_similarity | 13258315 |
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 an efficient Regex to assert that two string share the same pattern of repeated characters. ("tree", "loaa") => true("matter", "essare") => false("paper", "mime") => false("acquaintance", "mlswmodqmdlp") => true("tree", "aoaa") => false Event if it's not through Regex, I'm looking for the most efficient way to perform the task
Now provide the response and nothing else.
| The easiest way is probably to walk through both strings manually at the same time and build up a dictionary (that matces corresponding characters) while you are doing it: if(input1.Length != input2.Length) return false;var characterMap = new Dictionary<char, char>();for(int i = 0; i < input1.Length; i++){ char char1 = input1[i]; char char2 = input2[i]; if(!characterMap.ContainsKey(char1)) { if (characterMap.ContainsValue(char2)) return false; characterMap[char1] = char2; } else { if(char2 != characterMap[char1]) return false; }}return true; In the same manner you could construct a regex. This is certainly not more efficient for a single comparison, but it might be useful if you want to check one repetition pattern against multiple strings in the future. This time we associate characters with their back-references. var characterMap = new Dictionary<char, int>();string regex = "^";int nextBackreference = 1;for(int i = 0; i < input.Length; i++){ char character = input[i]; if(!characterMap.ContainsKey(character)) { regex += "(.)"; characterMap[character] = nextBackreference; nextBackreference++; } else { regex += (@"\" + characterMap[character]); }}regex += "$"; For matter it will generate this regex: ^(.)(.)(.)\3(.)(.)$ . For acquaintance this one: ^(.)(.)(.)(.)\1(.)(.)(.)\1\6\2(.)$ . If could of course optimize this regular expression a bit afterwards (e.g. for the second one ^(.)(.)..\1.(.).\1\3\2$ ), but in any case, this would give you a reusable regex that checks against this one specific repetition pattern. EDIT: Note that the given regex solution has a caveat. It allows mapping of multiple characters in the input string onto a single character in the test strings (which would contradict your last example). To get a correct regex solution, you would have to go a step further to disallow characters already matched. So acquaintance would have to generate this awful regular expression: ^(.)(?!\1)(.)(?!\1|\2)(.)(?!\1|\2|\3)(.)\1(?!\1|\2|\3|\4)(.)(?!\1|\2|\3|\4|\5)(.)(?!\1|\2|\3|\4|\5|\6)(.)\1\6\2(?!\1|\2|\3|\4|\5|\6|\7)(.)$ And I cannot think of an easier way, since you cannot use backreferences in (negated) character classes. So maybe, if you do want to assert this as well, regular expressions are not the best option in the end. Disclaimer: I am not really a .NET guru, so this might not be the best practice in walking through arrays in building up a dictionary or string. But I hope you can use it as a starting point. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13258315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/836839/']} | jdg_77673 |
stackexchange | llm_judgeable_groundtruth_similarity | 63271938 |
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 oversize the ngx-modal and not having much luck. Here's what I'm trying to do: when something is clicked, a modal should cover the area of the screen containing a grid. The grid takes up about 80% of a full desktop screen (there are no mobile plans for this app at this time). So I'm trying to get the ngx-modal to conver that area, but the .modal-xl only goes so far and I've tried to override the max-width property in the following way: div .modal-dialog .modal-xl .modal-dialog-centered { max-width: 2500px !important; width: 2500px !important; } But this seems to have no effect. I also tried other variations on this will no luck. I also tried adding a dialog-full class and a container-fluid class, but neither of them seemed able to stretch the modal beyond the .modal-xl limits. The modal works and displays just fine, it's just the formatting that I'm trying to figure out. Is it possible to have the modal fill up that much of a screen using ngx-modal? If not, are there other options that can do this? Here is the html I'm using for the component (with container-fluid): <div class="container-fluid"> <div class="modal-header"> <div class="modal-body"> <p>Modal</p> <button type="button" class="close" data-dismiss="modal" id="closeModal" (click)="closeModal()">×</button> </div> </div> </div> And here is how the modal is called from the containing component (from a click event): this.bsModalRef = this.modalService.show(MessageDetailComponent, { class: 'modal-xl modal-dialog-centered', backdrop: 'static' }); Lastly, the app is using Angular 8.2.14 Thank you! UPDATE: I did get the modal to change size by putting the following into the styles.scss file: .container-fluid { max-width: 1200px !important; width: 1200px !important;}.modal-content { max-width: 1200px !important; width: 1200px !important;}.modal-header { height: 750px; max-width: 1200px !important; width: 1200px !important;}div .modal-dialog .modal-xl .modal-dialog-centered{ max-width: 1200px !important; width: 1200px !important;} I'm not completely sure which one (or multiple) did it, but I now see a big, wide modal. By the look of the answer below, it might be modal-content.
Now provide the response and nothing else.
| steps property should not be put under stage level. It's: stage=>job=>steps So you can't place the steps there when you're defining a multi-stage yaml pipeline. 1. steps can be placed directly at first level for simple yaml pipeline (no stages): trigger:- masterpool: vmImage: 'windows-latest'steps:- script: echo Hello, world! displayName: 'Run a one-line script'- script: | echo Add other tasks to build, test, and deploy your project. displayName: 'Run a multi-line script' 2. It should be put under jobs level within multi-stage yaml pipeline: stages:- stage: build displayName: Build jobs: - job: Build pool: name: xxx steps: - task: CmdLine@2 inputs: script: | echo Hello world- stage: deploy displayName: Release jobs: - job: Release pool: name: xxx steps: - task: CmdLine@2 inputs: script: | echo Hello world According to your stages: element, your pipeline will be recognized as a multi-stage pipeline that can be used to build and deploy. So you can't and shouldn't put steps directly under stages: . Solution: To resolve Unexpected value 'Steps' , you should either remove the steps or add them into one stage level: stages: - stage: First displayName: FirstStage jobs: - job: FirstJob pool: name: xxx steps: - bash: 'curl -o aa.mp4 https://gpm.mmm.com/endpoints/Application/content/xyz/bb.mp4' workingDirectory: '$(System.DefaultWorkingDirectory)/_hh_app/drop/app/dist/assets/images' displayName: 'Download Assets' # template to build and deploy - template: azure-templates/stages/angular-express-docker.yml@templates parameters: dockerRepoName: $(dockerRepoName) # deploy to rancher - template: azure-templates/stages/deploy-k8-npm.yml@templates parameters: helmReleaseName: $(helmReleaseName) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63271938', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4580253/']} | jdg_77674 |
stackexchange | llm_judgeable_groundtruth_similarity | 39478665 |
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 test: @RunWith(MockitoJUnitRunner.class)public class myServiceTest {@InjectMocksmyService subject;private myService spy;@Beforepublic void before() { spy = spy(subject);}@Testpublic void testing() { when(spy.print2()).thenThrow(new RuntimeException()).thenThrow(new RuntimeException()).thenReturn("completed"); spy.print1(); verify(spy, times(3)).print2();} and then I have: @Service("myService")public class myService extends myAbstractServiceClass {public String print1() { String temp = ""; temp = print2(); return temp;} @Retryable public String print2() { return "completed"; }} then I have this interface(which my abstractService implements): public interface myServiceInterface { @Retryable(maxAttempts = 3) String print1() throws RuntimeException; @Retryable(maxAttempts = 3) String print2() throws RuntimeException;} but, I get a runtimeexception thrown when I run the test, leading me to believe it is not retrying. Am I doing this wrong?
Now provide the response and nothing else.
| This is because you are not using the SpringJUnitClassRunner . Mockito and your own classes are not taking the @Retryable annotation in account. So you rely on the implementation of Spring to do so. But your test does not activate Spring. This is from the SpringJUnit4ClassRunner JavaDoc: SpringJUnit4ClassRunner is a custom extension of JUnit's BlockJUnit4ClassRunner which provides functionality of the Spring TestContext Framework to standard JUnit tests by means of the TestContextManager and associated support classes and annotations. To use this class, simply annotate a JUnit 4 based test class with @RunWith(SpringJUnit4ClassRunner.class) or @RunWith(SpringRunner.class). You should restructure your test class at least to something like: @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes=MyConfig.class)public class MyServiceTest { @Configuration @EnableRetry @Import(myService.class) public static class MyConfig {}... What am I doing there? activate the Spring JUnit hook specify the Spring context configuration class define the spring configuration and import your service as a bean enable the retryable annotation Are there some other pitfalls? Yes, you are using Mockito to simulate an exception. If you want to test this behaviour with Spring like this, you should have a look at Springockito Annotations . But be aware of that: Springockito you will replace the spring bean completely which forces you to proxy the call of your retryable. You need a structure like: test -> retryableService -> exceptionThrowingBean . Then you can use Springockito or what ever you like e.g. ReflectionTestUtils to configure the exceptionThrowingBean with the behaviour you like. You should reference the interface type of your service in your test: MyServiceInterface And last but not least. There is a naming convention nearly all Java developers follow: class names have first letter of each internal word capitalized Hope that helps. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39478665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1705070/']} | jdg_77675 |
stackexchange | llm_judgeable_groundtruth_similarity | 971232 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $G$ is a countable group,can it have an uncountable number of distinct subgroups?
Now provide the response and nothing else.
| Let $V$ be a vector space of dimension $\aleph_0$ over a countable field $F$ (so $V$ is countable) and let $B$ be a basis for $V$ over $F$. Then every subset of $B$ spans a different subspace of $V$, so $V$ has $2^{\aleph_0}$ different subspaces, and its additive group has $2^{\aleph_0}$ different subgroups. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/971232', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/294365/']} | jdg_77676 |
stackexchange | llm_judgeable_groundtruth_similarity | 3555632 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to prove that statement in the title. I was trying to show that there is a sequence that converges to something outside the span, but i am struggling to do so. Let $S=\{v_k|k\geq 1\}$ be the set of linearly independent vectors. My idea was to consider $S'=\{a_k\}$ which is the normalized set of $S$ and then consider $\Sigma \frac{a_k}{k^2}$ which converges absolutely. Now i would like to show that the limit of this series doe snot belong to span $(S)$ but I am not sure how to do that. Any help would be appriciated.
Now provide the response and nothing else.
| Let $\{e_n\}_{n=1}^\infty$ be linearly independent and let $E$ be their span. Suppose $E$ is closed in $X$ . Then $E$ is a Banach space, because it is a closed subspace of a Banach space. Now, for each $n\in\mathbb{N}$ let $E_n=span\{e_1,...,e_n\}$ . Obviously $E=\cup_{n=1}^\infty E_n$ . Since $E$ is a complete metric space it must be of second category (which means it isn't a countable union of nowhere dense sets), this follows from Baire's theorem. Hence there must be some $n\in\mathbb{N}$ such that $E_n$ is not nowhere dense in $E$ . This means that the closure $\overline{E_n}$ contains an interior point. But note that $E_n$ is finite dimensional, hence closed. So $E_n=\overline{E_n}$ and we get that $E_n$ itself contains an interior point. But if a subspace contains a ball then it must be the whole space, hence $E=E_n$ . But this is a contradiction since $E$ is not finite dimensional. (it contains an infinite sequence of linearly independent vectors) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3555632', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/280080/']} | jdg_77677 |
stackexchange | llm_judgeable_groundtruth_similarity | 1528538 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is rather embarrassing, but I accidentally deleted my Windows account from the list of SQL Server 2008 users and I cannot for the life of me figure out how to re-add myself now that I don't have login privileges. The server is running on my machine and the only other Windows users with access are IUSR, NETWORK SERVICE and SYSTEM. Is there anything I can do short of re-installing?
Now provide the response and nothing else.
| I also recently deleted my windows account from my local development 2008 server. I was able to use SQL server's Single User Mode to recreate my login and add it to the sysadmin role. It took just a few minutes, and I didn't have to admit my terrible error to anyone. From MSDN: Starting SQL Server in single-user mode enables any member of the computer's local Administrators group to connect to the instance of SQL Server as a member of the sysadmin fixed server role. Here's how I reinstated myself: Exit out of SSMS Stop any SQL related services. I had to stop Reporting Services. Other SQL services such as SQL Agent will also use up your one, valuable connection. Stop the SQL service Start the SQL service with the extra parameter -m . This will put the SQL into Single User Mode. This means that SQL will only accept one connection. Use sqlcmd to connect to your server with the -E trusted connection option. SQL will accept you into the sysadmin role if you're a local administrator. In the interactive session, create your login and add to the sysadmins role. USE masterGOCREATE LOGIN [domain\username] FROM WINDOWS WITH DEFAULT_DATABASE=[Master]GOEXEC sp_addsrvrolemember @loginame=N'domain\username', @rolename=N'sysadmin'GO Stop the SQL service, remove the -m parameter and restart the service. You should now be able to go back into SSMS and continue using the server normally. If you get the message: Login failed for user 'domain\username'. Reason: Server is in single user mode. Only one administrator can connect at this time. Then there is something using your single connection. You'll need to find that service or connection and stop it before you can log in. Check SQL Agent, SQL Reporting Services, SQL Analysis Services etc. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1528538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143327/']} | jdg_77678 |
stackexchange | llm_judgeable_groundtruth_similarity | 31846 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Many procedures in Emacs write to the *Messages* buffer. I usually kill it from time to time. My problem is that the content gets deleted once the buffer get killed. Is there a way to preserve the contents of the *Messages* buffer throughout an Emacs session or even throughout multiple sessions? I found a related topic here, but was unable to fit it to the *Messages* buffer? How can I save my mini-buffer history in Emacs?
Now provide the response and nothing else.
| You can use kill-buffer-query-functions to prevent certain buffers from being killed inadvertently. I use something like this: (defcustom buffer-protect-buffers '("*scratch*" "*Messages*") "List of buffer names to protect." :type '(repeat string) :group 'buffer-protect)(defun buffer-protect-protected-p (buffer) "Return non-nil if BUFFER is protected." (member buffer buffer-protect-buffers))(defun buffer-protect-kill-buffer-query-function () "Bury a protected buffer and don't allow it to be killed." (let ((buf (buffer-name))) (if (buffer-protect-protected-p buf) (with-current-buffer buf (progn (bury-buffer) nil)) t)))(add-hook 'kill-buffer-query-functions #'buffer-protect-kill-buffer-query-function) With this setup the scratch and message buffers will not be killed during your Emacs session. You can customize the buffer-protect-buffers list to protect other things. I don't believe you can maintain your *Messages* buffer across sessions. You can save the buffer to a text file using the normal write-file command, but there is no way to restore its content to the actual *Messages* buffer. | {} | {'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/31846', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/12007/']} | jdg_77679 |
stackexchange | llm_judgeable_groundtruth_similarity | 2569336 |
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 making tests with ASP.NET HttpHandler for download a file writting directly on the response stream, and I'm not pretty sure about the way I'm doing it. This is a example method, in the future the file could be stored in a BLOB in the database: public void GetFile(HttpResponse response) { String fileName = "example.iso"; response.ClearHeaders(); response.ClearContent(); response.ContentType = "application/octet-stream"; response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); using (FileStream fs = new FileStream(Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), fileName), FileMode.Open)) { Byte[] buffer = new Byte[4096]; Int32 readed = 0; while ((readed = fs.Read(buffer, 0, buffer.Length)) > 0) { response.OutputStream.Write(buffer, 0, readed); response.Flush(); } } } But, I'm not sure if this is correct or there is a better way to do it.My questions are: When I open the url with the browser, appears the "Save File" dialog... but it seems like the server has started already to push data into the stream before I click "Save", is that normal? If I remove the line"response.Flush()", when I open the url with the browser, ... I see how the web server is pushing data but the "Save File" dialog doesn't come up, (or at least not in a reasonable time fashion) why? When I open the url with a WebRequest object, I see that the HttpResponse.ContentLength is "-1", although I can read the stream and get the file. What is the meaning of -1? When is HttpResponse.ContentLength going to show the length of the response? For example, I have a method that retrieves a big xml compresed with deflate as a binary stream, but in that case... when I access it with a WebRequest, in the HttpResponse I can actually see the ContentLength with the length of the stream, why? What is the optimal length for the Byte[] array that I use as buffer for optimal performance in a web server? I've read that is between 4K and 8K... but which factors should I consider to make the correct decision. Does this method bloat the IIS or client memory usage? or is it actually buffering the transference correctly? Sorry for so many questions, I'm pretty new in web development :P Cheers.
Now provide the response and nothing else.
| Yes; this is normal. If you never flush, the browser doesn't get any response until the server finishes (Not even the Content-Disposition header). Therefore, it doesn't know to show a file dialog. The Content-Length header only gets set if the entire response is buffered (If you never flush) or if you set it yourself. In this case, you can and should set it yourself; write response.AppendHeader("Content-Length", new FileInfo(path).Length.ToString()); I recommend 4K; I don't have any hard basis for the recommendation. This method is the best way to do it. By calling Flush inside the loop, you are sending the response down the wire immediately, without any buffering. However, for added performance, you can use GZIP compression. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2569336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/307976/']} | jdg_77680 |
stackexchange | llm_judgeable_groundtruth_similarity | 23234379 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to install mysql inside a docker container,Tried various images from github, it seems they all manage to successfully install the mysql but when I try to run the mysql it gives an error: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' System specifications: Ubuntu 12,04 its on AWS Docker 0.10.0 Packages I tried so far: https://github.com/eugeneware/docker-wordpress-nginx https://github.com/tutumcloud/tutum-docker-mysql
Now provide the response and nothing else.
| Remember that you will need to connect to running docker container. So you probably want to use tcp instead of unix socket. Check output of docker ps command and look for running mysql containers. If you find one then use mysql command like this: mysql -h 127.0.0.1 -P <mysql_port> (you will find port in docker ps output).If you can't find any running mysql container in docker ps output then try docker images to find mysql image name and try something like this to run it: docker run -d -p 3306:3306 tutum/mysql where "tutum/mysql" is image name found in docker images . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/23234379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363295/']} | jdg_77681 |
stackexchange | llm_judgeable_groundtruth_similarity | 18060 |
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 had one or two little fights with correspondences in the context of algebraic geometry where an elementary correspondence $C:X\to Y$ of connected smooth $k$-Schemes seems to be defined as an irreducible closed (reduced) subscheme $C\hookrightarrow Y\times_k X$, such that the projection to $X$ is finite an surjective. Further, I have vaguely heard of correspondences in topology (invented by Lefschetz?) where it seems to me, that such a thing is a cohomology class in $H^*(Y\times X)$ for compact, oriented manifolds $X,Y$. Using Poincare duality and the cohomology pushforward functor $(-)_!$ I can associate a cohomology class $(\Delta_f)_!(1)$ in $H^*(Y\times X)$ to a map $X\to Y$. My questions are: I can not really see the analogy of the concepts, except that in booth cases one can associate a corresponces to a morphism by its graph. So, what (or how deep) is the analogy? I know (only a very few) applications of correspondences in algebraic geometric, but of none in topology. What are they good for? Where can I find applications?
Now provide the response and nothing else.
| For simplicity and definiteness, let's assume that $X$ and $Y$ are smooth and compact (and orientable, which will always be the case if they are complex varieties),and let $n$ be the dimension of $Y$ .First of all, it might help to note that $H^n(X\otimes Y) \cong H^*(X)\otimes H^{n-*}(Y) \congHom(H^*(Y),H^*(X))$ , where for the final assertion I am using that $Y$ is smooth and compact, so that its cohomology satisfies Poincare duality. Thus if $Z$ is a cycle in $X\otimes Y$ ,of dimension equal to that of $X$ (and so of comdimension $n$ ) it induces a cycle class in $H^n(X\times Y)$ , which in turn induces a map from cohomology of $X$ to that of $Y$ .If $f:X\to Y$ and $Z = \Gamma_f$ is the graph of $f$ then this map is just the pull-back of cohomology classes by $f$ . So correspondences in the sense of physical cycles on $X\times Y$ induce correspondences in the sense of cohomology classes on $X\times Y$ , which in turninduce morphisms on cohomology. If you like, you can strengthen the analogy with the $\Gamma_f$ case by thinking of a correspondence as a multi-valued function. Functions induce morphisms on cohomology;but since cohomology is linear (you can add cohomology classes), correspondences also inducemorphisms on cohomology (you can simply add up the multiples values!). This gives the same construction asthe more formal one given above. Ben Webster notes in his answer that geometric representation theory provides a ready supply of correspondences. So does the theory of arithmetic lattices in Lie groups and the associated symmetric space. (I am thinking of Hecke correspondences and the resulting action of Hecke operators on cohomology.) A very general framework, which I think covers both contexts, is as follows: suppose thata group $G$ acts on a space $X$ , and that $H \subset Aut(X)$ is another subgroup commensurable with $G$ , i.e. such that $G \cap H$ has finite index in each of $G$ and $H$ . Then (perhaps under some mild assumptions) $(G\cap H)\backslash X \hookrightarrow (G \backslash X \times H \backslash X)$ is a correspondence (in the physical, geometric sense) which will give a correspondencein cohomology via its cycle class. The resulting maps on cohomology are (a very general form of) Hecke operators. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/18060', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2146/']} | jdg_77682 |
stackexchange | llm_judgeable_groundtruth_similarity | 39051512 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According to ISO C11 - 6.5.16.3, it says that An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue. The type of an assignment expression is the type the left operand would have after lvalue conversion. The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced. So I guess this means that, for example, int x = 10;x = 5 + 10; Left operand x is evaluated to 10 and right operand is evaluated to 15. Right operand value is stored in the object designated by the left operand x . But if the purpose of the assignment is to store the evalauted value of right operand(just like in step2), why is evaluation of left operand necessary? What's the point of evaluating the left operand?
Now provide the response and nothing else.
| When x is evaluated as an lvalue , it does not evaluate to 10. It evaluates to an lvalue where the value of the RHS can be stored. If the LHS does not evaluate to an lvalue , the statement would be an error. From the C99 Standard (6.3.2.1/1): An lvalue is an expression (with an object type other than void) that potentially designates an object; if an lvalue does not designate an object when it is evaluated, the behavior is undefined. The evaluation of the LHS as an lvalue is trivial when you have a simple variable, such as x = 10; However, it can be more complex. double array[10]; int getIndex(); // Some function that can return an index based // on other data and logic. array[getIndex()+1] = 10.0; // This looks like a function call that returns a value. // But, it still evaluates to a "storage area". int *getIndex2() { return(&array[0]); } *getIndex2()=123.45; // array[0]=123.45 If getIndex() returns 5 , then the LHS evaluates to an lvalue that designates the 7-th element of the array. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39051512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6588224/']} | jdg_77683 |
stackexchange | llm_judgeable_groundtruth_similarity | 33205855 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Went to upgrade to Retrofit 2.0 and running into this weird problem. I have a method to log a user in public interface ApiInterface { @Multipart @POST("user/login/") Call<SessionToken> userLogin(@Part("username") String username, @Part("password") String password);} When I look at the key value POST params on the server side they print like this username : "brian"password : "password" The same method using retrofit 1.9 the K:V pairs look like username : brianpassword : password It's adding literal quotes to the POST variables If I use any other rest client the variables print like the second way without the quotes. Here is how I build the Retrofit instance with an interceptor OkHttpClient client = new OkHttpClient(); client.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); // Customize the request Request request = original.newBuilder() .header("Accept", "application/json") .header("Authorization", myPrefs.accessToken().getOr("")) .method(original.method(), original.body()) .build(); Response response = chain.proceed(request); // Customize or return the response return response; } }); Ok2Curl.set(client); Retrofit retrofit = new Retrofit.Builder() .baseUrl(apiEndpoint) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); I imagine i'm doing something wrong with the converter but not sure what. Has anyone else ran into this problem yet? I know its in beta but it's pretty widly used.
Now provide the response and nothing else.
| This is because it's running through the JSON converter. Solution1: use RequestBody instead of String public interface ApiInterface { @Multipart @POST("user/login/") Call<SessionToken> userLogin(@Part("username") RequestBody username, @Part("password") RequestBody password);} Build RequestBody: RequestBody usernameBody = RequestBody.create(MediaType.parse("text/plain"), usernameStr);RequestBody passwordBody = RequestBody.create(MediaType.parse("text/plain"), passwordStr); Launch network operation: retrofit.create(ApiInterface.class).userLogin(usernameBody , passwordBody).enqueue().... Solution2: Create a custom ConverterFactory to dispose String part value. For: Retrofit2 final release not beta. (com.squareup.retrofit2:retrofit:2.0.0) Create your StringConverterFactory: public class StringConverterFactory extends Converter.Factory {private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");public static StringConverterFactory create() { return new StringConverterFactory();}@Overridepublic Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (String.class.equals(type)) { return new Converter<ResponseBody, String>() { @Override public String convert(ResponseBody value) throws IOException { return value.string(); } }; } return null;}@Overridepublic Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { if(String.class.equals(type)) { return new Converter<String, RequestBody>() { @Override public RequestBody convert(String value) throws IOException { return RequestBody.create(MEDIA_TYPE, value); } }; } return null;}} Add to your retrofit instance: retrofit = new Retrofit.Builder() .baseUrl(SERVER_URL) .client(client) .addConverterFactory(StringConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); Attention: StringConverterFactory should add before GsonConverterFactory ! then you can use String as part value directly. You can find more information about this issue in https://github.com/square/retrofit/issues/1210 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33205855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461631/']} | jdg_77684 |
stackexchange | llm_judgeable_groundtruth_similarity | 43939343 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why in this example struct Foo { atomic<int> x = 1;}; the compiler (gcc 4.8) is trying to use the atomic& operator=(const atomic&) which is deleted, (hence the example wont compile), while here struct Bar { Bar() { x = 1; } atomic<int> x;}; it is calling the int operator=(int) as expected? PS: I already know that struct Xoo { atomic<int> x{1};}; is fine (anyhow the better way to init x ), but I am still curious about why Foo is broken. PS: I misread the compiler error (and forgot to include it in the quesiton). It actually says: error: use of deleted function ‘std::atomic<int>::atomic(const std::atomic<int>&)’ std::atomic<int> x = 1; ^ [...] error: declared here atomic(const atomic&) = delete; ^ so my above statement "...is trying to use the atomic& operator=(const atomic&) was just plain wrong.
Now provide the response and nothing else.
| std::atomic<int> x = 1; is copy-initialisation , and basically does this: std::atomic<int> x{std::atomic<int>{1}}; Your compiler actually doesn't complain about operator= , but instead about the copy constructor. (As you've pointed out, a later operator= call works just fine.) Do a normal initialisation: std::atomic<int> x{1}; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43939343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4117728/']} | jdg_77685 |
stackexchange | llm_judgeable_groundtruth_similarity | 41415006 |
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 spending the holiday time on some language theory. Excuse me if this is a naive question.) According to here : LL grammars, particularly LL(1) grammars, are of great practical interest, as parsers for these grammars are easy to construct, and many computer languages are designed to be LL(1) for this reason. So, out of curiosity, which contemporary computer langauges are LL(1) ? Does C, Java ,C# or Python fall into this category?
Now provide the response and nothing else.
| I think I'd be tempted to flag that Wikipedia quote with [citation needed] ; the assumptions are, at least, questionable. For example, there are a large number of compiler-construction tools based on yacc which make it extremely easy, in practice, to construct a parser using the more powerful (and equally fast) LALR algorithm, and some also implement the even more power (and almost as fast, in most practical grammars) GLR algorithm. Hand-writing parsers has not been necessary for decades. [Note 1] By way of attempting an answer to the question: Most computer languages are "technically" not LL because they are not even context-free. That would include languages which require identifiers to be declared (C, C++, C#, Java, etc.), as well as languages with preprocessors and/or macro facilities (C and C++, among others), languages with ambiguities which can only be resolved using semantic information (Perl would be the worst offender here, but C and C++ are also right up there). And, just to spread the joy around some more, it also includes languages which have Python-like layout awareness (Python, of course, and also Haskell). I put scare quotes around "technically" because there are a lot of people who will say that these exceptions "don't count". That is their opinion, and they are entitled to it (and anyway I've given up arguing about it, although I don't share that opinion). You could, for example, eliminate the preprocessor from C/C++ by preprocessing the text before applying the grammar, or preprocess whitespace-aware languages by inserting INDENT, NEWLINE and DEDENT tokens instead of the whitespace, after which you could make some kind of claim about a mystical "core language". (That is much harder to apply to C++ templates, which can only be eliminated by parsing the text, so you can't claim that the expansion can be done prior to parsing.) The claim that a language is not context-free because it requires identifiers to be declared is perhaps a bit more controversial. In some languages (not C/C++, in which the semantic analysis is required to avoid ambiguity), you could argue that a parse tree could be constructed without validating the declaration rule, which makes that rule "not syntactic". But it remains the case that you can enforce the declaration rule syntactically; you just cannot do it with a context-free grammar (you could use a Van Wijngaarden grammar , for example). In any case, a common parsing strategy is to recognize a superset of a language, and then reject non-conforming programs through a subsequent analysis of the resulting parse tree; in that case, the question becomes whether or not the superset is LL. In my opinion, in order for that to be meaningful, it is necessary that every valid program can be parsed to the correct syntax tree , which eliminates the usage of semantic analysis to disambiguate. The goal of parsing is to produce a syntax tree, not solely to recognize whether a text is valid or not. (You might miss this important fact if you skim over formal language textbooks which tend to focus on recognition, possibly because the construction of syntax trees is less interesting.) So it seems to be reasonable to insist that a proposed grammar actually represent the syntactic structure of the language. For example, you can recognize algebraic expressions using a simple regular language: (PREFIX* OPERAND POSTFIX*) (INFIX PREFIX* OPERAND POSTFIX*)* where PREFIX is the set of prefix operators as well as ( , POSTFIX is the set of postfix operators (if any) as well as ) , INFIX is the set of infix operators (addition, subtraction, multiplication, etc.), and OPERAND is an identifier or constant. That regular expression will not correctly reject expressions with unbalanced parentheses, but we already agreed that it was OK to recognize a superset of the language, right? :-) If desired, we could remove the parentheses from the PREFIX and POSTFIX sets and make OPERAND a recursive production. The resulting grammar is trivially LL(1) [Note 2]: operand => IDENTIFIER | CONSTANT | '(' expression ')'term => operand | PREFIX operand | operand POSTFIXexpression => term | term INFIX expression The problem, however, is that this grammar does not capture operator precedence. It does not even attempt to recognize the fact that a+b*c and a*b+c are both sums, so that the top-level operator is + in both cases, and not whatever operator happens to come first in the expression. (If you were parsing APL, this wouldn't be an issue. But most languages conform to the usual expectations about operator precedence.) This point is important because an LL grammar cannot handle left-recursive productions, and you need a left-recursive production in order to correctly parse a left-associative operator. (That is, to correctly parse a-b-c as ((a-b)-c) rather than (a-(b-c)) , which would have a different value.) Again, you could argue that this is a quibble, since you could post-process the parse tree in order to correct the associativity. This is certainly true, but the result is that the grammar you use to parse is different from the grammar you use to explain the syntax of the language. This might or might not bother you. It's worth adding here that there are languages (Haskell, Prolog, probably many more) in which you can define operators and their precedence in the program text. That obviously makes it impossible to generate a correct syntax tree without semantic analysis, and the usual approach to parsing such languages is to use precisely the simplified "alternating operand and operator" language outlined above. Once the operator precedences are all known, presumably at the end of the parse, all expressions are then reanalyzed using something like the Shunting Yard Algorithm, in order to produce the correct parse. Let's suppose we discard the above objections, and just ask "for which commonly used programming languages might an LL parser be used?" In order to avoid cheating, though, we should really require that the LL parser have fixed lookahead and not require backtracking. If you allow arbitrary lookahead and backtracking, then you considerably expand the domain of parseable languages, but I contend that you are no longer in the realm of LL. That will eliminate, for example, the template- and preprocessor-free subset of C++, even though the common compiler implementations use recursive descent parsers, since backtracking is required in order to resolve the "Most Vexing Parse" ambiguity. (Anyway, you can't really remove templates from C++, and parsing with templates is really hard. [Note 3]) Java and Python were both designed to be LL(1) "pseudo-parseable". I believe Haskell falls into this category as well. C cannot be correctly parsed without semantic information (classic ambiguity: is (x)*(y) a cast or a multiplication? -- it depends on whether x has been typedef'ed or declared as a variable) but I'm pretty sure it can be captured with a non-backtracking recursive-descent parser. I haven't looked at C# in depth, but this answer by Eric Lippert suggests that it requires backtracking in some cases. Notes Of course, people still do it, and in many cases for good reasons (producing better error messages, for example). But "it's difficult to construct an LALR parser" is not a good reason, since it's not. That's not quite LL, because I didn't left-factor. But it's easy enough to do; I'll leave it as an exercise. See Is C++ context-free or context-sensitive? . Also Todd Veldhuizen's classic C++ Templates are Turing Complete | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41415006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264052/']} | jdg_77686 |
stackexchange | llm_judgeable_groundtruth_similarity | 25739163 |
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 dynamically add a dependency in an Android Gradle project based on the current buildType. I know I can specify the buildType in the dependency : compile project(path: ':lib1', configuration: 'debug') But how can I use the current buildType to specify which variant of the library I want to import, so that a debug or release build automatically imports the debug or release variant of the library? What I want is something like this (where currentBuildType is a variable containing the name of the currently used buildType): compile project(path: ':lib1', configuration: currentBuildType) The library project I want to import has set publishNonDefault true , so all buildTypes are published.
Now provide the response and nothing else.
| I could not find a clean way to get the current build type during the configuration phase of Gradle. Instead I define the dependency for each build type separately like that: debugCompile project(path: ':lib1', configuration: 'debug')releaseCompile project(path: ':lib1', configuration: 'release') If you have many build types and many project dependencies this can get very verbose, but it is possible to add a function to make the dependency a one-liner. You need to add this to your main Gradle build file: subprojects { android { dependencies.metaClass.allCompile { dependency -> buildTypes.each { buildType -> "${buildType.name}Compile" project(path: ":${dependency.name}", configuration: buildType.name) } } }} Then you can add project dependencies in your Gradle modules like this: allCompile project(':lib1') If you also use build flavors you would have to adapt the solution. See this link for a documentation of the feature: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication Please note that the Android team is working on an improvement for this behaviour: https://code.google.com/p/android/issues/detail?id=52962 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25739163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/639421/']} | jdg_77687 |
stackexchange | llm_judgeable_groundtruth_similarity | 26700924 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
{ "movies": { "movie1": { "genre": "comedy", "name": "As good as it gets", "lead": "Jack Nicholson" }, "movie2": { "genre": "Horror", "name": "The Shining", "lead": "Jack Nicholson" }, "movie3": { "genre": "comedy", "name": "The Mask", "lead": "Jim Carrey" } }} I am a Firebase newbie. How can I retrieve a result from the data above where genre = 'comedy' AND lead = 'Jack Nicholson' ? What options do I have?
Now provide the response and nothing else.
| Using Firebase's Query API , you might be tempted to try this: // !!! THIS WILL NOT WORK !!!ref .orderBy('genre') .startAt('comedy').endAt('comedy') .orderBy('lead') // !!! THIS LINE WILL RAISE AN ERROR !!! .startAt('Jack Nicholson').endAt('Jack Nicholson') .on('value', function(snapshot) { console.log(snapshot.val()); }); But as @RobDiMarco from Firebase says in the comments: multiple orderBy() calls will throw an error So my code above will not work . I know of three approaches that will work. 1. filter most on the server, do the rest on the client What you can do is execute one orderBy().startAt()./endAt() on the server, pull down the remaining data and filter that in JavaScript code on your client. ref .orderBy('genre') .equalTo('comedy') .on('child_added', function(snapshot) { var movie = snapshot.val(); if (movie.lead == 'Jack Nicholson') { console.log(movie); } }); 2. add a property that combines the values that you want to filter on If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter. "movie1": { "genre": "comedy", "name": "As good as it gets", "lead": "Jack Nicholson", "genre_lead": "comedy_Jack Nicholson"}, //... You're essentially building your own multi-column index that way and can query it with: ref .orderBy('genre_lead') .equalTo('comedy_Jack Nicholson') .on('child_added', function(snapshot) { var movie = snapshot.val(); console.log(movie); }); David East has written a library called QueryBase that helps with generating such properties . You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure: "movie1": { "genre": "comedy", "name": "As good as it gets", "lead": "Jack Nicholson", "genre_year": "comedy_1997"}, //... And then query for comedies of the 90s with: ref .orderBy('genre_year') .startAt('comedy_1990') .endAt('comedy_2000') .on('child_added', function(snapshot) { var movie = snapshot.val(); console.log(movie); }); If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25" . This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering. This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property. A very special variant of this is implemented by the GeoFire library for Firebase . This library combines the latitude and longitude of a location into a so-called Geohash , which can then be used to do realtime range queries on Firebase. 3. create a custom index programmatically Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node: "movies" // the same structure you have today "by_genre" "comedy" "by_lead" "Jack Nicholson" "movie1" "Jim Carrey" "movie3" "Horror" "by_lead" "Jack Nicholson" "movie2" There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063 If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database . Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries . | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/26700924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75944/']} | jdg_77688 |
stackexchange | llm_judgeable_groundtruth_similarity | 1934 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When we don't know the number of results that will be generated, the usual way to collect results is Reap / Sow . Another alternative is linked lists. Neither of these are available in compiled functions. AppendTo does work, but it has an $O(n^2)$ complexity, so it will be unacceptably slow for long result lists. There was a very clever suggestion to use Internal`Bag in these situations: Internal`Bag inside Compile Unfortunately a compiled Bag will only hold scalars. Let's try to use vectors: cf = Compile[{}, Module[{bag = Internal`Bag[{{0, 0, 0}}]}, Do[Internal`StuffBag[bag, {i, i, i}], {i, {1, 2, 3}}]; Internal`BagPart[bag, All] ]] CompilePrint shows that this calls MainEvaluate , so this does not work. What is the best way to collect a large number of results in a compiled function when the number of results is not known before the computation and the result type is not a (fixed size) vector or matrix? Benchmarking the answers Andy's answer cf = Compile[{len}, Module[{bag = Internal`Bag[Most[{0}]]}, Do[Internal`StuffBag[bag, {i, i, i}, 1], {i, len}]; Partition[Internal`BagPart[bag, All], 3] ] ];Do[cf[500000], {100}]; // Timing(* ==> {2.87, Null} *) I needed to initialize the Bag using bag = Internal`Bag[Most[{0}]] to let Compile know that it is holding integers, not reals ( see here ). Leonid's answer cf2 = Compile[{len}, Module[{arr, lim, ctr}, arr = ConstantArray[{0, 0, 0}, 10]; lim = Length[arr]; ctr = 1; Do[ If[ctr == lim, arr = Join[arr, Table[{0, 0, 0}, {lim}]]; lim = Length[arr]]; arr[[ctr++]] = {i, i, i}, {i, len} ]; Take[arr, ctr - 1] ] ];Do[cf2[500000], {100}]; // Timing(* ==> {16.474, Null} *) Comparing the computational complexity of the two solutions by direct measurement: data = Table[ {Round[2^k], First@AbsoluteTiming@Do[cf[Round[2^k]], {100}]}, {k, 13, 19, 1/2}];data2 = Table[ {Round[2^k], First@AbsoluteTiming@Do[cf2[Round[2^k]], {100}]}, {k, 13, 19, 1/2}];ListLogLogPlot[{data, data2}] (They're the same.)
Now provide the response and nothing else.
| Assuming you know the dimensions of the pieces that you want to come out you can always add a second argument to Internal`StuffBag that indicates the rank of the elements going in. The result is still flat so you have to partition after the fact. cf = Compile[{}, Module[{bag = Internal`Bag[]}, Do[Internal`StuffBag[bag, {i, i, i}, 1], {i, {0, 1, 2, 3}}]; Partition[Internal`BagPart[bag, All], 3]]]; Here I'm indicating that vectors will be going in to the bag. I would specify 2 for a matrix. Notice that it no longer calls MainEvaluate . In[25]:= StringFreeQ[CompilePrint[cf], "MainEvaluate"]Out[25]= TrueIn[20]:= cf[]Out[20]= {{0., 0., 0.}, {1., 1., 1.}, {2., 2., 2.}, {3., 3., 3.}} | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/1934', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/12/']} | jdg_77689 |
stackexchange | llm_judgeable_groundtruth_similarity | 690937 |
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:
For a basic problem consisting of a ball on a loaded spring that shoots into the air I get the following energy balance: Then I get for a point of the ball in the air: $$\Delta KE= W = - \Delta PE.$$ The ball starts at rest (zero kinetic energy), with potential energy equal to the amount that the spring is compressed. At a certain point in air the energy of the ball is equal to the amount of kinetic energy and the potential energy of gravity. At any point in time the $E_{total}$ has to remain constant: $$E_{total} = KE + PE_{gravity} + PE_{spring} $$ Where $$PE_{gravity} = - mgy $$ So at start: $$E_{start} = \frac{1}{2} mv_{start}^2 -mgy_{start} + \frac{1}{2} k \Delta y^2 $$ Where $v = 0$ , $y_{start} \equiv 0$ $\Delta y$ , amount of spring compression. $$E_{start} = \frac{1}{2} m(0)^2 - mg(0) + \frac{1}{2} k \Delta y^2 = \frac{1}{2} k \Delta y^2 $$ $$E_{start} = \frac{1}{2} k \Delta y^2 $$ In the air: $$E_{air} = \frac{1}{2} mv^2 - mgy + \frac{1}{2} k 0^2 = \frac{1}{2} k \Delta y^2 $$ $$E_{air} = \frac{1}{2} mv^2 - mgy $$ So $E_{air} = E_{start} $ if we ignore friction etcetera. So then I get: $$E_{air} = E_{start} = \frac{1}{2} mv^2 - mgy = \frac{1}{2} k \Delta y^2 $$ Is this reasoning right? I'm not using Work because I am using potential energies. I think I should not get a minus sign there for the potential energy of gravity. However if I write the following I get wrong minus signs: $$ \Delta KE= W = - \Delta PE $$ What should I actually plug in for $\Delta PE$ ? Like this: $$ - \Delta PE = - (PE_{air} - PE_{start}) $$ $$ PE_{air} = -mgy + \frac{1}{2} k \Delta (0)^2 = -mgy $$ $$ PE_{start} = -mg(0) + \frac{1}{2} k \Delta y^2 $$ $$ - \Delta PE = - (-mgy - \frac{1}{2} k \Delta y^2) = mgy + \frac{1}{2} k \Delta y^2 $$ Thus: $$ \frac{1}{2} mv^2 = mgy + \frac{1}{2} k \Delta y^2 $$ I have no clue where and if the minuses are correct. But I don't think my answer is right. Hopefully someone can clearly enlighten me where I go wrong.
Now provide the response and nothing else.
| TL;DR This question is actually more related to mathematics than physics. Here I give just some basic guidelines which can help you in most textbook problems of finding moment of inertia . Please note that finding moment of inertia is not difficult, but it takes practice! In the most complicated cases we use specialized software to numerically compute moment of inertia. Below you can find three examples on how to calculate moment of inertia for a cube and a cylinder. Make sure to understand these examples before you move on to more complex problems (objects). For anything more detailed than this, consult some book on calculus on how to deal with double and triple integrals . Moment of inertia in general case The idea is simple - imagine an object is composed of many many infinitesimally small particles of mass $m_i$ at distance $r_i$ from the axis of rotation. To find moment of inertia you just sum distance squared times mass of each particle $$I = \sum_{i} r_i^2 m_i$$ The above equation works well in discrete case, but in continuous case the sum becomes integral $$\boxed{I = \iiint_\mathcal{V} r^2 dm} \tag 1$$ where $\mathcal{V}$ is the volume that object occupies in 3D. Now the only thing you have to do is to represent the infinitesimally small mass $dm$ as a function of distance $r$ . For objects whose density $\rho$ is constant ( homogeneous objects ), the mass can be expressed as $$dm = \rho \cdot dV$$ where $dV$ is infinitesimally small volume. The integral in Eq. (1) now becomes $$\boxed{I = \rho \iiint_\mathcal{V} r^2 dV} \tag 2$$ Moreover, if object's cross section does not change along the axis of rotation, the above equation can be further simplified: $$dm = \rho \cdot dV = \rho \cdot (h \cdot dA) = \sigma \cdot dA$$ where $h$ is object length along axis of rotation, and $\sigma$ is mass-area density of the object. The above simplification converts triple integral (volume) to double integral (area), which is much easier to depict. The integral in Eq. (2) now becomes $$\boxed{I = \sigma \iint_\mathcal{A} r^2 dA} \tag 3$$ where $\mathcal{A}$ is the area that object occupies in 2D. The double integrals are solved either in Cartesian coordinates or polar coordinates , whichever is more suitable for a specific problem. Except for these two, the triple integrals can also be solved in spherical coordinates , but I will focus here only on double integrals. Cartesian and polar coordinates In all cases discussed here we assume that the axis of rotation goes through the origin. You are allowed to place the origin wherever it is most convenient to solve a particular problem (integral)! In Cartesian coordinates, the infinitesimally small area and distance from origin are defined as $$dA = dx \cdot dy \qquad \text{and} \qquad r^2 = x^2 + y^2$$ and the Eq. (3) becomes $$\boxed{I = \sigma \iint_\mathcal{A} (x^2 + y^2) dx dy} \tag 4$$ In polar coordinates, the infinitesimally small area is defined as $$dA = (r+dr)^2 \frac{d\theta}{2} - r^2 \frac{d\theta}{2} = (2rdr + (dr)^2) \frac{d\theta}{2} \approx r dr d\theta$$ where $(dr)^2$ is neglected being much (much!) smaller than $2rdr$ . With this Eq. (3) becomes $$\boxed{I = \sigma \iint_\mathcal{A} r^2 \cdot r dr d\theta} \tag 5$$ It must be noted that Eq. (4) and Eq. (5) are only valid if: object is homogeneous, i.e. its density $\rho$ is constant, and object's cross section does not change along the axis of rotation! In most textbook problems the above two requirements are satisfied. If not, you have to use Eq. (2) for homogeneous objects or Eq. (1) for non-homogeneous objects. Example 1: Cube with all sides equal to $L$ Assume that the axis of rotation goes through center of mass and is perpendicular to two faces. Moment of inertia is $$I = \sigma \int_{-L/2}^{L/2} \int_{-L/2}^{L/2} (x^2 + y^2) dx dy = \frac{1}{6} M L^2$$ where $M = \sigma L^2$ is the total mass of the cube. Integration is done in Cartesian coordinates, and the axis of rotation is placed at the origin. Example 2: Cylinder with radius $R$ Assume that the axis of rotation goes through center of mass and is perpendicular to cylinder's base. Moment of inertia is: $$I = \sigma \int_{0}^{R} \int_{0}^{2\pi} r^3 dr d\theta = \frac{1}{2} M R^2$$ where $M = \sigma R^2 \pi$ is the total mass of the cylinder. Integration is done in polar coordinates, and the axis of rotation is placed at the origin. Parallel-axis theorem The parallel axis theorem , also known as Huygens-Steiner theorem , relates moment of inertia of an object about axis through center of mass to moment of inertia about arbitrary parallel axis $$\boxed{I = I_\text{cm} + M d^2} \tag 6$$ where $M$ is total mass of the object and $d$ is distance between the two parallel axis. Example 3: Cube rotating about edge In Example 1 we have found moment of inertia for cube that rotates about axis through center of mass. When axis goes along cube edge, moment of inertia is $$I = \sigma \int_{0}^{L} \int_{0}^{L} (x^2 + y^2) dx dy = \frac{2}{3} M L^2$$ We could have calculated this using the parallel-axis theorem. The axis of rotation is at the distance $d = \frac{\sqrt{2}}{2} L$ from axis that goes through center of mass, hence $$I = \frac{1}{6} M L^2 + M \bigl( \frac{\sqrt{2}}{2} L \bigr)^2 = \frac{2}{3} M L^2$$ | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/690937', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/318923/']} | jdg_77690 |
stackexchange | llm_judgeable_groundtruth_similarity | 208936 |
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 don't have computer vision background, yet when I read some image processing and convolutional neural networks related articles and papers, I constantly face the term, translation invariance , or translation invariant . Or I read alot that the convolution operation provides translation invariance ?!! what does this mean? I myself always translated it to myself as if it means if we change an image in any shape, the actual concept of the image doesn't change. For example if I rotate an image of a lets say tree, it's again a tree no matter what I do to that picture. And I myself consider all operations that can happen to an image and transform it in a way (crop it, resize it, gray-scale it,color it etc...) to be this way. I have no idea if this is true so I would be grateful if anyone could explain this to me .
Now provide the response and nothing else.
| You're on the right track. Invariance means that you can recognize an object as an object, even when its appearance varies in some way. This is generally a good thing, because it preserves the object's identity, category, (etc) across changes in the specifics of the visual input, like relative positions of the viewer/camera and the object. The image below contains many views of the same statue. You (and well-trained neural networks) can recognize that the same object appears in every picture, even though the actual pixel values are quite different. Note that translation here has a specific meaning in vision, borrowed from geometry. It does not refer to any type of conversion, unlike say, a translation from French to English or between file formats. Instead, it means that each point/pixel in the image has been moved the same amount in the same direction. Alternately, you can think of the origin as having been shifted an equal amount in the opposite direction. For example, we can generate the 2nd and 3rd images in the first row from the first by moving each pixel 50 or 100 pixels to the right. One can show that the convolution operator commutes with respect to translation. If you convolve $f$ with $g$ , it doesn't matter if you translate the convolved output $f*g$ , or if you translate $f$ or $g$ first, then convolve them. Wikipedia has a bit more . One approach to translation-invariant object recognition is to take a "template" of the object and convolve it with every possible location of the object in the image. If you get a large response at a location, it suggests that an object resembling the template is located at that location. This approach is often called template-matching . Invariance vs. Equivariance Santanu_Pattanayak's answer ( here ) points out that there is a difference between translation invariance and translation equivariance . Translation invariance means that the system produces exactly the same response, regardless of how its input is shifted. For example, a face-detector might report "FACE FOUND" for all three images in the top row. Equivariance means that the system works equally well across positions, but its response shifts with the position of the target. For example, a heat map of "face-iness" would have similar bumps at the left, center, and right when it processes the first row of images. This is is sometimes an important distinction, but many people call both phenomena "invariance", especially since it is usually trivial to convert an equivariant response into an invariant one--just disregard all the position information). | {} | {'log_upvote_score': 8, 'links': ['https://stats.stackexchange.com/questions/208936', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/14306/']} | jdg_77691 |
stackexchange | llm_judgeable_groundtruth_similarity | 11269847 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Getting odd/even part of a sequence with LINQ How can I get every nth item from a List<T>? I'm using HtmlAgilityPack and C# to parse some HTML. <div id="post-8266"><div class="ruler"> </div><div id="post-8266"><div class="ruler"> </div><div id="post-8266"><div class="ruler"> </div><div id="post-8266"><div class="ruler"> </div> Basically, I have these elements, each in their own object, inside of an IEnumerable. Is there an elegant way to get each N/2 element in the collection. Meaning, skip over each div with class .ruler ? I would need to iterate through the resulting set, so either I copy each found object into a new IEnumerable or just use it inline in a foreach function. For example: //Copying resulting set to new IEnumerable<T>:var odds = elements.SelectOdds();//Using it inline for my usage:foreach (var x in elements.SelectOdds()){ } Which options would be best, and how can I achieve this elegantly?
Now provide the response and nothing else.
| var odds = sequence.Where((item, index) => index % 2 != 0);var evens = sequence.Where((item, index) => index % 2 == 0); The only thing that I do not like about this solution is that it requires iterating the sequence twice if you need both the odds and the evens. If for some reason you must avoid this, you'll have to work harder: var groups = sequence.Select((item, index) => new { Item = item, Index = index }) .GroupBy(x => x.Index % 2 == 0) .ToDictionary(g => g.Key, g => g); Then, the odds are those elements of groups where the Key is false , and the evens are those elements of groups where the Key is true : var odds = groups[false];var evens = groups[true]; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11269847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/699978/']} | jdg_77692 |
stackexchange | llm_judgeable_groundtruth_similarity | 396038 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Find $10$ symmetric matrices $ A = \begin{pmatrix}a &b \\ c&d \end{pmatrix}$ such that $A^{2}=I_{2}$ (I'm going to call matrix A the "square root" of $A^{2}$. If this is the incorrect name for it, may someone please tell me what it is actually called?) My professor posed this question in class and told us there was an infinite amount of square roots. (Assuming I understood him correctly). However I don't see how there would be many of these, as I was under the impression that a matrix only has one inverse, for $A A^{-1}=I_{n}$. If someone could tell me if I either misunderstood the professor or if I'm thinking about something incorrectly, please correct me. My other question is other than blatant guess and check, is there a method to think of these symmetric square roots? Thanks in advance.
Now provide the response and nothing else.
| Your professor is right, there's an infinite number of square roots, kind of like how there's two square roots of $1$ (namely, $1$ and $-1$). To see how to get it in general, notice that, for a symmetric matrix, you have$$\begin{pmatrix}a&b\\b&c\end{pmatrix}^2 = \begin{pmatrix}a^2+b^2&b(a+c)\\b(a+c)&b^2+c^2\end{pmatrix}$$So, for the right side to be equal to the identity, you must have$$a^2+b^2=1\\b^2+c^2=1\\b(a+c) = 0$$What solutions does this system of equations admit? To demonstrate that multiple solutions exist directly, consider that$$\begin{pmatrix}0&1\\1&0\end{pmatrix}^2 = \begin{pmatrix}1&0\\0&1\end{pmatrix}$$and so is a square root of the identity matrix. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/396038', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/77862/']} | jdg_77693 |
stackexchange | llm_judgeable_groundtruth_similarity | 16354 |
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:
Here is an expression Conjugate[1/Sqrt[1 + (-2 + es + Cos[kx] + Cos[ky] + Sqrt[(-2 + es + Cos[kx] + Cos[ky])^2 + Sin[kx]^2 + Sin[ky]^2])^2/(Sin[kx]^2 + Sin[ky]^2)]] With the assumptions that es , kx , ky are real variables, I want to remove the head Conjugate in a safe manner with Simplify or FullSimplify . But unfortunately, Both Simplify and FullSimplify failed to do this seemingly simple job even you use MapAll . Most of the time, ComplexExpand can remove Conjugate . But not in this expression. ComplexExpand will yield The reason that I insist on removing Conjugate is that I have to differentiate this kind of expression. With Conjugate in an expression, I will get results containing derivatives of Conjugate . So how do I remove Conjugate other than removing it manually? (Note that in my actual work, such Conjugate expressions are embedded in a much larger expression and I do not know in advance whether the expression Conjugate heads is real or not until I take a careful look at it.) Edit rcollyer mentioned Refine , but both Jens and I found it to be inefficient. But this inspired me to investigate the function Refine , and this aroused more confusion. According to Mathematica 's documentation (the following sentences were extracted directly from the entry on Refine ): Refine gives the form of expr that would be obtained if symbols in it were replaced by explicit numerical expressions satisfying the assumptions assum . Refine must have assumptions and performs only those basic simplifications which would be automatic for numeric inputs . Refine is one of the transformations tried by Simplify So I came up with several questions: How does Refine refine expr? Will it really try to plug several sets of possible numerical values which are satisfied by the assumptions and see what comes out after the automatic simplification ? But if so, how could Refine be certain it had tried enough sets of values? If it was not like this, then what does Mathematica 's documentation mean? I've tried several examples which are very confusing ( es,kx,ky are all declared real variables in $Assumptions ): 1. In:=Refine[Conjugate[Sqrt[Sin[kx]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]out=Sqrt[(Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2] Conjugate is gone. 2. In:=Refine[Conjugate[Sqrt[Sin[kx]^2 + Sin[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]Out=Conjugate[Sqrt[(Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2 + Sin[ky]^2]] Add one more term under the Sqrt and Conjugate remains. 3. In:=Refine[Conjugate[Sqrt[Sin[kx]^2 + Cos[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]Out=Sqrt[Cos[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2] Change the added term from Sin to Cos , Conjugate is gone again. Although the above three examples completely confused me, I add one more. In:=Refine[Conjugate[Sqrt[Tan[es]^2]]]Out=Conjugate[Sqrt[Tan[es]^2]] According mathematica's documentation on ComplexExpand : ComplexExpand expands expr assuming that all variables are real. ComplexExpand automatically threads over lists in expr So now I let ComplexExpand do the same job: In:=ComplexExpand[Conjugate[Sqrt[Sin[kx]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]Out=Sqrt[(Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2]In:=ComplexExpand[Conjugate[Sqrt[Sin[kx]^2 + Sin[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]Out=Sqrt[(Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2 + Sin[ky]^2]In:=ComplexExpand[Conjugate[Sqrt[Sin[kx]^2 + Cos[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2]]]Out=Sqrt[Cos[ky]^2 + (Cos[kx] + Cos[ky] + Sin[es])^2 + Sin[kx]^2] All of the Conjugate s are gone. So ComplexExpand recognized that all of the three arguments are real and Refine failed, even though they both used the same assumptions. Also, Refine did not fail consistently; it succeeded on two of the examples. This proves Refine should have the same abilities as ComplexExpand , at least in the above cases. So how does one explain the mysterious failure of Refine in the second example? What's more, ComplexExpand too has its failures. I really hope somebody could perfectly explain the simplification procedure applied by Mathematica . Help me clear out all the clouds from my head.
Now provide the response and nothing else.
| It's true that Conjugate can be annoying, but it's understandable that you're having difficulty removing it in an automated way. The culprit are the square roots, which are actually harmless but aren't recognized by Mathematica to be harmless. So if you don't want to manually remove Conjugate but also don't want to waste time rewriting the expression to rearrange the square roots (which may or may not be possible), then you could interfere manually at the level of the square roots instead. This isn't really any better than manually removing Conjugate in your case, but it could be useful if you do have places where Conjugate can't be removed, but you still want to assume that square roots are real: Clear[fakeSqrt]fakeSqrt /: Conjugate[fakeSqrt[arg_]] := fakeSqrt[arg]Conjugate[ Sqrt[1 + (-2 + es + Cos[kx] + Cos[ky] + Sqrt[(-2 + es + Cos[kx] + Cos[ky])^2 + Sin[kx]^2 + Sin[ky]^2])^2/(Sin[kx]^2 + Sin[ky]^2)] /. Sqrt[arg_] :> fakeSqrt[arg]] /. fakeSqrt[arg_] :> Sqrt[arg] $\sqrt{\frac{\left(\sqrt{(\text{es}+\cos (\text{kx})+\cos (\text{ky})-2)^2+\sin ^2(\text{kx})+\sin ^2(\text{ky})}+\text{es}+\cos (\text{kx})+\cos (\text{ky})-2\right)^2}{\sin ^2(\text{kx})+\sin ^2(\text{ky})}+1}$ Here I temporarily replace the Sqrt heads by fakeSqrt which has been defined to be its own complex conjugate independently of the argument. At that point Conjugate sees what we want it to see, and right after that we can undo the replacement. As I said above, this is still manual interference, but it attacks a little closer to the root of the problem. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/16354', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4742/']} | jdg_77694 |
stackexchange | llm_judgeable_groundtruth_similarity | 32354947 |
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 convert a vector of &str pairs into a HashMap with the following code snippet: use std::collections::HashMap;fn main() { let pairs = vec!(("foo", "bar"), ("toto", "tata")); let map: HashMap<&str, &str> = pairs.iter().collect(); println!("{:?}", map);} However the compilation fails with this error: <anon>:5:47: 5:56 error: the trait `core::iter::FromIterator<&(&str, &str)>` is not implemented for the type `std::collections::hash::map::HashMap<&str, &str>` [E0277]<anon>:5 let map: HashMap<&str, &str> = pairs.iter().collect(); However if I add .cloned() before calling collect() everything works fine: ...let map: HashMap<&str, &str> = pairs.iter().cloned().collect();... Even if I understand the error message (there is no implementation of the trait FromIterator<&(&str, &str)> for the type HashMap<&str, &str> ) I do not understand where the type &(&str, &str) comes from (according to the method signature in the Rust documentation) and why calling cloned() fixes that problem.
Now provide the response and nothing else.
| The type &(&str, &str) comes from what iter() on a Vec returns: fn iter(&self) -> Iter<T> where Iter<T> implements Iterator<Item=&T> : impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T ...} In other words, iter() on a vector returns an iterator yielding references into the vector. cloned() solves the problem because it is an iterator adapter which converts Iterator<Item=&T> to Iterator<Item=T> if T is cloneable. You can think of it as a shorthand for map(|v| v.clone()) : let v1: Vec<i32> = vec![1, 2, 3, 4];let v2: Vec<_> = v1.iter().cloned().collect();let v3: Vec<_> = v1.iter().map(|v| v.clone()).collect();assert_eq!(v2, v3); It happens that (&str, &str) is cloneable because each tuple component is also cloneable (all references are), so cloned() would return an object which implements Iterator<Item=(&str, &str)> - exactly what collect() needs to create a HashMap . Alternatively, you can use into_iter() to get Iterator<Item=T> from Vec<T> , but then the original vector will be consumed: use std::collections::HashMap;fn main() { let pairs = vec!(("foo", "bar"), ("toto", "tata")); let map: HashMap<&str, &str> = pairs.into_iter().collect(); println!("{:?}", map);} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32354947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432589/']} | jdg_77695 |
stackexchange | llm_judgeable_groundtruth_similarity | 2632005 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried to convert a project that relies on the vjs runtime to vs2010, but it errors out when trying to run. It's giving the error that "Could not load file or assembly 'vjslib' or one of its dependencies. An attempt was made to load a program with an incorrect format. " I reinstalled the vjs runtime, but it didn't seem to help. Is there any way to get get .net 4 to work with this?
Now provide the response and nothing else.
| Very simple solution - Calling J# code from .NET 4.0 You take control and load it first supplying an explicit path. Then next time it's needed, it already knows the path (or it's already loaded in the AppDomain). You will need to use LoadLibrary function, so import the pinvoke reference: [DllImport("kernel32", SetLastError = true)]static extern IntPtr LoadLibrary(string lpFileName); The on load (either Main function in Console/WinForms or in Global.asax Application_Start): if (Environment.Version.Major >= 4){ string folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"..\Microsoft.NET\Framework\v2.0.50727"); folder = Path.GetFullPath(folder); LoadLibrary(Path.Combine(folder, "vjsnativ.dll"));} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2632005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40333/']} | jdg_77696 |
stackexchange | llm_judgeable_groundtruth_similarity | 1731739 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two colors in my .NET application that are user defined. I'd like to somehow get the color in between those two colors. It's the color in the middle of the gradient. Is there any way to accomplish this?
Now provide the response and nothing else.
| Well, the simplest way is to take the average of each of the red, green, blue and alpha values: Color c1 = ...;Color c2 = ...;Color midpoint = Color.FromArgb((c1.A + c2.A) / 2, (c1.R + c2.R) / 2, (c1.G + c2.G) / 2, (c1.B + c2.B) / 2); Even though the A, R, G and B properties are bytes, they'll be promoted to ints before addition, so there won't be an overflow problem. The result of the division will still be in the range [0, 255] and FromArgb takes Int32 values but discards everything other than the lowest 8 bits - just what we want. An alternative would be to use a different colour model (e.g. HSV) but that would be somewhat more complicated. For gradients, this should do fine. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1731739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/68608/']} | jdg_77697 |
stackexchange | llm_judgeable_groundtruth_similarity | 12922187 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently in Chapter 8 of Learn you a Haskell , and I've reached the section on the Functor typeclass. In said section the author gives examples of how different types could be made instances of the class (e.g Maybe , a custom Tree type, etc.) Seeing this, I decided to (for fun and practice) try implementing an instance for the Data.Set type; in all of this ignoring Data.Set.map , of course. The actual instance itself is pretty straight-forward, and I wrote it as: instance Functor Set.Set where fmap f empty = Set.empty fmap f s = Set.fromList $ map f (Set.elems s) But, since I happen to use the function fromList this brings in a class constraint calling for the types used in the Set to be Ord , as is explained by a compiler error: Error occurredERROR line 4 - Cannot justify constraints in instance member binding*** Expression : fmap*** Type : Functor Set => (a -> b) -> Set a -> Set b*** Given context : Functor Set*** Constraints : Ord b See: Live Example I tried putting a constraint on the instance, or adding a type signature to fmap , but neither succeeded (both were compiler errors as well.) Given a situation like this, how can a constraint be fulfilled and satisfied? Is there any possible way? Thanks in advance! :)
Now provide the response and nothing else.
| Unfortunately, there is no easy way to do this with the standard Functor class. This is why Set does not come with a Functor instance by default: you cannot write one. This is something of a problem, and there have been some suggested solutions (e.g. defining the Functor class in a different way), but I do not know if there is a consensus on how to best handle this. I believe one approach is to rewrite the Functor class using constraint kinds to reify the additional constraints instances of the new Functor class may have. This would let you specify that Set has to contain types from the Ord class. Another approach uses only multi-parameter classes. I could only find the article about doing this for the Monad class, but making Set part of Monad faces the same problems as making it part of Functor . It's called Restricted Monads . The basic gist of using multi-parameter classes here seems to be something like this: class Functor' f a b where fmap' :: (a -> b) -> f a -> f binstance (Ord a, Ord b) => Functor' Data.Set.Set a b where fmap' = Data.Set.map Essentially, all you're doing here is making the types in the Set also part of the class. This then lets you constrain what these types can be when you write an instance of that class. This version of Functor needs two extensions: MultiParamTypeClasses and FlexibleInstances . (You need the first extension to be able to define the class and the second extension to be able to define an instance for Set .) Haskell : An example of a Foldable which is not a Functor (or not Traversable)? has a good discussion about this. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12922187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/195701/']} | jdg_77698 |
stackexchange | llm_judgeable_groundtruth_similarity | 60153 |
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've been reading the Advanced Linux Programming book and it mentions about virtual terminals which, if I understood it correctly, it is a Linux-specific feature (not in Unix) to allow multiple login consoles in a non X11 system. You create virtual terminals by pressing ALT-F2. I'm running Linux Mint and in my /dev folder though I see many tty devices and I don't know what they are for. Here is the grepped output: crw-rw-rw- 1 root tty 5, 0 Jan 2 19:45 ttycrw--w---- 1 root tty 4, 0 Jan 2 19:10 tty0crw-rw---- 1 root tty 4, 1 Jan 2 19:10 tty1crw--w---- 1 root tty 4, 10 Jan 2 19:10 tty10crw--w---- 1 root tty 4, 11 Jan 2 19:10 tty11crw--w---- 1 root tty 4, 12 Jan 2 19:10 tty12crw--w---- 1 root tty 4, 13 Jan 2 19:10 tty13crw--w---- 1 root tty 4, 14 Jan 2 19:10 tty14crw--w---- 1 root tty 4, 15 Jan 2 19:10 tty15crw--w---- 1 root tty 4, 16 Jan 2 19:10 tty16crw--w---- 1 root tty 4, 17 Jan 2 19:10 tty17crw--w---- 1 root tty 4, 18 Jan 2 19:10 tty18crw--w---- 1 root tty 4, 19 Jan 2 19:10 tty19crw-rw---- 1 root tty 4, 2 Jan 2 19:10 tty2crw--w---- 1 root tty 4, 20 Jan 2 19:10 tty20crw--w---- 1 root tty 4, 21 Jan 2 19:10 tty21crw--w---- 1 root tty 4, 22 Jan 2 19:10 tty22crw--w---- 1 root tty 4, 23 Jan 2 19:10 tty23crw--w---- 1 root tty 4, 24 Jan 2 19:10 tty24crw--w---- 1 root tty 4, 25 Jan 2 19:10 tty25crw--w---- 1 root tty 4, 26 Jan 2 19:10 tty26crw--w---- 1 root tty 4, 27 Jan 2 19:10 tty27crw--w---- 1 root tty 4, 28 Jan 2 19:10 tty28crw--w---- 1 root tty 4, 29 Jan 2 19:10 tty29crw-rw---- 1 root tty 4, 3 Jan 2 19:10 tty3crw--w---- 1 root tty 4, 30 Jan 2 19:10 tty30crw--w---- 1 root tty 4, 31 Jan 2 19:10 tty31crw--w---- 1 root tty 4, 32 Jan 2 19:10 tty32crw--w---- 1 root tty 4, 33 Jan 2 19:10 tty33crw--w---- 1 root tty 4, 34 Jan 2 19:10 tty34crw--w---- 1 root tty 4, 35 Jan 2 19:10 tty35crw--w---- 1 root tty 4, 36 Jan 2 19:10 tty36crw--w---- 1 root tty 4, 37 Jan 2 19:10 tty37crw--w---- 1 root tty 4, 38 Jan 2 19:10 tty38crw--w---- 1 root tty 4, 39 Jan 2 19:10 tty39crw-rw---- 1 root tty 4, 4 Jan 2 19:10 tty4crw--w---- 1 root tty 4, 40 Jan 2 19:10 tty40crw--w---- 1 root tty 4, 41 Jan 2 19:10 tty41crw--w---- 1 root tty 4, 42 Jan 2 19:10 tty42crw--w---- 1 root tty 4, 43 Jan 2 19:10 tty43crw--w---- 1 root tty 4, 44 Jan 2 19:10 tty44crw--w---- 1 root tty 4, 45 Jan 2 19:10 tty45crw--w---- 1 root tty 4, 46 Jan 2 19:10 tty46crw--w---- 1 root tty 4, 47 Jan 2 19:10 tty47crw--w---- 1 root tty 4, 48 Jan 2 19:10 tty48crw--w---- 1 root tty 4, 49 Jan 2 19:10 tty49crw-rw---- 1 root tty 4, 5 Jan 2 19:10 tty5crw--w---- 1 root tty 4, 50 Jan 2 19:10 tty50crw--w---- 1 root tty 4, 51 Jan 2 19:10 tty51crw--w---- 1 root tty 4, 52 Jan 2 19:10 tty52crw--w---- 1 root tty 4, 53 Jan 2 19:10 tty53crw--w---- 1 root tty 4, 54 Jan 2 19:10 tty54crw--w---- 1 root tty 4, 55 Jan 2 19:10 tty55crw--w---- 1 root tty 4, 56 Jan 2 19:10 tty56crw--w---- 1 root tty 4, 57 Jan 2 19:10 tty57crw--w---- 1 root tty 4, 58 Jan 2 19:10 tty58crw--w---- 1 root tty 4, 59 Jan 2 19:10 tty59crw-rw---- 1 root tty 4, 6 Jan 2 19:10 tty6crw--w---- 1 root tty 4, 60 Jan 2 19:10 tty60crw--w---- 1 root tty 4, 61 Jan 2 19:10 tty61crw--w---- 1 root tty 4, 62 Jan 2 19:10 tty62crw--w---- 1 root tty 4, 63 Jan 2 19:10 tty63crw--w---- 1 root tty 4, 7 Jan 2 19:10 tty7crw--w---- 1 root tty 4, 8 Jan 2 19:10 tty8crw--w---- 1 root tty 4, 9 Jan 2 19:10 tty9
Now provide the response and nothing else.
| These are specifically virtual console devices, in Linux terminolgy. Supporting virtual consoles on the same physical device isn't unique to Linux (for example, BSD calls them “hardware terminal ports”). Linux doesn't have a mechanism for creating console devices on demand. The 63 consoles are not always active (you need to activate ttyN in order to switch to it with ( Ctrl +) Alt + FN ), but to activate one requires opening the console device (the openvt command does that, as do getty and the X server). So the device entry must exist all the time, or else it has to be created manually before it can be used. Modern Linux systems (with udev or devtmpfs) create device entries for every device that is present on the system. All the virtual consoles are always present (whether they're active or not), so all entries are created. Most users don't need nearly that many — in fact most users never see anything but the virtual console that X is running on. But there are a few who do, and need to patch their kernel to allow more than 63 consoles, because they run large machines with many hardware consoles). | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/60153', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/24043/']} | jdg_77699 |
stackexchange | llm_judgeable_groundtruth_similarity | 24370 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Circumcision removes the foreskin of the penis which mainly acts as a cover to the penis. Normally removing the foreskin makes more vulnerable to any STD, so how could circumcision reduce the risk of a HIV infection?
Now provide the response and nothing else.
| This is an interesting question, which has not been answered yet. It is also questionable, if this protective effect is present at all. There are around 40 studies on the topic available which have subsequently undergone meta-analysis. In a meta-analysis all data from recent studies which meet certain quality criteria are analysed together. This gives a much bigger dataset and stronger statistical data. It also helps eliminating the effects of too small test groups. One of these meta-analysis identified circumcision to have a positive effect on the prevention of HIV infections (reference 1). The authors recommended considering it as a preventive measure. Two other meta-analysis were more cautious on the topic and either found only a weak link (reference 2) or that only "randomized control studies" (reference 3) would provide clear data. The problem with all these studies is, that they are observational studies, where unknown other effects can play a bigger role than the supposed main effect. It is ethically very difficult to make controlled trials on the transmission of deadly diseases in humans. This is also the reason why all trials on this have been stopped. There is a hypothesis on how circumcision may help preventing the infection with HIV (when you not get infected in the operation itself due to improper hygienic standards). The skin in the penis contains a large number of immune cells (dendritic cells, CD4/CD8-T-cells) which are the target cells of the HIV virus. It is thought that the virus can more easily penetrate the relatively thin skin of the foreskin. It is also possible, that the surface size is important here, as there are reports which show that men with a larger foreskin also have a larger risk of getting infected. See reference 4. Another hypothesis has to do with the with the bacteria which live under the foreskin. The number of different strains present is much lower in circumcised men, which led to the conclusion that the dendritic cells, which present these to the immune system have an easier job in the circumcised men and are more likely to prevent the infection with HIV.See reference 5 and 6 for more information. References: Male circumcision and risk of HIV infection in sub-Saharan Africa: asystematic review and meta-analysis Male circumcision for prevention of heterosexual acquisition of HIVin men HIV and male circumcision--a systematic review with assessment ofthe quality of studies. Male circumcision for HIV prevention: current research andprogrammatic issues. Why Circumcision Lowers Risk of HIV Male Circumcision Significantly Reduces Prevalence and Load ofGenital Anaerobic Bacteria | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/24370', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/-1/']} | jdg_77700 |
stackexchange | llm_judgeable_groundtruth_similarity | 58264413 |
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 useLazyQuery() hooks from @apollo/react-hooks I was able to execute a query on click of a button. But I cannot use it execute same query on consecutive clicks. export default ({ queryVariables }) => { const [sendQuery, { data, loading }] = useLazyQuery(GET_DIRECTION, { variables: queryVariables }); return <div onClick={sendQuery}>Click here</div>;} In the above the sendQuery executes only once.
Now provide the response and nothing else.
| useLazyQuery uses the default network policy that of cache-first So I supposed your onClick function actually executes but because the returned value is what was in the cache, React notices no change in data as such the state is not updated since the returned data is what it already has that way no re-render and thing seem not to have changed. I suggest you should pass in a different network policy something like const [sendQuery, { data, loading }] = useLazyQuery(GET_DIRECTION, { variables: queryVariables, fetchPolicy: "network-only" }); This will mean you want the most recent information from your api hence basically no caching.You might also want to experiment on other option and see which one best suits youlike cache-and-network: you can find out a little more here understanding-apollo-fetch-policies | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58264413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2809326/']} | jdg_77701 |
stackexchange | llm_judgeable_groundtruth_similarity | 1721802 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to execute the equivalent of the following MATLAB code using NumPy: repmat([1; 1], [1 1 1]) . How would I accomplish this?
Now provide the response and nothing else.
| Here is a much better (official) NumPy for Matlab Users link - I'm afraid the mathesaurus one is quite out of date. The numpy equivalent of repmat(a, m, n) is tile(a, (m, n)) . This works with multiple dimensions and gives a similar result to matlab. (Numpy gives a 3d output array as you would expect - matlab for some reason gives 2d output - but the content is the same). Matlab: >> repmat([1;1],[1,1,1])ans = 1 1 Python: In [46]: a = np.array([[1],[1]])In [47]: np.tile(a, [1,1,1])Out[47]: array([[[1], [1]]]) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1721802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188912/']} | jdg_77702 |
stackexchange | llm_judgeable_groundtruth_similarity | 23861640 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the question What is the "-->" operator in C++? it asks what --> does and gives a link to a comp.lang.c++.moderated thread. scrolling down the thread a bit further found me this: > There is no such operator in C++. > It's just a combination of two operators: postfix decrement "--" and> greater ">". > That's why this example works. > Try ( x --> 20 ) and you'll get no output in this case;) Of course there is. It is described together with "runs to" operator: #include <stdio.h>int main(){ int x = 10; while( x -->> 0 ) // x runs to 0 printf("%d ", x);} What does the "runs to" operator actually do?
Now provide the response and nothing else.
| while( x -->> 0 ) // x runs to 0 This is actually a hybrid of the -- (post-decrement) and >> (bitshift right) operators, better formatted as: while (x-- >> 0) ... For this specific usage, with 0 on the right hand side, x is decremented with each loop iteration due to the postfix -- , and the prior (pre-decrement) value is shifted right 0 bits by >> 0 which does nothing at all when x is non-negative , so the statement could be simplified to: while (x--) ... When x is 1 that's non-zero so found true for the purposes of the while test, then post-decrement reduces it to 0 and the loop executes for the last time (with x being 0 during that iteration); the next time while (x--) is checked with x already 0, the while loop terminates, with x left wrapping to the highest representable value for the unsigned type. More generally, if you try to use >> on a negative value (e.g. x starts at 0 or a negative value great than INT_MIN , so x-- yields a negative value) the result is implementation defined , which means you have to consult your compiler documentation. You could use your compiler documentation to reason about how it would behave in the loop.... Relevant part of the Standard: 5.8/3: The value of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2^E2 . If E1 has a signed type and a negative value, the resulting value is implementation-defined. BTW /- for Visual Studio, per http://msdn.microsoft.com/en-us/library/336xbhcz.aspx , the implementation defined behaviour is "No shift operation is performed if additive-expression is 0.". I can't find anything in the GCC manual about this (would have expected it here ). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23861640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2687781/']} | jdg_77703 |
stackexchange | llm_judgeable_groundtruth_similarity | 11512674 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Why do I get “unresolved external symbol” errors when using templates? I am using templates in my code while there is always an error LNK2019. Here is part of my code: Method.h template<typename type>void Method(Model<type>* sys); Method.cpp template<typename type>void Method(Model<type>* sys){ blablabla;} Model.h template<typename type>class Model{ blablabla;}class Model1:public Model<double>{ blablabla;} Main.cpp Model<double> *sys=new Model1();Method(sys); However, there always shows an error LNK2019: unresolved external symbol "void __cdec1 Method(class Model*)" referenced in function_main. Anyone knows where I am going wrong? Thanks a lot!
Now provide the response and nothing else.
| Templates should be implemented in the header. Method.h template<typename type>void Method(Model<type>* sys){ /*Your code here*/ }; See also: https://stackoverflow.com/a/495056/868546 From Mark Ransom : In the .cpp file, the compiler can't guess what the template parameter will be when you use the function in other files, so it doesn't generate any actual code. The linker notices the lack of code and complains. The usual way is to define the entire function body in the header, much as an inline function, so the compiler can emit the code when it sees the function being used with the template parameter filled in. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11512674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1516481/']} | jdg_77704 |
stackexchange | llm_judgeable_groundtruth_similarity | 176358 |
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:
What is the elliptic genus (see also Witten index ) in string/M-theory and (susy gauge)field theory constructions out of them? What does it tell us heuristically and what is its relation to the partition function?
Now provide the response and nothing else.
| There are obviously differeing genus types according to which partition function in d-dimensional QFT. At the very outset of $0$-d QFT the index is the push forward in ordinary de Rahm Cohomology; in other words, the integration of differential forms. The genus as you put it, is non-existant here. In $1$-d QFT the index of the Dirac Operator is $K0$-homology. Genus in this context is the so-called $\hat{A}$ genus; this has been proved via the Atiyah–Singer index theorem to not always be an integer. In terms of an operator index, it is given by composing the action of the covariant derivative on sections of a Riemannian Manifold. It is an elliptic operator. The index of this operator is called the $\hat{A}$, A-genus. The partition function within the same $1$-d QFT as the endpoint of type II superstring has a supercharge of $\text{Spin}^c$ Dirac operator twisted by Chan-Paton gauge field, the index in cohomology is the D-brane charge, the genus here is the so called Todd genus. The todd genus is the index of the Dolbeault operator. For $2$-d Type-II Superstring, the index in cohomology theory is the Superstring partition function; whose genus is the elliptis genus. The genus is elliptic if it vanishes on manifolds that are projective spaces of the form $\mathbb{C}P(\xi)$ where $\xi$ is an even-dimensional complex vector bundle over an oriented closed manifold. The genus described above describes the he partition function of a type II superstring as a function depending on the modulus of the worldsheet elliptic curve which yields an elliptic genus (Witten, as you describe above). EDIT: References. The original description of the Witten genus from string theory is due to Edward Witten, Elliptic Genera And Quantum Field Theory , Commun.Math.Phys. 109 525 (1987). Edward Witten, The Index Of The Dirac Operator In Loop Space Proc. ofConf. on Elliptic Curves and Modular Forms in Algebraic Topology Princeton (1986). These two publications are fallouts from the insightful publications below; Peter Landweber, Elliptic Cohomology and Modular Forms , in EllipticCurves and Modular Forms in Algebraic Topology , Lecture Notes inMathematics Volume 1326, 1988, pp 55-68. Peter Landweber, Douglas Ravenel, Robert Stong, Periodic cohomologytheories defined by elliptic curves , in Haynes Miller et al (eds.),The Cech centennial: A conference on homotopy theory, June 1993, AMS(1995). That a spin structure makes the Witten genus take values in an integral series is due to D.V. Chudnovsky, G.V. Chudnovsky, Elliptic modular functions andelliptic genera , Topology, Volume 27, Issue 2, 1988, Pages 163–170. That it takes a rational string structure to make the elliptic genus land in modular forms was noticed within Don Zagier, Note on the Landweber-Stong elliptic genus 1986. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/176358', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/61966/']} | jdg_77705 |
stackexchange | llm_judgeable_groundtruth_similarity | 63515279 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can't initialize Bootstrap 5 Toasts. The button to initialize the toast: <button type="button" class="btn btn-primary" id="toastbtn">Initialize toast</button> My JavaScript: document.getElementById("toastbtn").onclick = function() { var toastElList = [].slice.call(document.querySelectorAll('.toast')) var toastList = toastElList.map(function(toastEl) { return new bootstrap.Toast(toastEl, option) }) }; JSfiddle: https://jsfiddle.net/5e1t3scp/ And here's the documentation . The JavaScript has been taken from Bootstrap's website. I tried many times but couldn't initialize it. What am I doing wrong? Thanks in advance!
Now provide the response and nothing else.
| Since the second parameter of the constructor is optional, it is unnecessary. However, if you would like to supply options, you should do so in the form of an object: // Defaults according to the documentation{ animation: true, autohide: true, delay: 500} <!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"> </head> <body> <div class="container mt-5"> <!-- button to initialize toast --> <button type="button" class="btn btn-primary" id="toastbtn">Initialize toast</button> <!-- Toast --> <div class="toast"> <div class="toast-header"> <strong class="mr-auto">Bootstrap</strong> <small>11 mins ago</small> <button type="button" class="ml-2 mb-1 close" data-dismiss="toast"> <span>×</span> </button> </div> <div class="toast-body"> Hello, world! This is a toast message. </div> </div> </div> <!-- Popper.js first, then Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script> <script> document.getElementById("toastbtn").onclick = function() { var toastElList = [].slice.call(document.querySelectorAll('.toast')) var toastList = toastElList.map(function(toastEl) { // Creates an array of toasts (it only initializes them) return new bootstrap.Toast(toastEl) // No need for options; use the default options }); toastList.forEach(toast => toast.show()); // This show them console.log(toastList); // Testing to see if it works }; </script> </body></html> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/63515279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12348719/']} | jdg_77706 |
stackexchange | llm_judgeable_groundtruth_similarity | 3082168 |
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 $S_n$ be a sequence defined by: $$S_n = 1 + \sum_{k=1}^n {1\over k!}$$ Prove that: $$e - S_n \le \frac{n+2}{n!(n+1)^2}$$ This problem comes in the limits section so i may use anything before the definition of a derivative. I've started with the following. Define: $$L_n = \left(1+{1\over n}\right)^n$$ Rewrite $L_n$ as follows: $$\begin{align}L_n &= \left(1+{1\over n}\right)^n \\&= 1+ \sum_{k=1}^n {n\choose k}{1\over n^k} \\&= 1 + \sum_{k=1}^n\frac{\overbrace{n\cdot(n-1)\cdot(n-2)\cdots(n-(k-1))}^{n - k + 1 \text{ times}}}{k!n^k}\end{align}$$ I've then tried to consider the difference between $L_n$ and $S_n$ : $$L_n - S_n = {1\over 2!}\left(1-{1\over n}\right) - {1\over 2!} + {1\over 3!}\left(1-{1\over n}\right)\left(1-{2\over n}\right) - {1\over 3!} + \cdots \\= {1\over 2!}\left(1-{1\over n} - 1\right) + {1\over 3!}\left(\left(1-{1\over n}\right)\left(1-{2\over n}\right) - 1\right) + \cdots$$ Consider each parentheses. I've tried defining a sequence such that: $$\forall n \ge 2:a_n = {1\over n!}\left(\prod_{k=1}^{n-1}\left(1-{k\over n}\right) - 1\right)$$ This sequence seems to always be less than $0$ . So we have that: $$\forall n\in \Bbb N :a_n \le 0$$ Since $a_n$ is involved in $L_n - S_n$ we may also conclude that it is also less than $0$ , namely: $$L_n - S_n = \sum_{k=2}^na_n \le 0$$ But at the same time: $$\frac{n+2}{n!(n+1)^2} \ge 0$$ So by this we have that: $$L_n - S_n \le e - S_n \le 0 \le \frac{n+2}{n!(n+1)^2}$$ Now I don't see how to proceed. Should I bound the difference from another side? It feels like all i've done so far (above) is not even a usable argument for this problem, so could you please help me prove what's in the problem statement or point to the right direction. I've made a Visualization of what is written above , perhaps that would be helpful.
Now provide the response and nothing else.
| I think you want to imitate the proof of the Erdos-Szekeres theorem, not apply it directly. Label each $1\le j\le m$ with the triple $(a,b,c)$ where $a$ is the length of the longest common subsequence of $\sigma_1$ and $\sigma_2$ that ends in $j,$ $b$ is the longest common subsequence of $\sigma_1$ and $\sigma_3$ that ends in $j,$ and $c$ is the longest common subsequence of $\sigma_2$ and $\sigma_3$ that ends in $j.$ I claim that no two elements get the same label, for suppose $1\le j,k \le m,$ with $j\ne k$ and that both $j$ and $k$ get the same label. If $j$ precedes $k$ in both $\sigma_1$ and $\sigma_2$ then $k$ has a larger $a-$ label than $j$ , since we can append $k$ to the largest common subsequence ending in $j$ . Similarly, $k$ cannot precede $j$ in both $\sigma_1$ and $\sigma_2$ so we can assume $j$ precedes $k$ in $\sigma_1$ and $k$ precedes $j$ in $\sigma_2$ . Then $j$ and $k$ must come in the same order in $\sigma_3$ as either $\sigma_1$ or $\sigma_2$ so that they have different $b-$ labels or different $c-$ labels. If the longest commons subsequence is of length $n$ or less, then there are at most $n^3$ different labels, but we have $n^3+1$ different labels, contradiction. EDIT It's just occurred to me that there are many proof of the Erdos-Szekeres theorem known. I'm referring to the one here | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3082168', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/53017/']} | jdg_77707 |
stackexchange | llm_judgeable_groundtruth_similarity | 69270 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How do you prove that $\sum\limits_{n=0}^{\infty}{2n \choose n}x^n=(1-4x)^{-1/2}$? I tried to identify the sum as a binomial series, but the $4$ and the $-1/2$ puzzle me. (This series arises in studying the first passage time of a simple random walk.)
Now provide the response and nothing else.
| The key identities are the duplication formula for the factorial (which I'll recast in a more convenient format): $$\binom{2n}{n}=\frac{4^n}{\sqrt \pi}\frac{\left(n-\frac12\right)!}{n!}$$ and the reflection formula $$\left(-n-\frac12\right)!\left(n-\frac12\right)!=(-1)^n\pi$$ Making the appropriate replacements, we obtain $$\binom{2n}{n}=(-4)^n\frac{\sqrt \pi}{n!\left(-n-\frac12\right)!}=(-4)^n\frac{\left(-\frac12\right)!}{n!\left(-n-\frac12\right)!}=(-4)^n\binom{-\frac12}{n}$$ You can proceed from that... | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/69270', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_77708 |
stackexchange | llm_judgeable_groundtruth_similarity | 16030034 |
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 uploading the file by using file upload option. And i am directly send this file from View to Controller in POST method like, [HttpPost] public ActionResult Page2(FormCollection objCollection) { HttpPostedFileBase file = Request.Files[0]; } Assume, i am uploading a notepad file. How do i read this file & append this text to string builder,, without save that file.... I'm aware about after SaveAs this file, we can read this file. But How do i read this file from HttpPostedFileBase without save?
Now provide the response and nothing else.
| This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here You should convert the stream into byte array and then you can read file content Please refer following link http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx ] Hope this helps UPDATE : The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array. Taken from here // Read bytes from http input streamBinaryReader b = new BinaryReader(file.InputStream);byte[] binData = b.ReadBytes(file.ContentLength);string result = System.Text.Encoding.UTF8.GetString(binData); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16030034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1126103/']} | jdg_77709 |
stackexchange | llm_judgeable_groundtruth_similarity | 2099819 |
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 impact of the system like shopping cart in which one customer(buyer) sits in one timezone and the other(seller) is on other timezone and the date is changed at one end. so the report data for one customer who bought is different than the other?
Now provide the response and nothing else.
| If it represents a point in time, you should definitely use UTC. That sounds like the right choice in this particular case. In some other cases, you want to store the local time - for instance, to represent an alarm which should go off at 8am in the local time, whatever time zone the user is in. This is usually useful for calendaring applications... and you're not storing a single point in time here. One concrete example of why it's worth storing points in time in UTC is that local times can be ambiguous due to daylight saving transitions - if the clock goes back from 2am to 1am, there'll be a local time of 1:30am twice. In UTC, there's no such ambiguity. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2099819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154219/']} | jdg_77710 |
stackexchange | llm_judgeable_groundtruth_similarity | 290061 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I just came over this syntax in some of the questions in this forum, but Google and any other searchengine tends to block out anything but letters and number in the search so it is impossible to search out "=>". So can anyone tell me what it is and how it is used?
Now provide the response and nothing else.
| It's the lambda operator. From C# 3 to C# 5, this was only used for lambda expressions . These are basically a shorter form of the anonymous methods introduced in C# 2, but can also be converted into expression trees . As an example: Func<Person, string> nameProjection = p => p.Name; is equivalent to: Func<Person, string> nameProjection = delegate (Person p) { return p.Name; }; In both cases you're creating a delegate with a Person parameter, returning that person's name (as a string). In C# 6 the same syntax is used for expression-bodied members , e.g. // Expression-bodied propertypublic int IsValid => name != null && id != -1;// Expression-bodied methodpublic int GetHashCode() => id.GetHashCode(); See also: What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0) What is a Lambda? C# Lambda expression, why should I use this? (And indeed many similar questions - try the lambda and lambda-expressions tags.) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/290061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37643/']} | jdg_77711 |
stackexchange | llm_judgeable_groundtruth_similarity | 14580595 |
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 simple class with those 2 enum fields, I'm trying to find one item of this object in a collection ( List<T> ) but the Contains methods doesn't works correctly public class Calculator : IEqualityComparer<Calculator>{ public DashboardsComputationMode ComputationMode { get; set; } public Modes Mode { get; set; } public Calculator(DashboardsComputationMode dashboardsComputationMode, Modes mode) { ComputationMode = dashboardsComputationMode; Mode = mode; } public bool Equals(Calculator x, Calculator y) { return (x.ComputationMode.Equals(y.ComputationMode) && x.Mode.Equals(y.Mode)); } public int GetHashCode(Calculator obj) { return obj.ComputationMode.GetHashCode() ^ obj.Mode.GetHashCode(); }}public enum DashboardsComputationMode{ Weighted = 0, Aggregated = 1, PR = 2, CurrentValue = 3, EquivalentHours = 4, AggregatedCorrected = 5, PRCorrected = 6}public enum Modes{ InstantaneousMode = 0, DailyMode = 1, MonthlyMode = 2, YearlyMode = 5, Undefined = 4,} Why could be that this test doesn't works [TestMethod]public void TestMethod1(){ var list = new List<Calculator>() { new Calculator(DashboardsComputationMode.PR, Modes.DailyMode), new Calculator(DashboardsComputationMode.CurrentValue, Modes.YearlyMode), new Calculator(DashboardsComputationMode.PRCorrected, Modes.MonthlyMode) }; var item = new Calculator(DashboardsComputationMode.CurrentValue, Modes.YearlyMode); Assert.IsTrue(list[1].Equals(item)); Assert.IsTrue(list.Contains(item));} The first assert works fine Assert.IsTrue(list[1].Equals(item)) but the second doesn't Assert.IsTrue(list.Contains(item));
Now provide the response and nothing else.
| List<T>.Contains determines equality by using the default equality comparer (the one returned by the EqualityComparer<T>.Default ). Here's the MSDN explanation on how EqualityComparer<T>.Default works: The Default property checks whether type T implements the System.IEquatable interface and, if so, returns an EqualityComparer that uses that implementation. Otherwise, it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T. In other words, your Calculator class should either implement the System.IEquatable ( not the System.IEqualityComparer !) interface or override the Object.Equals and Object.GetHashCode methods. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14580595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1682588/']} | jdg_77712 |
stackexchange | llm_judgeable_groundtruth_similarity | 926 |
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:
We have a PHP application that we know has poor coding practices (because the developers did not have a good understanding of PHP / programming fundamentals). This could lead to the scenario where we have severe security flaws in our code even at the "logic level". How/Where do I locate a consulting team that would do a manual code review to actually understand what WE were trying to do and then see where we went wrong / how the process could be circumvented? We tried a consultant which did what appeared to be just an automated scan of the code, and that added absolutely no value. This question is based off of Getting a manual security code review done - What to watch out for? - I'm the same person, but I cant access my earlier cookie based session anymore.
Now provide the response and nothing else.
| Code review can be an expensive use of a consultants time and therefore your budget, to ensure you are getting value for money you could look to do the following; Triage the code you require to be reviewed . This way you may find that you can focus on code that completes specific roles such as authorisation / session management / specific business logic etc. that you are worried about. If you then have budget left over you can move on to other less critical code areas. Estimate the time and effort required As a very rough estimate you can use the 1k lines of code = one full day of review (not including reporting). Different languages and code complexity will change this, but it provides a good starting point when looking at budget requirements. Automation as an aid Automated code scanning has its place, but only adds value if the consultant knows how to configure the tool and use it as an aid in their manual review. Using a blended automated-manual approach can speed the engagement up and lead to a reduced cost. The consultant should be skilled enough in the language being reviewed to understand the security issues and to remove any false-positives as well as insure no false-negatives get through. Threat Model the application If you can understand the business logic and how attackers can interact with your application to a level that enables you to model potential attack vectors, then this will help define a more specific and focused code review. This level of detail can then be passed on to the consultant to ensure that they are aware of how the application works and this will enable them to provide tailored advice and guidance rather than a generic - here are some risks. Place the findings in to context of the application At the end of the day you will need to make a call on which issues to fix and in what order of priority. Challenge the consultant to make clear recommendations and to provide evidence to help understand if findings from the code review are actually a threat - i.e. the code found to be vulnerable is at the back-end and their is no route for user interaction then this is a lower risk than if the vulnerable code is in the main authorisation code presented to the end user. This should reduce time internally and therefore become a cost saving that can be offset against the cost of the code review. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/926', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/566/']} | jdg_77713 |
stackexchange | llm_judgeable_groundtruth_similarity | 22993408 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using an icon system for my app with SVG Sprite, created by IcoMoon App.In index.html I have now something like this: <html><head>...</head><body><svg display="none" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="752" height="80" viewBox="0 0 752 80"> <defs> <g id="icon-home"> <path class="path1" d="M32 18.451l-16-12.42-16 12.42v-5.064l16-12.42 16 12.42zM28 18v12h-8v-8h-8v8h-8v-12l12-9z" /> </g> <g id="icon-camera"> <path class="path1" d="M9.5 19c0 3.59 2.91 6.5 6.5 6.5s6.5-2.91 6.5-6.5-2.91-6.5-6.5-6.5-6.5 2.91-6.5 6.5zM30 8h-7c-0.5-2-1-4-3-4h-8c-2 0-2.5 2-3 4h-7c-1.1 0-2 0.9-2 2v18c0 1.1 0.9 2 2 2h28c1.1 0 2-0.9 2-2v-18c0-1.1-0.9-2-2-2zM16 27.875c-4.902 0-8.875-3.973-8.875-8.875 0-4.902 3.973-8.875 8.875-8.875 4.902 0 8.875 3.973 8.875 8.875 0 4.902-3.973 8.875-8.875 8.875zM30 14h-4v-2h4v2z" /> </g> </defs></svg> ...some html code...<!-- an image --><svg class="icon" viewBox="0 0 32 32"><use xlink:href="#icon-home"></use></svg></body><html> I need to move the svg sprite in a file and then include it as an external resource.How can I do this?
Now provide the response and nothing else.
| Try this: Create an SVG file, sprites.svg Place the following in it: <svg version="1.1" xmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink"> <path id="icon-home" class="path1" d="M32 18.451l-16-12.42-16 12.42v-5.064l16-12.42 16 12.42zM28 18v12h-8v-8h-8v8h-8v-12l12-9z" /> <path id="icon-camera" class="path1" d="M9.5 19c0 3.59 2.91 6.5 6.5 6.5s6.5-2.91 6.5-6.5-2.91-6.5-6.5-6.5-6.5 2.91-6.5 6.5zM30 8h-7c-0.5-2-1-4-3-4h-8c-2 0-2.5 2-3 4h-7c-1.1 0-2 0.9-2 2v18c0 1.1 0.9 2 2 2h28c1.1 0 2-0.9 2-2v-18c0-1.1-0.9-2-2-2zM16 27.875c-4.902 0-8.875-3.973-8.875-8.875 0-4.902 3.973-8.875 8.875-8.875 4.902 0 8.875 3.973 8.875 8.875 0 4.902-3.973 8.875-8.875 8.875zM30 14h-4v-2h4v2z" /></svg> Then whenever you want to include in a use element. <svg class="icon" viewBox="0 0 32 32"> <use xlink:href="sprites.svg#icon-home" /></svg> (At this time, Internet Explorer has a problem with this. IE would need a different approach. If you want, I can also show what's necessary for IE) EDIT - Cross-browser support: Place SVG sprite elements in an XML file and call them into a defs element. XML file, named sprites.xml: <?xml version="1.0" encoding="UTF-8"?><SPRITES xmlns="http://www.w3.org/2000/svg"><path id="iconHome" d="M32 18.451l-16-12.42-16 12.42v-5.064l16-12.42 16 12.42zM28 18v12h-8v-8h-8v8h-8v-12l12-9z" /><path id="iconCamera" d="M9.5 19c0 3.59 2.91 6.5 6.5 6.5s6.5-2.91 6.5-6.5-2.91-6.5-6.5-6.5-6.5 2.91-6.5 6.5zM30 8h-7c-0.5-2-1-4-3-4h-8c-2 0-2.5 2-3 4h-7c-1.1 0-2 0.9-2 2v18c0 1.1 0.9 2 2 2h28c1.1 0 2-0.9 2-2v-18c0-1.1-0.9-2-2-2zM16 27.875c-4.902 0-8.875-3.973-8.875-8.875 0-4.902 3.973-8.875 8.875-8.875 4.902 0 8.875 3.973 8.875 8.875 0 4.902-3.973 8.875-8.875 8.875zM30 14h-4v-2h4v2z" /></SPRITES> An example HTML file with Javascript to propagate the defs element. <!DOCTYPE HTML><html><head> <title>Sprites</title></head><body onLoad=loadSprites()><svg id=mySVG width="400" height="400"><defs id="spriteDefs" /> <use xlink:href="#iconHome" transform="translate(100 100)" /> <use xlink:href="#iconHome" transform="translate(200 100)" /> <use xlink:href="#iconHome" transform="translate(300 100)" /> <use xlink:href="#iconCamera" transform="translate(100 200)" /> <use xlink:href="#iconCamera" transform="translate(200 200)" /> <use xlink:href="#iconCamera" transform="translate(300 200)" /> <use xlink:href="#iconHome" transform="translate(200 300)" /></svg><script>function loadSprites(){ var xmlFile="sprites.xml" var loadXML = new XMLHttpRequest; loadXML.onload = callback; loadXML.open("GET", xmlFile, true); loadXML.send(); function callback() { //---responseText--- var xmlString=loadXML.responseText //---DOMParser--- var parser = new DOMParser(); var mySpritesDoc=parser.parseFromString(xmlString,"text/xml").documentElement ; var addSprites=mySpritesDoc.childNodes for(var k=0;k<addSprites.length;k++) { var sprite=addSprites.item(k).cloneNode(true) document.getElementById("spriteDefs").appendChild(sprite) } }}</script></body></html> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22993408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/343802/']} | jdg_77714 |
stackexchange | llm_judgeable_groundtruth_similarity | 310003 |
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 Sheather's book , it states that The Box-Cox procedure aims to find a transformation that makes the transformed variable close to normally distributed. To be specific: Also, when x and y are normally distributed, the maximum likelihood estimates of $\beta_0$ and $\beta_1$ are the same as the least squares estimates. But in simple linear regression, actually we don't assume this to be necessarily true. Why is that? (Since based on the picture above, it seems only when x and y are normally distributed will Y on X to be close to linear, which is just the linear regression model) Also, Box-Cox method's goal is to make X and Y more normally distributed, yet usually when people use this method for data transformation, they actually want to make the errors(or std.residuals) normally distributed. How does these two relate to each other?
Now provide the response and nothing else.
| In reality the box-cox transformation finds a transformation that homogenize variance. And constant variance is really an important assumption! The comment of @whuber: The Box-Cox transform is a data transformation (usually for positive data) defined by $Y^{(\lambda)}= \frac{y^\lambda - 1}{\lambda}$ (when $\lambda\not=0$ and its limit $\log y$ when $\lambda=0$). This transform can be used in different ways, and the Box-Cox method usually refers to likelihood estimation of the transform parameter $\lambda$. $\lambda$ could potentially be chosen in other ways, but this post (and the question) is about this likelihood method of choosing $\lambda$. What happens is that boxcox transform maximizes a likelihood function constructed from a constant variance normal model. And the main contribution in maximizing that likelihood comes from homogenizing the variance! ( * ) You could construct some similar likelihood function from some other location-scale family (maybe, for example, constructed from $t_{10}$, say) and the constant variance assumption, and it would give similar results. Or you could construct a boxcox-like criterion function from robust regression, again with constant variance. It would give similar results. (eventually, I want to come back here showing this with some code). ( * ) This shouldn't really be surprising. By drawing a few figures you can convince yourself that changing the scale of a density is a much larger change, influencing density values (that is, likelihood values) much more than just changing the basic form a little, but keeping the scale. I once built (with Xlispstat) a slider demonstration showing this convincingly, but what you should do is simply to make some simple examples and you will see this result for yourself. What happens is simply that the contribution to the likelihood function from constant variance assumption greatly overshadows changes to the likelihood by small changes to the form of the basic density $f_0$ used to generate the location-scale family. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/310003', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/161581/']} | jdg_77715 |
stackexchange | llm_judgeable_groundtruth_similarity | 97968 |
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:
Increasing voltage increases the RPM of the motor, but what does increasing current do? I can't seem to get a straight answer. Some googling has led me to believe that torque increases while rpm stays the same. I currently have two 24V batteries wired in parallel, and they are connected to a DC motor through a speed controller. I understand that the speed controller works by turning the circuit on and off very quickly to vary the speed of the motor. I just bought a third 24V battery that I plan to connect in parallel to the other two, and was wondering what I should expect when I hook it up.
Now provide the response and nothing else.
| By adding a battery in parallel, you do not increase the current. You increase the maximum current that the motor can take. Nothing will happen if you add another battery in parallel and the motor isn't suffering from shortage of current. Keep in mind that than in Ohm's law, you have 3 variables: \$V=RI\$. In this equation, you can affect one variable by changing the other two. For a given motor, R is constant, so that means that one of two possible variables you can change is out. You can either set the voltage to some level, which you seem to be doing by using the speed controller, and let the current come from the equation or you can use a different type of speed controller which sets the current and lets the voltage come out as a result of the equation. So how is torque related to this? Well motor has what's called back electromotive force and the equation for the Ohm's law is actually a bit different:$$I=\frac{V_{battery}-V_{back-EMF}}{R}$$The greater the torque provided by the motor, the lower is the \$V_{back-EMF}\$, resulting in greater current through the motor. When current is supplied by a battery, the battery's voltage usually drops. The drop depends on the type of battery and the current. If the current is above what battery is expected to provide, you can expect the battery to have lower voltage than expected, to overheat, maybe even explode. If the current provided by the battery is sufficient, the voltage drop isn't going to be as big. So it's as I said in the first paragraph: If the batteries can provide sufficient current to the motor (and you test this by checking the current when motor should be providing maximum torque), then adding another battery won't affect the current or the torque. If there isn't enough current and you add a battery, you can expect increase in torque because the voltage supplied by the batteries will be higher. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/97968', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/11153/']} | jdg_77716 |
stackexchange | llm_judgeable_groundtruth_similarity | 9466011 |
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 xml file which I modify with the following code: XmlDocument xlDoc = new XmlDocument(); string[] files = Directory.GetFiles("C:\\Program Files (x86)", "Product.config", SearchOption.AllDirectories); string sfile = files[0]; xlDoc.Load(sfile); XmlNodeList list = xlDoc.SelectNodes("//dependancy"); XmlNode foundNode = xlDoc.SelectSingleNode("//dependancies//dependancy[@name='Microsoft Windows NT']");int found = list.Count; if (foundNode == null) { foundNode = xmlElement; list[found - 1].AppendChild(foundNode); xlDoc.Save(sfile); ConfigurationManager.RefreshSection(sfile); } foreach (XmlNode node in list) { xlDoc.Load(sfile); try {//use inserted node} ... Now before the foreach is executed , I want to reload the XML document, so that the value is in the document. The problem I am experiencing is that the changes are only loaded if the application is restarted. How can I reload the file before moving on to the foreach segment?
Now provide the response and nothing else.
| Improving the WHERE clause Your EXPLAIN shows that MySQL is only utilizing one index ( type_id ) for selecting the rows that match the WHERE clause, even though you have multiple criteria in the clause. To be able to utilize an index for all of the criteria in the WHERE clause, and to reduce the size of the result set as quickly as possible, add a multi-column index on the following columns on the vehicles table: (status, date_from, date_to, type_id, price) The columns should be in order of highest cardinality to least. For example, vehicles.date_from is likely to have more distinct values than status , so put the date_from column before status , like this: (date_from, date_to, price, type_id, status) This should reduce the rows returned in the first part of the query execution, and should be demonstrated with a lower row count on the first line of the EXPLAIN result. You will also notice that MySQL will use the multi-column index for the WHERE in the EXPLAIN result. If, by chance, it doesn't, you should hint or force the multi-column index. Removing the unnecessary JOINs It doesn't appear that you are using any fields in any of the joined tables, so remove the joins. This will remove all of the additional work of the query, and get you down to one, simple execution plan (one line in the EXPLAIN result). Each JOINed table causes an additional lookup per row of the result set. So, if the WHERE clause selects 5,000 rows from vehicles, since you have 8 joins to vehicles, you will have 5,000 * 8 = 40,000 lookups. That's a lot to ask from your database server. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9466011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1170926/']} | jdg_77717 |
stackexchange | llm_judgeable_groundtruth_similarity | 1812545 |
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 my book this is termed as a theorem and the proof given is as follows :- $$\begin{align}\lim_{x \to a}\left(\frac{x^n - a^n}{x - a}\right)&=\lim_{x \to a}\left(\frac{(x - a)*(x^{x-1} + x^{n-2}*a + x^{n-3}*a^2 + x^{n-4}*a^3 + \cdots + x^1*a^{n-2} + a^{n-1})}{x - a}\right) \\ &=(a^{n-1} + a*a^{n-2} + \cdots + a^{n-1}) \\ &=(a^{n-1} + a^{n-1} + \cdots + a^{n-1}) \\ &=(n*a^{n-1}).\end{align}$$ Everything made sense to me except $$x^n - a^n = (x - a)*(x^{x-1} + x^{n-2}*a + x^{n-3}*a^2 + x^{n-4}*a^3 + \cdots + x^1*a^{n-2} + a^{n-1})$$ Somebody please enlighten me on this topic.
Now provide the response and nothing else.
| No, this isn't a binomial expansion. This is just long division. To check that it makes sense, we can just expand it out: \begin{align*}&(x - a)(x^{n - 1} + ax^{n - 2} + a^2x^{n - 3} + \cdots + a^{n - 2}x + a^{n - 1}) \\&= x(x^{n - 1} + ax^{n - 2} + a^2x^{n - 3} + \cdots + a^{n - 1}) \\&~~~~~~~~~~~~~~~~~- a(x^{n - 1} + ax^{n - 2} + \cdots + a^{n - 2}x + a^{n - 1}) \\&= (x^n \color{red}{+ ax^{n - 1} + a^2x^{n - 2} + \cdots + a^{n - 1}x}) \\&~~~~~~~+ (\color{red}{-ax^{n - 1} - a^2x^{n - 2} - \cdots - a^{n - 1}x} - a^n) \\&= x^n - a^n\end{align*} | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1812545', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_77718 |
stackexchange | llm_judgeable_groundtruth_similarity | 66189561 |
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 getting this error on my Vue 3 project: You are running the esm-bundler build of Vue. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle. See http://link.vuejs.org/feature-flags for more details. webpack.mix.js const mix = require ('laravel-mix');const path = require ('path');mix.webpackConfig ({ output: { chunkFilename: 'js/chunks/[name].[chunkhash].js' }, module: { rules: [ { test: /node_modules(?:\/|\\).+\.js$/, loader: 'babel-loader', options: { presets: [['@babel/preset-env', {targets: 'last 2 versions, ie >= 10'}]], plugins: ['@babel/plugin-transform-destructuring', '@babel/plugin-proposal-object-rest-spread', '@babel/plugin-transform-template-literals'], babelrc: false } }, { enforce: 'pre', test: /\.(js|vue)$/, loader: 'eslint-loader', exclude: /node_modules/ } ] }, resolve: { alias: { vue: "vue/dist/vue.esm-bundler.js" }, }, optimization: { providedExports: false, sideEffects: false, usedExports: false }});mix.js ("resources/js/entry-point.js", "public/js").vue({}).postCss ("resources/css/app.css", "public/css", [ require ("tailwindcss"),]);mix.extract (['vue']);if (mix.inProduction ()) { mix .version ();} In this case, it does not matter whether I set mix.webpackConfig or not. This is package.json : { "private": true, "scripts": { "dev": "npm run development", "development": "mix", "watch": "mix watch", "watch-poll": "mix watch -- --watch-options-poll=1000", "hot": "mix watch --hot", "prod": "npm run production", "production": "mix --production" }, "devDependencies": { "@vue/compiler-sfc": "^3.0.5", "autoprefixer": "^10.2.4", "axios": "^0.21", "cross-env": "^5.1", "css-loader": "^5.0.2", "eslint-plugin-vue": "^7.5.0", "file-loader": "^6.2.0", "laravel-mix": "^6.0.6", "mini-css-extract-plugin": "^1.3.6", "postcss": "^8.2.6", "resolve-url-loader": "^3.1.2", "tailwindcss": "^2.0.3", "url-loader": "^4.0.0", "vue-loader": "^16.1.2", "babel-eslint": "^10.1.0", "eslint": "^7.19.0", "eslint-config-google": "^0.14.0", "eslint-loader": "^4.0.2" }, "dependencies": { "vue": "^3.0.5", "vue-router": "4.0.3" }} I read the provided link, but I did not see a way to solve this issue.
Now provide the response and nothing else.
| The linked docs specify two configurable flags: __VUE_OPTIONS_API__ (enable/disable Options API support, default: true) __VUE_PROD_DEVTOOLS__ (enable/disable devtools support in production, default: false) For Webpack, use the DefinePlugin to set these flags: const webpack = require('webpack')mix.webpackConfig ({ plugins: [ new webpack.DefinePlugin({ __VUE_OPTIONS_API__: false, __VUE_PROD_DEVTOOLS__: false, }), ],}) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/66189561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7510971/']} | jdg_77719 |
stackexchange | llm_judgeable_groundtruth_similarity | 7999339 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: pass by reference in java I am new to java. I tried to search a lot for my query but could not find. Please help me if you know. I have a function: boolean func(int a, int b, myclass obj1, myclass2 obj2){ ...}void caller() { int a = 0, b=0; myclass obj1 = null; myclass1 obj2 = null; func(a,b,obj1,obj2); if (a == 5 && b ==2) { ... }} what should i do such that all passed variables have the value in caller function which was given by function func?
Now provide the response and nothing else.
| Unfortunately there's no built-in way to do what you want (it's a fairly-often-requested feature). One workaround is to implement a factory pattern, where you don't create objects by calling the constructor directly, but instead implement a static method to create them for you. For example: public class MyClass{ public MyClass() { // Don't call virtual methods here! } public virtual void Initialize() { // Do stuff -- but may be overridden by derived classes! }} then add: public static MyClass Create(){ var result = new MyClass(); // Safe to call a virtual method here result.Initialize(); // Now you can do any other post-constructor stuff return result;} and instead of doing var test = new MyClass(); you can do var test = MyClass.Create(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7999339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967491/']} | jdg_77720 |
stackexchange | llm_judgeable_groundtruth_similarity | 905754 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Web server running in Dutch(Belgium) double output;double.TryParse(txtTextbox1.Text, out output); Is this a good way to convert text to double in dutch environment? Let's say the input is " 24.45 " instead of " 24,45 "
Now provide the response and nothing else.
| If you want to use the Dutch (Belgium) number format: double output;double.TryParse("24,45", NumberStyles.Any, CultureInfo.GetCultureInfo("nl-BE"), out output); Or to use the US number format: double output;double.TryParse("24.45", NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out output); If you attempt to parse "24.45" with a Dutch culture set, you'll get back "2445", similarly, if you attempt to parse "24,45" with a US culture, you'll get "2445". If you want the parse to fail if the wrong decimal point is used, change NumberStyles.Any to exclude the flag: NumberStyles.AllowThousands : double output;if (double.TryParse("24.45", NumberStyles.Any ^ NumberStyles.AllowThousands, CultureInfo.GetCultureInfo("nl-BE"), out output)) If your entire application is in Dutch, you should change your cultureinfo globally - here's how to do it in WinForms and here's how to do it in ASP.NET . Once you're using a globally set CultureInfo, you can change the above code to: double output;double.TryParse("24.45", NumberStyles.Any, CultureInfo.CurrentCulture, out output); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/905754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34983/']} | jdg_77721 |
stackexchange | llm_judgeable_groundtruth_similarity | 2130721 |
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's basic difference between JsonStore and JsonReader in context to Ext.data? I mean when I should go for JsonStore and when I should use JsonReader as for me both are providing same solution.
Now provide the response and nothing else.
| Actually they are two separate things. A Ext.data.JsonReader reads a given JSON object and returns data records ( Ext.data.Record objects) that are later stored by the respective data store. The Ext.data.Store is the base class for all Ext storages and uses helper objects for retrieving data ( Ext.data.DataProxy ), for writing data ( Ext.data.DataWriter ) and for reading data ( Ext.data.DataReader ). These base classes come in different flavors such as: Ext.data.DataProxy : Ext.data.DirectProxy Ext.data.HttpProxy Ext.data.MemoryProxy Ext.data.ScriptTagProxy Ext.data.DataWriter Ext.data.JsonWriter Ext.data.XmlWriter Ext.data.DataReader Ext.data.JsonReader Ext.data.XmlReader This all builds up to a very extendable component that allows the developer to configure exactly what he needs to tweak. To make it easier for developers (especially new ones) Ext comes with some pre-configured data stores: Ext.data.ArrayStore to make reading from simple Javascript arrays easier Ext.data.DirectStore , just a store preconfigured with an Ext.data.DirectProxy and an Ext.data.JsonReader Ext.data.JsonStore , just a store preconfigured with an Ext.data.JsonReader Ext.data.XmlStore , just a store preconfigured with an Ext.data.XmlReader So actually a Ext.data.JsonStore is just a convenience class to make it easier for the developer. The following two snippets will create the same (or comparable) stores: var store = new Ext.data.JsonStore({ url: 'get-images.php', root: 'images', idProperty: 'name', fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]});// or var store = new Ext.data.Store({ url: 'get-images.php', reader: new Ext.data.JsonReader({ root: 'images', idProperty: 'name', fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}] });}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2130721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144408/']} | jdg_77722 |
stackexchange | llm_judgeable_groundtruth_similarity | 6929070 |
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 java.io.File objects A and B, where A represents a directory and B represents a file. B can be an absolute path or a relative path that is 0 or more levels below A. what's the most efficient way to determine if B is contained by A? For example, A is C:\Users\bill\Desktop\abc\xyz123 and B is C:\Users\bob\Documents\inc\data.inc or A is C:\Users\bill\Desktop\abc\xyz123 and B is C:\Users\bob\Documents\x1\y1\inc\data.inc or A is C:\Users\bill\Desktop\abc\xyz123 and B is ..\..\..\Documents\inc\data.inc
Now provide the response and nothing else.
| You can check to see if A is the parent of B by doing A.equals(B.getParentFile()) Edit: If you want to check if B is one or more levels below A, just keep getting the ParentFile until it's A or null File C = B.getParentFile();while(C != null) { if(A.equals(C)) return true; C = C.getParentFile();}return false; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6929070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21410/']} | jdg_77723 |
stackexchange | llm_judgeable_groundtruth_similarity | 8640692 |
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 JavaScript to generate a HTML table of 4 columns, but when the table became very large (e.g. more than 1000 rows), the user could face lag between their interaction (e.g. hovering on a row, scrolling, or clicking something) and the response of the webpage. This is the demo to show my issue, please run it on fullscreen, you can notice (or not noticing it if your computer is fast enough...) a small lag of hover effect when you move your mouse quickly between rows: /** * @namespace Start the project called 'stck' */var stck = {};/** * Variable to save stock loaded */stck.stockInfo = [];/** * Load the item informaction acording the SKU * @private * @param {string} SKU The SKU of the item */stck.loadItemInformation = function(SKU) { var descriptionsTable = document.getElementById('descriptionsTable'); for (var rowsLength = descriptionsTable.rows.length - 1; --rowsLength; ) { descriptionsTable.deleteRow(1); } var pricesTable = document.getElementById('pricesTable'); for (var rowsLength = pricesTable.rows.length - 1; --rowsLength; ) { pricesTable.deleteRow(1); } document.getElementById('tableHeader').style.cssText = ''; document.getElementById('tableContent').style.cssText = ''; // Load data with AJAX and process here document.getElementById('addItemButton').className = 'hidden'; document.getElementById('saveButton').className = document.getElementById('cancelButton').className = ''; document.getElementById('tables').className = 'hidden'; document.getElementById('editItem').className = 'active';};/** * Show row to the 'tableContent' table. * @public * @param {number} showQuantity The quantity that will be loaded * @param {boolean} isLoadNewStock Define if the quantity that are going to be show are lower than stock, will load new stock information or not */stck.showRow = function(showQuantity, isLoadNewStock) { var stock = stck.stockInfo; var tableContent = document.getElementById('tableContent'); var tableContentRowsLength = tableContent.rows.length; var stockInfoLength = stck.stockInfo.length; var toIndex = tableContentRowsLength + showQuantity; if (toIndex > stockInfoLength) { if (isLoadNewStock && stck.loadStock(10, true, false)) { return; } else { toIndex = stockInfoLength; } } for (var i = tableContentRowsLength, row, rowNumber, cellIndex, SKUCell, descriptionCell, stockCell, clickHandler; i < toIndex; ++i) { row = tableContent.insertRow(i); rowNumber = document.createElement('TH'); rowNumber.innerText = i + 1; row.appendChild(rowNumber); cellIndex = 0; SKUCell = row.insertCell(++cellIndex); SKUCell.innerHTML = stock[i][0]; descriptionCell = row.insertCell(++cellIndex); descriptionCell.innerHTML = stock[i][1]; stockCell = row.insertCell(++cellIndex); stockCell.className = 'stock'; stockCell.innerHTML = stock[i][2]; clickHandler = function(row) { return function() { stck.loadItemInformation(stock[row][0]); }; }; row.onclick = clickHandler(i); }};/** * This code is for test */for (var i = 0; i < 10000; ++i) { stck.stockInfo.push(['TESTSKU', 'A test item', i]);}stck.showRow(10000, false) html{height:100%;background-color:#FFF;background:-webkit-gradient(linear,left top,left bottom,from(#EEE),to(#FFF));background:-webkit-radial-gradient(#FFF,#FFF 35%,#EEE);background:-moz-radial-gradient(#FFF,#FFF 35%,#EEE);background:radial-gradient(#FFF,#FFF 35%,#EEE);-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:-moz-none;-o-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent;-webkit-text-size-adjust:none;-webkit-font-smoothing:antialiased;cursor:default}::-moz-selection,::selection{background:transparent}::-moz-focus-inner{border:none}body{margin:0;background-color:transparent;overflow:hidden}body,th,td,input,textarea{color:#333;font:13px/1.2 Arial,Helvetica,sans-serif;-webkit-border-radius:0;text-rendering:optimizelegibility}a{outline:none}img{border:none;behavior:url(/i/iepngfix.htc)}table{border-spacing:0;border-collapse:collapse}article,aside,hgroup,footer,header,nav,section{display:block}input,select{margin:2px 0;padding:3px;-webkit-border-radius:0;-webkit-box-shadow:none;-webkit-appearance:none;border:1px solid #B8ADA5;overflow:visible}input[type="number"]::-webkit-outer-spin-button{display:none}input:hover,select:hover{border-color:#4A0}input:focus,select:focus{border-color:#4A0;-webkit-box-shadow:0 0 3px #4A0;-moz-box-shadow:0 0 3px #4A0;box-shadow:0 0 3px #4A0;outline:none}input::-moz-focus-inner{border:0;padding:0}.b{clear:both;margin-top:10px;padding:0 4px;border-top:1px dashed #CCC;text-align:right}.b input{width:auto;min-width:54px;height:29px;margin:6px 0 6px 6px;padding:0 8px;border:1px solid #3079ED;-webkit-border-radius:2px;-moz-border-radius:2px;border-radius:2px;background-color:#4D90FE;background-image:-webkit-gradient(linear,left top,left bottom,from(#4D90FE),to(#4787ED));background-image:-moz-linear-gradient(top,#4D90FE,#4787ED);background-image:-o-linear-gradient(top,#4D90FE,#4787ED);background-image:linear-gradient(top,#4D90FE,#4787ED);color:#FFF;font-weight:700;text-decoration:none;line-height:27px;-webkit-transition:0.1s ease-in-out;-moz-transition:0.1s ease-in-out;-o-transition:0.1s ease-in-out;transition:0.1s ease-in-out;text-align:center;cursor:pointer}.b input:hover{background-color:#357AE8;background-image:-webkit-gradient(linear,left top,left bottom,from(#4D90FE),to(#357AE8));background-image:-moz-linear-gradient(top,#4D90FE,#357AE8);background-image:-o-linear-gradient(top,#4D90FE,#357AE8);background-image:linear-gradient(top,#4D90FE,#357AE8)}.b input:active,.b input:focus{-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.3);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,.3);box-shadow:inset 0 1px 2px rgba(0,0,0,.3);outline:none}input:disabled,textarea:disabled{color:#999;cursor:not-allowed}textarea:disabled::-webkit-input-placeholder{color:#F9F9F9}.b input:disabled{color:#EEE;cursor:not-allowed}.b input:disabled:hover{background-color:#4D90FE;background-image:-webkit-gradient(linear,left top,left bottom,from(#4D90FE),to(#4787ED));background-image:-moz-linear-gradient(top,#4D90FE,#4787ED);background-image:-o-linear-gradient(top,#4D90FE,#4787ED);background-image:linear-gradient(top,#4D90FE,#4787ED);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}#gpanel{position:fixed;top:0;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;width:100%;height:43px;padding:0 5px;-moz-border-radius:0 1px;border-bottom:1px solid #000;background-color:rgba(0,0,0,.85);line-height:46px;-webkit-transition:.1s ease-in-out;-moz-transition:.1s ease-in-out;-o-transition:0.1s ease-in-out;transition:.1s ease-in-out;overflow:hidden;z-index:10}#gpanel.hidden{top:-44px}#gpanel ul{list-style:none;margin:0;padding:0}#gpanel li{float:left;overflow:hidden}#gpanel a{display:block;padding:0 10px;color:#DDD;font-weight:700;text-decoration:none;white-space:nowrap;cursor:pointer;-webkit-transition:.1s ease-in-out;-moz-transition:.1s ease-in-out;-o-transition:0.1s ease-in-out;transition:.1s ease-in-out}#gpanel a:hover{background-color:rgba(204,204,204,.4);color:#FFF}@-webkit-keyframes loading { 0% {background-color:rgba(204,204,204,.4)} 50% {background-color:rgba(119,187,68,.9)} 100% {background-color:rgba(204,204,204,.4)}}@-moz-keyframes loading { 0% {background-color:rgba(204,204,204,.4)} 50% {background-color:rgba(119,187,68,.9)} 100% {background-color:rgba(204,204,204,.4)}}#gpanel a:active,#gpanel a:focus{background-color:rgba(119,187,68,.9);-webkit-animation:loading .5s infinite linear;-moz-animation:loading .5s infinite linear}#gnav{float:left;overflow:hidden}#gmanager{float:right;margin-right:4px}#body{margin-top:44px;overflow:auto}#overlay{position:fixed;top:0;right:0;bottom:0;left:0;background-color:rgba(127,127,127,0.5);background:-webkit-radial-gradient(rgba(127,127,127,.5),rgba(127,127,127,.5) 35%,rgba(0,0,0,.7));background:-moz-radial-gradient(rgba(127,127,127,.5),rgba(127,127,127,.5) 35%,rgba(0,0,0,.7));-webkit-transition:opacity .25s linear;-moz-transition:opacity .25s linear;transition:opacity .25s linear;opacity:1;overflow-y:auto;z-index:15}#overlay.hidden{opacity:0;visibility:hidden}#overlay .hidden{display:none}#overlay form{position:absolute;top:50%;left:50%;border:1px solid #BCC1D0;-webkit-border-radius:2px;-moz-border-radius:2px;-webkit-box-shadow:0px 5px 80px #505050;-moz-box-shadow:0px 5px 80px #505050;background:#FFF url(../image/lightbox.png) bottom repeat-x;text-align:left}.window p{margin:5px 0}.window label{display:block;text-transform:uppercase;font:700 10px Tahoma,Geneva,sans-serif;zoom:1}.window input[type="text"],.window input[type="number"],.window input[type="password"],.window textarea{padding:2px;border:1px solid;border-color:#999 #333 #333 #999;background:#FFF}.window table{margin:0;border-spacing:0;border-collapse:collapse}.window th,.window td{border:none;border-bottom:1px solid #CCC;background:none}.window select{width:65px}#code,#desc,#desc_cn,#password,#largedescription{width:350px}#price{width:100px}.window input[type="submit"]{padding:5px 10px;border:1px solid;border-color:#FC0 #F60 #F60 #FC0;background:#F90}.window input[type="reset"]{padding:5px 10px;border:1px solid;border-color:#EEE #333 #333 #EEE;background:#CCC}#overlay h1,#body h1{margin:0;padding:10px 20px 5px;border-bottom:1px solid #CCC;color:#848589;font:400 30px 'Segoe UI',Arial,Helvetica,sans-serif}#overlay h1{font-size:24px}#overlay .contentArea{padding:10px 15px 5px}#overlay label{font-weight:700}form#addItemPage{width:500px;margin:-126px 0 0 -251px}#addItemPage .contentArea p{overflow:auto}#addItemPage .contentArea label{display:block;width:470px;line-height:28px}#addItemPage .contentArea input{float:right;width:330px;margin-right:3px}#body h1{height:41px}#stock a{color:#FFF;background-color:#7B4}#functions{padding:13px 10px;float:right}#functions ul{list-style:none;margin:0;padding:0}#functions li{display:inline-block;min-width:54px;height:27px;margin-left:6px;padding:0 8px;border:1px solid #3079ED;-webkit-border-radius:2px;-moz-border-radius:2px;border-radius:2px;background:#4D90FE;background-image:-webkit-gradient(linear,left top,left bottom,from(#4D90FE),to(#4787ED));background-image:-moz-linear-gradient(top,#4D90FE,#4787ED);background-image:-o-linear-gradient(top,#4D90FE,#4787ED);background-image:linear-gradient(top,#4D90FE,#4787ED);color:#FFF;font-weight:700;text-decoration:none;line-height:27px;cursor:pointer}#functions li:hover{background:#357AE8;background-image:-webkit-gradient(linear,left top,left bottom,from(#4D90FE),to(#357AE8));background-image:-moz-linear-gradient(top,#4D90FE,#357AE8);background-image:-o-linear-gradient(top,#4D90FE,#357AE8);background-image:linear-gradient(top,#4D90FE,#357AE8)}#functions li:active,#functions li:focus{-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.3);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,.3);box-shadow:inset 0 1px 2px rgba(0,0,0,.3);outline:none}#functions li.hidden{display:none}#tables{position:absolute;top:101px;bottom:0;width:100%;-webkit-transition:.3s linear;-moz-transition:.3s linear;transition:.3s linear;overflow-y:scroll}#tables.hidden{opacity:0;-webkit-transform:scale(0);-moz-transform:scale(0);-o-transform:scale(0);-ms-transform:scale(0);transform:scale(0)}#tables:focus{outline:none}::-moz-focus-inner{border:none}#tables table{width:100%;border-collapse:collapse;border-spacing:0;table-layout:fixed;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}#tableHeader{top:101px}.indexCol{width:50px}.SKUCol{width:115px}.brandCol{width:105px}.stockCol{width:85px}tr#noItem{text-align:center;cursor:default}tr#noItem:hover{background:#FFF}.stock{text-align:right}#tables th,#tables td{padding:9px 6px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}#tables thead th{border-bottom:1px solid #CCC;background-color:#F5F5F5;background-image:-webkit-gradient(linear,left top,left bottom,from(#F5F5F5),to(#F1F1F1));background-image:-moz-linear-gradient(top,#F5F5F5,#F1F1F1);background-image:-o-linear-gradient(top,#F5F5F5,#F1F1F1);background-image:linear-gradient(top,#F5F5F5,#F1F1F1);font-weight:700;cursor:default}#tables tbody th{font-weight:700;text-overflow:none}#tables tbody tr{background:#FFF;cursor:pointer}#tables tbody tr:nth-child(even){background:#F8F9FC}#tables tbody tr:hover{background:#CDE}#editItem{position:fixed;top:101px;bottom:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;width:100%;padding:0 20px;visibility:hidden;opacity:0;-webkit-transform:scale(2);-moz-transform:scale(2);-o-transform:scale(2);-ms-transform:scale(2);transform:scale(2);-webkit-transition:.3s linear;-moz-transition:.3s linear;-o-transition:.3s linear;transition:.3s linear}#editItem.active{visibility:visible;opacity:1;-webkit-transform:scale(1);-moz-transform:scale(1);-o-transform:scale(1);-ms-transform:scale(1);transform:scale(1)}#editItem header{height:51px;overflow:auto}#editItem h2{float:left;margin:0 20px 0 0;padding:10px 0;color:#7B4;font:400 20px 'Seoge UI',Arial,Helvetica,sans-serif}#editItem ul{list-style:none;margin:10px 0;padding:0;border-bottom:1px solid #7B4}#editItem li{display:inline-block;margin:0 5px;padding:8px 10px 7px;color:#7B4;cursor:pointer;text-transform:uppercase;-webkit-transition:.15s linear;-moz-transition:.15s linear;transition:.15s linear}#editItem li:hover{background:rgba(204,204,204,.4);color:#000}#editItem li.active{background-color:#7B4;color:#FFF;font-weight:700;cursor:default}#editItem .container{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;height:100%;overflow:hidden}#editItem .tabs{position:relative;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;width:100%;height:100%;-webkit-transition:.5s ease-in-out;-moz-transition:.5s ease-in-out;-o-transition:.5s ease-in-out;transition:.5s ease-in-out}#editItem section{width:100%;height:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;overflow-y:auto}#editItem section div{float:left;width:50%;padding:5px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}#editItem label{float:left;width:20%;min-width:50px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}#editItem table{width:100%;table-layout:fixed}#descriptionsTable{margin-top:5px;border-top:1px solid #DDD}#editItem th{font-weight:700;text-align:left}#editItem th, #editItem td{padding:5px 2px}#editItem img{display:block;margin:0 auto;opacity:.5;cursor:pointer}#editItem tr:hover img{opacity:1}#inputsTable .labelCol{width:100px}#inputsTable label{float:none;display:block;width:100%;height:100%}#editItem input, #editItem select{width:100%;height:26px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}#editItem .languageCol{width:190px}#editItem .deleteCol{width:25px}#editItem #statusInput{width:auto;height:auto;margin:4px 4px 4px 0;-webkit-appearance:checkbox}#editItem label[for="statusInput"]{display:inline;width:auto;height:auto}#editItem textarea{box-sizing:border-box;width:100%}#newDescriptionRow select{visibility:hidden} <!DOCTYPE html><meta charset="utf-8"><link rel="stylesheet" media="screen" href="/s/master.css"><link rel="stylesheet" media="screen" href="/s/stock.css"><title>Existencia | HDX</title><body><header id="gheader"><nav id="gpanel"><ul id="gnav"><li id="stock"><a href="/76091132/existencia/">Existencia</a></ul><ul id="gmanager"><li id="user"><a href="/76091132/">Tester</a><li id="exit"><a href="/76091132/salir">Salir</a></ul></nav></header><div id="overlay" class="hidden"><form id="addItemPage" class="hidden"><h1>Agregar un artículo</h1><div class="contentArea"><p><label>SKU<input type="text" id="newSKUInput" maxlength="20" autocomplete="off"></label><p><label>Descripción<input type="text" id="newDescriptionInput" maxlength="100" autocomplete="off"></label><p><label>Precio unitario<input type="number" id="newUnitPriceInput" min="1" value="1" autocomplete="off"></label></div><div class="b"><input type="submit" value="Agregar"><input type="reset" value="Cancelar"></div></form></div><div id="body"><header><div id="functions"><ul><li id="addItemButton">Agregar un artículo<li id="cancelButton" class="hidden">Cancelar<li id="saveButton" class="hidden">Guardar</ul></div><h1 class="fn">Existencia</h1></header><div id="tables" tabindex="0"><table id="tableHeader"><colgroup><col class="indexCol"><col class="SKUCol"><col><col class="stockCol"></colgroup><thead><tr><th>#<th>SKU<th>Descripción<th>Existencia</thead></table><table id="tableContent"><colgroup><col class="indexCol"><col class="SKUCol"><col><col class="stockCol"></colgroup><tbody></tbody></table></div></div><div id="editItem"><header><h2>Editar artículo</h2><nav><ul id="tabsLabels"><li id="generalTabButton" class="active">General<li id="stockTabButton">Existencia<li id="facturationTabButton">Facturación<li id="optionsTabButton">Opciones</ul></nav></header><div id="tabsContainer" class="container"><div id="tabsContents" class="tabs"><section id="generalTab"><div><table id="inputsTable"><colgroup><col class="labelCol"></colgroup><tr><th><label for="SKUInput">SKU</label><td><input type="text" id="SKUInput" autocomplete="off"></table><table id="descriptionsTable"><colgroup><col><col class="languageCol"><col class="deleteCol"></colgroup><tr><th>Descripción<th>Idioma<th><tr id="newDescriptionRow"><td><input type="text" id="descriptionInput" placeholder="Escriba aquí para una descripción nueva en otro idioma" autocomplete="off"><td><select id="languageSelect"><option value="aa">afar<option value="ab">abjaso<option value="ae">avéstico<option value="af">afrikaans<option value="ak">akano<option value="am">amárico<option value="an">aragonés<option value="ar">árabe<option value="as">asamés<option value="av">avar<option value="ay">aimara<option value="az">azerí<option value="ba">baskir<option value="be">bielorruso<option value="bg">búlgaro<option value="bh">bhojpurí<option value="bi">bislama<option value="bm">bambara<option value="bn">bengalí<option value="bo">tibetano<option value="br">bretón<option value="bs">bosnio<option value="ca">catalán<option value="ce">checheno<option value="ch">chamorro<option value="cn">chino<option value="co">corso<option value="cr">cree<option value="cs">checo<option value="cu">eslavo eclesiástico antiguo<option value="cv">chuvasio<option value="cy">galés<option value="da">danés<option value="de">alemán<option value="dv">maldivo<option value="dz">dzongkha<option value="ee">ewe<option value="el">griego<option value="en">inglés<option value="eo">esperanto<option value="es">español<option value="et">estonio<option value="eu">euskera<option value="fa">persa<option value="ff">fula<option value="fi">finés<option value="fj">fiyiano<option value="fo">feroés<option value="fr">francés<option value="fy">frisón<option value="ga">irlandés<option value="gd">gaélico escocés<option value="gl">gallego<option value="gn">guaraní<option value="gu">guyaratí<option value="gv">manés<option value="ha">hausa<option value="he">hebreo<option value="hi">hindi<option value="ho">hiri motu<option value="hr">croata<option value="ht">haitiano<option value="hu">húngaro<option value="hy">armenio<option value="hz">herero<option value="ia">interlingua<option value="id">indonesio<option value="ie">occidental<option value="ig">igbo<option value="ii">yi de Sichuán<option value="ik">inupiaq<option value="io">ido<option value="is">islandés<option value="it">italiano<option value="iu">inuktitut<option value="ja">japonés<option value="jv">javanés<option value="ka">georgiano<option value="kg">kongo<option value="ki">kikuyu<option value="kj">kuanyama<option value="kk">kazajo<option value="kl">groenlandés<option value="km">camboyano<option value="kn">canarés<option value="ko">coreano<option value="kr">kanuri<option value="ks">cachemiro<option value="ku">kurdo<option value="kv">komi<option value="kw">córnico<option value="ky">kirguís<option value="la">latín<option value="lb">luxemburgués<option value="lg">luganda<option value="li">limburgués<option value="ln">lingala<option value="lo">lao<option value="lt">lituano<option value="lu">luba-katanga<option value="lv">letón<option value="mg">malgache<option value="mh">marshalés<option value="mi">maorí<option value="mk">macedonio<option value="ml">malayalam<option value="mn">mongol<option value="mr">maratí<option value="ms">malayo<option value="mt">maltés<option value="my">birmano<option value="na">nauruano<option value="nb">noruego bokmål<option value="nd">ndebele del norte<option value="ne">nepalí<option value="ng">ndonga<option value="nl">neerlandés<option value="nn">nynorsk<option value="no">noruego<option value="nr">ndebele del sur<option value="nv">navajo<option value="ny">chichewa<option value="oc">occitano<option value="oj">ojibwa<option value="om">oromo<option value="or">oriya<option value="os">osético<option value="pa">panyabí<option value="pi">pali<option value="pl">polaco<option value="ps">pastú<option value="pt">portugués<option value="qu">quechua<option value="rm">retorrománico<option value="rn">kirundi<option value="ro">rumano<option value="ru">ruso<option value="rw">ruandés<option value="sa">sánscrito<option value="sc">sardo<option value="sd">sindhi<option value="se">sami septentrional<option value="sg">sango<option value="sh">serbocroata<option value="si">cingalés<option value="sk">eslovaco<option value="sl">esloveno<option value="sm">samoano<option value="sn">shona<option value="so">somalí<option value="sq">albanés<option value="sr">serbio<option value="ss">suazi<option value="st">sesotho<option value="su">sundanés<option value="sv">sueco<option value="sw">suajili<option value="ta">tamil<option value="te">telugú<option value="tg">tayiko<option value="th">tailandés<option value="ti">tigriña<option value="tk">turcomano<option value="tl">tagalo<option value="tn">setsuana<option value="to">tongano<option value="tr">turco<option value="ts">tsonga<option value="tt">tártaro<option value="tw">twi<option value="ty">tahitiano<option value="ug">uigur<option value="uk">ucraniano<option value="ur">urdu<option value="uz">uzbeko<option value="ve">venda<option value="vi">vietnamita<option value="vo">volapük<option value="wa">valón<option value="wl">walisiano<option value="wo">wolof<option value="xh">xhosa<option value="yi">yídish<option value="yo">yoruba<option value="za">chuan<option value="zh">chino<option value="zu">zulú</select><td></table></div><div><table id="inputsTable"><colgroup><col class="labelCol"></colgroup><tr><th>Estado<td><input type="checkbox" id="statusInput" value="1"><label for="statusInput">Activo</label><!--<tr><th><label for="departmentSelect">Departamento</label><td><select></select><tr><th><label for="categorySelect">Categoría</label><td><select></select><tr><th><label for="noteTextArea">Notas</label><td><textarea></textarea>--></table></div></section><section id="stockTab"><div><table id="stadisticTable"><tr><th>Inventario<td>0<tr><th>Cantidad vendido<td>0<tr><th>Última fecha de modificación<td></table></div></section><section id="facturationTab"><div><table id="pricesTable"><colgroup><col><col><col><col><col class="deleteCol"></colgroup><tr><th>Código<th>Unidad<th>Cantidad equivalente<th>Precio<th><tr id="newPriceRow"><td><input type="text" id="codeInput" autocomplete="off"><td><input type="text" id="unitInput" autocomplete="off"><td><input type="text" id="quantityInput" autocomplete="off"><td><input type="text" id="priceInput" autocomplete="off"><td></table></div></section><section id="optionsTab"><p>Imprimir precio</section></div></div> Is there any solution to this problem?
Now provide the response and nothing else.
| The first thing that is slowing your loop down is .insertRow() . You're doing this at the top of your loop and then adding cells to it. After the row is added, and after each cell is added, the browser is doing layout calculations. Instead use .createElement() and then .appendChild() at the end of your loop. Demo: http://jsfiddle.net/ThinkingStiff/gyaGk/ Replace: row = tableContent.insertRow(i); With: row = document.createElement('tr'); And add this at the end of your loop: tableContent.tBodies[0].appendChild(row); That will solve your loading speed issue. As for the hover, you have way too many CSS rules affecting your tr and td elements using tag selectors. I removed a few, and used classes on a few, and the hover highlighting is much faster. Specifically, I noticed that overflow: hidden on the td elements slowed it down considerably. Consider combining some of your rules, using simpler selectors, and adding classes to elements for quicker CSS processing. During hover many things have to be recalculated by the the layout engine, and the fewer CSS rules the better. One example I saw in your code was #tables tbody tr when there was only one tbody in the table. #tables tr would have sufficed. Better than either of those is a class. I used .row in my demo. Best practices from Google Page Speed : Avoid descendant selectors: table tbody tr td Avoid redundant ancestors: body section article ( body never needed) Avoid universal (*) selectors: body * Avoid tag selectors as the key (right-most): ul li Avoid child or adjacent selectors: ul > li > a Avoid overly qualified selectors: form#UserLogin ( # is already specific) Make your rules as specific as possible (class or id). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8640692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015609/']} | jdg_77724 |
stackexchange | llm_judgeable_groundtruth_similarity | 8265612 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here im giving my code for google map view, this is not working if i simulate it will comes Force close error, any body healp me ,im giving my log cat details also... 1.gmap activity class package net.gmaps; import android.os.Bundle; import com.google.android.maps.MapActivity; public class GoogleMapsActivity extends MapActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); MapView mv = (MapView) findViewById(R.id.mapView); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } } 2.main.xml file <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <com.google.android.maps.MapView android:id="@+id/mapView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:enabled="true" android:clickable="true" android:apiKey="0jEK9Odr895XgKEM5xr-nCr6stwV9dUquFVdsWg" /> </RelativeLayout> 3.android manifest file <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.gmaps" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" /> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <uses-library android:name="com.google.android.maps"/> <activity android:label="@string/app_name" android:name=".GoogleMapsActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest> 4.my Logcat details 11-30 12:28:45.996: D/AndroidRuntime(306): Shutting down VM11-30 12:28:45.996: W/dalvikvm(306): threadid=3: thread exiting with uncaught exception (group=0x4001b188)11-30 12:28:45.996: E/AndroidRuntime(306): Uncaught handler: thread main exiting due to uncaught exception11-30 12:28:46.035: E/AndroidRuntime(306): java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation11-30 12:28:46.035: E/AndroidRuntime(306): at dalvik.system.DexFile.defineClass(Native Method)11-30 12:28:46.035: E/AndroidRuntime(306): at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:209)11-30 12:28:46.035: E/AndroidRuntime(306): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:203)11-30 12:28:46.035: E/AndroidRuntime(306): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)11-30 12:28:46.035: E/AndroidRuntime(306): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)11-30 12:28:46.035: E/AndroidRuntime(306): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)11-30 12:28:46.035: E/AndroidRuntime(306): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)11-30 12:28:46.035: E/AndroidRuntime(306): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)11-30 12:28:46.035: E/AndroidRuntime(306): at android.app.ActivityThread.access$2200(ActivityThread.java:119)11-30 12:28:46.035: E/AndroidRuntime(306): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)11-30 12:28:46.035: E/AndroidRuntime(306): at android.os.Handler.dispatchMessage(Handler.java:99)11-30 12:28:46.035: E/AndroidRuntime(306): at android.os.Looper.loop(Looper.java:123)11-30 12:28:46.035: E/AndroidRuntime(306): at android.app.ActivityThread.main(ActivityThread.java:4363)11-30 12:28:46.035: E/AndroidRuntime(306): at java.lang.reflect.Method.invokeNative(Native Method)11-30 12:28:46.035: E/AndroidRuntime(306): at java.lang.reflect.Method.invoke(Method.java:521)11-30 12:28:46.035: E/AndroidRuntime(306): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)11-30 12:28:46.035: E/AndroidRuntime(306): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)11-30 12:28:46.035: E/AndroidRuntime(306): at dalvik.system.NativeStart.main(Native Method)11-30 12:28:46.085: I/dalvikvm(306): threadid=7: reacting to signal 311-30 12:28:46.265: I/dalvikvm(306): Wrote stack trace to '/data/anr/traces.txt'
Now provide the response and nothing else.
| The new C++ standard has the std::unordered_map type which is a hash table . IIRC they wanted it to get into the previous standard as well, but there was not enough time during the discussions so it was left out. However, most popular compilers provided it in one way or another for years. In other words, don't worry about it too much. Use the proper data structure for the task at hand. As for your understanding of hash tables, it's inaccurate: I haven't heard of a hash function that dynamically adjust its table size as problem size grows All serious hash table implementation dynamically adjust themselves for growing input, by allocating a larger array and re-hashing all the keys. Although this operation is expensive, if designed properly (to be done rarely enough) the performance is still amortized O(1). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8265612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1059247/']} | jdg_77725 |
stackexchange | llm_judgeable_groundtruth_similarity | 565334 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are using Spring for my application purposes, and Spring Testing framework for unit tests. We have a small problem though: the application code loads a Spring application context from a list of locations (XML files) in the classpath. But when we run our unit tests, we want some of the Spring beans to be mocks instead of full-fledged implementation classes. Moreover, for some unit tests we want some beans to become mocks, while for other unit tests we want other beans to become mocks, as we are testing different layers of the application. All this means I want to redefine specific beans of the application context and refresh the context when desired. While doing this, I want to redefine only a small portion of the beans located in one (or several) original XML beans definition file. I cannot find an easy way to do it. It's always regarded that Spring is a unit-testing-friendly framework, so I must be missing something here. Do you have any ideas how to do it? Thanks!
Now provide the response and nothing else.
| I would propose a custom TestClass and some easy rules for the locations of the spring bean.xml: @RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath*:spring/*.xml", "classpath*:spring/persistence/*.xml", "classpath*:spring/mock/*.xml"})@Transactional@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class, DirtiesContextTestExecutionListener.class})public abstract class AbstractHibernateTests implements ApplicationContextAware { /** * Logger for Subclasses. */ protected final Logger log = LoggerFactory.getLogger(getClass()); /** * The {@link ApplicationContext} that was injected into this test instance * via {@link #setApplicationContext(ApplicationContext)}. */ protected ApplicationContext applicationContext; /** * Set the {@link ApplicationContext} to be used by this test instance, * provided via {@link ApplicationContextAware} semantics. */ @Override public final void setApplicationContext( final ApplicationContext applicationContext) { this.applicationContext = applicationContext; }} If there are mock-bean.xml in the specified location, they will override all "real" bean.xml files in the "normal" locations - your normal locations might differ. But … I would never mix mock and non-mock beans, as it's hard to trace problems when the application grows older. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/565334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62346/']} | jdg_77726 |
stackexchange | llm_judgeable_groundtruth_similarity | 50183 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
This question stems from the paper "Computably categorical fields via Fermat's Last Theorem," by Russell Miller and Hans Schoutens (available online at http://qcpages.qc.cuny.edu/~rmiller/Fermat.pdf ). In this paper, they construct a field $F$ by starting with the field $\mathbb{Q}(x_0, x_1, x_2, . . .)$ of infinite transcendence degree over $\mathbb{Q}$, and then adjoining elements $y_i$ such that $(x_i, y_i)$ is a solution to the polynomial $X_i^{p_i}+Y_i^{p_i}=1$ for some odd prime $p_i$ (see paragraph 2, page 3); they then show that the resulting field has interesting computability-theoretic properties. In particular, they show that this field is computably categorical (i.e., any two computable presentations are computably isomorphic). I have only started reading this paper, but I have two questions, a simple one and a probably not-so-simple one: Question 1: It is unclear to me exactly how much of Fermat's Last Theorem (FLT) is required for this paper, but certainly we need at least the existence of infinitely many primes $p$ such that $X^p+Y^p=1$ has no nontrivial rational solutions. How difficult is this fact to prove? (And, historically, when was it first known?) Question 2: How much of FLT is actually required for the paper? I would be very interested if full FLT was required; although, as the authors point out, there has been at least one previous attempt made to prove the same result that apparently did not rely on FLT. Thank you very much in advance, Noah S
Now provide the response and nothing else.
| Actually, I am harder-pressed to say anything the supposedly simpler question. For Question 1, I would just add that we need the existence of an infinite computably enumerable set of primes satisfying FLT, and that this ought to suffice. (Since the set P of primes NOT satisfying FLT is obviously $\exists$-definable and hence c.e., another way to say this is that we need to show that P is not a simple set.) I would not have guessed that any odd prime was known to satisfy FLT, up until Wiles's proof, but I'm ready to be corrected on that. For Question 2, I do think that one could come up with a proof avoiding FLT entirely. I can't do so myself; I'm in computability, and when I was thinking about computable categoricity for fields of infinite transcendence, I realized that we needed multivariable polynomials with known finite numbers of rational solutions, and I thought of the Fermat polynomials because I didn't know any other candidates. (Of course, this condition was not all that was needed, but clearly it's necessary.) I'm still a computability theorist, and I still don't know any other candidates, but field theorists have told me that they could come up with other such polynomials fairly readily. Whether those would satisfy the more difficult requirements (basically Theorem 3.1 in the paper) is not so clear, but I suspect that it can be done with other polynomials. Bjorn Poonen suggested at one point that the Fermat polynomials were actually a bad choice, because their symmetry creates an extra solution whenever one adds a single transcendental solution to the field. As a related question: is there a computably stable field of infinite transcendence degree? A computable structure $\mathcal{A}$ is computably stable if, for every computable structure $\mathcal{B}$, every isomorphism from $\mathcal{A}$ onto $\mathcal{B}$ is computable. (Example: $\mathbb{Z}$ under the successor function.) A common way to build computably stable structures is to make them computably categorical and rigid, i.e. with no nontrivial automorphisms, so that the isomorphism from $\mathcal{A}$ onto any computable copy must be unique (by rigidity), hence computable (by categoricity). I would conjecture that it is possible to mimic the construction in the Fermat paper, with different polynomials, and to get a computably stable field of infinite transcendence degree, but I certainly don't know offhand what polynomials one might use. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/50183', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8133/']} | jdg_77727 |
stackexchange | llm_judgeable_groundtruth_similarity | 5491791 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hey, im trying to add an annotation on my map. How can i do it? Heres my code: - (void)abreMapa:(NSString *)endereco {NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", [endereco stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];NSArray *listItems = [locationString componentsSeparatedByString:@","];double latitude = 0.0;double longitude = 0.0;if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) { latitude = [[listItems objectAtIndex:2] doubleValue]; longitude = [[listItems objectAtIndex:3] doubleValue];}else { //Show error}CLLocationCoordinate2D coordinate;coordinate.latitude = latitude;coordinate.longitude = longitude;myMap.region = MKCoordinateRegionMakeWithDistance(coordinate, 2000, 2000);[self.view addSubview:mapa]; } Thanks!
Now provide the response and nothing else.
| Since MKAnnotation is a protocol, you'll have to define your own class that implements the protocol. For example, @interface SPAnnotation : NSObject <MKAnnotation> { CLLocationCoordinate2D coordinate;}@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate; If you have a latitude, longitude for the location you'd like to map: SPAnnotation *annotation = [[Annotation alloc] initWithCoordinate:CLLocationCoordinate2DMake(latitude, longitude)];[myMap addAnnotation:annotation]; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5491791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/486509/']} | jdg_77728 |
stackexchange | llm_judgeable_groundtruth_similarity | 3701025 |
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 key difference between memcpy() and memmove() is that memmove() will work fine when source and destination overlap. When buffers surely don't overlap memcpy() is preferable since it's potentially faster. What bothers me is this potentially . Is it a microoptimization or are there real significant examples when memcpy() is faster so that we really need to use memcpy() and not stick to memmove() everywhere?
Now provide the response and nothing else.
| At best, calling memcpy rather than memmove will save a pointer comparison and a conditional branch. For a large copy, this is completely insignificant. If you are doing many small copies, then it might be worth measuring the difference; that is the only way you can tell whether it's significant or not. It is definitely a microoptimisation, but that doesn't mean you shouldn't use memcpy when you can easily prove that it is safe. Premature pessimisation is the root of much evil. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3701025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57428/']} | jdg_77729 |
stackexchange | llm_judgeable_groundtruth_similarity | 42054451 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I do global average pooling in TensorFlow? If I have a tensor of shape batch_size, height, width, channels = 32, 11, 40, 100 , is it enough to just use tf.layers.average_pooling2d(x, [11, 40], [11, 40]) as long as channels = classes?
Now provide the response and nothing else.
| You could also do tf.reduce_mean(x, axis=[1,2]) , specially if your height and width are not defined. Typically, in a CNN, tensors have a shape of b, h, w, c where b is the batch size, w and h correspond to the width and height dimensions, and c is the number of channels/filters. When you reduce along the axis [1,2] , you reduce on the first and second dimensions of the tensor (keeping the batch size, and the number of channels/filters) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42054451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7287271/']} | jdg_77730 |
stackexchange | llm_judgeable_groundtruth_similarity | 20919998 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I use a header location in jQuery for redirection or refresh? Like in PHP: header('location:www.google.co.in');header("Refresh:1,url=home.php"); If not, what is the alternative way?
Now provide the response and nothing else.
| Headers are interpreted prior to the rendering of the document, and before jQuery is even loaded so these aren't an option. Instead, you can redirect the browser using document.location . document.location.href = 'www.google.co.in'; For a jQuery approach you can use $(location).attr('href', 'www.google.co.in'); however I would favor the plain javascript version. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20919998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3115085/']} | jdg_77731 |
stackexchange | llm_judgeable_groundtruth_similarity | 86954 |
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:
So I understand the idea that the decision problem is defined as Is there a path P such that the cost is lower than C? and you can easily check this is true by verifying a path you receive. However, what if there is no path that fits this criteria? How would you verify the answer of "no" without solving the best path TSP problem, and finding out the best one has a worse cost than C?
Now provide the response and nothing else.
| NP is the class of problems where you can verify "yes" instances. No guarantee is given that you can verify "no" instances. The class of problems where you can verify "no" instances in polynomial time is co-NP . Any language in co-NP is the complement of some language in NP , and vice-versa. Examples include things like non-3-colourability. The problem you describe, "Is there no TSP path with length at most $C$?" is also in co-NP : if you unpick the double-negation, a "no" instance to that problem is a "yes" instance to TSP and we can verify those in polynomial time. There are some problems, such as integer factorization and any problem in P , that we know to be in both NP and co-NP . (Thanks to user21820 for pointing this out.) It's not known whether NP and co-NP are the same set of problems. If they're the same, then we can verify both "yes" and "no" instances of TSP. If they're different, then P$\,\neq\,$NP , since we know that P$\,=\,$co-P (because we can just negate the answer of a deterministic machine, giving the answer to the complement problem). | {} | {'log_upvote_score': 6, 'links': ['https://cs.stackexchange.com/questions/86954', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/81348/']} | jdg_77732 |
stackexchange | llm_judgeable_groundtruth_similarity | 37797908 |
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 write a program for a simple calculator that just adds two numbers and shows it in a JLabel . I have managed to design a working Window, Button, etc. But if I click the Button the Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException - Error happens and I don´t know how to solve it. Here is the code : import java.awt.EventQueue;public class Rechnerwin {private JFrame frame;private JTextField textFielda;private JTextField textFieldb;private JLabel label;int A;int B;int C;String a;String b;String c;public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Rechnerwin window = new Rechnerwin(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }public Rechnerwin() { initialize();}private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); textFielda = new JTextField(); textFielda.setBounds(44, 41, 86, 20); frame.getContentPane().add(textFielda); textFielda.setColumns(10); textFieldb = new JTextField(); textFieldb.setBounds(307, 41, 86, 20); frame.getContentPane().add(textFieldb); textFieldb.setColumns(10); JButton btnAdd = new JButton("Add"); btnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String a = textFielda.getText(); String b = textFieldb.getText(); int A = Integer.parseInt(a); int B = Integer.parseInt(b); int C = A + B; String c = Integer.toString(C); label.setText(c); } }); btnAdd.setBounds(169, 85, 89, 23); frame.getContentPane().add(btnAdd); JLabel label = new JLabel("a"); label.setBounds(146, 184, 131, 20); frame.getContentPane().add(label); }}
Now provide the response and nothing else.
| If you are saying that you want moment to display your date and time (which is UTC, as indicated by the 'Z'), exactly as is, you should use moment.utc: moment.utc('2016-06-03T04:00:00.000Z').format()"2016-06-03T04:00:00Z" When you use the default moment constructor, as you are now, you are telling moment to convert your UTC time to local time, and this is why you are seeing a time difference. For instance, on my local machine (I am currently UTC-5) I get the following: moment('2016-06-03T04:00:00.000Z').format()"2016-06-02T23:00:00-05:00" This question comes up quite a lot, so I wrote this blog post that explains moment's constructor functions and how it converts ISO8601 dates in detail: https://maggiepint.com/2016/05/14/moment-js-shows-the-wrong-date/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37797908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6461327/']} | jdg_77733 |
stackexchange | llm_judgeable_groundtruth_similarity | 13334 |
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm just starting out. How could I use my Raspberry Pi to do the following: when any movement is detected at my front door, send me a text message (SMS)?
Now provide the response and nothing else.
| My answer is in two parts, one for motion detection and another for SMS. A project like this has two components: hardware and software. Detecting motion is the hardware part and everything else is software. Motion Hardware To detect movement, get a motion sensor. I use the Parallax PIR Motion Sensor: Amazon affiliate link here. The sensor has 3 pins: GND, VCC and OUT. Connect the pins to your RPi or connect them to a breadboard and connect the pins from the RPi to the same breadboard. Connect GND to a GND pin (6), VCC to a 3.3v pin (1) and OUT to GPIO0 (11). Software I recommend you use the WiringPi library. Follow these instructions to download and install the library on your Pi: Wiring Pi Library Download and Install . The pin on the motion sensor reads High if motion is detected and Low if it's not. The motion detector resets itself after about 10 seconds when continuous motion ends. So the pin could fire many times in response to a single motion. To avoid getting SMS messages every few seconds, you probably want to include logic in your program to wait a certain amount of time before sending another SMS. SMS There are a few different ways you can do this. One way is to subscribe to a paid service that provides a library you can call with the pertinent information to send the SMS. Twilio API Libraries is a good example of this. If you don't want to spend any money and you have a Google Voice number connected to your cellphone, you can use the Google Voice C++ API that Steven Hickson developed for the RPi ( Google Voice C++ API ). The end result might look something like this (I wrote it but did not load and test it on the RPi): #include <wiringPi.h>#include <time.h>#include <string.h>#include "gvoice.h"int sendSMS(void);#define MOTION_PIN 0#define MINUTES_TO_WAIT 5// some made-up error codes for SMS result#define SUCCESS 0#define LOGIN_ERROR 1#define SMS_ERROR 2static char *number = "2125551212", *message = "Motion detected!";int main(int argc, char** argv) { time_t lastSent, now; int result; // track the time we sent the last SMS lastSent = time(NULL) - 60*(MINUTES_TO_WAIT + 1) // set up motion pin wiringPiSetup(); pinMode(MOTION_PIN, INPUT); while (true) { if (digitalRead(MOTION_PIN)==HIGH) { // motion detected // get the current time time(&now); // if we've waited long enough, send a message if (difftime(now, lastSent)/60) > MINUTES_TO_WAIT) { if (result = sendSMS()) { print("Message sent!\n"); lastSent = now; } else { printf("Error %d. Message not sent!\n", result); } } } }}int sendSMS(void) { // Uses the Google Voice C++ API by Steven Hickson GoogleVoice gv; char *username = "username", *password = "password"; if (gv.Login(username, password)) { if (gv.SendSMS(number, message)) { return SUCCESS; } else { return SMS_ERROR; } } else { return LOGIN_ERROR; }} | {} | {'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/13334', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/12326/']} | jdg_77734 |
stackexchange | llm_judgeable_groundtruth_similarity | 38842507 |
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 implementing scheduled tasks using Spring, and I see there are two types of config options for time that schedule work again from the last call. What is the difference between these two types? @Scheduled(fixedDelay = 5000) public void doJobDelay() { // do anything } @Scheduled(fixedRate = 5000) public void doJobRate() { // do anything }
Now provide the response and nothing else.
| fixedRate : makes Spring run the task on periodic intervals even if thelast invocation may still be running. fixedDelay : specifically controls the next execution time when thelast execution finishes. In code: @Scheduled(fixedDelay=5000)public void updateEmployeeInventory(){ System.out.println("employee inventory will be updated once only the last updated finished "); /** * add your scheduled job logic here */}@Scheduled(fixedRate=5000)public void updateEmployeeInventory(){ System.out.println("employee inventory will be updated every 5 seconds from prior updated has stared, regardless it is finished or not"); /** * add your scheduled job logic here */} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38842507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5694338/']} | jdg_77735 |
stackexchange | llm_judgeable_groundtruth_similarity | 24883 |
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Genesis, we read the infamous story of Joseph and Potiphar's wife. Potiphar's wife (who is named Zuleikha, at least according Sefer HaYashar) repeatedly makes sexual advances on Joseph, and as we know, Joseph consistently stays true to his morals (not to mention loyalty to Potiphar) and staunchly refuses (even resulting to running away)! I've always wondered why Zuleikha would make more than one attempt after she is clearly rejected, and why she should would be so "desperate." But it occurred to me, that possibly Potiphar was a eunuch. In ancient Egypt, court officials were often castrated so that the authoritative powers knew that their "second in commands" were not a threat to their women. Do you think this is a likely scenario for Potiphar? And Zuleikha wasn't being satisfied by her husband physically? (By no means, am I giving her an excuse for her lewd behavior, but it may help me better understand the historical context). Do you think this is a viable possibility?
Now provide the response and nothing else.
| The word used to describe Potiphar's relationship with Pharaoh (37:36, 39:1) is sārı̂s , which is indeed commonly glossed "eunuch" (e.g. BDB ; cf. LXX εὐνοῦχος). However, to my knowledge no major English translation, including the KJV, translates it thus in this pericope (rather "officer" or "official"). There are several reasons for this, but perhaps the most obvious: what is a eunuch doing with a wife? Modern lexicons agree that the word sārı̂s has a two distinct meanings in Biblical Hebrew that reflect a diachronic shift in usage: court official, royal steward (preexilic); eunuch = royal steward, harem guard (exilic and post exilic).* The use of sārı̂s in the Joseph story — which includes not only Potiphar but also the chief cupbearer and chief baker with whom Joseph is later imprisoned — falls into the first category. Gordon Johnston discusses the application of the term to Potiphar and points out: research has failed to turn up any evidence for the use of eunuchs as officials in Egypt.* He further notes: Although later uses of סָרִיס designate eunuchs, neither the original [Akkadian] etymology nor the Egyptian usage of the term had any connotation of sexual impotence. *Gordon H. Johnston, "סריס", New International Dictionary of Old Testament Theology and Exegesis , (Zondervan, 1997) 3:289-290. | {} | {'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/24883', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/15877/']} | jdg_77736 |
stackexchange | llm_judgeable_groundtruth_similarity | 5795263 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I get content of an exe file and convert it into Base64 encoding ? Edit I use D2010 and I want to know how is it possible exactly ? open an exe file convert its content into base64
Now provide the response and nothing else.
| In Delphi 2009/2010/XE there is unit EncdDecd.pas ( Soap.EncdDecd.pas for Delphi XE2) containing the functions EncodeBase64 and DecodeBase64 . You can load the exe file into a memorystream and then call EncodeBase64. function EncodeFile(const FileName: string): AnsiString;var stream: TMemoryStream;begin stream := TMemoryStream.Create; try stream.LoadFromFile(Filename); result := EncodeBase64(stream.Memory, stream.Size); finally stream.Free; end;end; | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5795263', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/381979/']} | jdg_77737 |
stackexchange | llm_judgeable_groundtruth_similarity | 21333474 |
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 my PHP script I need to create an array of >600k integers. Unfortunately my webservers memory_limit is set to 32M so when initializing the array the script aborts with message Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 71 bytes) in /home/www/myaccount/html/mem_test.php on line 8 I am aware of the fact, that PHP does not store the array values as plain integers, but rather as zvalues which are much bigger than the plain integer value (8 bytes on my 64-bit system). I wrote a small script to estimate how much memory each array entry uses and it turns out, that it's pretty exactly 128 bytes. 128!!! I'd need >73M just to store the array. Unfortunately the webserver is not under my control so I cannot increase the memory_limit . My question is, is there any possibility in PHP to create an array-like structure that uses less memory. I don't need this structure to be associative (plain index-access is sufficient). It also does not need to have dynamic resizing - I know exactly how big the array will be. Also, all elements would be of the same type. Just like a good old C-array. Edit: So deceze 's solution works out-of-the-box with 32-bit integers. But even if you're on a 64-bit system, pack() does not seem to support 64-bit integers. In order to use 64-bit integers in my array I applied some bit-manipulation. Perhaps the below snippets will be of help for someone: function push_back(&$storage, $value){ // split the 64-bit value into two 32-bit chunks, then pass these to pack(). $storage .= pack('ll', ($value>>32), $value);}function get(&$storage, $idx){ // read two 32-bit chunks from $storage and glue them back together. return (current(unpack('l', substr($storage, $idx * 8, 4)))<<32 | current(unpack('l', substr($storage, $idx * 8+4, 4))));}
Now provide the response and nothing else.
| The most memory efficient you'll get is probably by storing everything in a string, packed in binary, and use manual indexing to it. $storage = '';$storage .= pack('l', 42);// ...// get 10th entry$int = current(unpack('l', substr($storage, 9 * 4, 4))); This can be feasible if the "array" initialisation can be done in one fell swoop and you're just reading from the structure. If you need a lot of appending to the string, this becomes extremely inefficient. Even this can be done using a resource handle though: $storage = fopen('php://memory', 'r+');fwrite($storage, pack('l', 42));... This is very efficient. You can then read this buffer back into a variable and use it as string, or you can continue to work with the resource and fseek . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21333474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/867161/']} | jdg_77738 |
stackexchange | llm_judgeable_groundtruth_similarity | 10511779 |
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 how currying works in functional programming. I have gone through wiki and a couple of questions about the same on SO. Need help understanding lambda (currying) What is 'Currying'? I understand that currying is all about splitting a function that takes n arguments into n or less functions with one argument each. I theoretically comprehend it but I am not able to connect the dots while coding for the same. Perhaps it is my lack of knowledge in functional programming languages or C# (as many answers in the above questions deal with). Anyway, I understand groovy & java. So I tried to get an outline for the standard add(a,b) function in groovy but I couldn't finish it. def closure = { arg -> // ??}def add(anotherClosure , a){ return closure // ??} Can someone help me understand currying using groovy closures?
Now provide the response and nothing else.
| You can roll your own currying functionality by writing a closure that takes another closure and a curried parameter to set, and returns a closure that uses this value. // Our closure that takes 2 parameters and returns a Stringdef greet = { greeting, person -> "$greeting $person" }// This takes a closure and a default parameter// And returns another closure that only requires the// missing parameterdef currier = { fn, param -> { person -> fn( param, person ) }}// We can then call our currying closuredef hi = currier( greet, 'Hi' )// And test it outhi( 'Vamsi' ) But you're better sticking with the inbuilt Groovy curry method as shown by jalopaba . (there is also rcurry and ncurry which curry from the right, and at a given position respectively) It should be said, that the Groovy curry method is a misnomer as it is more a case of partial application as you do not need to get down to a closure requiring only a single parameter, ie: def addAndTimes = { a, b, c -> ( a + b ) * c }println addAndTimes( 1, 2, 3 ) // 9def partial = addAndTimes.curry( 1 )println partial( 2, 3 ) // 9 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10511779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/619361/']} | jdg_77739 |
stackexchange | llm_judgeable_groundtruth_similarity | 8236 |
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 figure out the size of a file, in bytes? #include <stdio.h>unsigned int fsize(char* file){ //what goes here?}
Now provide the response and nothing else.
| On Unix-like systems, you can use POSIX system calls: stat on a path , or fstat on an already-open file descriptor (POSIX man page , Linux man page ). (Get a file descriptor from open(2) , or fileno(FILE*) on a stdio stream). Based on NilObject's code: #include <sys/stat.h>#include <sys/types.h>off_t fsize(const char *filename) { struct stat st; if (stat(filename, &st) == 0) return st.st_size; return -1; } Changes: Made the filename argument a const char . Corrected the struct stat definition, which was missing the variable name. Returns -1 on error instead of 0 , which would be ambiguous for an empty file. off_t is a signed type so this is possible. If you want fsize() to print a message on error, you can use this: #include <sys/stat.h>#include <sys/types.h>#include <string.h>#include <stdio.h>#include <errno.h>off_t fsize(const char *filename) { struct stat st; if (stat(filename, &st) == 0) return st.st_size; fprintf(stderr, "Cannot determine size of %s: %s\n", filename, strerror(errno)); return -1;} On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64 , otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432/']} | jdg_77740 |
Subsets and Splits