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
203550
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm running a LAMP server on Fedora 13 that's working fine; however, I just added an ".htaccess" file to my current site's docroot folder that is being completely ignored. I've tried half a dozen different tests, including this one: RewriteEngine onRewriteBase /RewriteRule ^.*$ index.php But images and all other pages load fine, and non-existent files still 404. I also tried this: order deny,allowdeny from all But every page still loads just fine. Again the .htaccess file is simply ignored 100%. We put our virtualhost records in /etc/httpd/conf.d/virtual.conf. It looks like this: NameVirtualHost *<VirtualHost *> ServerName intranet DocumentRoot /var/www/default <Directory "/var/www/default"> Options FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory></VirtualHost><VirtualHost *> ServerName ourwebsite.com DocumentRoot /var/www/html/ourwebsite.com/docroot <Directory "/var/www/html/ourwebsite.com/docroot"> Options FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory></VirtualHost> What else could be causing our server to completely IGNORE the .htaccess file?? Edit: I changed the .htaccess file to above to better demonstrate that my changes are being ignored. Note that I tried the exact same .htaccess file on the production server and it worked fine. Edit 2: OK, I have new information! Just for testing purposes, I went through and temporarily changed EVERY "AllowOverride" directive to AllowOverride All . I figured out that the very first Directory entry seems to overpower all others: <Directory /> Options FollowSymLinks AllowOverride None</Directory> When I changed that to AllowOverride All , my .htaccess files begin taking effect. It's like all the other AllowOverride All directives in my config files are being ignored! What Gives?? Now provide the response and nothing else.
Unbelievable. Remember how I said this is a development server? Yeah.. well here's what my virtual host entry REALLY looks like: <VirtualHost *> ServerName dev.ourwebsite.com DocumentRoot /var/www/html/dev.ourwebsite.com/docroot <Directory "/var/www/html/ourwebsite.com/docroot"> Options FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory></VirtualHost> Do you see it? Well I didn't. I FORGOT To change my "Directory" entry to dev.ourwebsite.com instead of ourwebsite.com -- and that made all the difference. I just assumed that Apache would have thrown an error if the directory didn't exist; but that only applies to the DocumentRoot directive. is match-based -- meaning it applies the rules if it matches the incoming request, but otherwise, it doesn't care if you tell it to AllowOverride on magic unicorns. Let this be a lesson to any others who come looking -- when all else fails, consider the almighty Typo.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/203550', 'https://serverfault.com', 'https://serverfault.com/users/34350/']}
jdg_75841
stackexchange
llm_judgeable_groundtruth_similarity
17725821
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First of all i have check this answer . What i am trying to do is extending Location class calling it LocationPlus which has some member variables. functionality i am trying to achieve is pass the object of LocationPlus class from one activity to another. Here is my CREATOR public static final Parcelable.Creator<LocationPlus> CREATOR = new Parcelable.Creator<LocationPlus>() { @Override public LocationPlus createFromParcel(Parcel source) { return new LocationPlus(source); } @Override public LocationPlus[] newArray(int size) { return new LocationPlus[size]; }}; problem i am facing is this error Implicit super constructor Location() is undefined. Must explicitly invoke another constructor when trying to write constructor public LocationPlus(Parcel in) { Someone in comment ask me to post LocationPlus class so here it is public class LocationPlus extends Location{ private int mBattery = -1; public LocationPlus(String locationName) { super(locationName); } public LocationPlus(Location location) { super(location); } public int getmBattery() { return mBattery; } public void setmBattery(int mBattery) { this.mBattery = mBattery; } @Override public int describeContents() { return 0; } public static final Parcelable.Creator<LocationPlus> CREATOR = new Parcelable.Creator<LocationPlus>() { @Override public LocationPlus createFromParcel(Parcel source) { return new LocationPlus(source); } @Override public LocationPlus[] newArray(int size) { return new LocationPlus[size]; } }; @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(mBattery); } public LocationPlus(Parcel in) { mBattery =in.readInt(); }} Now provide the response and nothing else.
Parcelable, the Speed King According to google engineers , this code will run significantly faster. One of the reasons for this is that we are being explicit about the serialization process instead of using reflection to infer it. It also stands to reason that the code has been heavily optimized for this purpose. public abstract class BaseClass implements Parcelable { public String FullName; public boolean IsValidUser; public String UserName; public BaseClass () { } protected BaseClass(Parcel in) { FullName = in.readString(); IsValidUser = in.readByte() != 0; UserName = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(FullName); dest.writeByte((byte) (IsValidUser ? 1 : 0)); dest.writeString(UserName); }} Child class will be as follows with usage of list adding into parcelable object: public class DerivedClass extends BaseClass { public boolean IsSuccess; public String Message; public List<AnotherClass> AnotherClassObj; public DerivedClass () { super(); } protected DerivedClass(Parcel in) { super(in); AnotherClassObj = new ArrayList<AnotherClass>(); IsSuccess = in.readByte() != 0; Message = in.readString(); AnotherClassObj = in.readArrayList(AnotherClass.class.getClassLoader()); } public static final Creator<DerivedClass> CREATOR = new Creator<DerivedClass>() { @Override public DerivedClass createFromParcel(Parcel in) { return new DerivedClass(in); } @Override public DerivedClass[] newArray(int size) { return new DerivedClass[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeByte((byte) (IsSuccess ? 1 : 0)); dest.writeString(Message); dest.writeList(AnotherClassObj); } public int describeContents() { return 0; }} Another child class : public class AnotherClass extends BaseClass { public AnotherClass() { super(); } protected AnotherClass(Parcel in) { super(in); } public int describeContents() { return 0; } public static final Creator<AnotherClass> CREATOR = new Creator<AnotherClass>() { @Override public AnotherClass createFromParcel(Parcel in) { return new AnotherClass(in); } @Override public AnotherClass[] newArray(int size) { return new AnotherClass[size]; } }; @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); }} In Activity : Intent intent = new Intent(LoginActivity.this, MainActivity.class); intent.putExtra("UserObject", parcelableObject); startActivity(intent); finish(); In receiving activity: Bundle extras = getIntent().getExtras(); if (extras != null) { userObject = extras.getParcelable("UserObject"); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17725821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/932225/']}
jdg_75842
stackexchange
llm_judgeable_groundtruth_similarity
41695283
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any algorithm to calculate (1^x + 2^x + 3^x + ... + n^x) mod 1000000007 ? Note: a^b is the b-th power of a. The constraints are 1 <= n <= 10^16, 1 <= x <= 1000 . So the value of N is very large. I can only solve for O(m log m) if m = 1000000007 . It is very slow because the time limit is 2 secs. Do you have any efficient algorithm? There was a comment that it might be duplicate of this question , but it is definitely different. Now provide the response and nothing else.
You can sum up the series 1**X + 2**X + ... + N**X with the help of Faulhaber's formula and you'll get a polynomial with an X + 1 power to compute for arbitrary N . If you don't want to compute Bernoulli Numbers , you can find the the polynomial by solving X + 2 linear equations (for N = 1, N = 2, N = 3, ..., N = X + 2 ) which is a slower method but easier to implement. Let's have an example for X = 2 . In this case we have an X + 1 = 3 order polynomial: A*N**3 + B*N**2 + C*N + D The linear equations are A + B + C + D = 1 = 1 A*8 + B*4 + C*2 + D = 1 + 4 = 5 A*27 + B*9 + C*3 + D = 1 + 4 + 9 = 14 A*64 + B*16 + C*4 + D = 1 + 4 + 9 + 16 = 30 Having solved the equations we'll get A = 1/3 B = 1/2 C = 1/6 D = 0 The final formula is 1**2 + 2**2 + ... + N**2 == N**3 / 3 + N**2 / 2 + N / 6 Now, all you have to do is to put an arbitrary large N into the formula. So far the algorithm has O(X**2) complexity (since it doesn't depend on N ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41695283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7215982/']}
jdg_75843
stackexchange
llm_judgeable_groundtruth_similarity
284788
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 was watching the said movie the other night, and I started thinking about the equation posed by Nash in the movie. More specifically, the one he said would take some students a lifetime to solve (obviously, an exaggeration). Nonetheless, one can't say it's a simple problem. Anyway, here it is $$V = \{F:\mathbb{R^3}/X\rightarrow \mathbb{R^3} \text{ so } \hspace{1mm}\nabla \times F=0\}$$$$W = \{F = \nabla g\}$$$$\dim(V/W) = \; 8$$ I haven't actually attempted a solution myself to be honest, but I thought it would be an interesting question to pose. I have done a quick search on this site and Google, but there were surprisingly few results. In any case, I was curious if anyone knew the answer aside from the trivial. Now provide the response and nothing else.
The problem is to find a subset $X$ of $\mathbb{R}^3$ such that if $V$ is the vector space of vector fields $F$ on $\mathbb{R}^3$ \ $X$ with $\nabla\times F = 0$ and $W$ is the vector space of vector fields $F$ on $\mathbb{R}^3$ \ $X$ satisfying $F = \nabla g$ , for some function $g$ on $\mathbb{R}^3$ \ $X$ , then $V / W$ has dimension $8$ . If $F$ does equal $\nabla g$ , then the line integral of $F$ along a path will be independent of the path, so the line integral of $F$ around any closed curve must vanish. Suppose we take $X$ to be the (infinite) line $x=y=0$ . In this case the vector field $$F_0 = \left(\frac{−y}{(x^2 + y^2)},\ \frac{x}{(x^2 + y^2)},\ 0\right) $$ has vanishing curl on $\mathbb{R}^3$ \ $X$ but it does not satisfy $F_0 = \nabla g$ , as if we integrate $F$ counterclockwise around the unit circle in the $z=0$ plane, we will get $2\pi \neq 0$ . Now, given any vector field $F$ on $\mathbb{R}^3$ \ $X$ with $\nabla\times F = 0$ , we can make its line integral around the unit circle vanish by subtracting off some multiple of $F_0$ . I claim that this is enough to make $F = \nabla g$ . We can try to find a $g$ with $F = \nabla g$ by starting at some point $x_0$ not in $X$ and integrating $F$ along a path from $x_0$ to some other point not in $X$ , $x$ , say. $g(x)$ can then be set equal to the value of this integral. By Stokes's Theorem, we will get the same result integrating along a path $P$ as along a path $Q$ as long as the gap between $P$ and $Q$ can be filled in by a surface which avoids $X$ . Suppose we take $x_0 = (1,0,0)$ , and for each $x$ not in $X$ , we pick a reference path $P_x$ from $x_0$ to $x$ . Remaining inside $\mathbb{R}^3$ \ $X$ , we can continuously deform any path $P'_x$ from $x_0$ to $x$ into a path that: $(1)$ moves around the unit circle in either a counterclockwise or a clockwise direction a number of times, possibly zero and then $(2)$ goes along $P_x$ to $x$ . (This is because we are free to move the path around as we choose as long as we don't intersect the line $x=y=0$ .) Since the line integral of $F$ around the unit circle vanishes, this means that $F$ has the same integral along $P_x$ as along $P'_x$ . Hence the integral is independent of path and so $F = \nabla g$ . This means that for the linear map $L$ from $V$ to the real numbers given by integration around the unit circle, $\text{Ker}\ L = W$ . Therefore $V/W$ is isomorphic to the real numbers and so is $1$ -dimensional. In general, we will get one extra dimension of $V/W$ for each independent element of $X$ which stops us from continuously deforming paths into other paths. Placing a point or ball into $X$ will not increase the dimension of $V/W$ as we can simply move the paths around it. To get an example with $\text{dim} V/W = 8$ , we can take $X$ to be any set of $8$ non-intersecting lines, for example $$\{x=y=0\} \cup \{x=0,\ y=2\} \cup \{x=0,\ y=4\} \cup \ldots \cup \{x=0,\ y=14\}$$ In this case, for $i=0, \ldots, 7$ , we can define the vector field $F_i$ in $V$ to be $$F_i = \left(\frac{−(y−2i)}{(x^2 + (y−2i)^2)},\ \frac{x}{(x^2 + (y−2i)^2)},\ 0\right)$$ We can then define a linear map $L$ from $V$ to $\mathbb{R}^8$ by setting $$L(F) = (I_0(F), \ldots, I_7(F))$$ where $I_j(F)$ is the line integral of $F$ around the circle $\{x^2 + (y−2j)^2 = 1,\ z = 0\}$ , taken in the counterclockwise sense. We have $$I_j(F_i) = \begin{cases} 2\pi & i = j \\ 0 & i ≠ j \end{cases}$$ so $L$ is surjective, and clearly $\text{Ker}\ L \supseteq W$ . By an argument similar to the one in the last paragraph, we can prove that $\text{Ker}\ L \subseteq W$ . Hence $\text{Ker}\ L = W$ and so $L$ gives an isomorphism from $V/W$ to $\mathbb{R}^8$ . This problem is a special case of what is called de Rham cohomology , where people construct vector spaces of differential forms on a space in such a way that their dimension yields topological information about the space. $V/W$ has the name $H^1_{dR}(\mathbb R^3\setminus X)$ , the dimension $1$ de Rham cohomology group of $\mathbb R^3\setminus X$ . Its dimension gives the number of dimension $1$ holes in $\mathbb R^3\setminus X$ . We can also construct $H^0_{dR}(\mathbb R^3\setminus X)$ . This is the vector space of functions $f$ on $\mathbb R^3\setminus X$ such that $\nabla f = 0$ , i.e. $f$ is locally constant. Its dimension will equal the number of connected components of $\mathbb R^3\setminus X$ . Finally, we can construct $H^2_{dR}(\mathbb R^3\setminus X)$ . This will give the number of dimension $0$ holes in $\mathbb R^3\setminus X$ ; for example, if we take $X = \{0\}$ , then $H^2_{dR}(\mathbb R^3\setminus X)$ will have dimension $1$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/284788', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43045/']}
jdg_75844
stackexchange
llm_judgeable_groundtruth_similarity
13558522
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 receive UDP data that is broadcast to network address 192.168.103.255 port 3000 by PlayCap ( http://www.signal11.us/oss/playcap/ ). I'm having problems binding to this address and port. Here's my Java code: public static void main(String[] args) { try { DatagramSocket s = new DatagramSocket(); InetSocketAddress address = new InetSocketAddress("192.168.103.255", 3000); s.bind(address); byte buffer[] = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); System.out.println("Waiting..."); s.receive(packet); System.out.println("Received!"); } catch (Exception e) { e.printStackTrace(); }} This returns the error: java.net.SocketException: already bound at java.net.DatagramSocket.bind(Unknown Source) at runner.main(runner.java:12) I have run the command "netstat -a -n", and neither address 192.168.103.255 nor port 3000 are listed anywhere in the output, so I don't think this port is already in use. In fact, I get this error for any address/port combination I try (including my static IP address). I also wrote some C code to make a socket and bind to this address and port, but it also fails on the bind call. This code, however, will bind to ports on my static IP address (192.168.1.149). Here's that code: #include <stdio.h>#include <sys/types.h>#include <winsock.h>#include <unistd.h>#define a1 192#define a2 168#define a3 103#define a4 255#define PORT 3000int main() { /* Open windows connection */ WSADATA w; if (WSAStartup(0x0101, &w) != 0) { printf("Could not open Windows connection.\n"); exit(0); } /* Clear out server struct */ SOCKADDR_IN server; memset((void *)&server, '\0', sizeof(struct sockaddr_in)); /* Set family and port */ server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.S_un.S_un_b.s_b1 = (unsigned char)a1; server.sin_addr.S_un.S_un_b.s_b2 = (unsigned char)a2; server.sin_addr.S_un.S_un_b.s_b3 = (unsigned char)a3; server.sin_addr.S_un.S_un_b.s_b4 = (unsigned char)a4; /* Open a datagram socket */ int sd = socket(AF_INET, SOCK_DGRAM, 0); if (sd == INVALID_SOCKET) { printf("Could not create socket.\n"); WSACleanup(); exit(0); } /* Bind address to socket */ if (bind(sd, (struct sockaddr *)&server, sizeof(SOCKADDR_IN)) == -1) { printf("Could not bind name to socket.\n"); closesocket(sd); WSACleanup(); exit(0); } /* Receive */ char data[1024]; printf("Waiting to receive...\n"); if (recv(sd, (char *)&data, (int)sizeof(data), 0)) { printf("Error receiving data.\n"); closesocket(sd); WSACleanup(); exit(0); } printf("Data: %s", data); return 0;} I'm using a Windows 7 machine. I'm running the Java code in Eclipse. I'm compiling the C code with MinGW using the command: gcc a.c -lws2_32 ("a.c" is the file name). While the Java code is more important, I would be happy to know where I'm going wrong in either of my code examples. Any suggestions are very much appreciated. Now provide the response and nothing else.
Try this for your Java code instead: public static void main(String[] args) { try { DatagramSocket s = new DatagramSocket(null); InetSocketAddress address = new InetSocketAddress("192.168.103.255", 3000); s.bind(address); } catch (Exception e) { e.printStackTrace(); }} Calling the no-arg constructor for a datagram socket will cause it to bind to a random, available port. Once bound, further attempts to (re)bind will throw a socket exception (with the error you were seeing). To 'defer' binding, you instead create the datagram socket in an unbound state (by passing a null in the constructor), then calling bind later on.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13558522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1822907/']}
jdg_75845
stackexchange
llm_judgeable_groundtruth_similarity
21666874
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 Mockito there is option to verify if mock method has been called, and specify timeout for this verification ( VerificationWithTimeout ), for example: verify(mock, timeout(200).atLeastOnce()).baz(); It there any equivalent to such functionality in Spock? Now provide the response and nothing else.
I was trying to use PollingConditions to satisfy a similar scenario (which wasn't helpful), but instead found satisfaction in Spock's BlockingVariables . To verify that SomeService.method() is invoked at least once in function ClassBeingTested.method() within a given timeout period: def "verify an interaction happened at least once within 200ms"(){ given: def result = new BlockingVariable<Boolean>(0.2) // 200ms SomeService someServiceMock = Mock() someServiceMock.method() >> { result.set(true) } ClassBeingTested clazz = new ClassBeingTested(someService: someServiceMock) when: clazz.someMethod() then: result.get()} When the result is set, the blocking condition will be satisfied and result.get() would have to return true for the condition to pass. If it fails to be set within 200ms, the test will fail with a timeout exception.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21666874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3017003/']}
jdg_75846
stackexchange
llm_judgeable_groundtruth_similarity
18710325
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working with Twitter bootstrap on a Django site I'm making. I have a page where users can enter all of their technical skills in a text input equipped with a bootstrap typeahead. I'm trying to access the text within the currently selected within the dropdown menu, such that when ENTER is pressed and an element is highlighted in the dropdown, it takes that value and displays it below the input text field. Then the input text field is cleared and the user can search for another skill. $(document).keyup(function(event) { if (event.keyCode == 13) { if ($('.dropdown-menu').css('display') != 'none'){ var newskill = $(".dropdown-menu > li.active").val(); alert('Yay'); } else{ var newskill = $("#enterbox").val(); alert('Boo'); } return false; } }); If the dropdown is visible, then the enter keypress function takes the currently active element of the dropdown and pastes it into the text box (built in to Bootstrap). No alert box shows. Any idea how I can get my function to trigger before that happens, ie before Bootstrap's function kicks in? Now provide the response and nothing else.
Demo Instead of listening for a keypress (what if the user makes a selection with their mouse?), we can take advantage of the custom events Twitter's Typeahead emits. Namely, typeahead:selected – Triggered when a suggestion from the dropdown menu is explicitly selected. Capturing the selection You can listen for it using jQuery's .on() method, and you will be provided with information about the user's selection in the second argument. $('input.typeahead').on('typeahead:selected', function(event, selection) { alert(selection.value);}); Clearing the input field From there you can do as you like with the selection.value . The only "gotcha" would be trying to clear the input using .val() . Since Typeahead does quite a bit of fancy DOM rewriting, you'll need to use their 'setQuery' method as well. $('input.typeahead').typeahead('setQuery', '');
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18710325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1550155/']}
jdg_75847
stackexchange
llm_judgeable_groundtruth_similarity
22658908
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 I use nginx and php-fpm, I used Apache, so when I wanted only one of my cron jobs to run without time execution limitation, I used these lines in my PHP code: set_time_limit(0);ini_set('max_execution_time', 0); but after I migrated from Apache to nginx, this code doesn't work. I know ways to change nginx.conf to increase maximum execution time. But I want to handle this with php code. Is there a way?I want to specify only one file that can run PHP code without time limitation. Now provide the response and nothing else.
Try This: Increase PHP script execution time with Nginx You can follow the steps given below to increase the timeout value. PHP default is 30s. : Changes in php.ini If you want to change max execution time limit for php scripts from 30 seconds (default) to 300 seconds. vim /etc/php5/fpm/php.ini Set… max_execution_time = 300 In Apache, applications running PHP as a module above would have suffice. But in our case we need to make this change at 2 more places. Changes in PHP-FPM This is only needed if you have already un-commented request_terminate_timeout parameter before. It is commented by default, and takes value of max_execution_time found in php.ini Edit… vim /etc/php5/fpm/pool.d/www.conf Set… request_terminate_timeout = 300 Changes in Nginx Config To increase the time limit for example.com by vim /etc/nginx/sites-available/example.comlocation ~ \.php$ { include /etc/nginx/fastcgi_params; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_read_timeout 300; } If you want to increase time-limit for all-sites on your server, you can edit main nginx.conf file: vim /etc/nginx/nginx.conf Add following in http{..} section http { #... fastcgi_read_timeout 300; #...} Reload PHP-FPM & Nginx Don’t forget to do this so that changes you have made will come into effect: service php5-fpm reloadservice nginx reload or try this fastcgi_send_timeout 50;fastcgi_read_timeout 50; fastcgi has it's own set of timeouts and checks to prevent it from stalling out on a locked up process. They would kick in if you for instance set php's execuction time limit to 0 (unlimited) then accidentally created an infinite loop. Or if you were running some other application besides PHP which didn't have any of it's own timeout protections and it failed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22658908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1241241/']}
jdg_75848
stackexchange
llm_judgeable_groundtruth_similarity
7943573
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Some of the users of my application complain that sometimes (in a random way) the settings of my application are getting reverted to their default state (usually after a reboot of the phone). I never managed to reproduce the problem though. I am thinking it is due to the fact that in many places in my app I have a piece of code that calls the shared preferences editor and commits changes - Can it resolves in corrupting the shared preference file if I try to commit several changes to the same preference file at the same time? (Multi-thread application) I am really lost. I tried to look in the web for hours to find a solution without a success. If anyone has even an idea so I can start investigating, I would be grateful. Thanks,Amit Moran Now provide the response and nothing else.
I'd echo the other answers - that you need to avoid conflicts if you don't want to corrupt the file - and I'd go further to suggest that you're probably misuing SharedPreferences. SPs are designed to store small pieces of information about your app - user settings like volume or whether music is playing or things like that. SPs are NOT designed for storing data which changes often and/or large amounts of data and it's a bad idea to try to do this (for the reasons you've discovered and a few others). Remember that SPs are really just an XML file - you're incurring the overhead of parsing and recreating that every time you change it too! The idea of an App which updates SPs in more than one thread is a bit mad I think - you need a better way of managing and storing the data you're saving - it will pay-off for you in more than one way...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7943573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1020420/']}
jdg_75849
stackexchange
llm_judgeable_groundtruth_similarity
468781
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 was asked to define a non-perfect square. Now obviously, the first definition that comes to mind is a square that has a root that is not an integer. However, in the examples, 0.25 was considered a perfect square. And the square itself + its root were both not integers. Is it that all non-perfect squares have irrational roots, e.g. $\sqrt{2}$? Now provide the response and nothing else.
In the integers, a perfect square is one that has an integral square root, like $0,1,4,9,16,\dots$ The square root of all other positive integers is irrational. In the rational numbers, a perfect square is one of the form $\frac ab$ in lowest terms where $a$ and $b$ are both perfect squares in the integers. So $0.25=\frac 14$ is a perfect square in the rationals because both $1$ and $4$ are perfect squares in the integers. Any rational that has a reduced form where one of the numerator and denominator is not a perfect square in the integers is not a perfect square. For example, $\frac 12$ is not a perfect square in the rationals. $1$ is a perfect square in the integers, but $2$ is not, and there is no rational that can be squared to give $\frac 12$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/468781', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/53861/']}
jdg_75850
stackexchange
llm_judgeable_groundtruth_similarity
91224
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: How do we go about finding the LUDecomposition for non-square matrices. When i try to input the standard LUDecomposition command, it tells me that the matrix is not-invertible (understandable). Is there still a way to somehow find the LUDecomposition ? This is the matrix: a = {{2, 4, -1, 5, -2}, {-4, -5, 3, -8, 1}, {2, -5, -4, 1, 8}, {-6, 0, 7, -3, 1}} This is what i did: {lu, p, c} = LUDecomposition[a] Result: LUDecomposition::sing: "Matrix {{2,4,-1,5,-2},{-4,-5,3,-8,1},{2,-5,-4,1,8},{-6,0,7,-3,1}} is singular" {{2, 4, -1, 5, -2}, {-2, 3, 1, 2, -3}, {1, -3, 0, 2, 1}, {-3, 4, 0, 2, 5}}, {1, 2, 3, 4}, 0} The output data is different from the input data so i figured i may be able to still go ahead and use the upper and lower triangularize commands, but i get an error saying that Mathematica can't combine objects of unequal length. Now provide the response and nothing else.
I have used the functions EdgeDelete and EdgeAdd to expand the graph.The code generates new vertex names by incrementing the largest vertex name in the graph. nextVertexNames[g_] := Max[VertexList[g]] + {{1, 2, 3}, {4, 5, 6}}replaceTripod[g_, v_] := Module[{ oldNeighbors = DeleteCases[VertexComponent[g, v, 1], v], newNeighbors = nextVertexNames[g], go = g }, EdgeAdd[ EdgeDelete[go, v <-> _], Flatten@{ UndirectedEdge[v, #] & /@ First[newNeighbors], UndirectedEdge @@@ Partition[Riffle @@ newNeighbors, {2}, 1, 1], UndirectedEdge @@@ Thread[{Last@newNeighbors, oldNeighbors}]} ] ]replaceTripods[g_] := Fold[replaceTripod, g, Extract[VertexList[g], Position[VertexDegree[g], 3]]]; For your case, use replaceTripods[g] to replace all tripods in the graph g . Update As kindly suggested by halmir below, the resulting graph can be displayed just as in your example using the option GraphLayout -> "TutteEmbedding" . g = Graph[{1 <-> 2, 1 <-> 3, 1 <-> 4, 2 <-> 3, 2 <-> 4, 3 <-> 4}, VertexLabels -> "Name", GraphLayout -> "TutteEmbedding"];replaceTripods[g]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/91224', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/31088/']}
jdg_75851
stackexchange
llm_judgeable_groundtruth_similarity
26382810
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 got an object that has a collection of properties. When I get the specific entity I can see the field I'm looking for ( opportunityid ) and that it's Value attribute is the Guid for this opportunity. This is the value I want, but it won't always be for an opportunity, and therefore I can't always look at opportunityid , so I need to get the field based on input supplied by the user. My code so far is: Guid attrGuid = new Guid();BusinessEntityCollection members = CrmWebService.RetrieveMultiple(query);if (members.BusinessEntities.Length > 0){ try { dynamic attr = members.BusinessEntities[0]; //Get collection of opportunity properties System.Reflection.PropertyInfo[] Props = attr.GetType().GetProperties(); System.Reflection.PropertyInfo info = Props.FirstOrDefault(x => x.Name == GuidAttributeName); attrGuid = info.PropertyType.GUID; //doesn't work. } catch (Exception ex) { throw new Exception("An error occurred when retrieving the value for " + attributeName + ". Error: " + ex.Message); }} The dynamic attr contains the field I'm looking for (in this case opportunityid ), which in turn contains a value field, which is the correct Guid . However, when I get the PropertyInfo info ( opportunityid ) it no longer has a Value attribute. I tried looking at the PropertyType.GUID but this doesn't return the correct Guid . How can I get the value for this property? Now provide the response and nothing else.
Unless the property is static , it is not enough to get a PropertyInfo object to get a value of a property. When you write "plain" C# and you need to get a value of some property, say, MyProperty , you write this: var val = obj.MyProperty; You supply two things - the property name (i.e. what to get) and the object (i.e. from where to get it). PropertyInfo represents the "what". You need to specify "from where" separately. When you call var val = info.GetValue(obj); you pass the "from where" to the PropertyInfo , letting it extract the value of the property from the object for you. Note: prior to .NET 4.5 you need to pass null as a second argument: var val = info.GetValue(obj, null);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26382810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2381942/']}
jdg_75852
stackexchange
llm_judgeable_groundtruth_similarity
13816596
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to receive the resource-ids being kept by a as an int[] programmatically without referring to the resource-class R? <declare-styleable name="com_facebook_login_view"> <attr name="confirm_logout" format="boolean"/> <attr name="fetch_user_info" format="boolean"/> <attr name="login_text" format="string"/> <attr name="logout_text" format="string"/></declare-styleable> The problem is that I cannot resolve the ID of the defined 'declare-styleable' attribute - 0x00 is always returned: int id = context.getResources().getIdentifier( "com_facebook_login_view", "declare-styleable", context.getPackageName() ); int[] resourceIDs = context.getResources().getIntArray( id ); Now provide the response and nothing else.
Here is the solution that delivers the resource-IDs programmatically for the child-<attr>-tags defined for a <declare-styleable> tag: /********************************************************************************** Returns the resource-IDs for all attributes specified in the* given <declare-styleable>-resource tag as an int array.** @param context The current application context.* @param name The name of the <declare-styleable>-resource-tag to pick.* @return All resource-IDs of the child-attributes for the given* <declare-styleable>-resource or <code>null</code> if* this tag could not be found or an error occured.*********************************************************************************/public static final int[] getResourceDeclareStyleableIntArray( Context context, String name ){ try { //use reflection to access the resource class Field[] fields2 = Class.forName( context.getPackageName() + ".R$styleable" ).getFields(); //browse all fields for ( Field f : fields2 ) { //pick matching field if ( f.getName().equals( name ) ) { //return as int array int[] ret = (int[])f.get( null ); return ret; } } } catch ( Throwable t ) { } return null;} Maybe this could help somebody one day.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13816596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1389153/']}
jdg_75853
stackexchange
llm_judgeable_groundtruth_similarity
336859
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 recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent. The previous developer used two ways of declaring functions and I can't work out if there is a reason behind it or not. The two ways are: var functionOne = function() { // Some code}; function functionTwo() { // Some code} What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other? Now provide the response and nothing else.
The difference is that functionOne is a function expression and so only defined when that line is reached, whereas functionTwo is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting ). For example, a function expression: // TypeError: functionOne is not a functionfunctionOne();var functionOne = function() { console.log("Hello!");}; And, a function declaration: // Outputs: "Hello!"functionTwo();function functionTwo() { console.log("Hello!");} Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block. 'use strict'; { // note this block! function functionThree() { console.log("Hello!"); }}functionThree(); // ReferenceError
{}
{'log_upvote_score': 13, 'links': ['https://Stackoverflow.com/questions/336859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31569/']}
jdg_75854
stackexchange
llm_judgeable_groundtruth_similarity
51480885
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So for example this is my view: <div> <img src='../../minus.png' /></div> Now I want to make that on each click the image changes from plus.png to minus.png . So, click once: minus.png => plus.png , click again: plus.png => minus.png , and so on. How can I make this? Now provide the response and nothing else.
This can be achieved with a simple toggle handler: const imagesPath = { minus: "https://images.vexels.com/media/users/3/131484/isolated/preview/a432fa4062ed3d68771db7c1d65ee885-minus-inside-circle-icon-by-vexels.png", plus: "https://cdn3.iconfinder.com/data/icons/glypho-generic-icons/64/plus-big-512.png"}class App extends React.Component { state = { open: true } toggleImage = () => { this.setState(state => ({ open: !state.open })) } getImageName = () => this.state.open ? 'plus' : 'minus' render() { const imageName = this.getImageName(); return ( <div> <img style={{maxWidth: '50px'}} src={imagesPath[imageName]} onClick={this.toggleImage} /> </div> ); }}const rootElement = document.getElementById("root");ReactDOM.render(<App />, rootElement); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div> Edit Note that I passed a function parameter for setState because my new state depends on the old state. You can read more about it in the docs
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51480885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_75855
stackexchange
llm_judgeable_groundtruth_similarity
45958226
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I recently added get location function. When I try to show longitude and latitude, it returns zero. This my LocationListener class: inner class MylocationListener: LocationListener { constructor():super(){ mylocation= Location("me") mylocation!!.longitude mylocation!!.latitude } override fun onLocationChanged(location: Location?) { mylocation=location } override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {} override fun onProviderEnabled(p0: String?) {} override fun onProviderDisabled(p0: String?) {}} And this my GetUserLocation function: fun GetUserLocation(){ var mylocation= MylocationListener() var locationManager=getSystemService(Context.LOCATION_SERVICE) as LocationManager locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0.1f,mylocation)} And this my function to return my longitude and latitude: fun getLoction (view: View){ prgDialog!!.show(); GetUserLocation() button.setTextColor(getResources().getColor(R.color.green)); textView.text = mylocation!!.latitude.toFloat().toString() Toast.makeText(this, mylocation!!.latitude.toFloat().toString(), Toast.LENGTH_LONG).show() Toast.makeText(this, mylocation!!.longitude.toFloat().toString(), Toast.LENGTH_LONG).show() prgDialog!!.hide()} Now provide the response and nothing else.
When GetUserLocation returns, locationManager goes out of scope and presumably is destroyed, preventing onLocationChanged from being called and providing updates. Also, you've defined mylocation inside of GetUserLocation so it also goes out of scope and further kills any chance or your getting an update. You have not shown where and how the outer mylocation is declared (outside of GetUserLocation ), but how ever it is declared, it is being shadowed by the one inside of GetUserLocation . So you aren't getting much. Here is an example of how you might do it. (The variable thetext is defined within the layout xml and accessed with Kotlin extensions.) // in the android manifest<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>// allow these through Appliation Manager if necessary// inside a basic activityprivate var locationManager : LocationManager? = nulloverride fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) // Create persistent LocationManager reference locationManager = getSystemService(LOCATION_SERVICE) as LocationManager? fab.setOnClickListener { view -> try { // Request location updates locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListener) } catch(ex: SecurityException) { Log.d("myTag", "Security Exception, no location available") } }}//define the listenerprivate val locationListener: LocationListener = object : LocationListener { override fun onLocationChanged(location: Location) { thetext.text = ("" + location.longitude + ":" + location.latitude) } override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {} override fun onProviderEnabled(provider: String) {} override fun onProviderDisabled(provider: String) {}}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45958226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8490394/']}
jdg_75856
stackexchange
llm_judgeable_groundtruth_similarity
5019478
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm a Grails beginner, so please be patient with me. Currently I'm having hard times manipulating file uploads. As far as I understand using request.getFile() I can easily get the stream of bytes. But before I do that, I want to check the following: file name of the file being uploaded file size of the file being uploaded content/file type of the file being uploaded How can this be done? Is it even possible before the file is uploaded to the server? I would like to block uploading of large files. Now provide the response and nothing else.
All the information is contained in the CommonsMultipartFile object that you can cast your request parameter to. You can use it like that (in your controller) def uploaded = { def CommonsMultipartFile uploadedFile = params.fileInputName def contentType = uploadedFile.contentType def fileName = uploadedFile.originalFilename def size = uploadedFile.size} As far as blocking large file uploads, this could be done by adding the following to your form: <INPUT name="fileInputName" type="file" maxlength="100000"> but not all browsers will support it. The other limit is you container upload limit (see Tomcat configuration or whatever container you are using). Other than that, you have to check the size and reject it in the controller.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5019478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138255/']}
jdg_75857
stackexchange
llm_judgeable_groundtruth_similarity
312229
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: $V$ is a scalar field, then $$\nabla\times \nabla V = 0$$ Faraday's law: $$\nabla \times \mathbf{E} = -\frac{d\mathbf{B}}{dt},\\\mathbf{E} = -\nabla V\, .$$ Now provide the response and nothing else.
The theorem is about fields, not about physics, of course. The fact thatdB/dt induces a curl in E does not mean that there is an underlying scalar field V which corresponds to that E-field. Only conservative electric fields havea representation as gradient of the scalar potential. In the presence of a changing B field, E is not conservative, and V is undefined (well, at least poorly defined, and not easy to measure).
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/312229', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/145537/']}
jdg_75858
stackexchange
llm_judgeable_groundtruth_similarity
67599438
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I upgrade in an Android project to Gradle 7.0 and want to publish aar library in jitpack.io I run into Script '/script/maven-plugin.gradle' line: 2* What went wrong:A problem occurred evaluating script.> Failed to apply plugin 'com.github.dcendents.android-maven'. > Could not create plugin of type 'AndroidMavenPlugin'. > Could not generate a decorated class for type AndroidMavenPlugin. > org/gradle/api/publication/maven/internal/MavenPomMetaInfoProvider See full log https://jitpack.io/com/github/appdevnext/moka/0.7.1/build.log Now provide the response and nothing else.
The Maven plugin has been eliminated in Gradle 7.0, please use the maven-publish plugin instead. I made it work with plugins { id 'maven-publish' ...}task androidSourcesJar(type: Jar) { classifier 'sources' from android.sourceSets.main.java.srcDirs }project.afterEvaluate { publishing { publications { release(MavenPublication) { from components.release artifact androidSourcesJar // optional sources } } }} and you need an own jitpack.yml jdk: - openjdk11install: - ./gradlew build :lib:publishToMavenLocal Here you see complete pull request https://github.com/AppDevNext/Moka/pull/77 now it works https://jitpack.io/#AppDevNext/moka/1.0
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/67599438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1079990/']}
jdg_75859
stackexchange
llm_judgeable_groundtruth_similarity
27882800
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On the surface, it looks like both drain and into_iter provide similar iterators, namely over the values of the collection. However, they are different: fn main() { let mut items1 = vec![0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let items2 = items1.clone(); println!("{:?}", items1.drain().count()); println!("{:?}", items2.into_iter().count()); println!("{:?}", items1); // println!("{:?}", items2); Moved} drain takes a &mut to the collection and the collection is available afterwards. into_iter consumes the collection. What are the appropriate uses for each iterator? Now provide the response and nothing else.
They are somewhat redundant with each other. However, as you say, Drain just borrows the vector, in particular, it has a lifetime connected with the vector. If one is wishing to return an iterator, or otherwise munge iterators in the most flexible way possible, using into_iter is better, since it's not chained to the owner of the originating Vec . If one is wishing to reuse the data structure (e.g. reuse the allocation) then drain is the most direct way of doing this. Also, a (somewhat) theoretical concern is that Drain needs to result in the originating structure being a valid instance of whatever type it is, that is, either preserve invariants, or fix them up at the end, while IntoIter can mangle the structure as much as it likes, since it has complete control of the value. I say only "somewhat" theoretical because there is a small, real world example of this in std already: HashMap exposes .drain and .into_iter via its internal RawTable type, which also has those methods. into_iter can just read the hash of the value being moved directly and that's that, but drain has to be careful to update the hash to indicate that the cell is then empty , not just read it. Obviously this is absolutely tiny in this instance (probably only one or two additional instructions) but for more complicated data structures like trees there may be some non-trivial gains to be had from breaking the invariants of the data structure.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27882800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155423/']}
jdg_75860
stackexchange
llm_judgeable_groundtruth_similarity
4344512
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: $X$ is a random variable. $$ \mathbb E ( | X | ) < \infty \implies \forall \epsilon > 0, \sum_n \mathbb P ( | X | \geq n \epsilon ) < \infty. $$ Any help to prove this? (This amounts to prove that $\mathbb E[ |X| ] < \infty \iff \forall \epsilon : \mathbb E[ |X / \epsilon | ] < \infty$ ). ---------------------------------------------------- original post Since I know that $$X \in L^1 \iff \sum \mathbb P ( | X | \geq n) < \infty$$ I was given the hint to try to prove the statement hereinafter: Let us say that $X$ is a random variable. $$\forall \epsilon > 0, \exists K>0, \forall n \in \mathbb N: \mathbb P( X \geq n \epsilon ) \leq K \mathbb P ( X \geq n), $$ is a useful fact that I need in some proof of my probability lecture, however I am quite unsure about how to prove such statement. Any idea? ---------------------------------------------------- comment I guess that the original post is completly wrong because one cannot bound each term (cf. Ian comment), however bounding the whole sum is doable somehow. Now provide the response and nothing else.
$\newcommand{\dd}{\mathop{}\!\mathrm{d}}$ Recall that $\mathbb E|X|=\int_0^\infty\mathbb P(|X|>t)\dd t$ . Then since $t\mapsto\mathbb P(|X|>t)$ is a decreasing function, we can bound this integral via upper and lower Riemann sums as $$\epsilon\cdot\sum_{n=1}^\infty\mathbb P(|X|>n\epsilon)\leq\int_0^\infty\mathbb P(|X|>t)\dd t\leq\epsilon\cdot\sum_{n=0}^\infty\mathbb P(|X|>n\epsilon).$$ So it turns out that $\mathbb E|X|<\infty\iff\sum\mathbb P(|X|>n\epsilon)<\infty$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4344512', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/497474/']}
jdg_75861
stackexchange
llm_judgeable_groundtruth_similarity
201335
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: by expanding into series ( sorry i have tried but get no answer) how could i prove that $$ \sqrt \pi\frac{d^{1/2}}{dx^{1/2}}J_{0} (a\sqrt x) = \frac{\cos(a\sqrt x)}{\sqrt x}$$ Now provide the response and nothing else.
A related problem . The power series of $J_{0} (a\sqrt x)$ is $$J_{0} (a\sqrt x)= \sum _{{\it k}=0}^{\infty }{\frac { \left( -1 \right) ^{{\it k}}a^{2k}x^{{\it k}}}{ 2^{2k}\Gamma \left( 1+{\it k} \right) ^{2}}} $$ Applying the formula for fractional derivative of a monomial $$ \frac{d^q}{dx^q} x^m = \frac{\Gamma(m+1)}{\Gamma(m-q+1 )} x^{m-q}\,, $$ to the above series yields $$ \frac{d^{\frac{1}{2}}}{dx^{\frac{1}{2}}}J_{0} (a\sqrt x) =\sum _{{\it k}=0}^{\infty }{\frac { \left( -1 \right) ^{{\it k}}a^{2k}\Gamma(k+1)\,x^{{\it k-\frac{1}{2}}}}{ 2^{2k}\Gamma(k+\frac{1}{2})\Gamma\left( 1+{\it k}\right) ^{2}}} \,. $$ Simplifying the above series and using the identity $ \Gamma(2k+1)=\frac{1}{\sqrt{\pi}}2^{2k}\Gamma(k+1)\Gamma(k+\frac{1}{2}) $, we get $$ \frac{d^{\frac{1}{2}}}{dx^{\frac{1}{2}}}J_{0} (a\sqrt x) =\frac{1}{\sqrt{\pi}\sqrt{x}}\,\sum _{{\it k}=0}^{\infty }{\frac { \left( -1 \right)^{{\it k}}\,(a\sqrt{x})^{2k}}{ \Gamma(2k+1)}} \,. $$ Multiplying both sides of the above equation by $ \sqrt{\pi} $, we reach the desired result follow$$ \sqrt{\pi} \frac{d^{\frac{1}{2}}}{dx^{\frac{1}{2}}}J_{0} (a\sqrt x) =\frac{1}{\sqrt{x}}\,\sum _{{\it k}=0}^{\infty }{\frac { \left( -1 \right)^{{\it k}}\,(a\sqrt{x})^{2k}}{ \Gamma(2k+1)}}=\frac{\cos(a\sqrt x)}{\sqrt x} \,. $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/201335', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17341/']}
jdg_75862
stackexchange
llm_judgeable_groundtruth_similarity
3049575
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 F be a field, and $p(x) \in F[x]$ an irreducible polynomial. Consider $n \in \mathbb{N}$ and let's define an ideal $J = F[x]p(x)^n$ in polynomials algebra $F[x]$ , and now we shall define the quotient algebra $A = F[x]/J$ . Prove that $A$ is semi-simple iff $n=1$ . (when we define $A$ to be semi-simple if it can be written as a sum of minimal left ideals - which is equivalent to the definition that Jacobson radical is 0). Now, I believe that i have an argument to the first part: if $A$ is semi-simple means $A = \sum_{\alpha \in \Gamma}J_{\alpha}$ (where $J_{\alpha}$ are left minimal ideals) we can assume by contradiction that $n>1$ . let's define $I_k:= $ { $[q(x)] \in A: p(x)^k | q(x)$ } for $k=1,...,n-1$ - which are all left ideals ( $I_n = $ { $[0]$ } and $I_{n-1}$ is minimal and also $I_{n-1} \subseteq I_1$ ). now since we know that there exists $\alpha_0 \in \Gamma$ such that $p(x) \in J_{\alpha _ 0}$ we deduce $I_1 \subseteq J_{\alpha _0}$ which means contradiction to minimalism of $J_{\alpha _0}$ or $I_{n-1} = J_{\alpha_0}$ which means $I_{n-1} = I_{1}$ also a contradiction. I'm not sure in my solution and also i seek for a proof in the other direction. thanks ahead Now provide the response and nothing else.
For the first one : $$\left(x-\frac{1}{x}\right)^2 = x^2 - 2 + \frac{1}{x^2} \Leftrightarrow x^2 + \frac{1}{x^2} = \left(x-\frac{1}{x}\right)^2 + 2 \implies x^2+ \frac{1}{x^2} = 11$$ For the second one, observe that : $$\frac{x}{x+y} + \frac{y}{x+y} = 1 \Rightarrow 5 + \frac{y}{x+y} = 1 \Leftrightarrow \frac{y}{x+y} = -4 $$ For the third one, a small hint : $$(x^2-y^2)^2 = x^4 - 2x^2y^2 + y^4$$ Alternativelly, observe that it also is : $$x^4 + y^4 = 6 x^2 y^2 \Leftrightarrow \frac{x^2}{y^2} + \frac{y^2}{x^2} = 6$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3049575', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/489746/']}
jdg_75863
stackexchange
llm_judgeable_groundtruth_similarity
11194757
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 consume my WordPress blog's RSS feed to display my latest blog posts on my homepage? I ran into the following piece of code to do this: Function GetRSSFeed(strURL as String) as DataTable 'Get the XML data Dim reader as XmlTextReader = New XmlTextReader(strURL) 'return a new DataSet Dim ds as DataSet = New DataSet() ds.ReadXml(reader) Return ds.Tables(2) End Function But it errors out at this line: 'ds.ReadXml(reader)' with the following error: A column named 'comments' already belongs to this DataTable. Perhaps it doesn't work since this code is from 2003? Does anyone have a working code sample? Many thanks in advance! Now provide the response and nothing else.
You can use LINQ to XML to read a WordPress RSS feed. First get the feed. Make a Uri instance out of it. var rssFeed = new Uri("https://github.com/geersch/feed/"); Then perform a GET request. var request = (HttpWebRequest) WebRequest.Create(rssFeed);request.Method = "GET";var response = (HttpWebResponse) request.GetResponse(); Get the response stream and read it to download the contents of the feed. using (var reader = new StreamReader(response.GetResponseStream())){ var feedContents = reader.ReadToEnd(); //...} Still within the above using statement use LINQ to XML to parse the downloaded content and extract the information you need. var document = XDocument.Parse(feedContents);var posts = (from p in document.Descendants("item") select new { Title = p.Element("title").Value, Link = p.Element("link").Value, Comments = p.Element("comments").Value, PubDate = DateTime.Parse(p.Element("pubDate").Value) }).ToList(); Now you can iterate over the results. foreach(var post in posts){ Console.WriteLine(post.Title); Console.WriteLine(post.Link); Console.WriteLine(post.Comments); Console.WriteLine(post.PubDate);} Here I just used an anonymous type to capture the output in, but feel free to create your own BlogPost class or something similar which you can use in the LINQ query. I'm used to C#, so that's why I've used it in my reply. But you can easily convert it. There are some online converters which you can use. Regarding your issue with the DataSet (which I personally would not use to implement this), it is caused by an item (blog post) having nodes with the same name. For example: <comments>...</comments><slash:comments>5</slash:comments> Sure the second one has a different namespace (slash), but DataSet's ReadXml(...) method does not care about namespaces. It tries to create a second column named "comments". That is why you get the exception. You can still use a DataSet / DataTable if you want to. Just extract the data from the feed using LINQ to XML as shown above. Then create a DataSet and add a new table to it. var dataSet = new DataSet();var blog = new DataTable("Blog");blog.Columns.Add("Title", typeof(string));blog.Columns.Add("Link", typeof(string));blog.Columns.Add("Comments", typeof(string));dataSet.Tables.Add(blog); Iterate over the extracted data and add it to the DataTable: foreach (var post in posts){ var newRow = blog.NewRow(); newRow["Title"] = post.Title; newRow["Link"] = post.Link; newRow["Comments"] = post.Comments; blog.Rows.Add(newRow); } Voila, we've now fixed your issue by no longer relying on the DataSet's ReadXml(...) method. Download the feed, extract the data you are interested in and persist it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11194757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1174406/']}
jdg_75864
stackexchange
llm_judgeable_groundtruth_similarity
261657
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: Gödel's Theorem says that I can construct a mathematical statement like "f(x1,x2,...,x_n)=0 has no integer solution", where it is impossible (in a certain system of axioms) to formally prove that it's true, and also impossible to formally prove that it's false. I have often heard a school of thought that goes like "Well, in reality , we know that this particular statement is true. Why? Because if f has an integer solution, then it would obviously be possible to prove that f has an integer solution. (Plug it in and check it.) Yet I just constructed f in an elaborate way to ensure that no such formal proof exists." Although this isn't a formal axiomatic proof that the statement is true, it is still a "proof" using meta-reasoning. (Is that a fair description?) If this is correct so far, is there some generalization of Gödel's Theorem that says "There are statements which cannot be "proven" true, nor "proven" false, nor "proven" formally undecidable, even if the word "proven" is taken more broadly to allow any kind of "meta-reasoning" that mathematicians are capable of? Makes my head spin to think about it. Thanks in advance! Now provide the response and nothing else.
Yes, for most reasonable meanings of the words, there are statements that can neither be proved nor disproved nor proved to be independent. However, "any kind of meta-reasoning that mathematicians are capable of" is slightly too fuzzy to work as a reasonable meaning here. Some mathematicians are capable of reasonings that other mathematicians consider faulty, for example. Generally Gödel-like results always work particular proof systems , which are presumed to be "sane" in the sense that: Any valid proof or disproof can be encoded as a sequence of bytes. (Consistency): there is nothing that has both a proof and a disproof. One can write a computer program that reads a sequence of bytes and then tells us whether it encodes a valid proof or disproof -- and if so, what it proves/disproves. The last of these conditions fail if you try to make "provability" mean something non-operational such as "whatever will convince most real-life mathematicians". And it happens to be an essential technical part of the arguments. One way to see there must be a sentence thar is neither provable nor disprovable nor provably independent is to consider all sentences of the form "$P$ halts" for all programs $P$ in your favorite programming language. If they are all either provable or disprovable, you could decide the halting problem by searching simultaneously for a proof and a disproof. So some of then (we don't know exactly which) must be neither provable nor disprovable. But if all of those could be proved independent, then we could solve the halting problem by searching simultaneously for a proof or a disproof or a proof of independendce. (If we know that the program's halting sentence is independent, then it cannot actually halt, because everything that halts does so provably).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/261657', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33165/']}
jdg_75865
stackexchange
llm_judgeable_groundtruth_similarity
15684846
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 curl command: curl -i -u guest:guest -H "content-type:application/json"-XPUT \ http://localhost:15672/api/traces/%2f/my-trace \-d'{"format":"text","pattern":"#"}' And I want to create HTTP Request in Java API which will do the same thing. This curl command can be found in this README . It is used to start recording log on RabbitMQ. Response is not important. For now I created something like this (I've deleted less important lines i.e. with catching exception etc.), but unfortunately it doesn't work: url = new URL("http://localhost:15672/api/traces/%2f/my-trace");uc = url.openConnection();uc.setRequestProperty("Content-Type", "application/json");uc.setRequestProperty("format","json");uc.setRequestProperty("pattern","#")String userpass = "guest:guest";String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());uc.setRequestProperty ("Authorization", basicAuth); ENTIRE CODE Now provide the response and nothing else.
This is final solution: import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.net.Proxy;import java.net.InetSocketAddress;import java.io.OutputStreamWriter;public class Curl { public static void main(String[] args) { try { String url = "http://127.0.0.1:15672/api/traces/%2f/trololo"; URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); conn.setRequestMethod("PUT"); String userpass = "user" + ":" + "pass"; String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8")); conn.setRequestProperty ("Authorization", basicAuth); String data = "{\"format\":\"json\",\"pattern\":\"#\"}"; OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream()); out.write(data); out.close(); new InputStreamReader(conn.getInputStream()); } catch (Exception e) { e.printStackTrace(); } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15684846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2219448/']}
jdg_75866
stackexchange
llm_judgeable_groundtruth_similarity
6332259
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I cannot delete files to Recycle Bin. VAR SHFileOpStruct: TSHFileOpStruct;begin with SHFileOpStruct do begin wnd := Handle; wFunc := FO_DELETE; pFrom := PChar(FileName); fFlags:= 0; pTo := NIL; hNameMappings:= NIL; lpszProgressTitle:= NIL; end; Result:= SHFileOperation(SHFileOpStruct); end; I can delete files in this format: '1.xyz' but not in this format '12.xyz' (file name is longer than 1 character). Now provide the response and nothing else.
According to the documentation of SHFileOperation you should not use GetLastError to see if the operation succeeds. Check the Result of the function and use the documentation to figure out the error it returns. That should give you a better clue what the problem is. EDIT: Best guess from reading the documentation: pFrom Although this member is declared as a single null-terminated string, it is actually a buffer that can hold multiple null-delimited file names. Each file name is terminated by a single NULL character. The last file name is terminated with a double NULL character ("\0\0") to indicate the end of the buffer So you should make sure pFrom is ended with a double 0. Try the following pFrom := PChar(FileName + #0); Also, what Delphi version are you using? EDIT2: Also make sure the structure is properly initialized to 0. Uncomment the FillChar
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6332259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46207/']}
jdg_75867
stackexchange
llm_judgeable_groundtruth_similarity
191894
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 am trying to fill a file with a sequence of random 0 and 1s with a user-defined number of lines and number of characters per line. the first step is to get a random stream of 0 and 1s: cat /dev/urandom | tr -dc 01 then I tried to fill a file with this stream (and end the process of filling by ctrl+c) cat /dev/urandom | tr -dc 01 > foo when I count the numbers of lines of the so created foo file I get 0 lines. cat foo | wc -l0 Now I tried to control the stream, so I created a named pipe and directed the stream into it. Then I made a connection to the named pipe with the dd command in vain hope to control this way the amount of characters per line and number of lines in the file. makefifo namedpipecat /dev/urandom | tr -dc 01 > namedpipedd if=namedpipe of=foo bs=10 count=5 the foo file got indeed filled with 50 byte of 0 and 1 , but the number of lines was still 0. How can I solve it, I guess maybe I have to insert each number of characters a newline into the file, but if so , I do not know how. Now provide the response and nothing else.
How about fold ? It's part of coreutils... $ tr -dc 01 < /dev/urandom | fold -w 30 | head -n 5001010000111110001100101101101000101110011011100100101111000111010101011100101010110111001111011000000000101111110110100110011010111001110011010100011 Or if that's not available, some flavour of awk : $ tr -dc 01 < /dev/urandom | awk \$0=RT RS=.\{,30} | head -n 5000100010010001110100110100111101010010100100110111010001110100011100101001010111101001111010010100111100101101100010100001101100000101001111011011000 Or you could just do something with a loop... $ for line in $(seq 1 5)> do> echo $(tr -dc 01 < /dev/urandom | head -c 30)> done100101100111011110010010100000000000010000010010110111101011010000111110010010000000010100001110110001111011101011001001001010111011000111110001100110 I'm sure there are other ways... I thought maybe hexdump with a custom format could do it, but apparently not... ;)
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/191894', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/102788/']}
jdg_75868
stackexchange
llm_judgeable_groundtruth_similarity
7292052
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 find a solution (here and on the web) for simply selecting/inserting/deleting stuff surrounded by dots (a common case in development) : someobject.some-property-with-hyphens.otherproperty How to select the middle property ? I tried : vi. (dot is for executing last command) viw (don't include hyphens) 4viw (still nop) vis (select full line) Edit : more common exemple (in javascript) app.object['key'].$object_with_a_dollar_sign.function() Now provide the response and nothing else.
I suspect the real issue here is that hyphens are not considered a part of an identifier You should try adding :se iskeyword+=- for your file type. That way, v i w will do exeactly what you want To make this setting automatic for, say, strange files: :autocmd BufReadPost *.strange se isk+=- Adding that line to your vimrc ( :e $MYVIMRC ) you'll never have to think about adding the iskeyword setting. See also :he modeline for alternative ways to set this setting per file Update an even purer solution would to create your own operator-mapping . A quick draft of this, that seemed to work very nicely for me: xnoremap <silent>. f.oT.oxnoremap <silent>a. f.oF.oxnoremap <silent>i. t.oT.oonoremap <silent>. :<C-u>exec 'normal v' . v:count1 . '.'<CR>onoremap <silent>a. :<C-u>exec 'normal v' . v:count1 . 'a.'<CR>onoremap <silent>i. :<C-u>exec 'normal v' . v:count1 . 'i.'<CR> Examples for the following buffer contents ( cursor on the letter w ): someobject.some-property-with-hyphens.SUB.otherproperty v . selects some-property-with-hyphens. in visual mode v a . selects .some-property-with-hyphens. in visual mode v i . selects some-property-with-hyphens in visual mode Motions can be chained and accept a count : v . . selects some-property-with-hyphens.SUB. in visual mode v 2. also selects some-property-with-hyphens.SUB. in visual mode v 2 a . selects .some-property-with-hyphens.SUB. in visual mode v 2 i . selects some-property-with-hyphens.SUB in visual mode You can use the operators as operators to any editing command: d . results in someobject.SUB.otherproperty c i . shortname results in someobject.shortname.SUB.otherproperty c 2 . get(" results in someobject.get("otherproperty It doesn't matter where in a 'dot-delimited-identifier' the cursor is to start with. Note that for convenience, all visual mode mappings position the cursor at the end of the selection (so you can do continue extending the selection by e.g. % and other motions).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7292052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/926408/']}
jdg_75869
stackexchange
llm_judgeable_groundtruth_similarity
14709802
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 fairly simple Express.js app with a login component that I'd like to exit early if login fails. I'm seeing indications that the app isn't doing that and I haven't found a definitive answer that indicates whether calling res.send() halts any further processing. Here's my code as it stands now: client.login( username, password, function( auth, client ) { if( !auth ) { res.send( 401 ); } // DO OTHER STUFF IF AUTH IS SUCCESSFUL} If I read the source code correctly, it should end the request (aborting further processing), but I'm new to node, so I'm not quite ready to trust what I think I'm reading. To boil it down, I guess I'm mostly looking for a definitive answer from a more trustworthy source that my own interpretation of unfamiliar source code. If send() doesn't abort processing, what's the right way to do that? Now provide the response and nothing else.
If you are using express as your framework, you should call next() instead. Each handler in express receives 3 parameters (unlinke 2 for basic http) which are req , res and next next is a function that when called with no arguments will trigger the next handler in the middleware chain. If next is called with an arguments, this argument will be interpreter as an error, regardless of the type of that argument. Its signature is next([error]) . When next is called with an error, then instead of calling the next handler in the middleware chain, it calls the error handler. You should handle the 401 response code in that error handler. See this for more info on error handling in Express EDIT: As @Baptiste Costa commented, simply calling next() will not cease the current execution but it will call on the next middleware. It is good practice to use return next() instead to prevent Node from throwing errors further on (such as the can't set headers after they are sent - error). This includes the above suggestion of error throwing which is common: return next(new Error([error]));
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14709802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1665/']}
jdg_75870
stackexchange
llm_judgeable_groundtruth_similarity
9453701
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ive saw the next paragraph in some computer science test and i'll hope i can get here a good explanation of what it means because i googled it for an hour and can't find anything.. "When we say Java language has virtual method calling we mean that in java applications the executed method is determined by the object type in run time" What does it mean? can anyone explain it better? Now provide the response and nothing else.
The author of these lines used the c++ terminology of virtual . A better terminology is dynamic binding / dynamic dispatch . That means, that the object's dynamic type is "chosing" which method will be invoked, and not the static type. For example: [pseudo code]: class A { public void foo() { }}class B extends A { public void foo() { }} when invoking: A obj = new B();obj.foo(); B.foo() will be invoked, and NOT A.foo() , since the dynamic type of obj is B .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9453701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1024246/']}
jdg_75871
stackexchange
llm_judgeable_groundtruth_similarity
17999
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose there is a random walk starting at the origin such that the probability to move right is $\frac13$ and the probability to move left is $\frac23$ . What is the probability to return to the origin? Now provide the response and nothing else.
Let $P_{i\ge 0}$ be the probability of ever reaching position $x+i$ when starting from position $x$ (this is independent of $x$, since the transition probabilities are). Clearly $P_0=1$, and $P_i\rightarrow 0$ as $i\rightarrow\infty$ provided that the right-hop probability $q < 1/2$ (in this case $q = 1/3$). Otherwise,$$P_i = qP_{i-1} + (1-q)P_{i+1},$$You can guess the solution to be of the form $P_i = \alpha^i$ for some $0 < \alpha < 1$. This turns out to satisfy the conditions if$$\alpha = q + (1-q) \alpha^2,$$which has the solution $\alpha = q/(1-q)$ in this case. For the problem specified, you want to know the total probability of returning to the origin after the first step. If the first step is to the right (which happens with probability $q$), then you must return to the origin; if it is to the left (with probability $1-q$), then you will return to the origin with probability $P_1 = \alpha = q/(1-q)$. So the solution is$$P_{\text{return}} = q + (1-q)\alpha = q + (1-q)\frac{q}{1-q} = 2q$$for general $q<1/2$, and $P_{\text{return}} = 2/3$ in this case.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/17999', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5145/']}
jdg_75872
stackexchange
llm_judgeable_groundtruth_similarity
1123725
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 should default parameters be added last in C++ functions? Now provide the response and nothing else.
To simplify the language definition and keep code readable. void foo(int x = 2, int y); To call that and take advantage of the default value, you'd need syntax like this: foo(, 3); Which was probably felt to be too weird. Another alternative is specifying names in the argument list: foo(y : 3); A new symbol would have to be used because this already means something: foo(y = 3); // assign 3 to y and then pass y to foo. The naming approach was considered and rejected by the ISO committee because they were uncomfortable with introducing a new significance to parameter names outside of the function definition. If you're interested in more C++ design rationales, read The Design and Evolution of C++ by Stroustrup.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1123725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22076/']}
jdg_75873
stackexchange
llm_judgeable_groundtruth_similarity
1391239
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $(X_t)_{t\geq 0}$ be the zero-mean Ornstein-Uhlenbeck process such that $X_0 = 0$ almost surely, i.e.$$X_t = \sigma e^{-\alpha t}\int_0^t e^{\alpha s}\,dB_s \quad \qquad (\triangle)$$ On the other hand, $(X_t)$ is the unique process that satisfies the SDE$$dX_t = \alpha X_t\,dt + \sigma\,dB_t \quad X_0 = 0 \qquad (\square)$$ Since the SDE $(\square)$ satisfies the growth and the Lipschitz conditions, we know that the strong solution to this SDE, $(X_t)$, exists, is unique and continuous. From the latter $[X,X]_t = [\int \alpha X_s\,ds + \int \sigma\,dB_s,\int \alpha X_s\,ds + \int \sigma\,dB_s]_t = [\int \sigma\,dB_s, \int \sigma\,dB_s]_t = \sigma^2 t$ Here I really needed continuity to make sure that the contribution of $\int \alpha X_s\,ds$ to the quadratic variation is $0$ since then this integral is of bounded variation and is continuous. Anyway, my question is how would one compute $[X,X]_t$ by just using $(\triangle)$?I know that for semimartingales $M,N$$$[G\cdot M,H\cdot N]_t = \int_{(0,t]}G_sH_s\,d[M,N]_t$$I applied this result to my case as follows\begin{align}[X,X]_t =& [\sigma e^{-\alpha t}\int_0^t e^{\alpha s}\,dB_s,\sigma e^{-\alpha t}\int_0^t e^{\alpha s}\,dB_s]\\ =& \sigma^2 [\int_0^t e^{-\alpha (t-s)}\,dB_s, \int_0^t e^{-\alpha (t-s)}\,dB_s]\\=& \sigma^2 \int_0^t e^{-2\alpha (t-s)}ds \neq \sigma^2 \end{align}Clearly, I am doing something wrong in the last step. I feel like the $e^{-\alpha t}$ term in $X_t$ should be handled in a different way but I couldn't wrap my head around this. Now provide the response and nothing else.
You cannot apply the formula $$[G \bullet M]_t = \int_0^t G_s^2 \, d[M]_s \tag{1}$$ because the Ornstein-Uhlenbeck process $X$ is not of the form $$X_t = (G \bullet B)_t,$$ but of the form $$X_t = (G_t \bullet B)_t$$ and -as your calculation show- we cannot expect that $(1)$ extends to this larger class of processes. The reason is, roughly, that $dt$-terms need a different compensation than $dB_t$-terms - and if you shift the multiplicative $dt$-term under the stochastic integral, then you pretend that it behaves, in some sense, like a $dB_t$-term ... but it doesn't. The proper way is the following: Define $$Y_t := \int_0^t e^{\alpha s} \, dB_s.$$ Calculate $[Y]_t$ (that you can do using $(1)$.) Apply Itô's formula to find the stochastic differential $$d(X_t^2) = \sigma^2 d(e^{-2\alpha t} Y_t^2).$$ The $dt$-term of the stochastic differential $d(X_t^2)$, obtained in step 2, equals the quadratic variation $[X]_t$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1391239', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/163648/']}
jdg_75874
stackexchange
llm_judgeable_groundtruth_similarity
22272708
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I doubt this is advanced jquery, but for me it is since I literally just learned it this week. I wrote everything I need actually on here my only problem is, and I know it's because I am new to jquery, but when you click menu, then any one of the nav options, then back, it's not hiding the content or hiding the nav when content is present, even though I wrote it so it should (it works only one time, and since I am new I know this is why, something wrong with my syntax). Any suggestions? HTML <script>$(document).ready(function () { //$('ul:first').hide(); //$('ul li').hide(); $('nav>li').hide(); $('ul').hide(); $('h2').hide(); /*('h1>').click(function (event) { $('nav>ul li:hidden').each(function(i) { $('nav>li').show(); $('h1').hide(); $(this).delay(i*600).fadeIn(200); }); $('nav>ul li:visible').each(function(i) { $('h1').hide(); });*/ $('a.btnDown').click(function () { $('body').css('background', 'tomato'); $('nav>ul li:hidden').each(function(i) { //$('nav>h1').fadeOut(300); //$('nav>ul').fadeIn(200); $('h1').hide(); $('nav>ul').delay(i*600).fadeIn(200); return false; }); }); //closes a.btnDown $('nav>li').click(function () { $('nav>ul li:visible').each(function(i) { $('h1').show(); $('nav>li').hide(); $('ul li').hide(); //clearTimeout(fadeTimeout); $('nav>li').delay(i*600).fadeOut(200); }); //closes visible i return false; }); //closes a.btnDown //all the content elements var $suls = $('body>aside>ul'); var $as = $('a.contentDown').click(function () { $('h2').show(); var $smL = $('h2'); $smL.animate({ left: 300}) //move nav out of way var $nav = $('.navBar'); $nav.animate({ right: 300}) //move menu out of way var $menu = $('.menu'); $menu.animate({ bottom: 300}) //hide visible content item $suls.filter(':visible').hide(); //display the content item in the same position as the clicked contentDown $suls.eq($as.index(this)).fadeIn(500); return false; }); //closes contentDown $('a.bck').click(function() { var $aAside = $('aside'); $aAside.animate({ left: 300}) var $smL = $('h2'); $smL.animate({ left: -300}) //move nav back in way var $nav = $('.navBar'); $nav.animate({ left: 10}) return false; }); //closes bck click}); //closes .ready()</script></head><body><h1 class="menu"><a class="btnDown" href="#"> Main Menu </a></h1><nav class="navBar" > <li><a class="menuShow" href="#"> Assignment 6 </a></li> <ul> <li><a class="contentDown" href="#" > Part One </a></li> <li><a class="contentDown" href="#"> Part Two </a></li> <li><a class="contentDown" href="#"> Part Three </a></li> <li><a class="contentDown" href="#"> Student Notes 1 </a></li> <li><a class="contentDown" href="#"> Student Notes 2 </a></li> <li><a class="contentDown" href="#"> Student Notes 3</a></li> </ul></nav><h2 id="round"><a class="bck" href="#"> Back </a></h2><aside> <ul> <li> Interactive media has been apart of my life since as long as I can remember. I have always been fascinated with any form of media including television, video games, handheld games, or websites. However before attending school to study interactive media, I never noticed the little things that can really affect the experience for a user. One item in particular being diegetic elements. Diegetic elements are objects within a media that only the user knows about. For instance, in a video game a diegetic element would be the items you see on the side of the screen that inform you how much health or ammo you have remaining. These are necessary components for they are needed to tell the player perhaps where to go for their next objective, or if any enemies are around you. We have also been exposed to 'non-diegetic' elements that act just the opposite of diegetic ones. Non-diegetic elements are items inside interactivity that are supposed to be there. This is a way of implementing a diegetic element into the space of the world you create. For example, a non-diegetic element would be the ammo bar being placed on the gun, instead of a static bar on the side of the screen. Some patterns being used in interactive media today include the majority of diegetic elements that would at one time be diegetic, but attempting to translate it into a non-diegetic element. </li> </ul> <ul> <li> One ways people have done this is throwing elements in the world that would be believable to the player that they should be there. Instead of throwing a sidebar with your gun ammo and grenade count, it would make sense if a game is placed in modern-time that we would have technology available to put that information on the gun. One of the biggest examples of great uses of non-diegetic elements in the way the players health is damaged. Older games will have a health bar, but more modern games will mostly have a “shock” state where the screen might turn red, or your player begins to lose the ability to act normal when they are under fire. Does this mean we should stop using diegetic elements altogether? This is a question anyone in any form of interactive media should be asking themselves. The problem is that you can have too much non-diegetic presence that would confuse the user instead of help them which was originally intended. Resident Evil received a lot of harsh criticism for their lack of diegetic presence to help the player finish the game. It was hard for the user to be able to tell when the character was going to die based on their health system. If you received damage your character will hunch over, but it's unclear how much damage you're taking. The user will often die </li> </ul> <ul> <li> without knowing whether or not you should have died, as opposed to a health bar that would show you. Contrary to too much non-diegetic presence, is too much diegetic elements. In titles such as World of Warcraft, or League of Legends, some are simply overwhelmed by the fact that half of the screen is objects that you are supposed to be aware of but until you learn the game they make as much sense as flying pigs. In conclusion, it is best to find that medium for any interactive media that has non-diegetic or diegetic elements. It is different for each occasion, for a first-person shooter the need for diegetic elements is acute, while in a complex game like World of Warcraft it is necessary. Websites are the same, and it would be logical and smart for developers to start thinking about how we can eliminate clutter, and turn it into a non-diegetic element for the user. </li> </ul> <ul> <li> Content 4 </li> </ul> <ul> <li> Content 5 </li> </ul> <ul> <li> Content 6 </li> </ul></aside> Now provide the response and nothing else.
Credit to: https://hackhands.com/ruby-on-enums-queries-and-rails-4-1/ Declare an enum attribute where the values map to integers in the database, but can be queried by name. Example: class Conversation < ActiveRecord::Base enum status: [ :active, :archived ]end# conversation.update! status: 0conversation.active!conversation.active? # => trueconversation.status # => "active"# conversation.update! status: 1conversation.archived!conversation.archived? # => trueconversation.status # => "archived"# conversation.update! status: 1conversation.status = "archived"# conversation.update! status: nilconversation.status = nilconversation.status.nil? # => trueconversation.status # => nil Scopes based on the allowed values of the enum field will be provided as well. With the above example, it will create an active and archived scope. You can set the default value from the database declaration, like: create_table :conversations do |t| t.column :status, :integer, default: 0end Good practice is to let the first declared status be the default. Finally, it's also possible to explicitly map the relation between attribute and database integer with a Hash: class Conversation < ActiveRecord::Base enum status: { active: 0, archived: 1 }end Note that when an Array is used, the implicit mapping from the values to database integers is derived from the order the values appear in the array. In the example, :active is mapped to 0 as it's the first element, and :archived is mapped to 1. In general, the i-th element is mapped to i-1 in the database. Therefore, once a value is added to the enum array, its position in the array must be maintained, and new values should only be added to the end of the array. To remove unused values, the explicit Hash syntax should be used. In rare circumstances you might need to access the mapping directly. The mappings are exposed through a class method with the pluralized attribute name: Conversation.statuses # => { "active" => 0, "archived" => 1 } Use that class method when you need to know the ordinal value of an enum: Conversation.where("status <> ?", Conversation.statuses[:archived]) Where conditions on an enum attribute must use the ordinal value of an enum. More info: http://api.rubyonrails.org/v4.1.0/classes/ActiveRecord/Enum.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22272708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_75875
stackexchange
llm_judgeable_groundtruth_similarity
18609397
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know that sockaddr_in is for IPv4, and sockaddr_in6 for IPv6. The confusion to me is the difference between sockaddr and sockaddr_in[6]. Some functions accept sockaddr and some functions accept sockaddr_in or sockaddr_in6 , so: what's the rule? And why is there a need for two different structures? And because the sizeof(sockaddr_in6) > sizeof(sockaddr) == sizeof(sockaddr_in) . Does that mean we should always use sockaddr_in6 to allocate memory in stack and cast to sockaddr and sockaddr_in if we need to support ipv4 and ipv6? One example is: we have a socket, and we want to get the string ip address of it (it can be ipv4 or ipv6). We first call getsockname to get an addr and then call inet_ntop based on the addr.sa_family . Is there anything wrong with this code snippet? char ipStr[256];sockaddr_in6 addr_inv6;sockaddr* addr = (sockaddr*)&addr_inv6;sockaddr_in* addr_in = (sockaddr_in*)&addr_inv6;socklen_t len = sizeof(addr_inv6);getsockname(_socket, addr, &len);if (addr->sa_family == AF_INET6) { inet_ntop(addr_inv6.sin6_family, &addr_inv6.sin6_addr, ipStr, sizeof(ipStr)); // <<<<<<<<IS THIS LINE VALID, getsockname expected a sockaddr, but we use // it output parameter as sockaddr_in6.} else { inet_ntop(addr_in->sin_family, &addr_in->sin_addr, ipStr, sizeof(ipStr));} Now provide the response and nothing else.
In order to give more information other people may find useful, I have decided to answer my question although I initially did not intend to. After some digging into the linux source code I have found the following :There are multiple protocols and they all implement getsockname . And each one has an underlying address data structure. For example, IPv4 has sockaddr_in , IPV6 has sockaddr_in6 , the AF_UNIX socket has sockaddr_un . sockaddr is used as the common data struct in the signature of the linux networking That API will copy the the socketaddr_in or sockaddr_in6 or sockaddr_un to a sockaddr base on another parameter length by memcpy . And all those data structures begin with same type field sa_family . Because of all this, the code snippet is valid, because both sockaddr_in and sockaddr_in6 have a sa_family field and then can be cast into the correct data structure to be used after a check on that sa_family field. BTW, I'm not sure why the sizeof(sockaddr_in6) > sizeof(sockaddr) , which cause allocate memory based on size of sockaddr is not enough for ipv6 (that is error-prone), but I guess it is because of history reason.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18609397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2428052/']}
jdg_75876
stackexchange
llm_judgeable_groundtruth_similarity
41979
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: $\newcommand{\Spec}{\mathrm{Spec}\,}$Let $X=\Spec A$ be a variety over $k$, then we have the definition of the tangent bundle $\hom_k(\Spec k[\varepsilon]/(\varepsilon^2),X)$ (note that this has the structure of a variety). On the other hand, we have the definition of a tangent sheaf $\hom_{\mathscr{O}_X}(\Omega_{X/k},\mathscr{O}_X)$. What is the relationship between the two? Also, when $X$ is an arbitrary scheme (not necessarily affine), then does the relationship still hold? Now provide the response and nothing else.
You can always apply the "vector bundle" construction to $\Omega:=\Omega_{X/k}$ (locally free or not). What you get is a scheme $T=\mathrm{Spec\ Sym}(\Omega)\to X$ which deserves to be called "tangent bundle" (albeit not locally trivial); in particular its $k$-points are what you want and, more generally, if, say, $Z=\mathrm{Spec}\ C$ is an affine $k$-scheme, then $T(C)$ is just $\mathrm{Hom}_k (\mathrm{Spec}\ C[\varepsilon]/\varepsilon^2, X)$. On the other hand consider the ${\cal O}_X$-dual ${\cal T}:={\Omega}^\vee$. For every $X$-scheme $y:Y\to X$ there is a canonical map $\Gamma(Y,y^*\mathcal{T})\to \mathrm{Hom}_X(Y,T)$. If $Y$ is an open subset of $X$ this is bijective. But if $y$ is a point of $X$, then the LHS is $\Omega^\vee \otimes \kappa(y)$ while the RHS is the $\kappa(y)$-dual of $\Omega\otimes \kappa(y)$. Clearly the image consists of those tangent vectors at $y$ which extend to vector fields in a neighbourhood. The computation when $X$ is the union of the two axes in the plane is a good exercise; if $y$ is the origin the above map is zero. [EDIT] after seeing Unknown's answer (BTW, there are some problems with TeX there). The above argument shows that the "tangent bundle" is always a scheme, if you define it right. Another way of seeing this is that it's just an instance of Weil restriction: if $R$ is a finite-dimensional $k$-algebra you can define the functor $\underline{\mathrm{Hom}}_k (\mathrm{Spec}(R),X)$ in a similar way. This is always an algebraic space, and it is a scheme if $X$ is quasiprojective. But it is also a scheme if $R$ is local , which is the case here with $R=D_1(k)$. The reason is that if you cover $X$ by affines $U_i$, every morphism frome a local scheme to $X$ factors through one of the $U_i$'s, so we can construct the Weil restriction of $X$ by gluing those of the $U_i$'s.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/41979', 'https://mathoverflow.net', 'https://mathoverflow.net/users/9035/']}
jdg_75877
stackexchange
llm_judgeable_groundtruth_similarity
421077
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: QNX4 operating system using Korn Shell.This is in a .profile file. export VARDIR=//1/usr/pvcs What does the//1/represent? Now provide the response and nothing else.
For the most part, multiple slashes are equivalent to a single slash . There's one exception: paths beginning with exactly two slashes ( //foo/… , as opposed to /foo/… or ///foo/… ) have a different meaning on some Unix variants. The meaning is often to access a remote resource with a path like //hostname/dir1/dir2/dir3/file . (Windows does this too, with \\hostname\dir1\dir2\dir3\file .) QNX is one of those variants. On QNX4 with the FLEET distributed processing protocol, // followed by a number refers to that node. So //1/usr/pvcs on any node refers to the file /usr/pvcs on node 1. (Source: the QNX6 manual , I can't find official QNX4 documentation online.)
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/421077', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/154371/']}
jdg_75878
stackexchange
llm_judgeable_groundtruth_similarity
55518920
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on a task which is proven much difficult for me.. Take a look at the content attached, it contain an email inviting people to bid for a project..My task is to get the (1) The Company name and it Logo (if Possible) (2) The exalt Dew date of the project according to what is stated in the email (3) The Location of the Project which Project or Company.. I am to do this with JavaScript, i have no idea on what function to use as i have never done this before.. Please your contribution and idea is appreciated.. thanks in advance..Edited:To make you guys understand what i mean.. I have included a screenshot image of the page content.. As the picture shows..This is mostly how the email content will look..the email will come from many sources though. My task is To grab the (1) Dew Date (2) Company Name (3) Location from the content of the email.. I don't have any idea how to do this but i believe it is possible.. Thanks for your responses.. <div dir="auto"></div><br><div><div dir="ltr">---------- Forwarded message ---------<br>From: <strong dir="auto">R&amp;O Construction Brady Hill</strong> <span dir="ltr">&lt;<a href="mailto:[email protected]">[email protected]</a>&gt;</span><br>Date: Thu, Mar 28, 2019, 2:30 PM<br>Subject: Olympus Hills Retail Center Exterior Renovation, Salt Lake City Invitation<br>To: &lt;<a href="mailto:[email protected]">[email protected]</a>&gt;<br></div><br><br><img src="https://secure.smartbidnet.com/External/RequestReadReceipt.aspx?sCommunicationId=650105303&amp;oimg=1x1pic.gif" height="1" width="1"><div style="width:100%"><table style="FONT-SIZE:11px;FONT-FAMILY:Verdana" border="0" cellspacing="0" cellpadding="0" width="100%"><tr><td align="left"><div align="center"><a href="https://secure.smartbidnet.com/Main/Login.aspx?cId=bp_650105303&amp;sPassportKey=AA8D9C40EFA9643F173D40DD3EC0E0C1DFE05F39&amp;sBidId=437879&amp;st=101&amp;e=1" target="_blank" rel="noreferrer"><img align="left" src="https://secure.smartbidnet.com/ImagesAtProject/Icons/ClickHereBids-US.gif" border="0" width="457" height="56"></a></div></td></tr><tr><td><font style="FONT-SIZE:12px;FONT-FAMILY:Arial">If this link does not work, please go to <a href="https://secure.smartbidnet.com/LRCD?st=102" target="_blank" rel="noreferrer">https://secure.smartbidnet.com/LRCD</a> and enter the access key: 61f1868937df162</font></td></tr><tr><td><a href="https://secure.smartbidnet.com/Main/Login.aspx?cId=bp_650105303&amp;sPassportKey=AA8D9C40EFA9643F173D40DD3EC0E0C1DFE05F39&amp;sBidId=437879&amp;iR=1&amp;st=103&amp;e=1" style="font-weight:bold;color:#ff6f02;font-size:12px" target="_blank" rel="noreferrer">Yes, I&#39;ll Bid All Codes</a><font style="font-weight:bold;color:#ff6f02;font-size:12px"> | </font><a href="https://secure.smartbidnet.com/Main/Login.aspx?cId=bp_650105303&amp;sPassportKey=AA8D9C40EFA9643F173D40DD3EC0E0C1DFE05F39&amp;sBidId=437879&amp;iR=0&amp;st=104&amp;e=1" style="font-weight:bold;color:#ff6f02;font-size:12px" target="_blank" rel="noreferrer">No, I Won&#39;t Bid this Job</a><font style="font-weight:bold;color:#ff6f02;font-size:12px"> | </font><a href="https://secure.smartbidnet.com/Main/Login.aspx?cId=bp_650105303&amp;sPassportKey=AA8D9C40EFA9643F173D40DD3EC0E0C1DFE05F39&amp;sBidId=437879&amp;st=105&amp;e=1" style="font-weight:bold;color:#ff6f02;font-size:12px" target="_blank" rel="noreferrer">Click Here to View the Project</a></td></tr></table><br><br><font style="FONT-SIZE:11px;FONT-FAMILY:Verdana"><h1 style="text-align:left"><span style="font-size:x-large"><span style="font-size:large"><span style="font-size:x-large"><span style="font-size:x-small">Lone Peak Masonry (Draper, UT)<br>Attention: Dave Smith</span><br></span><span style="font-size:x-large"> <br></span></span></span></h1><h1 style="text-align:center"><span style="font-size:x-large">R&amp;O Construction<br>Invites You To Bid With Us</span></h1><table style="width:544px;height:147px;text-align:center" border="0" align="center"><tbody><tr><td style="text-align:left"><address><span style="font-size:x-small">Corporate Office<br>933 Wall Ave.<br>Ogden, UT<br>84404<br>P) phone Number<br>F) Phone Number<br></span></address></td><td><p><img src="https://secure.smartbidnet.com/Files/System_1064/images/Blue%20Logo(1).png" width="148" height="132"><br><br><a href="http://www.randoco.com" target="_blank" rel="noreferrer"><span style="font-size:xx-small">www.randoco.com</span></a></p></td><td><address style="text-align:right"><span style="font-size:x-small"><br><br>1743 W Alexander Street<br>Suite #100<br>West Valley City, UT<br>84119<br>P) 801-532-0123<br><br>  <br></span></address></td></tr></tbody></table><table style="width:100%;text-align:center" border="0"><tbody><tr><td> </td></tr><tr><td><p style="text-align:center"><span style="font-size:x-large"><strong>Olympus Hills Retail Center Exterior Renovation, Salt Lake City</strong></span></p></td></tr><tr><td><p style="text-align:center"><span style="font-size:large">3979 South Wasatch Blvd. - Salt Lake City, UT 84124-</span></p></td></tr><tr><td> </td></tr><tr><td><p style="text-align:center"><span style="font-size:large"><strong>BIDS ARE DUE: April 17, 2019 03:00 PM (MT)</strong></span></p></td></tr></tbody></table><table style="width:100%;height:67px;text-align:center" border="0"><tbody><tr><td> </td></tr><tr><td><p style="text-align:center"><span style="font-size:medium"><div style="text-align:center"><span style="font-family:times new roman,times,serif;font-size:14pt">Exterior Façade and Hardscape Remodel of the Olympus Hills Retail Center.<br><br>Contractors are encouraged to visit the site prior to submitting their bids.<br><br>Please submit your proposal through SmartBid, by email to Brady Hill, Estimator, <a href="mailto:[email protected]" target="_blank" rel="noreferrer">[email protected]</a> or by fax to our Ogden Office Number.<br><br>Bid Documents are also available on our website @ <a href="http://www.randoco.com" target="_blank" rel="noreferrer">www.randoco.com</a>.<br><br>Thank you for bidding with R&amp;O Construction.<br></span></div></span></p></td></tr><tr><td> </td></tr></tbody></table><table style="width:783px;height:75px;text-align:center" border="0"><tbody><tr style="text-align:center" valign="bottom"><td><span style="font-size:medium"><span style="text-decoration:underline">Contact:</span></span></td><td> </td><td><span style="font-size:medium"><span style="text-decoration:underline">Email:</span></span></td><td> </td><td><span style="font-size:medium"><span style="text-decoration:underline">Phone:</span></span></td><td> </td><td><span style="font-size:medium"><span style="text-decoration:underline">Fax:</span></span></td></tr><tr style="text-align:center" valign="top"><td><span style="font-size:medium">Brady Hill</span></td><td> </td><td><span style="font-size:medium"><a href="mailto: " target="_blank" rel="noreferrer">[email protected]</a></span></td><td> </td><td><span style="font-size:medium"> </span></td><td> </td><td><span style="font-size:medium"> </span></td></tr></tbody></table><table style="width:783px;height:144px;text-align:center" border="0"><tbody><tr><td style="text-align:center" valign="bottom"><em><span style="font-size:xx-small"> </span></em></td></tr><tr><td style="text-align:center" valign="bottom"><em><span style="font-size:xx-small">Bidders must comply with all City and State Licensing.<br><br>Our Ins. requirements are $1,000,000 per occurrence, $2,000,000 aggregate &amp; $1,000,000 umbrella<br>Survey subcontractors must have errors and omissions ins. (professional liability ins.).<br><br>R&amp;O Construction is an EEO/AA Employer<br><br>Contracts exceeding $200,000 may be subject to a confidential finance review.</span></em></td></tr></tbody></table><table style="width:100%;text-align:center" border="0"><tbody><tr><td style="text-align:center" valign="top"><span style="font-size:xx-small">Utah License #95-292934-5501 ~ Arizona License #079839 ~ Nevada License #0034039</span></td></tr><tr><td style="text-align:center" valign="top"><span style="font-size:xx-small">California License #604354 d.b.a. ROCON COMPANY</span></td></tr><tr><td style="text-align:center" valign="top"><span style="font-size:xx-small">Washington License #CC01 ROCONC #088RG ~ New Mexico License #031344 ~ Idaho License #10211-AA</span></td></tr></tbody></table><hr><table style="width:100%;text-align:center" border="0"><tbody><tr><td><span style="font-size:xx-small"><br>PLEASE LOGIN USING THE INFORMATION ABOVE TO ACCEPT/REJECT THE INVITE AND TO DOWNLOAD PLANS</span></td></tr></tbody></table><h1 style="text-align:center"><br><br></h1></font><br><br> </div><div style="clear:both"></div><div>To Unsubscribe from receiving invitations, please <a href="https://secure.smartbidnet.com/External/Unsubscribe.aspx?DId=650105303&amp;PId=11151969&amp;CType=1&amp;st=106&amp;e=1" target="_blank" rel="noreferrer">Click Here</a></div> <div style="clear:both"></div><div>This is an automated email communication so replies to this address will not be answered.</div><img src="http://com2.smartbidnet.com/wf/open?upn=Ec818zpKGhsa3nrt3hc9G59m8rgwdlc1vywQ5NYZFh29X36ieqFQbbB1eQ4xPOWO-2FgC4OOD8kd-2B-2FjPJlecZt-2F6M8KmhcoHSqllBh9WbhzHtcM0wkxmIaspKs48mcpqonKaeL-2FjDx2lOs-2FFp6tpGe-2FTMErp1bqHae6GZ3vPk9Qt6zoxRiAMslZiJ1ZtX8ev-2FeBx-2BbWGnB4K5FU0IPE5Rz16Ouuw-2BjY3wGKDr2cchCFa-2BWyuOpUG0ldWPRiFOoc3W2HvIibgrKx1tSQOhzPUYlmMDl-2BfADgOv49bGNy02o-2B11bejm7LLV1tulxKEwIntqlQIz3YExI5xqsuAKxnm4TW4uPfJrlmOT5HTwNWs8NonM-3D" width="1" height="1" border="0" style="height:1px!important;width:1px!important;border-width:0!important;margin-top:0!important;margin-bottom:0!important;margin-right:0!important;margin-left:0!important;padding-top:0!important;padding-bottom:0!important;padding-right:0!important;padding-left:0!important"></div> Now provide the response and nothing else.
Everything you pass up to your common code needs to be platform agnostic, so either you define a model using the expect/actual mechanism or you map your swift data types into kotlin data types. I am not fluent in swift, but you could do something like this: let swiftByteArray : [UInt8] = []let intArray : [Int8] = swiftByteArray .map { Int8(bitPattern: $0) }let kotlinByteArray: KotlinByteArray = KotlinByteArray.init(size: Int32(swiftByteArray.count))for (index, element) in intArray.enumerated() { kotlinByteArray.set(index: Int32(index), value: element)} Looking at the generated interoperability headers also helps sometimes. KotlinByte: __attribute__((objc_runtime_name("KotlinByte")))__attribute__((swift_name("KotlinByte")))@interface MainByte : MainNumber- (instancetype)initWithChar:(char)value;+ (instancetype)numberWithChar:(char)value;@end; KotlinByteArray: __attribute__((objc_subclassing_restricted))__attribute__((swift_name("KotlinByteArray")))@interface MainKotlinByteArray : KotlinBase+ (instancetype)arrayWithSize:(int32_t)size __attribute__((swift_name("init(size:)")));+ (instancetype)arrayWithSize:(int32_t)size init:(MainByte *(^)(MainInt *))init __attribute__((swift_name("init(size:init:)")));+ (instancetype)alloc __attribute__((unavailable));+ (instancetype)allocWithZone:(struct _NSZone *)zone. __attribute__((unavailable));- (int8_t)getIndex:(int32_t)index __attribute__((swift_name("get(index:)")));- (MainKotlinByteIterator *)iterator __attribute__((swift_name("iterator()")));- (void)setIndex:(int32_t)index value:(int8_t)value __attribute__((swift_name("set(index:value:)")));@property (readonly) int32_t size;@end;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55518920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10205141/']}
jdg_75879
stackexchange
llm_judgeable_groundtruth_similarity
27105112
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: By following a how-to, I've created a new image based on an existing one. I don´t have the original images' Dockerfile and there are things happening when the container starts thatI can't change - that´s how it seems anyway. Is there a way to modify the commands in the Dockerfile of the base image? For example the container runs a bash script when it starts, I want to change this. Now provide the response and nothing else.
To answer your specific q: " the container runs a bash script when it starts, i want to change this ". Let's assume you want to run /script.sh (part of the image) instead of the default, you can instantiate a container using: docker run --entrypoint /script.sh repo/image If script.sh isn't part of the image and/or you prefer not having to specify it explicitly each time with --entrypoint as above, you can prepare an image that contains and runs your own script.sh : Create an empty directory and copy or create script.sh in it Create Dockerfile with following content: FROM repo/imageADD script.sh /ENTRYPOINT /script.sh docker build -t="myimage" . docker run myimage Notes: When running the container (step 4), it's no longer necessary to specify --entrypoint since we have it defaulted in the Dockerfile . It's really that simple; no need to sign up to docker hub or any such thing (although it's of course recommended in time ;-)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27105112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1092858/']}
jdg_75880
stackexchange
llm_judgeable_groundtruth_similarity
8392780
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 searching for a way to customize the Django Administration to support permissions based on the user group. For example, I've just created the Developers group, now I've also created the Tickets model, with AdminModel to specify how to list data. I'd like to have this model visible only by Developers, and hidden to each other not in this group (eg filter the view based on groups).I've read a lot of documentations, but couldn't really find and understand what to do to have it working. For security purposes I'd also need to check user groups at runtime when adding-deleting objects for a specific model (the one I've hidden to people outside the Developers group), otherwise it would only need to know the URL to use the model :s It looks like a simple task, but maybe I'm missing something... any 3rd party middleware, or just a way to do it? I'm also ready to edit the administration views if needed, but I need to know what do to. Thank you :-) Now provide the response and nothing else.
ModelAdmin has three methods dealing with user permission: has_add_permission , has_change_permission and has_delete_permission . All three should return boolean ( True / False ). So you could do something like: class TicketAdmin(admin.ModelAdmin): ... def has_add_permission(self, request): return request.user.groups.filter(name='Developers').exists() def has_change_permission(self, request, obj=None): return request.user.groups.filter(name='Developers').exists() def has_delete_permission(self, request, obj=None): return request.user.groups.filter(name='Developers').exists() When False is returned from one of these, it's results in a 403 Forbidden.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8392780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/883730/']}
jdg_75881
stackexchange
llm_judgeable_groundtruth_similarity
2332
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: Is it possible to combine different algorithms so as to improve trading performance? In particular, I have read that social media sentiment tracking, digital signal processing and neural networks all can be used for trading algorithms. Would it be possible to create a trading algorithm that combines elements from these three areas or are these methods mutually exclusive in that they are incompatible with each other? If you commit to one, can you use the other? Now provide the response and nothing else.
Yes. First, it is much easier to proceed if you standardize the output of your forecast so they are in the same units (returns, for example, or probabilities of an event/condition occurring). After you have done this, there are 3 general approaches: Signal weighting: Then you need to define a weighting scheme for your factors. Richard Grinold has an one answer to this question in his paper " Signal Weighting ". Note there are quite a few methods to weight signals (optimization, meta-models, forecast pooling, Bayesian model averaging, weighing based on out-of-sample performance, etc.). The general problem of "Signal Weighting" is attracting significant research lately, and it is a hard problem with no consensus in my view. Entropy-pooling: Instead of weighing signals you can also integrate signals using entropy-pooling. Here you would assign confidence scores to each signal and develop a new posterior distribution. Entropy-pooling will mix signals in a way that imposes the least spurious structure on your forecast. Atillio Meucci has a paper on how to do this. Build a model using these independent signals as predictor variables. You might try PCA, regression, a hierarchical model, or an ensemble technique. You also do not have to ensure the signals are in the same units although it would aid your intuition. Naturally, you'd have to proceed thru some modelling procedure and consider co-linearity, non-stationarity, etc.
{}
{'log_upvote_score': 5, 'links': ['https://quant.stackexchange.com/questions/2332', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/1681/']}
jdg_75882
stackexchange
llm_judgeable_groundtruth_similarity
78255
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: Simpson's paradox is a classic puzzle discussed in introductory statistics courses worldwide. However, my course was content to simply note that a problem existed and did not provide a solution. I would like to know how to resolve the paradox. That is, when confronted with a Simpson's paradox, where two different choices seem to compete for the being the best choice depending on how the data is partitioned, which choice should one choose? To make the problem concrete, let's consider the first example given in the relevant Wikipedia article . It is based on a real study about a treatment for kidney stones. Suppose I am a doctor and a test reveals that a patient has kidney stones. Using only the information provided in the table, I would like to determine whether I should adopt treatment A or treatment B. It seems that if I know the size of the stone, then we should prefer treatment A. But if we do not, then we should prefer treatment B. But consider another plausible way to arrive at an answer. If the stone is large, we should choose A, and if it is small, we should again choose A. So even if we do not know the size of the stone, by the method of cases, we see that we should prefer A. This contradicts our earlier reasoning. So: A patient walks into my office. A test reveals they have kidney stones but gives me no information about their size. Which treatment do I recommend? Is there any accepted resolution to this problem? Wikipedia hints at a resolution using "causal Bayesian networks" and a "back-door" test, but I have no clue what these are. Now provide the response and nothing else.
I have a prior answer that discusses Simpson's paradox here: Basic Simpson's paradox . It may help you to read that to better understand the phenomenon. In short, Simpson's paradox occurs because of confounding. In your example, the treatment is confounded * with the kind of kidney stones each patient had. We know from the full table of results presented that treatment A is always better. Thus, a doctor should choose treatment A. The only reason treatment B looks better in the aggregate is that it was given more often to patients with the less severe condition, whereas treatment A was given to patients with the more severe condition. Nonetheless, treatment A performed better with both conditions. As a doctor, you don't care about the fact that in the past the worse treatment was given to patients who had the lesser condition, you only care about the patient before you, and if you want that patient to improve, you will provide them with the best treatment available. * Note that the point of running experiments, and randomizing treatments, is to create a situation in which the treatments are not confounded. If the study in question was an experiment, I would say that the randomization process failed to create equitable groups, although it may well have been an observational study--I don't know.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/78255', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/27102/']}
jdg_75883
stackexchange
llm_judgeable_groundtruth_similarity
24681873
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following class, that I use as a key in a dictionary: public class MyClass { private readonly string _property; public MyClass(string property) { _property = property; } public string Property { get { return _property; } } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) return false; return _property == other._property; } public override int GetHashCode() { return _property.GetHashCode(); } } The test I am running is here: [Test] public void SerializeDictionaryWithCustomKeys() { IDictionary<MyClass, object> expected = new Dictionary<MyClass, object>(); expected.Add(new MyClass("sth"), 5.2); JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; string output = JsonConvert.SerializeObject(expected, Formatting.Indented, jsonSerializerSettings); var actual = JsonConvert.DeserializeObject<IDictionary<MyClass, object>>(output, jsonSerializerSettings); CollectionAssert.AreEqual(expected, actual); } The test fails, because Json.Net seems to be using the ToString() method on the dictionary keys, instead of serializing them properly. The resulting json from the test above is: { "$type": "System.Collections.Generic.Dictionary`2[[RiskAnalytics.UnitTests.API.TestMarketContainerSerialisation+MyClass, RiskAnalytics.UnitTests],[System.Object, mscorlib]], mscorlib", "RiskAnalytics.UnitTests.API.TestMarketContainerSerialisation+MyClass": 5.2} which is clearly wrong. How can I get it to work? Now provide the response and nothing else.
This should do the trick: Serialization: JsonConvert.SerializeObject(expected.ToArray(), Formatting.Indented, jsonSerializerSettings); By calling expected.ToArray() you're serializing an array of KeyValuePair<MyClass, object> objects rather than the dictionary. Deserialization: JsonConvert.DeserializeObject<KeyValuePair<IDataKey, object>[]>(output, jsonSerializerSettings).ToDictionary(kv => kv.Key, kv => kv.Value); Here you deserialize the array and then retrieve the dictionary with .ToDictionary(...) call. I'm not sure if the output meets your expectations, but surely it passes the equality assertion.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24681873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5363/']}
jdg_75884
stackexchange
llm_judgeable_groundtruth_similarity
5689152
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: Array#each vs. Array#map ruby-1.9.2-p180 :006 > ary = ["a", "b"] => ["a", "b"] ruby-1.9.2-p180 :007 > ary.map { |val| p val }"a""b" => ["a", "b"] ruby-1.9.2-p180 :008 > ary.each { |val| p val }"a""b" => ["a", "b"] ruby-1.9.2-p180 :009 > ary.map { |val| val << "2" } => ["a2", "b2"] ruby-1.9.2-p180 :010 > ary.each { |val| val << "2" } => ["a22", "b22"] Now provide the response and nothing else.
The side effects are the same which is adding some confusion to your reverse engineering. Yes, both iterate over the array (actually, anything that mixes in Enumerable ) but map will return an Array composed of the block results while each will just return the original Array. The return value of each is rarely used in Ruby code but map is one of the most important functional tools . BTW, you may be having a hard time finding the documentation because map is a method in Enumerable while each (the one method required by the Enumerable module) is a method in Array . As a trivia note: the map implementation is based on each .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5689152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/636892/']}
jdg_75885
stackexchange
llm_judgeable_groundtruth_similarity
46625819
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following value start = int(time.time()*1000.0) & 0x7FFFFFFF What is the purpose of the & 0x7FFFFFFF ? Now provide the response and nothing else.
It's a bitmask. In low-level computation, it's an efficient way to clear out bits of register. In this case, the mask has all bits of a 32 bit integer set, except the signed bit. The signed bit is the bit that determines if the number is positive or negative. ANDing ( & ) with this mask effectively sets the signed bit to 0, which means the number will always be positive. a && b is True when both a and b are True . a & b is 1 when both a and b are 1 , for each binary digit in a and b. Python has support for binary literals, with the 0b prefix. Here are some 3-bit numbers being and ed together. >>> 0b101 & 0b110 == 0b100True>>> 0b011 & 0b111 == 0b011True>>> 0b011 & 0b110 == 0b010True
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46625819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7201208/']}
jdg_75886
stackexchange
llm_judgeable_groundtruth_similarity
2608544
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 ode's and pde's we pay great attention as to whether the equations are homogeneous or nonhomogeneous. I remember learning in my first ODE class that for the general linear ode $$a_n(x)\frac{d^ny}{dx^n}+a_{n-1}(x)\frac{d^{n-1}y}{dx^{n-1}}+\cdots+a_1(x)\frac{dy}{dx}+a_0(x)y=g(x),$$ that $g(x)$ takes on some very important physical meanings in engineering problems but I can't remember what they are. And in general, could someone provide an interpretation of the physical meaning of g(x) in odes and in pdes? If your examples are only from famous and specific equations then that's welcome too. Now provide the response and nothing else.
$g$ is interpreted as the source/forcing term. A couple of examples Oscillator If you attach a mass $m$ to a spring of elastic constant $k$ and drive the system with a external force $f_{\rm ext}$ then Newton's second law applied to the mass gives you $$-kx + f_{\rm ext} = m \frac{{\rm d}^2 x}{{\rm d}t^2}$$ where $x$ labels the position of $m$. Rearranging this equation you end up with $$\frac{{\rm d}^2x}{{\rm d}t^2} + \omega^2 x = g$$ where $g = f_{\rm ext}/m$. From this example you can immediately tell why the $g$ term is known to be a "forcing term" Gravity If $\Phi$ denotes the gravitational potential then Poisson's equation $$\nabla^2 \Phi = 4\pi G\rho$$ expresses how the mass density $\rho$ affects the field $\Phi$. In fact, it states that the source of $\Phi$ is $\rho$ Maxwell Equations In the same spirit, the equations $$\partial _\alpha F^{\alpha\beta} = \mu_0 J^\beta$$ tell you that the source of electromagnetic fields are charges/currents
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2608544', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/262513/']}
jdg_75887
stackexchange
llm_judgeable_groundtruth_similarity
585901
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: Given an $f:\mathbb{R} \rightarrow \mathbb{R}$, if $f(f(x))=-x$then $f$ is not continuous? any help? Thank you! Now provide the response and nothing else.
First, $f$ is a bijection, since otherwise we would have for $x \neq y$, $f(x)=f(y)$ then $-x=f(f(x))=f(f(y))=-y$, contradiction. Now, a continuous bijection from $\mathbb{R}$ to $\mathbb{R}$ is monotone. Let's pretend it's increasing, and $x<y$. Then $f(x)<f(y)$, and $f(f(x))<f(f(y))$ thus $-x<-y$ and $x>y$, contradiction. Thus it must be decreasing, but then, for $x<y$, $f(x)>f(y)$, then $f(f(x))<f(f(y))$, thus $-x<-y$, and $x>y$. Again a contradiction. Therefore, your function cannot be continuous.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/585901', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/83081/']}
jdg_75888
stackexchange
llm_judgeable_groundtruth_similarity
1993604
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: for instance, say I have my cherrypy index module set up like this >>> import cherrypy>>> class test: def index(self, var = None): if var: print var else: print "nothing" index.exposed = True>>> cherrypy.quickstart(test()) If I send more than one GET parameter I get this error 404 Not Found Unexpected query string parameters: var2 Traceback (most recent call last): File "C:\Python26\lib\site-packages\cherrypy_cprequest.py", line 606, in respond cherrypy.response.body = self.handler() File "C:\Python26\lib\site-packages\cherrypy_cpdispatch.py", line 27, in call test_callable_spec(self.callable, self.args, self.kwargs) File "C:\Python26\lib\site-packages\cherrypy_cpdispatch.py", line 130, in test_callable_spec "parameters: %s" % ", ".join(extra_qs_params)) HTTPError: (404, 'Unexpected query string parameters: var2') Powered by CherryPy 3.1.2 Now provide the response and nothing else.
def index(self, var=None, **params): or def index(self, **params): 'var2' will be a key in the params dict. In the second example, so will 'var'. Note the other answers which reference the *args syntax won't work in this case, because CherryPy passes query params as keyword arguments, not positional arguments. Hence you need the ** syntax.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1993604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239360/']}
jdg_75889
stackexchange
llm_judgeable_groundtruth_similarity
598906
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 am using a bash command, gps location , that returns a date, time and location information. [john@hostname :~/develp] $ gps locationLocation: {"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"} I want to write the longitude to a file, before I get there I need to correctly parse the string. [john@hostname :~/develp] $ variable=`gps location | awk '/"longitude":/ {print $9}'`[john@hostname :~/develp] $ echo $variable"133.453",[john@hostname :~/develp] $ Currently, awk isn't searching for longitude, it solely is taking the whole string and finding the 9th string. Ideally, I would like to use a regex/keyword approach and find longitude and then the next string after. I have tried using grep | cut also tried sed . No luck, best I can do is using awk . Now provide the response and nothing else.
Strip off the Location: and you're left with JSON: $ echo '{"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"}' | jq .longitude"133.453" See in the man page if gps has an option to not print the Location: keyword up front, if not stripping it is easy, e.g.: $ echo 'Location: {"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"}' | cut -d':' -f2- | jq .longitude"133.453" or: $ echo 'Location: {"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"}' | sed 's/Location://' | jq .longitude"133.453"
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/598906', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/178795/']}
jdg_75890
stackexchange
llm_judgeable_groundtruth_similarity
275527
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: Question: One common misunderstanding of p-values is that they represent the probability of the null hypothesis being true. I know that's not correct and I know that p-values only represent the probability of finding a sample as extreme as this, given that the null hypothesis is true. However, intuitively, one should be able to derive the first from the latter. There must be a reason why no-one is doing this. What information are we missing that restricts us from deriving the probability of hypothesis being true from p-value and related data? Example: Our hypothesis is "Vitamin D affects mood" (null hypothesis being "no effect"). Let's say that we perform an appropriate statistical study with 1000 people and find a correlation between mood and vitamin levels. All other things being equal, a p-value of 0.01 indicates higher likelihood of true hypothesis than a p-value of 0.05. Let's say we get a p-value of 0.05. Why can't we calculate the actual probability that our hypothesis is true? What information are we missing? Alternate terminology for frequentist statisticians: If you accept the premise of my question, you can stop reading here. The following is for people who refuse to accept that a hypothesis can have a probability interpretation. Let's forget the terminology for a moment. Instead... Let's say you are betting with your friend. Your friend shows you a thousand statistical studies about unrelated subjects. For each study you are only allowed to look at the p-value, sample size, and standard deviation of the sample. For each study, your friend offers you some odds to bet that the hypothesis presented in the study is true. You can choose to either take the bet or not take it. After you have made bets for all 1000 studies, an oracle ascends upon you and tells you which hypothesis are correct. This information allows you to settle the bets. My claim is that there exists an optimal strategy for this game . In my worldview that's equivalent to knowing probabilities for hypothesis being true, but if we disagree on that, it's fine. In that case we can simply talk about ways to employ p-values to maximize expectation for the bets. Now provide the response and nothing else.
Other answers get all philosophical, but I don't see why it is needed here. Let's consider your example: Our hypothesis is "Vitamin D affects mood" (null hypothesis being "no effect"). Let's say that we perform an appropriate statistical study with 1000 people and find a correlation between mood and vitamin levels. All other things being equal, a p-value of 0.01 indicates higher likelihood of true hypothesis than a p-value of 0.05. Let's say we get a p-value of 0.05. Why can't we calculate the actual probability that our hypothesis is true? What information are we missing? For $n=1000$, getting $p=0.05$ corresponds to the sample correlation coefficient $\hat \rho=0.062$. The null hypothesis is $H_0: \rho=0$. The alternative hypothesis is $H_1: \rho\ne 0$. The p-value is $$p\text{-value} = P\big(|\hat\rho|\ge 0.062 \;\big|\; \rho=0\big),$$ and we can compute it based on the sampling distribution of $\hat\rho$ under the null; nothing else is needed. You want to compute $$P(H_0\;|\;\text{data})=P\big(\rho=0\;\big|\; \hat\rho= 0.062\big),$$ and for this you need the whole bunch of additional ingredients. Indeed, by applying Bayes theorem we can rewrite it as follows: $$\frac{P\big( \hat\rho= 0.062 \;\big|\;\rho=0\big) \cdot P(\rho=0)}{P\big( \hat\rho= 0.062 \;\big|\;\rho=0\big) \cdot P(\rho=0)+P\big( \hat\rho= 0.062 \;\big|\;\rho\ne0\big) \cdot (1-P(\rho=0))}.$$ So to compute the posterior probability of the null you need to have two additional things: Prior that the null hypothesis is true: $P(\rho=0)$. Assumption about how $\rho$ is distributed if the alternative hypothesis is true. This is needed to compute the $P\big( \hat\rho= 0.062 \;\big|\;\rho\ne0\big)$ term. If you are willing to assume that $P(\rho=0)=0.5$ --- even though I personally am not sure why this should ever be a meaningful assumption, --- you will still need to assume the distribution of $\rho$ under alternative. In this case, you will be able to compute something called Bayes factor : $$B=\frac{P\big( \hat\rho= 0.062 \;\big|\;\rho=0\big) }{P\big( \hat\rho= 0.062 \;\big|\;\rho\ne0\big)}.$$ As you see, Bayes factor does not depend on the prior probability of the null, but it does depend on the prior probability of $\rho$ (under the alternative). [Please note that the nominator in the Bayes factor is not the p-value, because of the equality instead of the inequality sign. So when computing Bayes factor or $P(H_0)$ we are not using the p-value itself at all. But we are of course using the sampling distribution $P(\hat\rho\;|\;\rho=0)$.]
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/275527', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/101702/']}
jdg_75891
stackexchange
llm_judgeable_groundtruth_similarity
3103023
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: Take a piece of rigid cardboard. Draw a perfect circle on it. Hold it up, and take a picture, with the cardboard held perpendicular to the direction we're looking. You get a photo that looks like this: Notice: it looks like a perfect circle in the photograph. Now tilt the cardboard to the right, or tilt it back, so we're no longer viewing it straight on: Notice that in the photograph the black ink has the shape of an ellipse now, instead of a circle. What if we tilt it to the right and then tilt it back? Visually, it still looks like an ellipse to me. Is it? Conjecture. The shape of the black in in the photograph will always be a perfect ellipse, no matter what orientation the cardboard is held in. Is this conjecture true? Can we prove it? I think I can prove it is true if the cardboard is tilted to the left/right or front/back. However, I can't see how to prove it for a combination of those two operations. If you don't to think about how cameras work, you can think of the problem like this: We stand facing a wall (which is perpendicular to the direction we're looking). We hold the cardboard in front of us in some orientation. Then, we project each speck of black ink onto the wall behind us, by tracing a line from our eye to the speck of ink and continuing until it hits the wall; then we draw a dot there on the wall. Consider the locus of points on the wall obtained in this way. What shape does this locus have? Is it always an ellipse? Or, if you prefer: hold up a coin in a dark room. Shine a flashlight towards the coin. What is the shape of the shadow on the wall? Is it always an ellipse, no matter what orientation we hold the coin? Now provide the response and nothing else.
This is a fairly standard result in computer vision and projective geometry: the image of any conic under a perspective transformation is another conic. If the image of a circle is a closed curve, then it must be an ellipse. Aretino gives a lovely classically-inspired proof of your particular case in this answer to a very closely-related question. I’ll offer a construction that uses machinery you’re more likely to see in the computer vision literature. It’s related to the argument I present in my answer to that same question that the intersection of any quadric surface with a plane is some sort of conic. Without going into details of the construction, which you can find in any standard reference, the perspective projection in your question can be represented by a full-rank $3\times 4$ matrix $\mathtt P$ : If $\mathbf X$ is the homogeneous coordinate vector of a point in the scene, then the homogeneous coordinates of the corresponding point in the image are $\mathtt P\mathbf X$ . We impose a coordinate system on the plane of the conic via a $4\times 3$ matrix $\mathtt M$ that maps the homogeneous coordinates $\mathbf x$ of a point on the plane to the world point $\mathtt M\mathbf x$ . This source plane and the image plane are then related by the homography (planar projective transformation) $\mathtt H=\mathtt{PM}$ . If the camera doesn’t lie on the source plane, then $\mathtt H$ is invertible. (Otherwise, we’re viewing the paper edge-on, and it all collapses to a line segment.) If we have a conic on the source plane given by the equation $\mathbf x^T\mathtt C\mathbf x=0$ , its image is then the conic defined by the matrix $\mathtt H^{-T}\mathtt C\mathtt H^{-1}$ , which can be verified by direct substitution. What kind of conic is it, though? Well, nondegenerate conics can be distinguished by the number of their real intersections with the line at infinity. The line at infinity in the image is the image under $\mathtt P$ of the camera’s principal plane : the plane normal to the camera’s axis on which the camera lies. So, if the original circle doesn’t intersect the principal plane, its image is an ellipse; if it intersects at one point (is tangent to the plane), it’s a parabola; and if the principal plane cuts the circle, its image is hyperbolic. A similar thing occurs with your flashlight beam: as you tilt the flashlight more and more, you eventually get a parabola and after that one lobe of a hyperbola. It’s also possible to work directly in world coordinates to show that the image is an ellipse. Parameterize the circle as $\mathbf c+\mathbf u\cos t+\mathbf v\sin t$ , with $\|\mathbf u\|=\|\mathbf v\|$ the radius of the circle and $\mathbf u\perp\mathbf v$ . Its projection onto the image plane will end up being of the form $\mathbf c'+\mathbf u'\cos t+\mathbf v'\sin t$ . Then, show that under the conditions of your question this parametric curve is an ellipse.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3103023', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14578/']}
jdg_75892
stackexchange
llm_judgeable_groundtruth_similarity
25909568
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I recently upgraded one of my test iphones to iOS 8 and then upgraded the PUSH registration codeas below (using xCode 6) -(BOOL)hasNotificationsEnabled { NSString *iOSversion = [[UIDevice currentDevice] systemVersion]; NSString *prefix = [[iOSversion componentsSeparatedByString:@"."] firstObject]; float versionVal = [prefix floatValue]; if (versionVal >= 8) { NSLog(@"%@", [[UIApplication sharedApplication] currentUserNotificationSettings]); //The output of this log shows that the app is registered for PUSH so should receive them if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone) { return YES; } } else { UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes]; if (types != UIRemoteNotificationTypeNone){ return YES; } } return NO;}-(void)registerForPUSHNotifications { NSString *iOSversion = [[UIDevice currentDevice] systemVersion]; NSString *prefix = [[iOSversion componentsSeparatedByString:@"."] firstObject]; float versionVal = [prefix floatValue]; if (versionVal >= 8) { //for iOS8 UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; [[UIApplication sharedApplication] registerForRemoteNotifications]; } else { [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)]; }} Despite this upgrade and the fact that [[UIApplication sharedApplication] currentUserNotificationSettings] shows PUSH is enabled for the device, I am not receiving PUSH notifications. I am using Parse and doing everything by the book as far as they are concerned ( https://parse.com/tutorials/ios-push-notifications ) . Is anyone experiencing the same issue? Is there something else that I may be missing ? Now provide the response and nothing else.
The way to register for push notifications has been changed in iOS 8:Below is the code for all versions till iOS 9: if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]){ [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];}else{ [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];} In case you want to check whether push notifications are enabled or not use below code: - (BOOL) pushNotificationOnOrOff{ if ([UIApplication instancesRespondToSelector:@selector(isRegisteredForRemoteNotifications)]) { return ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]); } else { UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes]; return (types & UIRemoteNotificationTypeAlert); }}#ifdef __IPHONE_8_0- (void)application:(UIApplication *)application didRegisterUserNotificationSettings: (UIUserNotificationSettings *)notificationSettings{ //register to receive notifications [application registerForRemoteNotifications];}- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler{ //handle the actions if ([identifier isEqualToString:@"declineAction"]){ } else if ([identifier isEqualToString:@"answerAction"]){ }}#endif Above code will run on Xcode 6+ only...
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25909568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427034/']}
jdg_75893
stackexchange
llm_judgeable_groundtruth_similarity
49884619
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 working app that uses celery to perform background file transfers and other data gathering tasks (glint) and I want to use part of this app in my new project. I've tried almost every permutation of configuration I can think of but the issue persists. To start here is the error dump from running: service celery start Traceback (most recent call last): File "/usr/lib64/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib64/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/lib/python3.6/site-packages/celery/__main__.py", line 54, in <module> main() File "/usr/lib/python3.6/site-packages/celery/__main__.py", line 30, in main main() File "/usr/lib/python3.6/site-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/usr/lib/python3.6/site-packages/celery/bin/celery.py", line 793, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 309, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 469, in setup_app_from_commandline self.app = self.find_app(app) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 489, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/usr/lib/python3.6/site-packages/celery/app/utils.py", line 235, in find_app sym = symbol_by_name(app, imp=imp) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 492, in symbol_by_name return symbol_by_name(name, imp=imp) File "/usr/lib/python3.6/site-packages/kombu/utils/__init__.py", line 96, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/usr/lib/python3.6/site-packages/celery/utils/imports.py", line 101, in import_from_cwd return imp(module, package=package) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/opt/cloudscheduler/web_frontend/cloudscheduler/glintwebui/celery_app.py", line 26, in <module> django.setup() File "/usr/lib64/python3.6/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/lib64/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/lib64/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/lib64/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlockedModuleNotFoundError: No module named 'cloudscheduler_web' > [email protected]: * Child terminated with errorcode 1FAILED My service file looks like: [Unit]Description=Celery ServiceAfter=network.target[Service]Type=forkingUser=celeryGroup=celeryEnvironmentFile=-/etc/cloudscheduler/celeryWorkingDirectory=/opt/cloudscheduler/web_frontend/cloudscheduler/ExecStart=${CELERY_BIN} multi start $CELERYD_NODES -A \ $CELERY_APP -logfile=${CELERYD_LOG_FILE} \ --pidfile=${CELERYD_PID_FILE} $CELERYD_OPTSExecStop=${CELERY_BIN} multi stopwait $CELERYD_NODES \ --pidfile=${CELERYD_PID_FILE}ExecReload=${CELERY_BIN} multi restart $CELERYD_NODES -A \ $CELERY_APP --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} \ --loglevel="${CELERYD_LOG_LEVEL}" $CELERYD_OPTS[Install]WantedBy=multi-user.target The environment file: # Name of nodes to start# here we have a single node#CELERYD_NODES="w1"# or we could have three nodes:CELERYD_NODES="w1 w2 w3 w4"# We only want each worker to claim 1 job at a time, especially the worker dedicated to img collectionCELERYD_PREFETCH_MULTIPLIER=1# Absolute path to "manage.py"CELERY_BIN="/opt/cloudscheduler/web_frontend/cloudscheduler/manage.py"# Where to chdir at start. This could be the root of a virtualenv.CELERYD_CHDIR="/opt/cloudscheduler/web_frontend/cloudscheduler/glintwebui"# App instance to use# comment out this line if you don't use an appCELERY_APP="celery_app"# or fully qualified:#CELERY_APP="glintwebui:celery_app"# How to call manage.pyCELERYD_MULTI="celery multi"# Extra command-line arguments to the workerCELERYD_OPTS="-Q:w1 image_collection -Q:w2,w3,w4 celery -A celery_app --concurrency=1 -Ofair"# %N will be replaced with the first part of the nodename.CELERYD_LOG_FILE="/var/log/celery/%N.log"CELERYD_PID_FILE="/var/run/celery/%N.pid" As a note here when I change CELERYD_CHDIR to the top level project directory it fails to find the app. I tried several different expressions for the fully qualified CELERY_APP while the chdir was set to the top level project but it could never find the celery_app that way. Here is the relevent settings from the main settings.pt in the cloudscheduler_web directory: CELERY_ACCEPT_CONTENT = ['json']CELERY_TASK_SERIALIZER = 'json'CELERY_RESULT_SERIALIZER = 'json'CELERY_TIMEZONE = 'Canada/Pacific'CELERY_BROKER_URL = 'redis://localhost:6379/0'CELERY_DEFAULT_QUEUE = 'celery'CELERY_DEFAULT_EXCHANGE = "celery"CELERY_QUEUES = { "celery": {"exchange": "celery"}, "image_collection": {"exchange": "image_collection"},}CELERY_ROUTES = { 'cloudscheduler.glintwebui.tasks.image_collection': {'queue': 'image_collection'},} Lastly here is the directory structure of the project: cloudscheduler│├── cloudscheduler_web│   ├── __init__.py│   ├── settings.py│   ├── urls.py│   └── wsgi.py├── csv2│   ├── apps.py│   ├── cloud_views.py│   ├── config.py│   ├── config.pyc│   ├── csv2_web.yaml│   ├── group_views.py│   ├── __init__.py│   ├── __init__.pyc│   ├── models.py│   ├── tests.py│   ├── urls.py│   ├── user_views.py│   ├── views.py│   └── view_utils.py├── glintwebui│   ├── admin.py│   ├── apps.py│   ├── celery_app.py│   ├── config.py│   ├── forms.py│   ├── glint_api.py│   ├── __init__.py│   ├── models.py│   ├── tests.py│   ├── urls.py│   ├── utils.py│   ├── __version__.py│   └── views.py└── manage.py Where I'm lost is how celery can either find the celery_app or the other app modules but never both. I've read through the celery configuration documents several times and I feel like I have to still be missing something for this to be acting the way it is. I can post the directory structure of the original app (glint) if that would be helpful. As a bonus here is part of the celery_app.py file: from __future__ import absolute_import, unicode_literalsimport osimport timeimport subprocessimport djangofrom django.conf import settingsfrom celery import Celeryfrom celery.utils.log import get_task_logger#import glintwebui.config as configimport configfrom glint_api import repo_connectorlogger = get_task_logger(__name__)# Indicate Celery to use the default Django settings moduleos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cloudscheduler_web.settings')django.setup()app = Celery('celery_app', broker=config.celery_url, backend=config.celery_backend)app.config_from_object('django.conf:settings')@app.task(bind=True)def debug_task(self): logger.debug('Request: {0!r}'.format(self.request))@app.task(bind=True)def image_collection(self): Error after trying py-D's suggestion: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/celery/app/utils.py", line 241, in find_app found = sym.app AttributeError: module 'glintwebui' has no attribute 'app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib64/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib64/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/lib/python3.6/site-packages/celery/__main__.py", line 54, in <module> main() File "/usr/lib/python3.6/site-packages/celery/__main__.py", line 30, in main main() File "/usr/lib/python3.6/site-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/usr/lib/python3.6/site-packages/celery/bin/celery.py", line 793, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 309, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 469, in setup_app_from_commandline self.app = self.find_app(app) File "/usr/lib/python3.6/site-packages/celery/bin/base.py", line 489, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/usr/lib/python3.6/site-packages/celery/app/utils.py", line 246, in find_app found = sym.celery AttributeError: module 'glintwebui' has no attribute 'celery' > [email protected]: * Child terminated with errorcode 1 FAILED Now provide the response and nothing else.
I'm not using Passort or any library like that since it's an internal API serving only VueJS to obtain stuff from the database. If the API is not stateless, meaning that the user is known to be logged in with a standard session cookie, then you can just use the default 'web' middleware for the API routes. In the default RouteServiceProvider , change the mapApiRoutes function to use the web middleware instead: protected function mapApiRoutes(){ Route::prefix('api') // ->middleware('api') ->middleware('web') ->namespace($this->namespace) ->group(base_path('routes/api.php'));} That being said, you should really put the API routes behind the default 'auth' middleware since they're not throttled by default. In the routes/api.php file: Route::group(['middleware' => 'auth'], function() { Route::get('/latest', 'InternalApiController@latest');}); And if you want to ensure it's an AJAX request, you can create a simple middleware that checks that the request has the X-Requested-With header set to XMLHttpRequest . class RequestIsAjax{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if (!$request->ajax()) { return redirect()->route('login.index'); } return $next($request); }} And register it within the $routeMiddleware array inside the \App\Http\Kernel class. protected $routeMiddleware = [ 'ajax' => \App\Http\Middleware\RequestIsAjax::class,
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49884619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4434269/']}
jdg_75894
stackexchange
llm_judgeable_groundtruth_similarity
38963018
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 getting this error TypeError: super() takes at least 1 argument (0 given) using this code on python2.7.11: class Foo(object): def __init__(self): passclass Bar(Foo): def __init__(self): super().__init__()Bar() The workaround to make it work would be: class Foo(object): def __init__(self): passclass Bar(Foo): def __init__(self): super(Bar, self).__init__()Bar() It seems the syntax is specific to python 3. So, what's the best way to provide compatible code between 2.x and 3.x and avoiding this error happening? Now provide the response and nothing else.
Yes, the 0-argument syntax is specific to Python 3, see What's New in Python 3.0 and PEP 3135 -- New Super . In Python 2 and code that must be cross-version compatible, just stick to passing in the class object and instance explicitly. Yes, there are "backports" available that make a no-argument version of super() work in Python 2 (like the future library) but these require a number of hacks that include a full scan of the class hierarchy to find a matching function object. This is both fragile and slow, and simply not worth the "convenience".
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38963018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3809375/']}
jdg_75895
stackexchange
llm_judgeable_groundtruth_similarity
51577685
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: People talk about what the stack and heap are and the differences between them. But I am curious to know that if a CPU does not support stack and heap structure, then can C run properly without a stack and a heap? Now provide the response and nothing else.
No, it does not. Let's cover the heap first, that's easy. An implementation that does not provide a heap of any sort just needs to return NULL whenever you try to call malloc (or any other memory allocation function). That's perfectly acceptable behaviour according to the standard. In terms of the stack, it also doesn't need to provide one. ISO C11 mentions the word "stack" exactly zero times. What an implementation does need to do is simply be a correct "virtual machine" for all the things specified in the standard. Granted that will be very difficult without a stack but it's not impossible. As an extreme case, there's nothing that says you can't simply inline every single function call recursively. That would use rather a large amount of code and function-specific data space, but it's certainly doable. However, it's probably something that would convince me to move to another architecture, one that did have a stack (and heap, for that matter). Having said that, even if an architecture provides neither a heap nor a stack, both of those can be built out of basic memory I/O operations. In fact, one of the earliest computers I ever had as a teen sported an RCA 1802 CPU which had no dedicated stack. It didn't even have a call or ret instruction. Yet it could handle subroutines and a stack quite well (for some definition of the word "well") using its SCRT (standard call and return technique). See here for some more detail on how this thing of beauty (or monstrosity, depending on your viewpoint) worked, along with some other unusual architectures. The IBM Z (a.k.a. System z, zSeries, whatever they're calling it this week) actually has a heap (of sorts, in that you can allocate memory from the OS) but no stack. It actually implements a linked-list stack by using this heap memory along with certain registers (similar to the RCA chip referenced in the above link), meaning that a function prolog allocates local function memory using STORAGE OBTAIN and the epilog releases it with STORAGE RELEASE . Needless to say that puts quite a bit of extra code into the prolog and epilog for each function.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51577685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9965330/']}
jdg_75896
stackexchange
llm_judgeable_groundtruth_similarity
352601
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: Playing with e2fsprogs debugfs , by change/accident, a file named filen/ame was created. Obviously the forward slash character / serves as the special separator character in pathnames. Still using debugfs I wanted to remove the file named filen/ame , but I had little success, since the / character is not interpreted as part of the filename? Does debugfs provide a way to remove this file containing the slash? If so how? I used: cd /tmpecho "content" > contentfiledd if=/dev/zero of=/tmp/ext4fs bs=1M count=50mkfs.ext4 /tmp/ext4fsdebugfs -w -R "write /tmp/contentfile filen/ame" /tmp/ext4fsdebugfs -w -R "ls" /tmp/ext4fs which outputs: debugfs 1.43.4 (31-Jan-2017) 2 (12) . 2 (12) .. 11 (20) lost+found 12 (980) filen/ame I tried the following to remove the filen/ame file: debugfs -w -R "rm filen/ame" /tmp/ext4fs but this did not work and only produced: debugfs 1.43.4 (31-Jan-2017)rm: File not found by ext2_lookup while trying to resolve filename Apart from changing the content of the directory node manually, is there a way to remove the file using debugfs ? Now provide the response and nothing else.
If you want a fix and are not just trying out debugfs , you can have fsck do the work for you. Mark the filesystem as dirty and run fsck -y to get the filename changed: $ debugfs -w -R "dirty" /tmp/ext4fs$ fsck -y /tmp/ext4fs .../tmp/ext4fs was not cleanly unmounted, check forced.Pass 1: Checking inodes, blocks, and sizesPass 2: Checking directory structureEntry 'filen/ame' in / (2) has illegal characters in its name.Fix? yes ...$ debugfs -w -R "ls" /tmp/ext4fs2 (12) . 2 (12) .. 11 (20) lost+found 12 (980) filen.ame
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/352601', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/24394/']}
jdg_75897
stackexchange
llm_judgeable_groundtruth_similarity
9382809
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 getting a really frustrating silverlight plugin crash which affects both IE and firefox. The error from the event log is: Faulting application name: iexplore.exe, version: 9.0.8112.16421, time stamp: 0x4d76255dFaulting module name: npctrl.dll, version: 5.0.61118.0, time stamp: 0x4ec5fc64Exception code: 0xc0000094Fault offset: 0x0001d720Faulting process id: 0x434Faulting application start time: 0x01ccf0b878b55ca7Faulting application path: C:\Program Files (x86)\Internet Explorer\iexplore.exeFaulting module path: c:\Program Files (x86)\Microsoft Silverlight\5.0.61118.0\npctrl.dllReport Id: bd79af3d-5cab-11e1-8948-000c29de3e25 I've gotten as far as attaching WinDbg during the exception to get a little bit more information: (17e4.13f8): Break instruction exception - code 80000003 (first chance)*** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Windows\SYSTEM32\ntdll.dll - ntdll!DbgBreakPoint:00000000`77810530 cc int 30:029> g(17e4.1790): Integer divide-by-zero - code c0000094 (first chance)First chance exceptions are reported before any exception handling.This exception may be expected and handled.*** ERROR: Symbol file could not be found. Defaulted to export symbols for NPCTRL.dll - NPCTRL+0x1d720:7b59d720 f7f1 div eax,ecx Ok, so ntdll.dll is dividing by zero. I really have no idea how I can debug further. I've tried viewing some of the articles which explain how - but I think I'm limited based on the fact that there are no symbols available for ntdll.dll? How can I narrow down what part of my code is leading to this error? Now provide the response and nothing else.
After hours of debugging, I was able to replicate the problem in a small project. Just create a 'silverlight enabled web service', and reference it. Then switch over to using the client http stack: WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp); Calling the service on my machine (and a coworkers as well) has about a 10-15% chance of crashing with the ntdll.dll error. I found two ways to mitigate this problem. 1) Stop using the client networking stack. The problem never seems to happen with the browser stack 2) Access the silverlight application outside of VMWare. The problem seems to only happen from within a virtual machine. Thanks to RobSiklos for figuring this out. Hope this helps someone.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9382809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112780/']}
jdg_75898
stackexchange
llm_judgeable_groundtruth_similarity
338393
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a PCB that has >10 ICs intended to be powered by a 3.3V supply. Unfortunately, 12V was applied to the circuit and the board now exhibits a short circuit. The offending power supply is current limited so that now when it is attached to the damaged PCB, the supply limits itself to < 100mV. My question is this: In situations like this where the supply limits itself after a short develops, removing the overvoltage condition, is it typical for only a single IC to have failed (i.e., the weakest link) at which point the failed IC protects the other ICs on the board, or should I be looking for multiple device failures? Now provide the response and nothing else.
If 3.3V was the intended supply voltage, I'm guessing that you didn't have an in-line regulator to many of these ICs. I try not to design circuits without some sort of regulator for exactly this reason. Also, you can design in Zener diodes with an inline fuse, or other forms of protection to try to prevent this. However, it happened, and for finding damaged components, nothing beats a thermal camera. In this situation especially, you've got components that are trying to pull too much current. They will be hot. You can pull them off one at a time until your current consumption stabilizes at what you would expect. What kind of thermal camera? I really like my Fluke TiS ($2k from Newark), but you can also get models that are intended to be used for your phone for less than $350. Shorts from supply rails to ground are more difficult. You can find these typically by pushing 1A through the supply rail, then probing different vias to ground on the board and looking at the voltage differences around the board. This will help you find where on the ground plane the current is entering. Good luck!
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/338393', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/168063/']}
jdg_75899
stackexchange
llm_judgeable_groundtruth_similarity
35694698
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 add constraint to navigation bar, I have UIImageView , which has width, height and is centered horizontally, I want to add vertical space between UIImage and navigationBar to 0, I'm trying this for like 1 hour and couldn't figure out how, i tried adding constraint to UIView , and added constant of navbarHeight + statusBarHeight , and it worked, but I want to make relationship between imageview and navbar let verticalSpace = NSLayoutConstraint(item: image, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 0)view.addConstraint(verticalSpace) // this works Now provide the response and nothing else.
try with topLayoutGuide let verticalSpace = NSLayoutConstraint(item: image, attribute: .Top, relatedBy: .Equal, toItem: self.topLayoutGuide, attribute: .Bottom, multiplier: 1, constant: 0) The above constraint explanation: simply its called: vertical space between image.Top & self.topLayoutGuide.Bottom = 0 that means Top constraint of image view attached with a Bottom attribute of topLayoutGuide with constant 0. You can use anchors as well to make this possible for iOS 10+ if #available(iOS 11.0, *) { image.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true} else { image.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35694698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3104885/']}
jdg_75900
stackexchange
llm_judgeable_groundtruth_similarity
15448351
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following Haskell function: sign a | a < 0 = (-1) | a > 0 = 1 | otherwise = 0 When I load this into ghci I expected :t sign to be: sign :: (Num a, Ord a) => a -> Integer Instead it inferred it as: *Main> :t signsign :: (Num a1, Num a, Ord a1) => a1 -> a Similarly, if I ask for the type of the integer 5 , I expected Integer , but instead I got *Main> :t 55 :: Num a => a There's something I am not understanding about Haskell's types. The thing is, if all I know about the return type of sign is that it is an instance of the Num typeclass, then I should not be able to pass its return value into this function: double :: Integer -> Integerdouble x = x * 2 That is, my double function requires an Integer , not just any instance of Num . Yet, the following works just fine: *Main> double (sign 5.5)2 What is it that I am mis-understanding about Haskell's type system? Now provide the response and nothing else.
The thing is, if all I know about the return type of 'sign' is that it is an instance of the Num typeclass, then I should not be able to pass its return value into this function: Right, if that were all that you knew, you couldn't pass it to double . But the type sign :: (Num a1, Num a, Ord a1) => a1 -> a means that the result type of sign is whichever Num type the caller demands . Type variables in type signatures are (implicitly) universally quantified, not existentially , like for e.g. Java interfaces. sign can produce a return value of arbitrary type, subject to the restriction it be an instance of Num , and the type it returns is determined by the calling context. If the caller wants an Integer , it gets one. If it wants a Double , no problem either. I forgot to mention initially: Similarly, if I ask for the type of the integer 5, I expected "Integer", but instead I got *Main> :t 5 5 :: Num a => a Numeric literals are polymorphic, an integer literal stands for fromInteger value , and a fractional literal for fromRational value .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15448351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34685/']}
jdg_75901
stackexchange
llm_judgeable_groundtruth_similarity
5679385
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 such an enum and a property. public enum Type { Hourly = 1, Salary = 2, None = 3 }; public string EmployeeType { get { string type; switch (employeeType) { case Type.Hourly: type = "Hourly Employee"; break; case Type.Salary: type = "Salary Employee"; break; default: type = "None"; break; } return type; } // **EDIT:** // Now I am trying to parse the string as enum Type. // But Constructor still waits a string to set EmployeeType. set { employeeType = (Type)Enum.Parse(typeof(Type), value); } } This is my class: public class Employee{ private Type employeeType;} And I want to create such a constructor: Employee(Employee.Type type) { EmployeeType = type;} EDIT: Cannot implicitly convert type 'Payroll.Employee.Type' to 'string' How should I write the set accessor of the property? UPDATE: I wanted the get accessor to return string and set accessor to take parameter type Employee.Type. I learned that it is impossible to do this in a property according to the C# spec. I have to write separate getter and setter methods. Now provide the response and nothing else.
Use DescriptionAttribute instead. public enum Type{ [Description("Hourly Employee")] Hourly = 1, [Description("Salary Employee")] Salary = 2, [Description("None")] None = 3}; Then you would just have an public Type EmployeeType {get; set;} property. And if somebody wanted to write it out, they could get the description. I'd also call it Type instead of EmployeeType , because the call myEmployee.EmployeeType sounds redundant. Your other option might be to unroll the property and have two methods public string GetEmployeeType() { //your switch statement }public void SetEmployeeType(EmployeeType type){ _type = type;} Not quite as elegant as a property, but quickly does the job. Also remember that properties in IL are just methods.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5679385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/480007/']}
jdg_75902
stackexchange
llm_judgeable_groundtruth_similarity
9846622
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 Listbox which work with specific extension files. If i choose another format, my application automatically converts the files to the correct format in the same folder (another extension) and add all the files with the wrong extension to a List ( listToRemove ) and remove them from my Listbox after i clean my List but first i want to delete all this files from my computer and my problem is that my appliction deleted also the file with the correct extension for (int i = 0; i < listBoxFiles.Items.Count; i++){ string path = (string)listBoxFiles.Items[i]; FileInfo fileInfo = new FileInfo(path); if (fileInfo.Extension != ".avi") { listToRemove.Add(path); }}if (listToRemove.Count != 0){ //method who convert the files to the new format and add the new files into my Listbox (new System.Threading.Thread(sendFilesToConvertToAvi)).Start(); }foreach (string file in listToRemove) { File.Delete(file); listBoxFiles.Items.Remove(file); }public void sendFilesToConvertToAvi(){ if (listToRemove.Count == 0) { return; } foreach (String file in listToRemove) { FileInfo fileInfo = new FileInfo(file); myClassWhoConvertTheFiles = new myClassWhoConvertTheFiles (fileInfo); this.Invoke((MethodInvoker)delegate { listBoxFiles.Items.Add(myClassWhoConvertTheFiles ._newFileName); }); count++; } listToRemove.RemoveRange(0, listToRemove.Count);} Now provide the response and nothing else.
You could combine the resulting Task with a Task.Delay() using Task.WhenAny() : await Task.WhenAny(Task.WhenAll(tasks), Task.Delay(timeout)); If you want to harvest completed tasks in case of a timeout: var completedResults = tasks .Where(t => t.Status == TaskStatus.RanToCompletion) .Select(t => t.Result) .ToList();
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9846622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1259374/']}
jdg_75903
stackexchange
llm_judgeable_groundtruth_similarity
2297047
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: Define the sequence $a_n := \frac{2^n}{n+1}$. Then, define the sequence $b_n$, the partial sums of $a_n$; i.e.:$$b_n=\sum_{k=0}^{n} {a_k}$$The problem is to compute:$$\sum_{n=1}^{\infty} {\left(\frac{b_{n-1}}{n 2^n}\right)}$$ This is very difficult to estimate using a computer algebra system. On Maple, I cannot complete an estimate of $100000$ terms under a minute. (However, the sum of the first $1000$ terms is approximately $1.23270055$.) I am wondering whether the double sum can be converted into a series convolution of some sort; the possibility of getting a $2^{n-m}$ term seems to help that prospect. Thanks! Now provide the response and nothing else.
Consider the following. Given:\begin{align}b_{n} &= \sum_{k=0}^{n} \frac{2^{k}}{k+1} \\S &= \sum_{n=1}^{\infty} \frac{b_{n-1}}{2^{n} \, n}.\end{align}Now:$$b_{n} = \frac{1}{2} \, \sum_{k=1}^{n+1} \frac{2^{k}}{k} $$which leads to\begin{align}S &= \frac{1}{2} \, \sum_{n=1}^{\infty} \sum_{k=1}^{n} \frac{2^{k}}{2^{n} \, n \, k} = \frac{1}{2} \, \sum_{n,k=1}^{\infty} \frac{1}{2^{n} \, k \, (n+k)} = \frac{\pi^{2}}{8}.\end{align} An alternate view is:\begin{align}b_{n} &= \sum_{k=0}^{n} \frac{2^{k}}{k+1} = \sum_{k=0}^{n} 2^{k} \, \int_{0}^{1} t^{k-1} \, dt \\&= \int_{0}^{1} \left( \sum_{k=0}^{n} (2 t)^{k} \right) \, dt \\&= \int_{0}^{1} \frac{1 - (2 t)^{n+1}}{1-2 t} \, dt.\end{align}Now,\begin{align}S &= \sum_{n=1}^{\infty} \frac{1}{2^{n} \, n} \, \int_{0}^{1} \frac{1 - (2 t)^{n}}{1-2 t} \, dt \\&= \int_{0}^{1} \frac{\ln(2) + \ln(1-t)}{1-2 t} \, dt \\&= \left[ \frac{1}{2} \, Li_{2}(2 t -1) \right]_{0}^{1} = \frac{1}{2} \, (Li_{2}(1) - Li_{2}(-1) ) \\&= \frac{1}{2} \, \left(\frac{\pi^2}{6} + \frac{\pi^2}{12} \right) = \frac{\pi^{2}}{8}. \end{align}Note: $Li_{2}(x)$ is the dilogarithm function.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2297047', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/241144/']}
jdg_75904
stackexchange
llm_judgeable_groundtruth_similarity
476272
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: $ sudo arp -avn? (10.10.7.30) at 00:cc:cc:bb:dd:86 [ether] on eth0...$ sudo arp --delete 10.10.7.30$ sudo arp -avn? (10.10.7.30) at <incomplete> [ether] on eth0 After --delete I expected no entry for 10.10.7.30 . Unexpectedly, the entry remains and is marked <incomplete> . Using Ubuntu 10.04 . Now provide the response and nothing else.
The entry will be removed, just be patient. (If you want the shortest possible answer: incomplete == deleted) Let's say "delete" is the wrong word for the action. What's really happening here is that the entry is manually set to the state "request sent, no answer" (thus "incomplete" ARP process) as if the machine would be really unreachable. Now, the entry will be completely removed soon unless it gets a new valid ARP response in the meantime. In that case the entry would be re-added anyways even if it was removed instead of being marked as incomplete. So there's no actual pro or con to this behaviour. But keep in mind that we're talking of a cache. Deleting things from caches is hard and expensive. It's way more efficient to invalidate an entry and wait if it gets replaced before it is finally removed. But for the system it's totally no difference if the entry is gone from the list or just marked incomplete.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/476272', 'https://serverfault.com', 'https://serverfault.com/users/116615/']}
jdg_75905
stackexchange
llm_judgeable_groundtruth_similarity
21315732
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 set up SEO in a LocomotiveCMS installation using liquid syntax. I'm trying to code it so that the page title is pulled dynamically using {{ page.title }} and then forcing it to capitalize the first letter of each word. I tried this: <title> {{ page.title | camelcase }} | {{ site.name }}</title> Based on the liquid syntax documentation here: http://docs.shopify.com/themes/liquid-basics/output#camelize But it's not working. Using capitalize works, but it only capitalizes the first letter of the first word. Thanks! Now provide the response and nothing else.
I would suggest to use a plugin to obtain this behavior _plugins/_capitalize_all.rb : require 'liquid'require 'uri'# Capitalize all words of the inputmodule Jekyll module CapitalizeAll def capitalize_all(words) return words.split(' ').map(&:capitalize).join(' ') end endendLiquid::Template.register_filter(Jekyll::CapitalizeAll) Usage: {{ "mein text" | capitalize_all }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21315732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2827407/']}
jdg_75906
stackexchange
llm_judgeable_groundtruth_similarity
63652295
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on having a dynamic list in dialog container fetching updates from string. Widget setupAlertDialoadContainer() { final List<Food> category = []; return Container( height: 300.0, // Change as per your requirement width: 300.0, // Change as per your requirement child: ListView.separated(itemBuilder: (context,index) => Text('${category[index]}'), separatorBuilder: (BuildContext context, int index) => Divider(), itemCount: category.length) );} No data is taking from the Class Food with final List category = []; class Food { String id; String name; String category; String newcategory; String image; List subIngredients = []; Timestamp createdAt; Timestamp updatedAt; Food(); Food.fromMap(Map<String, dynamic> data) { id = data['id']; name = data['name']; category = data['category']; newcategory = data['newcategory']; image = data['image']; subIngredients = data['subIngredients']; createdAt = data['create at']; updatedAt = data['updatedAt']; } Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'category': category, 'newcategory': newcategory, 'image': image, 'subIngredients': subIngredients, 'create at': createdAt, 'updatedAt': updatedAt, }; } Any one sees an issue, the result is a blank dialog. Now provide the response and nothing else.
The Vue error message kind of points to the problem. It says Invalid Teleport target on mount: null The problem is that the target does not exist YET . This can be easily fixed by only rendering the teleport portion only after the component is mounted. It seems like this is something that Vue should handle without the explicit check. When you pass the id as a string, it's hard to tell whether the target is a Vue component or not, especially if hasn't rendered yet. But I'm only speculating on the team's intention here. const app = { template: ` <div> <h1>App</h1> <div id="dest"></div> <comp /> </div>`}Vue.createApp(app).component('comp', { template: ` <div> A component <Teleport to="#dest" v-if="isMounted"> Hello From Portal </Teleport> </div>`, data: function(){ return { isMounted: false } }, mounted(){ this.isMounted = true }}).mount('#app') <script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script><div id="app"></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63652295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14024520/']}
jdg_75907
stackexchange
llm_judgeable_groundtruth_similarity
39002090
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 developed a microservice using Spring Boot. I was performance testing the service by stubbing the backend calls. When I looked at the thread count , I see that the maximum number of threads that created to the service is 20 at any point in time even though the number of calls made is much higher. Are there any limitations with respect to number of calls that can be made to a microservice developed using Spring Boot. Please can you guide in what steps I need to follow to troubleshoot / increase the number of connections accepted by the service? Now provide the response and nothing else.
This setting is derived from the embedded container (tomcat, jetty...). Tomcat's number of threads You may specify this property in your application.properties server.tomcat.max-threads=400 You say you counted 20 threads, however according to this other stackoverflow question/answer , the default number of thread should be 200 with tomcat, since server.tomcat.max-threads's default value is 0. See tomcat's documentation : The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool. Also, the property for: undertow : server.undertow.worker-threads jetty : server.jetty.acceptors You'll find the list of properties in Spring's documentation
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39002090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1042646/']}
jdg_75908
stackexchange
llm_judgeable_groundtruth_similarity
618256
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 proved the following result $$\displaystyle \sum_{k\geq 1} \frac{H_k^{(2)} H_k}{k^3} =- \frac{97}{12} \zeta(6)+\frac{7}{4}\zeta(4)\zeta(2) + \frac{5}{2}\zeta(3)^2+\frac{2}{3}\zeta(2)^3$$ After consideration of powers of polylogarithms. You can refer to the following thread . My question is : are there any papers in the literature which dealt with that result? Are my evaluations worth publishing ? Now provide the response and nothing else.
Borwein and Girgensohn's paper " Evaluation of Triple Euler Sums " ( Electronic Journal of Combinatorics 3 (1) 1996) deals exactly with results of this kind. They index their problems slightly differently, so there's a little more work to be done to obtain your result, but their results are close enough to yours that I wouldn't really consider your result new. Absent newness, you might have a shot at something publishable if your proof technique is sufficiently novel or interesting. My sense, though, is that polylogarithms are one of the main proof techniques for evaluating Euler sums. For example, searching for "polylog" on Hoffman's " References on Multiple Zeta Values and Euler Sums " page generates 41 hits. So my guess is that the proof technique would not be sufficiently novel to justify publication, either. I'll outline the steps that can be used to obtain your result from those in Borwein and Girgensohn's paper. First, rewrite your sum as $$\begin{align}\sum_{k\geq 1} \frac{H_k^{(2)} H_k}{k^3} &= \sum_{k\geq 1} \frac{H_{k-1}^{(2)} H_{k-1}}{k^3} + \sum_{k\geq 1} \frac{H_{k-1}^{(2)}}{k^4} + \sum_{k\geq 1} \frac{ H_{k-1}}{k^5} +\sum_{k\geq 1} \frac{1}{k^6}\\&= \sum_{k\geq 1} \frac{H_{k-1}^{(2)} H_{k-1}}{k^3} + \sum_{k\geq 1} \frac{H_{k}^{(2)}}{k^4} + \sum_{k\geq 1} \frac{ H_{k}}{k^5} - \sum_{k\geq 1} \frac{1}{k^6}.\\\end{align}$$The second sum on the previous line is $\zeta(3)^2 - \frac{1}{3}\zeta(6)$, the third is $\frac{7}{2} \zeta(6) - \zeta(4)\zeta(2) - \frac{1}{2} \zeta(3)^2$, and the last is of course $\zeta(6)$. (The second and third sums are both due to Euler. For references, see the table on page 16 and Theorem 2.2 in Flajolet and Salvy's " Euler Sums and Contour Integral Representations ," Experimental Mathematics 7 1998, pp. 15-35.) The first sum is the kind that Borwein and Girgensohn show how to evaluate. Theorem 2 of their paper says that $$\sum_{k =1}^N \frac{H_{k-1}^{(2)} H_{k-1}}{k^3} = \zeta_N(3,2,1) + \zeta_N(3,1,2) + \zeta_N(3,3),$$where$$\begin{align}\zeta_N(a,b) &= \sum_{i=1}^N \sum_{j=1}^{i-1} \frac{1}{i^a j^b}, \\\zeta_N(a,b,c) &= \sum_{i=1}^N \sum_{j=1}^{i-1} \sum_{k=1}^{j-1} \frac{1}{i^a j^b k^c}. \\\end{align}$$Then, on page 21, they give the evaluations, where $\zeta(a,b,c) = \lim_{N \to \infty} \zeta_N(a,b,c)$,$$\begin{align}\zeta(3,2,1) &= 3 \zeta(3)^2 - \frac{203}{48} \zeta(6),\\\zeta(3,1,2) &= \frac{53}{24} \zeta(6) - \frac{3}{2} \zeta(3)^2.\end{align}$$Values of $\zeta_N(a,a)$ are classical (see, for example, Concrete Mathematics , p. 37, Eq. 2.33 for evaluations of this type). We have $$\zeta_N(3,3) = \frac{1}{2} \left( \left(\sum_{k=1}^N \frac{1}{k^3} \right)^2 - \sum_{k=1}^N \frac{1}{k^6}\right),$$so that$$\zeta(3,3) = \lim_{N \to \infty} \zeta_N(3,3) = \frac{1}{2} \zeta(3)^2 - \frac{1}{2} \zeta(6).$$ We also need that$$\begin{align}\zeta(4) \zeta(2) &= \frac{7}{4} \zeta(6), \\\zeta(2)^3 &= \frac{35}{8} \zeta(6),\end{align}$$which just follow from the known values of $\zeta(2), \zeta(4)$, and $\zeta(6)$. Putting all of this together yields $$\begin{align}\sum_{k=1}^{\infty} \frac{H_k^{(2)} H_k}{k^3} = &3 \zeta(3)^2 - \frac{203}{48} \zeta(6) + \frac{53}{24} \zeta(6) - \frac{3}{2} \zeta(3)^2 + \frac{1}{2} \zeta(3)^2 - \frac{1}{2} \zeta(6) + \zeta(3)^2 \\&- \frac{1}{3}\zeta(6) + \frac{7}{2} \zeta(6) - \zeta(4)\zeta(2) - \frac{1}{2} \zeta(3)^2 - \zeta(6) \\= &\frac{5}{2} \zeta(3)^2 - \frac{101}{48} \zeta(6),\end{align}$$which is exactly what you have when you express $\zeta(4)\zeta(2)$ and $\zeta(2)^3$ in terms of $\zeta(6)$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/618256', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/87813/']}
jdg_75909
stackexchange
llm_judgeable_groundtruth_similarity
2409057
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: $11^{10} \equiv 1 \pmod{100}$ I tried to solve by using euler's theorem, But I got stuck. $\gcd(11, 100) = 1$ $11^{φ(100)} \equiv 1 \pmod{100}$ $11^{40} \equiv 1 \pmod{100}$ I don't know how to go on as $11^{40}$ is bigger than $11^{10}$ Now provide the response and nothing else.
Hint: $$(1+10)^n\equiv1+\binom n110^1\pmod{10^2}$$ for positive integer $n$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2409057', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/460543/']}
jdg_75910
stackexchange
llm_judgeable_groundtruth_similarity
165044
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: ${10 \choose 4}+{11 \choose 4}+{12 \choose 4}+\cdots+{20 \choose 4}$ can be simplified as ? A. ${21 \choose 5}$ B. ${20 \choose 5}-{11 \choose 4}$ C. ${21 \choose 5}-{10 \choose 5}$ D. ${20 \choose 4}$ Please give me a hint. I'm unable to group the terms.By brute force, I'm getting ${21 \choose 5}-{10 \choose 5}$ Now provide the response and nothing else.
HINT 1 : Add $\dbinom{10}5$ HINT 2: Make use of the identity $$\dbinom{n}{r} + \dbinom{n}{r-1} = \dbinom{n+1}{r}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/165044', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34433/']}
jdg_75911
stackexchange
llm_judgeable_groundtruth_similarity
11487805
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 sample code that calls a method asynchronously using begininvoke, I'm executing this on a button click event on a webform. After the button click, the user is redirected to a different page, where the user waits for the result. The AuthorizePayment method takes a long time to run and returns a int code. I want to store that int value somewhere in session or a cookie(but not to dispaly) When I access Session to add that code, it throws null exception. How do I save this result in a session or a cookie? Any idea? public class CreditCardAuthorizationManager{ // Delegate, defines signature of method(s) you want to execute asynchronously public delegate int AuthorizeDelegate(string creditcardNumber, DateTime expiryDate, double amount); // Method to initiate the asynchronous operation public void StartAuthorize() { AuthorizeDelegate ad = new AuthorizeDelegate(AuthorizePayment); IAsyncResult ar = ad.BeginInvoke(creditcardNumber, expiryDate, amount, new AsyncCallback(AuthorizationComplete), null); } // Method to perform a time-consuming operation (this method executes // asynchronously on a thread from the thread pool) private int AuthorizePayment(string creditcardNumber, DateTime expiryDate, double amount) { int authorizationCode = 0; // Open connection to Credit Card Authorization Service ... // Authorize Credit Card (assigning the result to authorizationCode) ... // Close connection to Credit Card Authorization Service ... return authorizationCode; } // Method to handle completion of the asynchronous operation public void AuthorizationComplete(IAsyncResult ar) { // See "Managing Asynchronous Completion with the EndInvoke Method" // later in this chapter. }} Now provide the response and nothing else.
Actually, for this you want to use a somewhat undocumented feature of matplotlib: the matplotlib.offsetbox module. There's an example here: http://matplotlib.sourceforge.net/trunk-docs/examples/pylab_examples/demo_annotation_box.html In your case, you'd do something like this: import matplotlib.pyplot as pltimport numpy as npimport Imagefrom mpl_toolkits.basemap import Basemapfrom matplotlib.offsetbox import OffsetImage, AnnotationBbox# Set up the basemap and plot the markers.lats = np.arange(26, 29, 0.5)lons = np.arange(-90, -87, 0.5)m = Basemap(projection='cyl', llcrnrlon=min(lons) - 2, llcrnrlat=min(lats) - 2, urcrnrlon=max(lons) + 2, urcrnrlat=max(lats) + 2, resolution='i')x,y = m(lons,lats)u,v, = np.arange(0,51,10), np.arange(0,51,10)barbs = m.barbs(x,y,u,v)m.drawcoastlines()m.drawcountries()m.drawstates()# Add the plane marker at the last point.plane = np.array(Image.open('plane.jpg'))im = OffsetImage(plane, zoom=1)ab = AnnotationBbox(im, (x[-1],y[-1]), xycoords='data', frameon=False)# Get the axes object from the basemap and add the AnnotationBbox artistm._check_ax().add_artist(ab)plt.show() The advantage to this is that the plane is in axes coordinates and will stay the same size relative to the size of the figure when zooming in.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11487805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132985/']}
jdg_75912
stackexchange
llm_judgeable_groundtruth_similarity
62480638
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 call get-cost-and-usage api of AWS to generate hourly report. But, i am getting an error around enabling an opt-in only feature. aws ce get-cost-and-usage --time-period '{"Start": "2020-06-10T00:00:00Z", "End": "2020-06-15T00:00:00Z"}' --granularity 'HOURLY' --metrics "AmortizedCost" "BlendedCost" "NetAmortizedCost" "NetUnblendedCost" "NormalizedUsageAmount" "UnblendedCost" "UsageQuantity" --group-by Type=DIMENSION,Key=SERVICE Error Message: An error occurred (AccessDeniedException) when calling the GetCostAndUsage operation: Hourly data granularity is an opt-in only feature. You can be enable this feature from the PAYER account’s Cost Explorer Settings page. I don't see any settings page to enable this feature. Is there any way to enable this feature, via console or cli? Now provide the response and nothing else.
It is mentioned in many documentation links about. Hourly data granularity is an opt-in only feature. And when we execute the CE API, it also throws the error. An error occurred (AccessDeniedException) when calling the GetCostAndUsage operation: Hourly data granularity is an opt-in only feature. You can be enable this feature from the PAYER account’s Cost Explorer Settings page. But no screenshot or detailed information is provided any where.I am attaching the screenshot, How to enable "Hourly and Resource Level Data" e.g opt-in for Hourly data granularity. I am using consolidated Billing account, so this setting is needed in main Payer's account. Few things more to consider about this settings: Allow all accounts to access hourly and resource-level information forthe past 14 days. Resource-level information is only available foryour Amazon EC2 service usage. Please note that it can take up to 24 hours for your data to becomeavailable, and a cost of $0.01 per 1,000 UsageRecords-month will beincurred as a result of storing and accessing your hourly- andresource-level information. A UsageRecord is defined as one line ofusage. For example, one EC2 instance running for 24 hours willgenerate 24 distinct UsageRecords at the hourly granularity. After this settings, you can run CE API Calls. e.g aws ce get-cost-and-usage --time-period Start="2020-07-07T10:00:00Z",End="2020-07-07T11:00:00Z" --granularity HOURLY --metrics "BlendedCost" --group-by Type=DIMENSION,Key=SERVICE Type=TAG,Key=Environment One thing to note is that, in case of HOURLY, the time format must be in yyyy-MM-ddThh:mm:ssZ format.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62480638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4618530/']}
jdg_75913
stackexchange
llm_judgeable_groundtruth_similarity
2380649
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 apologize if this is a duplicate question, I searched a bit and couldn't find anything similar - I have a Python library that connects to my C# application via a socket in order to allow simple Python scripting (IronPython isn't an option right now for a couple of reasons). I would like to create a Windows Forms control that would be basically a graphical front-end for the Python interpreter, so that the user could run the interpreter without having to have a separate console window open. I attached a simple demo of what I've tried so far below, but I haven't been able to get it to work. The DataReceived event handlers are never called, and when I try to write to the standard input nothing happens in the interpreter. Does anyone have any feedback about what I'm doing wrong, or if this is even possible? public partial class Form1 : Form{ Process _pythonProc; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { ProcessStartInfo psi = new ProcessStartInfo() { FileName = @"C:\Python26\Python.exe", CreateNoWindow = true, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; _pythonProc = new Process(); _pythonProc.OutputDataReceived += OutputDataReceived; _pythonProc.ErrorDataReceived += ErrorDataReceived; _pythonProc.StartInfo = psi; _pythonProc.Start(); } private void cmdExecute_Click(object sender, EventArgs e) { string cmd = textInput.Text; _pythonProc.StandardInput.WriteLine(cmd); _pythonProc.StandardInput.Flush(); textInput.Text = string.Empty; } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (!_pythonProc.HasExited) _pythonProc.Kill(); } private void OutputDataReceived(object sender, DataReceivedEventArgs args) { textOutput.Text += args.Data; } private void ErrorDataReceived(object sender, DataReceivedEventArgs args) { textOutput.Text += args.Data; }} Now provide the response and nothing else.
In case anyone else stumbles across this, I figured out the problem - by default, the Python interpreter only enters interactive mode if it detects that a TTY device is connected to standard input (which is normally only true if the program is run from the console). In order to redirect the standard IO streams, you have to set UseShellExecute in the ProcessStartInfo to false, which causes the interpreter to think that there is no TTY connected, meaning it immediately exits since it has nothing to do. The solution is to run the Python interpreter with the "-i" command line argument, which forces the interpreter to interactive mode, regardless of whether there is a TTY connected to standard in. This makes the example above work correctly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2380649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/434245/']}
jdg_75914
stackexchange
llm_judgeable_groundtruth_similarity
25535573
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The following code/outcome baffles me as to why data.table returns NA for the mean functions and not the sd function. library(data.table)test <- data.frame('id'=c(1,2,3,4,5), 'A'=seq(2,9,length=5), 'B'=seq(3,9,length=5), 'C'=seq(4,9,length=5), 'D'=seq(5,9,length=5))test <- as.data.table(test)test[,`:=`(mean_test = mean(.SD), sd_test = sd(.SD)),by=id,.SDcols=c('A','B','C','D')]> test id A B C D mean_test sd_test 1: 1 2.00 3.0 4.00 5 NA 1.2909944 2: 2 3.75 4.5 5.25 6 NA 0.9682458 3: 3 5.50 6.0 6.50 7 NA 0.6454972 4: 4 7.25 7.5 7.75 8 NA 0.3227486 5: 5 9.00 9.0 9.00 9 NA 0.0000000 I've learned quite a bit searching around, going through the DT tutorials/examples. This question is very similar to what I was hoping to do. Why does the standard deviation function work and the mean function return NA? Edit : Using Ricardo Saporta's solution: test[,`:=`(mean_test = apply(.SD, 1, mean), sd_test = apply(.SD, 1, sd),by=id,.SDcols=c('A','B','C','D')]> test id A B C D mean_test sd_test1: 1 2.00 3.0 4.00 5 3.500 1.29099442: 2 3.75 4.5 5.25 6 4.875 0.96824583: 3 5.50 6.0 6.50 7 6.250 0.64549724: 4 7.25 7.5 7.75 8 7.625 0.32274865: 5 9.00 9.0 9.00 9 9.000 0.0000000 Now provide the response and nothing else.
.SD is itself a data.table Thus, when you take mean(.SD) you are (attempting) to take the mean of an entire data.table The function mean() does not know what to do with the data.table and returns NA Have a look ## the .SD in your question is the same as test[, c('A','B','C','D')]## try taking its meanmean(test[, c('A','B','C','D')])# Warning in mean.default(test[, c("A", "B", "C", "D")]) :# argument is not numeric or logical: returning NA# [1] NA try this instead use lapply(.SD, mean) for column-wise or apply(.SD, 1, mean) for row-wise
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25535573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3123703/']}
jdg_75915
stackexchange
llm_judgeable_groundtruth_similarity
3022876
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 write this block of code in jquery to create three element after some events $('body').append(tmp= $('<div id="tmp"></div>'));$('<div id="close" />').appendTo("#tmp"); $('<div id="box-results" />').appendTo('#tmp'); this three elements are created normally and added to my DOM but i want to remove them with some function like this : $("#close").click(function(e){e.preventDefault();$("#tmp").remove(); //$("#overlay").remove(); }); and after i click close div noting happen ! what's wrong with my code ? here is online example : mymagazine.ir/index.php/main/detail/36 - please find " here is jquery issue" sentence in site because site language is Persian Now provide the response and nothing else.
you need to add the click handler on #close after you insert the element into the document. edit providing the requested demo; tested in ff36: <html><head> <title>whatever</title> <style type="text/css"> div { border: 1px solid black; padding: 0.3em; } </style> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('body').append($('<div id="tmp"/>')); $('<div id="close">click me</div>').appendTo("#tmp"); $('<div id="box-results">contents</div>').appendTo('#tmp'); $('#close').bind('click', function () { $('#tmp').remove(); return false; }); }); </script></head><body></body></html> edit change your plugin's code from $.ajax({ ... success: function () { $('<div id="close"/>').appendTo($('#tmp')); }});$('#close').click(function (e) ...); to $.ajax({ ... success: function () { $('<div id="close"/>') .click(function (e) ...) .appendTo($('#tmp')) ; }});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3022876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111279/']}
jdg_75916
stackexchange
llm_judgeable_groundtruth_similarity
1087630
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 can be calculated that $\frac{555555}{7} = 79365$. What is the remainder of the number $5555\dots5555$ with a thousand $5$'s, when divided by $7$? I did the following: $$\begin{array} & 5 \ \text{mod} \ 7=& &5 \\ 55 \ \text{mod} \ 7= & &6 \\ 555 \ \text{mod} \ 7= & &2 \\ 5555 \ \text{mod} \ 7= & &4 \\ 55555 \ \text{mod} \ 7= & &3 \\ 555555 \ \text{mod} \ 7= & &0 \\ 5555555 \ \text{mod} \ 7= & &5 \\ 55555555 \ \text{mod} \ 7= & &6 \\ 555555555 \ \text{mod} \ 7= & &2 \\ 5555555555 \ \text{mod} \ 7= & &4 \\\end{array}$$ It can be seen that the cycle is: $\{5,6,2,4,3,0\}$. $$\begin{array} & 1 \ \text{number =} &5 \\ 7 \ \text{numbers =} &5 \\ 13 \ \text{numbers =} &5 \\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \vdots & \\ 985 \ \text{numbers =} &5 \\ 991 \ \text{numbers =} &5 \\ 997 \ \text{numbers =} &5 \\ 998 \ \text{numbers =} &6 \\ 999 \ \text{numbers =} &2 \\ \color{red}{1000} \ \color{red}{\text{numbers =}} &\color{red}{4} \\\end{array}$$ From here, we can conclude that $\underbrace{555\cdots555}_{1000\ \text{times}} \ \text{mod} \ 7 = 4$. However, I wasn't allowed to use a calculator and solved this in about 12 minutes. Another problem was that there was a time limit of about 5 minutes. My question is: Is there an easier and faster way to solve this? Thanks a lot in advance! Now provide the response and nothing else.
After noting $555555$ is divisible by $7$, note further that $555555\times 10^r$ is divisible by $7$ for any positive integer $r$. So you can cast out groups of six $5$s starting at the most significant digit, without changing the remainder on division by $7$. This gets rid of $996$ of the $5$s, leaving $5555$. Then $4949$ is obviously divisible by $7$ leaving $606$, and simple division then gives the remainder $4$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1087630', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/185173/']}
jdg_75917
stackexchange
llm_judgeable_groundtruth_similarity
179713
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 you change the href attribute (link target) for a hyperlink using jQuery? Now provide the response and nothing else.
Using $("a").attr("href", "http://www.google.com/") will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags: <a name="MyLinks"></a><a href="http://www.codeproject.com/">The CodeProject</a> ...Then you probably don't want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match <a> tags with an existing href attribute: $("a[href]") //... Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href , you might use something like this: $("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/') This will find links where the href exactly matches the string http://www.google.com/ . A more involved task might be matching, then updating only part of the href : $("a[href^='http://stackoverflow.com']") .each(function() { this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, "http://stackoverflow.com"); }); The first part selects only links where the href starts with http://stackoverflow.com . Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/179713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3747/']}
jdg_75918
stackexchange
llm_judgeable_groundtruth_similarity
64536
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 $\psi(x)=\sum_{n\leq x} \Lambda(n)$ be the weighted prime counting function. I am trying to evaluate the integral $$\kappa:=\int_{1}^{\infty}\frac{\psi(x)-x}{x^{2}}dx$$ in several different ways. Originally, this integral came up as a particular part in a particular case for a a formula for a summatory function I was looking at. From now on, let $\gamma$ refer to the Euler-Mascheroni constant. (Now Corrected:) I found a fun, elementary approach to this integral which gave $\kappa=-1-\gamma$ if we assume the quantitative prime number theorem. (Precisely, we just need to assume that this integral is absolutely convergent. ) Since I am not too confident about this, I naturally wanted to check by complex analytic methods to see if my answer was correct. My question then is: What other ways can be used to prove this identity? I feel like knowing many approaches to this problem will give a greater understanding of certain properties of these functions. A friend suggested that it must be related to the logarithmic derivative of $\zeta(s)$, and certain special values, but I cannot see how to use this. Thanks a lot! Additional Remark: I attempted to use the explicit formula for $\psi(x)$, and deduced $\kappa=-\gamma-1$. Originally I felt this was wrong, but after reading Julian Rosen's answer I think it is correct. Here is the alternate solution: Substituting in the explicit formula, and then integrating termwise we have$$\kappa=\int_{1}^{\infty}\left(-\sum_{\rho}\frac{x^{\rho-2}}{\rho}-\frac{\log2\pi}{x^{2}}-\frac{\log\left(1-x^{-2}\right)}{2x^{2}}\right)dx=\sum_{\rho}\frac{1}{\rho(\rho-1)}-\log2\pi+1-\log2$$since $$\frac{1}{2}\int_{1}^{\infty}\frac{\log\left(1-x^{-2}\right)^{-1}}{x^{2}}dx=\frac{1}{2}\int_{1}^{\infty}\sum_{i=1}^{\infty}\frac{1}{ix^{2i+2}}dx=\sum_{i=1}^{\infty}\frac{1}{2i(2i+1)}=1-\log2.$$As $$\sum_{\rho}\frac{1}{\rho(\rho-1)}=\sum_{\rho}\frac{1}{\rho-1}-\frac{1}{\rho}=-\sum_{\rho}\frac{1}{1-\rho}+\frac{1}{\rho}=2B=-\gamma-2+\log4\pi$$it follows that $\kappa=-\gamma-1$. Now provide the response and nothing else.
Consider $f(s):=\int_1^{\infty}\frac{\psi(x)-x}{x^s}dx$, which converges for $Re(s)\geq2$. For $Re(s)>2$, we can separate the numerator and integrate by parts (using the Riemann-Stieltjes integral, for convenience) to get $f(s)=\frac{1}{s-1}\int_1^{\infty}\frac{1}{x^{s-1}}d\psi(x)-\frac{1}{s-2}$. Now, $\frac{\zeta'}{\zeta}(s)=-\sum\frac{\Lambda(n)}{n^s}=-\int_1^{\infty}\frac{1}{x^s}d\psi(x)$, so we can write $f(s)=\frac{-1}{s-1}\frac{\zeta'}{\zeta}(s-1)-\frac{1}{s-2}$. $\frac{\zeta'}{\zeta}(s-1)$ has a Laurent expansion at $s=2$ of the form $\frac{\zeta'}{\zeta}(s-1)=\frac{-1}{s-2}+\gamma+O(s-2)$, so that $f(s)=\frac{-1-\gamma}{s-1}+O(s-2)$. This holds for $Re(s)>2$, but if we let $s$ decrease to 2 and use the dominated convergence theorem, we get that the value of the integral is $-\gamma-1$. Hmm...this isn't quite the same as either value you gave. Maybe I made a mistake somewhere.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/64536', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12176/']}
jdg_75919
stackexchange
llm_judgeable_groundtruth_similarity
34156585
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: public class NumFormatTest{ public static void main(String[] args) throws ParseException { String num = "1 201"; DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRANCE); System.out.println("Number Before parse: "+num); double dm = df.parse(num).doubleValue(); System.out.println("Number After parse: "+dm); }} Output: Number Before parse: 1 201 Number After parse: 1.0 Expected Output: Number Before parse: 1 201 Number After parse: **1201** Can any please help me understand why parse is not able to convert a FRENCH locale formatted string (1 201) to normal double value (1201.0)? Now provide the response and nothing else.
There are two kinds of spaces. The "normal" space character (No. 32 - HEX 0x20) and the non-breaking space (NBSP) (No. 160 - HEX 0xA0). The French locale expects the whitespace character between the digits to be the non breaking space! You can help yourself with this line of code: String num = "1 201";num = num.replaceAll(" ", "\u00A0"); // '\u00A0' is the non breaking whitespace character! This way your code will work like expected. Please note that if you format a double into a String with French locale the resulting whitespace character will be the NBSP too!!! DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.FRENCH);System.out.println(df.format(1201.1));// This will print "1 202,1" But the space character will be '\u00A0'!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34156585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5351011/']}
jdg_75920
stackexchange
llm_judgeable_groundtruth_similarity
13550427
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When you inject a datasource in your application and get a connection by invoking getConnection() on it, are you supposed to close the connection? Now provide the response and nothing else.
Even though the datasource itself is container managed, the API indeed requires the programmer to close connections. This is different from a couple of other container managed resources (like the entity manager), where the container takes care of closing. Note that closing here in the majority of cases doesn't actually closes the connection here, but returns the connection to a connection pool. As a rule of thumb, if you use a factory-ish resources to obtain one or more other resources from that can be closed, you have to close them. Otherwise the container does this. Since Connection implements AutoCloseable , you can use a try-with-resources block for this: @Statelesspublic class MyBean { @Resource(lookup = "java:/app/datasource") private DataSource dataSource; public void doStuff() { try (Connection connection = dataSource.getConnection()) { // Work with connection here } catch (SQLException e) { throw new SomeRuntimeException(e); } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13550427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454049/']}
jdg_75921
stackexchange
llm_judgeable_groundtruth_similarity
4928323
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 System;public class clsPerson{ public string FirstName; public string MI; public string LastName;}class class1{ static void Main(string[] args) { clsPerson p=new clsPerson(); p.FirstName = "Jeff"; p.MI = "A"; p.LastName = "Price"; System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType()); x.Serialize(Console.Out, p); Console.WriteLine(); Console.ReadLine(); }} taken from http://support.microsoft.com/kb/815813 1) System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType()); What does this line do? what is GetType()? 2) how do I get the encoding to <?xml version="1.0" encoding="utf-8"?>< clsPerson xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> instead of <?xml version="1.0" encoding="IBM437"?> <clsPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3 .org/2001/XMLSchema"> or not include the encoding type at all? Now provide the response and nothing else.
If you pass the serializer an XmlWriter, you can control some parameters like encoding, whether to omit the declaration (eg for a fragment), etc. This is not meant to be a definitive guide, but an alternative so you can see what's going on, and something that isn't just going to console first. Note also, if you create your XmlWriter with a StringBuilder instead of a MemoryStream, your xml will ignore your Encoding and come out as utf-16 encoded. See the blog post writing xml with utf8 encoding for more information. XmlWriterSettings xmlWriterSettings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = false, Encoding = Encoding.UTF8 };using (MemoryStream memoryStream = new MemoryStream() )using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream, xmlWriterSettings)){ var x = new System.Xml.Serialization.XmlSerializer(p.GetType()); x.Serialize(xmlWriter, p); // we just output back to the console for this demo. memoryStream.Position = 0; // rewind the stream before reading back. using( StreamReader sr = new StreamReader(memoryStream)) { Console.WriteLine(sr.ReadToEnd()); } // note memory stream disposed by StreamReaders Dispose()}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4928323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103264/']}
jdg_75922
stackexchange
llm_judgeable_groundtruth_similarity
41853463
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My current work is to migrate my Java EE application from Jboss 7 server to Wildfly 10. I have a problem with integrate CDI and Spring-Data. I use this same configuration that worked on Jboss 7. When im trying deploy my application to Wildfly server I receive errors related to inject spring data repositories into some CDI and EJB beans. Errors look like this: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type StudentExtTrainingRepository with qualifiers @Default at injection point [BackedAnnotatedField] @Inject private pl.mynetwork.mylearning.logic.historyTraining.HistoryTrainingService.studentExtTrainingRepository at pl.mynetwork.mylearning.logic.historyTraining.HistoryTrainingService.studentExtTrainingRepository(HistoryTrainingService.java:0) at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:359) at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:281) at org.jboss.weld.bootstrap.Validator.validateGeneralBean(Validator.java:134) at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:155) at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:518) at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:68) at org.jboss.weld.bootstrap.ConcurrentValidator$1.doWork(ConcurrentValidator.java:66) at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:63) at org.jboss.weld.executor.IterativeWorkerTaskFactory$1.call(IterativeWorkerTaskFactory.java:56) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at org.jboss.threads.JBossThread.run(JBossThread.java:320) I configured my application according to spring data configuration guide, that i found here https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpd.misc.cdi-integration but on wildfly it doesnt work. I have producer class for Entity Manager like this @Dependentpublic class SpringDataConfigurationProducer { @Produces @ApplicationScoped public EntityManagerFactory createEntityManagerFactory() { return Persistence.createEntityManagerFactory("base-pu"); } @Produces @RequestScoped public EntityManager createEntityManager(EntityManagerFactory entityManagerFactory) { return entityManagerFactory.createEntityManager(); } } Of course i have files beans.xml in my projects under META-INF directory. Repository, that im trying inject looks like this: @Repository@Transactional@Dependentpublic interface StudentExtTrainingRepository extends JpaRepository<StudentExtTraining, Long> {} Service where i want to inject Repository looks : @Servicepublic class HistoryTrainingService { @Inject private StudentExtTrainingRepository studentExtTrainingRepository;} I have separate project for spring data repositories and separate for Services/EJBs. Both are packed to one EAR. Does anyone have any sugestions what wrong is ? I spent many hours with this problem and i can`t find solution. Now provide the response and nothing else.
Undefined behavior You're invoking undefined behavior by calling foo before the object is fully initialized. Quote from 12.6.2 in the C++ standard : Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer ) before all the mem-initializers for base classes have completed, the result of the operation is undefined. [ Example: class A {public: A(int);};class B : public A { int j;public: int f(); B() : A(f()), // undefined: calls member function // but base A not yet initialized j(f()) { } // well-defined: bases are all initialized};class C {public: C(int);};class D : public B, C { int i;public: D() : C(f()), // undefined: calls member function // but base C not yet initialized i(f()) { } // well-defined: bases are all initialized}; — end example ] In other words, this would be ok according to the standard : C(int i=0) : B(), A(i) { B::b = foo();} And this will print 10 instead of the 0 that you got (which could have been anything else, since that was undefined behavior). Initialization order Setting aside this matter of undefined behavior, and to address your question, the order in which initialization happens is well-defined : In a non-delegating constructor, initialization proceeds in the following order: — First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list . — Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers ). — Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers ). — Finally, the compound-statement of the constructor body is executed. [ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. — end note ] So, in your code, the initialization order is : B ( B::b ), A ( A::a ), C (). As noted in the comments below though, changing this initialization order (by eg. using struct C : A, B instead of struct C : B, A ) would not however get rid of the undefined behavior. Calling A::foo before the B part is initialized remains undefined, even if the A part is initialized.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41853463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2514376/']}
jdg_75923
stackexchange
llm_judgeable_groundtruth_similarity
14796620
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This question is concerning joining two databases in Google spreadsheet using =QUERY function I have a table like so in range A1:C3 a d gb e hc f i I have another table c j ma k nb l o I want the final table to look like this a d g k nb e h l o c f i j m I can do this by using a vlookup function pretty easily in cell D1 and paste it down and across, but my dataset is huge. I would need a whole page of vlookups and Google Spreadsheet tells I'm at my limit in complexities. I look at the Google's Query Language reference... there doesn't seem to be an type of "join" functions mentioned. You would think it would be an easy "join on A" type operation. Can anybody solves this without a vlookup? Now provide the response and nothing else.
Short answer Google QUERY Language version 0.7 (2016) doesn't include a JOIN (LEFT JOIN) operator but this could be achieved by using an array formula which result could be used as input for the QUERY function or for other uses. Explanation Array formulas and the array handling features of Google Sheets make possible to make a JOIN between two simple tables. In order to make easier to read, the proposed formula use named ranges instead of range references. Named Ranges table1 : Sheet1!A1:C3 table2 : Sheet2!A1:C3 ID : Sheet1!A1:A3 Formula =ArrayFormula( { table1, vlookup(ID,table2,COLUMN(Indirect("R1C2:R1C"&COLUMNS(table2),0)),0) }) Remarks: Using open ended ranges is possible but this could make the spreadsheet slower. To speed up the recalculation time : Replace Indirect("R1C2:R1C"&COLUMNS(table2),0) by an array of constants from 2 to number of columns of table2. Remove the empty rows from the spreadsheet Example See this sheet for an example Note On 2017 Google improved the official help article in English about QUERY, QUERY function . It still doesn't include yet topics like this but could be helpful to understand how it works.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14796620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1744744/']}
jdg_75924
stackexchange
llm_judgeable_groundtruth_similarity
285917
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have this true/false question that I think is true because I can not really find a counterexample but I find it hard to really prove it. I tried with the regular epsilon/delta definition of a limit but I can't find a closing proof. Anyone that If $\lim_{x \rightarrow a} | f(x) | = | A |$ then $ \lim_{x \rightarrow a}f(x) = A $ Now provide the response and nothing else.
As the others have pointed out, one fundamental use of ordered basis is to specify coordinates. Often, when we say something like $v=(1,2,3)$, we have already assumed that we are talking about coordinates w.r.t. an ordered basis: the canonical basis. If the order is not known, all we know is that $v$ has three coordinates $1,2,3$, but which one is the $x$-coordinate and which ones are $y$ and $z$ would be unknown to us, and hence we cannot be sure where exactly the point $v$ is. Another purpose of ordering a basis is to make the matrix representation of a linear operator simpler. For instance, consider $f:\mathbb{R}^5\to\mathbb{R}^5$, where the matrix representation of $f$ w.r.t. the canonical basis $A=\{e_1,\ldots,e_5\}$ is given by$$[f]_A^A=\begin{pmatrix}3&0&4&0&2\\5&4&0&0&4\\0&0&2&0&1\\2&0&5&1&3\\0&0&0&0&1\end{pmatrix}.$$Can you tell me the value of $\det f$? For some, the answer can be obtained using only mental calculation, but for the others, the answer is not that easy to obtain. However, if we reorder the basis as $B=\{e_4,e_2,e_1,e_3,e_5\}$, the answer will become utterly obvious:$$[f]_B^B=\begin{pmatrix}1&0&2&5&3\\0&4&5&0&4\\0&0&3&4&2\\0&0&0&2&1\\0&0&0&0&1\end{pmatrix}.$$Admittedly, this example is a bit contrived, but the reordering of bases does sometimes help simplifying the structure of a matrix. For instance, in my answer to a recent question , I had used this trick to make the matrix representation of a certain linear operator block upper triangular, so that I could write down the determinant of this operator immediately.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/285917', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59511/']}
jdg_75925
stackexchange
llm_judgeable_groundtruth_similarity
404838
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I asked this question on StackOverflow recently: Is there a Map in Java that supports looking up Keys by (non-Unique) Value? As I suspected, the answer was "no", but I'm wondering why there is no data structure that captures the relationship in question: Value put(Key, Value) List<Key> lookup(Value) Is a fairly common set of requirements, and it's one that is supported pretty commonly in database languages like SQL (e.g. SELECT key WHERE value = ${val} ) So why do no major languages support this relationship ? Note that this is different to a bi-map relationship, where the 1-1 relationship is enforced in both directions. Now provide the response and nothing else.
Unit tests don't care about internal state I have created a class that implements behavior which is difficult to test without some intimate knowledge of internal state. This is a contradiction. When talking about testing, behavior is specifically defined as public behavior, i.e. what is externally visible. Internal state is pretty much the exact opposite. This doesn't nullify the question, but it does reframe both your expectations and your question. If your public behavior can only be observed using internal state, then that which is internal state should be part of the public behavior. To give a simple example, suppose we create a simple addition tool: public class Adder{ public int Add(int a, int b) { // magic }} I say magic to prove the point. You're only made aware of the public behavior of this class, not the internal behavior. How do we test that this adder works? A simple test would be: public void TestAdder(){ var adder = new Adder(); Assert.AreEqual(adder.Add(1,1), 2); Assert.AreEqual(adder.Add(1,2), 3); Assert.AreEqual(adder.Add(2,1), 3);} This is provably a working test, yet you did not know how the adder actually works internally. Maybe it does simple + addition, maybe it uses a library, maybe it asks Google, maybe it posts a question to a math forum and parses the answer, maybe it emails me personally to ask for the answer, maybe... The purpose of unit testing is so that you are able to completely change the internal working of your class, while being able to run the same test to confirm that your changes did not break the class. If your test relies on the internal state (or knowledge thereof), it wouldn't be a useful unit test as it would inherently break when the (affected) internals change. How to test the outcome public class ComplicatedThing{ // The important behavior public void DoStuff() { ... }} The lasting effects of having called DoStuff() (i.e. the changes that DoStuff() caused) fit into one of two categories: Internal state Public behavior, which falls into one of two subcategories: Returning a value Interacting with dependencies Since you didnt show us exactly what it is you intend to test and where this effect can be found, I'll list how to approach either possibility. Internal state , for example: public class ComplicatedThing{ private string _privateField = "joke"; public void DoStuff() { _privateField = "secret"; }} Very simply put, this should not be tested . Knowing whether this private value is "joke" or secret" is not part of the public behavior, and therefore it doesn't matter for a unit test. However, it is possible (and indeed likely) that this internal state in some way impacts other external behavior, for example: public class ComplicatedThing{ private string _privateField = "joke"; public void DoStuff() { _privateField = "secret"; } public string TellMeSomething() { return $"I know a {_privateField}"; }} This public behavior ( TellMeSomething() ) can and should be tested, as it is part of the public contract. You'd expect a test along the lines of: public void Tells_me_it_knows_a_joke_without_doing_stuff(){ // Arrange var thing = new ComplicatedThing(); // Act var result = thing.TellMeSomething(); // Assert Assert.AreEqual(result, "I know a joke");}public void Tells_me_it_knows_a_secret_after_doing_stuff(){ // Arrange var thing = new ComplicatedThing(); // Act thing.DoStuff(); var result = thing.TellMeSomething(); // Assert Assert.AreEqual(result, "I know a secret");} But I do need to stress here that you should not expand the external behavior just because you want to test something. The justification of a behavior's existence should be that you need it for the codebase's purpose, not just so you can test it. Test that which is public behavior. Don't write public behavior so you can test. Returning a value The test for TellMeSomething() that I just showed you actually already answers this. You simply observe the returned result and assert that it conforms to your expectations. Interacting with dependencies , for example: public class ComplicatedThing{ private Foo _foo; public ComplicatedThing(Foo foo) { _foo = foo; } public void DoStuff() { _foo.PostMessage("secret"); }} This is a dependency that's injected in the constructor, but you can also have dependencies that are passed as method parameters: public class ComplicatedThing{ public void DoStuff(Foo foo) { foo.PostMessage("secret"); }} For the current topic, these are equally valid dependencies. The rest of the answer applies in either case. In a unit test, all dependencies should be mocked . The nice thing about this is that your unit test can therefore create a mocked object that secretly records what happens to it, so you can find out afterwards if certain methods were called with certain parameters. I tend to use NSubstitute for this, but other mocking frameworks exist, and you could also do this by yourself but it'd take more time. You would test this (using NSubstitute syntax) as follows: public void Posts_secret_message_to_foo(){ // Arrange var mockedFoo = Substitute.For<Foo>(); // this is a FAKE foo! var thing = new ComplicatedThing(mockedFoo); // we make thing use the fake foo // Act thing.DoStuff(); // thing doesn't know it's using a fake foo // Assert // our fake foo secretly recorded how it was being handled by thing mockedFoo.Received(1).PostMessage("secret");} The assert tests two things: It ensures that PostMessage was called exactly once It ensures that the method parameter passed to PostMessage was equal to "secret" Obviously, these asserts can be changed to what you actually need to assert. Conclusion In this answer are all the possible effects that calling a certain method can have, and how to test each of them. Combined with the knowledge that unit tests should never care about internal state (as this violates the concept of what a unit test tries to achieve), then we've eliminated all possibilities. The approach you suggest taking is not correct. Depending on where the mistake/misconception lies, one of the given solutions is the appropriate one. To summarize: This should indeed be internal state => then don't test it. This should have been a return value => test the return value This should have caused changes to take place in dependencies => mock the dependencies and assert that they were interacted with in the way you expect them to be
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/404838', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/366/']}
jdg_75926
stackexchange
llm_judgeable_groundtruth_similarity
1786130
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I easily convert complex number from exponential or trigonometric form to algebraic? Update In fact I'm trying to simplify this expression: The only way I see is to convert to trigonometric form then expand but I can't make Maple calculate cos and sin. So how can I do this? My code: restart; w1 := 100; L2 := 100*10^(-3); L3 := L2; L5 := 200*10^(-3); C6 := (200/3)*10^(-6); psi1 := 32.5 degrees;Z6 := -I/(w1*C6);Z5 := I*w1*L5;Z2 := I*w1*L2;Z1 := 75;Z3 := I*w1*L3;Z4 := 75;Z7 := 75;eq := {Imk-(U1-U2)/Z2-(U2-U3)/Z1 = 0, U1/Z4+U1/(Z5+Z6+Z7)+U3/Z3 = 0, (U1-U2)/Z2-U1/(Z5+Z6+Z7)-U1/Z4 = 0};a := solve(eq, {U1, U2, U3});U1 := eval(U1, a);U1 := convert(U1, float);Imk1 := [.575, .868*exp(I*psi1), -.366, .243, -.183];Ink := Array(1 .. 5);for n to 5 do Ink[n] := simplify((32.14738845-6.185240008*I)*Imk1[n]/(Z5+Z6+Z7)) end do; Ud := 0; for n to 5 do: Ud := Ud+(1/2)*Ink[n]^2 end do;Ud := simplify(sqrt(Ud), sqrt);print(Ink[2]); expand(convert(Ink[2], trig)); Now provide the response and nothing else.
Ok, one way to intimidate students is to use large numbers like 6000 in questions. A simple tool to beat this strategy of examiner is to replace the big number by a generic symbol say $n$. We thus calculate the limit $$f(n) = \lim_{x \to 0}\frac{x^{n} - \sin^{n}x}{x^{2}\sin^{n}x}$$ where $n$ is a positive integer. The answer for the question is $f(6000)$. We have\begin{align}f(n) &= \lim_{x \to 0}\frac{x^{n} - \sin^{n}x}{x^{2}\sin^{n}x}\notag\\&= \lim_{x \to 0}\dfrac{x - \sin x}{x^{3}\cdot\dfrac{\sin x}{x}}\cdot\dfrac{{\displaystyle \sum_{i = 0}^{n - 1}x^{i}\sin^{n - 1 - i}x}}{\sin^{n - 1}x}\notag\\&= \lim_{x \to 0}\frac{x - \sin x}{x^{3}}\sum_{i = 0}^{n - 1}\left(\frac{x}{\sin x}\right)^{i}\notag\\&= \sum_{i = 0}^{n - 1} 1\cdot \lim_{x \to 0}\frac{1 - \cos x}{3x^{2}}\text{ (via L'Hospital's Rule)}\notag\\&= \frac{n}{6}\notag\end{align}and hence the desired answer is $f(6000) = 1000$.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1786130', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/335213/']}
jdg_75927
stackexchange
llm_judgeable_groundtruth_similarity
15538479
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 code that dynamically search for data in the database using ajax but I can search for only 1 keyword in a time. I would like to modify it so I can search for multiple keywords. Now, if I type 2 keywords separated by a space and in the database, the data is not separated by a space, there will be no result.If in the database the data is: 'playstation3' or 'play cool station3' and I search for: play station there would be no results. I would like to know if it possible to modify my code so I can search 2 or more keywords or words separated by a space or another word or a DOT or an underscore or a (-) or a (+) or a (%) or (anything else lol). I know that I should use pdo or mysqli but i'm using this for testing only! $queried = $_POST['query'];$search = mysql_query("SELECT * FROM links WHERE name LIKE '%$queried%'");while($searche = mysql_fetch_array($search)){ echo "".$searche['link']."</br>".$searche['name']."</br>".$searche['size']."</br>".$searche['category']."<hr></br></br>"; } Now provide the response and nothing else.
To dynamically search all keywords, you can use the explode function to seperate all keywords; $queried = mysql_real_escape_string($_POST['query']); // always escape$keys = explode(" ",$queried);$sql = "SELECT * FROM links WHERE name LIKE '%$queried%' ";foreach($keys as $k){ $sql .= " OR name LIKE '%$k%' ";}$result = mysql_query($sql); Note 1: Always escape user input before using it in your query. Note 2: mysql_* functions are deprecated, use Mysqli or PDO as an alternative Update 2018 - Note 3: Don't forget to check the length of the $queried variable and set a limit. Otherwise the user can input a vary large string and crash your database.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15538479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1932820/']}
jdg_75928
stackexchange
llm_judgeable_groundtruth_similarity
613900
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 $f$ a continous function defined in the interval $[0,1]$. Assuming: $\forall x \in [0,1]:f(x) > x$ Prove: $\forall x \in [0,1]:f(x) > x + \varepsilon $ I tried to use Heine–Cantor theorem and did some Algebra tricks but it didn't bring me to a safe shore :) What do you suggest? Thanks! Now provide the response and nothing else.
Let $h:x\mapsto f(x)-x$ then $h$ is continuous on the compact $I=[0,1]$ hence $h$ is bounded (here we need to say bounded below) and reaches its minimum at $x_0\in I$ hence we have$$h(x)\geq h(x_0)>0,\;\forall x\in I$$Now take $\epsilon=\frac{h(x_0)}{2}$ and you have the result.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/613900', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/115727/']}
jdg_75929
stackexchange
llm_judgeable_groundtruth_similarity
57237381
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use a pre-trained model. Here's where the problem occurs Isn't the model supposed to take in a simple colored image? Why is it expecting a 4-dimensional input? RuntimeError Traceback (most recent call last)<ipython-input-51-d7abe3ef1355> in <module>() 33 34 # Forward pass the data through the model---> 35 output = model(data) 36 init_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability 37 5 frames/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in forward(self, input) 336 _pair(0), self.dilation, self.groups) 337 return F.conv2d(input, self.weight, self.bias, self.stride,--> 338 self.padding, self.dilation, self.groups) 339 340 RuntimeError: Expected 4-dimensional input for 4-dimensional weight 32 3 3, but got 3-dimensional input of size [3, 224, 224] instead Where inception = models.inception_v3()model = inception.to(device) Now provide the response and nothing else.
As Usman Ali wrote in his comment, pytorch (and most other DL toolboxes) expects a batch of images as an input. Thus you need to call output = model(data[None, ...]) Inserting a singleton "batch" dimension to your input data . Please also note that the model you are using might expect a different input size (3x229x229) and not 3x224x224.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57237381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6458245/']}
jdg_75930
stackexchange
llm_judgeable_groundtruth_similarity
3070144
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 get hold of the addresses to the currently used DNS servers in my application, either I'm connected thru Wifi or mobile.The DhcpInfo object should provide this but how can I get hold of a valid DhcpInfo object? Now provide the response and nothing else.
Calling for the getRuntime().exec can hang your application. android.net.NetworkUtils.runDhcp() cause unnecessary network requests. So I prefer to do this: Class<?> SystemProperties = Class.forName("android.os.SystemProperties");Method method = SystemProperties.getMethod("get", new Class[] { String.class });ArrayList<String> servers = new ArrayList<String>();for (String name : new String[] { "net.dns1", "net.dns2", "net.dns3", "net.dns4", }) { String value = (String) method.invoke(null, name); if (value != null && !"".equals(value) && !servers.contains(value)) servers.add(value);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3070144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/370344/']}
jdg_75931
stackexchange
llm_judgeable_groundtruth_similarity
4452943
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anybody know if there is a way to get direct links to advertisers on Commission Junction with tracking? We don't want to rely on the links sent down in the feed because a lot of them are junk. What I'd like is a link that just goes to the advertiser's homepage and still allows us to receive commissions. Something like: http://www.newegg.com?pid=123123&aid=321123 If it has to run through CJ's tracking URL's that's fine too, but I just want the user on the homepage. Thanks Now provide the response and nothing else.
Old thread but figured it needs an answer. Solution is quite simple. What you need to construct is a URL that like this: http://<cj-root-domain>/click-<your-pid>-<advertiser-link-id>?url=<url-encoded-redirect-link> E.g.: http://www.jdoqocy.com/click-1245-10888587?url=http%3A%2F%2Fwww.jewelry.com%2Fdaily-deal.shtml So... Pick a CJ root domain to link on. www.anrdoezrs.net, www.tkqlhce.com or any others on this thread will work. Find any generic link ID for the advertiser by logging into CJ and viewing the Links tab. A good link to use will be something that's not likely to be deleted, like their brand logo. Take note of your Publisher PID URL-encode the actual destination you want to link to
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4452943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/295796/']}
jdg_75932
stackexchange
llm_judgeable_groundtruth_similarity
19485949
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 put in a different image for each resolution. It worked for normal screen and smartphones, however I cannot get it to show up for the large resolution screens. Here are the relevant sections of code: CSS: /* Large screens ----------- */@media only screen and (min-width : 1800px) {html { background: #000000 url(images/blackmagic.png) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover;}body { background-color:transparent; font-size: 100%; color:#000000;}h1 { color:#000000; text-transform:uppercase; font-family: 'Sancreek', Impact, sans-serif; font-size:2.5em;}h2 { font-family: 'Pathway Gothic One', Verdana, sans-serif; font-size:1.875em; color:#000000;}a:link { color:#000000;}a:hover { color:#9b0505;}p { color:#000000; font-family: 'Monda', Verdana, sans-serif; font-size:0.875em; text-align:justify;}#container { position:relative; width: 2200px; margin: 0 auto; z-index: 0;}#social { position:relative; margin-left: 450px; z-index: 0;}#header { display:none; position:relative;}#headerm { display:none; position:relative;}#headerl { position:relative; z-index:1; margin-top:-500px; margin-left:200px; width: 100%;} HTML: <div id="container" class="outer"> <div id="border" class="outer"> <div id="header" class="inner"> <img src="/images/header.png" id="headerimage" /> </div> <div id="headerl" class="inner"> <img src="/images/headerlg.png" id="headerimage" /> </div> <div id="headerm" class="inner"> <img src="/images/headerm.jpg" id="headerimage" /> </div> Now provide the response and nothing else.
This function is inadequate for several reasons: It's buggy . Notice that value is declared as an int rather than a double , which means that if you try to compute power(1.5, 1) , you'll get back 1 rather than 1.5 . In fact, it will be wrong on almost all inputs. It doesn't handle negative exponents. Try computing power(2, -1) . The correct answer is 0.5 , but your function (after fixing the int bug noted above) will return 1 rather than 0.5 . You can fix this pretty easily (you could, for example, compute power(2, 1) and then take the reciprocal), but it's troublesome as currently written. It's slow. Most exponentiation, when the power is an integer, is computed using an algorithm called exponentiation by squaring , which is considerably faster than your code. Exponentiation by squaring will do Θ(log Y) multiplications, compared to the Θ(Y) multiplications your code makes. It will take exponentially longer for your function to complete. It doesn't handle fractional exponents. Try computing power(1.5, 1.5) . You'll get the wrong answer because the exponent is an int , not a double . Correcting this isn't easy; search around on Stack Overflow for other questions on how to implement this properly. It reinvents the wheel . At a fundamental level, you should ask yourself why you're rewriting a function provided to you by the language's math libraries. This can introduce bugs or inefficiencies into the program (see the earlier bullet points) and at the end of the day you haven't increased the functionality. Hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19485949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2901677/']}
jdg_75933
stackexchange
llm_judgeable_groundtruth_similarity
50554170
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 nodejs , I have a small mongoose module which exports the model (User) . When I require the module without using destructuring assignment and I create the new instance of the model using new operator, I get the error that the model is not a function. But if i use the destructuring assignment when I require the model, everything works fine. Not able to understand why. User.js exports the model const mongoose = require('mongoose');exports.User = mongoose.model('User', { email:{ type: String, trim: true, minlength: 1, reuqired: true }}); Below code throws error if I dont use destructuring operator on line 2 : server.js const mongoose = require('../DB/mongoose');const User = require('../Models/User');console.log(typeof(User));let user = new User({ email: "sdfdsf"}); server.js throws the below error: let user = new User({ ^TypeError: User is not a constructor at Object.<anonymous> (F:\javascript\nodePractice\ToDoApp\server\server.js:6:12) at Module._compile (internal/modules/cjs/loader.js:678:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10) at Module.load (internal/modules/cjs/loader.js:589:32) at tryModuleLoad (internal/modules/cjs/loader.js:528:12) at Function.Module._load (internal/modules/cjs/loader.js:520:3) at Function.Module.runMain (internal/modules/cjs/loader.js:719:10) at startup (internal/bootstrap/node.js:228:19) at bootstrapNodeJSCore (internal/bootstrap/node.js:576:3) But If I use a destructuring assignment on line 2 , it works all fine. server.js : const mongoose = require('../DB/mongoose');const {User} = require('../Models/User');console.log(typeof(User));let user = new User({ email: "sdfdsf"}); Now provide the response and nothing else.
const {User} = require('../Models/User'); is equivalent to const User = require('../Models/User').User;// ^^^^^ The module object that require() returns (the exports object that your module filled) does have a .User property . If you don't access that but try to use the module object as a constructor, it throws. To be explicit, you might want to use const userModule = require('../Models/User');console.log(typeof userModule);console.log(typeof userModule.User);let user = new userModule.User({ email: "sdfdsf"}); Alternatively, if you insist on doing const User = require('../Models/User'); , you can also make the constructor function the exported object by overwriting module.exports instead of creating a property on it: const mongoose = require('mongoose');module.exports = mongoose.model('User', { …});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50554170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4384490/']}
jdg_75934
stackexchange
llm_judgeable_groundtruth_similarity
51559
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: Many games today are prereleased in an alpha/beta state and instantly overwhelmed by "hackers" downloading programs manipulating the game itself to become overpowered. I guess they make injections into certain memory addresses in runtime but I have no clue of how to go about to create a program like that. Also, how do you prevent it? Any suggestions of how they do this are greatly appriciated. The more details, the better! Now provide the response and nothing else.
Your question is really broad. I can tell you about how I did in one instance, for fun, in a small arcade game several years ago. This should make you gain some educational insight, but won't help you much otherwise, I'm afraid. I simply had another program running in background, scoping the memory of the arcade game. I started playing, and then I lost one life. Hit both shift keys -- and a snapshot of the memory was saved to disk unbeknownst to the running arcade. Then another. BAM another snapshot. A third, and a fourth. And then game over and I exited the arcade game. Then I just compared the snapshots, looking for a memory location that changed from one snapshot to the next, either increasing or decreasing by exactly one. I remember finding some twenty of them. I could have checked all of them, but I spotted immediately that one among them, and only one, had value "five" at the start of the game, and became "four" on my first death. And I had started with five ships. Now that's interesting... So I wrote a small program that would look for that memory address, recognizing it by its distance from other pieces of code and strings that didn't change, checking its value every few seconds, and just poking back "5" into it as soon as it became anything less: : install look for string 'COPYRIGHT ACME GAMES' add 1138 is it a five? no, abort, something went wrong yes. lie in wait.: wait is it still a five? no. Set it to five. sleep for a couple of seconds goto wait Sure enough, the next game, I died - and an instant later, my four remaining starships became five again. For the heck of it, I discovered that I could get up to seven 'lives' with this method (eight crashed the game). By using a "debugger" it would also have been possible to stop the program as soon as the location was modified, thereby seeing which instruction had done the deed. Then you would just blot out that one instruction from the assembler code. Or you could follow the program flow in reverse, and discover where, for example, the collision check was made between your player's sprite and the enemy missiles'. Thwart that check, and the enemy missiles no longer affect you (possibly, also yours no longers affect them; it's a tricky business). I expect the techniques to have matured and progressed a great deal in these years, but I'm confident that basically the idea is still the same - spot the change you don't like, then either defang the code causing it, or patch the code so that the damage is undone as soon as it happens. To make things more difficult one could devise strategies to make the changes stand out less, or make them seemingly random. Add "chaff" or "dummy" variables that change just as if they were useful. Use them as telltales - if all variables don't tally, it means that someone is trying to hack. In the end, however, you can't beat a determined and experienced hacker. All you can do is try making the deed not worth his while. There are code obfuscators, code protectors, code encryptors, debugger detectors, anti-virtualization techniques...
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/51559', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/40113/']}
jdg_75935
stackexchange
llm_judgeable_groundtruth_similarity
2091649
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 the context of general topology, a function is said to be continuous if the pre-image of any open subset is also an open subset. Of course, this does not say that the image of an open set must be an open set (and in fact, this is not true in general). But, what about the statement "all sets whose image is open must be open" ? This is a different statement, and I don't know what to think of it intuitively. My thoughts: Let $X$ and $Y$ be topological spaces and let $f : X \to Y$ continuous. Let $A$ be a set such that $f(A)$ is open. I am trying to decide whether or not $A$ is necessarily open. I know from set theory that $A \subseteq f^{-1}(f(A))$, and the fact that it is not an equality is very important (if this was an equality, the statement would be immediately true). With this, I am able to conclude that $A$ is a subset of the open set $f^{-1}(f(A))$, and apparently I can't conclude anything better. With this in mind, it seems to me that the statement is probably false, but I was unable to find any counterexample either. Now provide the response and nothing else.
Since you ask it in a general context let me add a simple abstract example. Let $Y$ be a topological space with a unique element. Let $X$ be any topological space. Then the unique $f:X \to Y$ is continuous. We have $f(A)$ is open for every $A \subset X$. Thus, as soon as in $X$ not every set is an open set, you have a counterexample.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2091649', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/183815/']}
jdg_75936
stackexchange
llm_judgeable_groundtruth_similarity
2171200
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have some issue wrapping my mind around the concepts of enumeration of infinite sets, and infinite sets as whole complete objects in general. I know a lot of people struggle with this, and some people (even some of the greatest mathematicians of all time) have resisted these notions. I just want to get past the point where I’m haunted by ambiguities that I perceive through standard explanations. The first thing I want to clear up is the notion that an infinite set can be enumerated. I know that we say that an infinite set is enumerable if it can be put into bijection with the natural numbers. This makes sense from the surface, but my senses fail me at the part where we assume that such a set can actually be “enumerated” in the sense of a verb, i.e. enumeration is an action that on an infinite set can be completed. My intuition suggests that such a definition is actually only a rule for enumeration, but there is no such thing as a completed enumeration. The idea being that you “can describe how to do something that cannot be done". With this problem I have a problem conceptualizing Cantors diagonalization proof. It goes by assuming something is an enumeration of some infinite set. Then it selects something not in that set by selecting something that differs by value for each digit with respect to every element in the enumerated set. It seams like you first need the notion that selecting this new element can ever be done, since there is no end (no base case where such a procedure would ever end). Such an element seams "un-selectable" by nature purely by assumption that the supposedly enumerated set is infinite. So to me it seams like trying to select this element is a little like trying to select the largest natural number. Maybe I am coming at this from the wrong angle. Any insight is appreciated. Now provide the response and nothing else.
The key is to stop thinking about enumerations as something that you do, and think about them as something that exists in the mathematical universe . Of course, asking you to think that something exists does not make it exist in general. I could think of an even number less than $2$, it won't make it pop into mathematical existence, and I can think about a cold pint of beer right now, but unless I go outside and buy myself a cold pint of beer, it doesn't exist in my current world. So how do we bridge that issue? We are handed a mathematical universe with the tacit agreement that it satisfies some axioms. These could be set theory axioms, or some type theory, or other foundational theory which gives us a general framework. This universe is given to you, with everything inside of it, and now the question is what can you ensure that is there if you use the axioms and the inference rules. Now the definition of being countable makes more sense. If there is a function from the natural numbers to some set which is a bijection, then the set is countable, and that function is call an enumeration. We can prove that the rational numbers are countable, and we can prove that some sets are countable; and Cantor's diagonal argument shows that no matter what, we cannot prove that the real numbers are countable. Namely, the idea is that given any function from the natural numbers into the real numbers, we can define from that function a real number which is not any of the values given by our function. But the function is inside our universe, and the tacit axioms of our universe should allow us to use definitions like that. It is true, however, that in another universe the diagonal proof might not work. In some constructive settings it can fail, or if you assume there are no such thing as irrational numbers, then it will fail. But in general, most of mathematics is not concerned with you enumerating, but rather with you proving the existence or nonexistence of an enumerating function.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2171200', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/83657/']}
jdg_75937
stackexchange
llm_judgeable_groundtruth_similarity
454583
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose we have a unit cube (side=1) and a plane with equation $x+y+z=\alpha$. I'd like to compute the volume of the region that results once the plane sections the cube (above the plane). There are three cases to analyze, and I can't quite visualize one of them. Case 1: $0 \le \alpha < 1$ In this case, the section looks like a triangle, and the volume of interest is 1 minus the volume of the lower left tetrahedron, i.e., $$V = 1 - \int_0^\alpha \int_0^{\alpha-x} \int_0^{\alpha-x-y} dz\,dy\,dx = 1 - \frac{\alpha^3}{6}.$$ Case 3: $2 < \alpha \le 3$. Here, the section is again a triangle, and the volume of interest is the upper right tetrahedron, i.e., $$V = \int_{\alpha-2}^1 \int_{\alpha-x-1}^1 \int_{\alpha-x-y}^1 dz\,dy\,dx = \frac{(3-\alpha)^3}{6}.$$ Case 2: $1 \le \alpha \le 2$. This is where I'm sort of stuck. The section is a hexagon, with one of the inequalities being $\alpha-x-y \le z \le 1$, hence the innermost integral should be $\int_{\alpha-x-y}^1 dz$. The projection of the hexagon slice onto the $xy$-plane is described by $y \ge \alpha-1-x$ and $y \le \alpha-x$. Hence, the area of the hexagon projection is $$ A = \int_0^{\alpha-1} \int_{\alpha-x-1}^1 dy\,dx + \int_{\alpha-1}^1 \int_0^{\alpha-x} dy\,dx$$ Question: When I move from $A$ to $V$ am I allowed to distribute the innermost integral between the summing terms, i.e. is it correct to write $$V = \int_0^{\alpha-1} \int_{\alpha-x-1}^1 \int_{\alpha-x-y}^1 dz\,dy\,dx + \int_{\alpha-1}^1 \int_0^{\alpha-x} \int_{\alpha-x-y}^1 dz\,dy\,dx \quad ??$$ If not, what's the approach? Note that there's a neat connection between this problem and figuring out the CDF of a sum of a random variable that has triangular distribution with support on $[0,2]$ and a random variable with uniform distribution on $[0,1]$ (assuming independence). Hence, I know what the answer should be for Case 2 because I worked out the convolution, but I just want to figure out the answer geometrically as well. Now provide the response and nothing else.
For $1 \le \alpha \le 2$, it is much easier to visualize the integral by subtracting instead of adding pieces of the volume. As shown in the picture below, when $1 \le \alpha \le 2$, the volume of cube section below intersection of the plane $x + y + z = \alpha$ is the difference of the volume ofone big tetrahedron with width/height/depth $= \alpha$ with three smaller ones with width/height/depth $= \alpha-1$. So the volume above the intersection becomes $$1 - \left( \frac16 \alpha^3 - 3 ( \frac16 (\alpha-1)^3 )\right) = 1 - \frac16 \alpha^3 + \frac12 (\alpha-1)^3$$ Update About the question whether this argument can be extended to higher dimension, the answer is yes. Let's look at the 3-dimension $2 \le \alpha \le 3$ case first. As one increases $\alpha$ beyond $2$, the three tetrahedron in first figure start overlap.As shown in second figure, the intersection of the three tetrahedra are now three even smaller tetrahedra of width/height/depth = $\alpha -2$. Previous way to compute the "volume" of cube section below the plane $x + y + z = \alpha$ now subtract too much from this three even smaller tetrahedron. One need to add them back.As a result, the volume above the plane becomes: $$\begin{align}&1 - \left( \frac16 \alpha^3 - 3(\frac16 (\alpha-1)^3 + 3(\frac16 (\alpha-2)^3 \right)\\= & 1 - \frac16 \alpha^3 + \frac12 (\alpha-1)^3 - \frac12 (\alpha-2)^3\\ = & \frac{(3-\alpha)^3}{6}\end{align}$$ Let us switch to the $k$-dimension case. To compute the "volume" of the hypercube section above the hyperplane $x_1 + \ldots + x_k = \alpha$, the first step is to subtract the volume of a $k$-simplex of size $\alpha$ from 1. if $\alpha \le 1$, we are done. if $\alpha > 1$, we over subtract the volume of $\binom{k}{1}$ simplices of size $\alpha-1$ and need to add them back. if $\alpha > 2$, the $\binom{k}{1}$ simplices of size $\alpha-1$ in step 2 intersectand the intersection is a union of $\binom{k}{2}$ $\;k$-simplices of size $\alpha-2$. Thismeans in step 2, we have added back too much and need to subtract the volume again. Repeat these arguments and notice in the middle of the process, we need to either add or subtract the volumes of $\binom{k}{i}$ $\;k$-simplices of size $\alpha-i$. The "volume" of interest finally becomes: $$1 -\sum_{i=0}^{\lfloor \alpha \rfloor} (-1)^i \binom{k}{i} \frac{(\alpha-i)^k}{k!}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/454583', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/67409/']}
jdg_75938
stackexchange
llm_judgeable_groundtruth_similarity
10443891
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: rm is to remove item, but what is the parameter -rf do or signify? Whenever I typed help -rf it printed the entire list of available commands in powershell. What happens if you type rm -rf in powershell? From reading around I've gathered that it will delete everything on the drive? I'm not sure? Also, is rm -rf same as rm -rf / ? Now provide the response and nothing else.
PowerShell isn't UNIX. rm -rf is UNIX shell code, not PowerShell scripting. This is the documentation for rm (short for Remove-Item ) on PowerShell . This is the documentation for rm on UNIX . See the difference? On UNIX, rm -rf alone is invalid. You told it what to do via rm for remove with the attributes r for recursive and f for force , but you didn't tell it what that action should be done on. rm -rf /path/to/delete/ means rm ( remove ) with attributes r ( recursive ) and f ( force ) on the directory /path/to/remove/ and its sub-directories. The correct, equivalent command on PowerShell would be: rm C:\path\to\delete -r -fo Note that -f in PowerShell is ambiguous for -Filter and -Force and thus -fo needs to be used.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10443891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1366993/']}
jdg_75939
stackexchange
llm_judgeable_groundtruth_similarity
2530096
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 proper way to get a list of all available serial ports/devices on a Linux system? In other words, when I iterate over all devices in /dev/ , how do I tell which ones are serial ports in the classic way, that is, those usually supporting baud rates and RTS/CTS flow control? The solution would be coded in C. I ask because I am using a third-party library that does this clearly wrong: It appears to only iterate over /dev/ttyS* . The problem is that there are, for instance, serial ports over USB (provided by USB-RS232 adapters), and those are listed under /dev/ttyUSB*. And reading the Serial-HOWTO at Linux.org , I get the idea that there'll be other name spaces as well, as time comes. So I need to find the official way to detect serial devices. The problem is that none appears to be documented, or I can't find it. I imagine one way would be to open all files from /dev/tty* and call a specific ioctl() on them that is only available on serial devices. Would that be a good solution, though? Update hrickards suggested to look at the source for "setserial".Its code does exactly what I had in mind: First, it opens a device with: fd = open (path, O_RDWR | O_NONBLOCK) Then it invokes: ioctl (fd, TIOCGSERIAL, &serinfo) If that call returns no error, then it's a serial device, apparently. I found similar code in Serial Programming/termios , which suggested to also add the O_NOCTTY option. There is one problem with this approach, though: When I tested this code on BSD Unix (that is, Mac OS X), it worked as well. However , serial devices that are provided through Bluetooth cause the system (driver) to try to connect to the Bluetooth device, which takes a while before it'll return with a timeout error. This is caused by just opening the device. And I can imagine that similar things can happen on Linux as well - ideally, I should not need to open the device to figure out its type. I wonder if there's also a way to invoke ioctl functions without an open, or open a device in a way that it does not cause connections to be made? What should I do? Now provide the response and nothing else.
The /sys filesystem should contain plenty information for your quest. My system (2.6.32-40-generic #87-Ubuntu) suggests: /sys/class/tty Which gives you descriptions of all TTY devices known to the system. A trimmed down example: # ll /sys/class/tty/ttyUSB*lrwxrwxrwx 1 root root 0 2012-03-28 20:43 /sys/class/tty/ttyUSB0 -> ../../devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.4/2-1.4:1.0/ttyUSB0/tty/ttyUSB0/lrwxrwxrwx 1 root root 0 2012-03-28 20:44 /sys/class/tty/ttyUSB1 -> ../../devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.3/2-1.3:1.0/ttyUSB1/tty/ttyUSB1/ Following one of these links: # ll /sys/class/tty/ttyUSB0/insgesamt 0drwxr-xr-x 3 root root 0 2012-03-28 20:43 ./drwxr-xr-x 3 root root 0 2012-03-28 20:43 ../-r--r--r-- 1 root root 4096 2012-03-28 20:49 devlrwxrwxrwx 1 root root 0 2012-03-28 20:43 device -> ../../../ttyUSB0/drwxr-xr-x 2 root root 0 2012-03-28 20:49 power/lrwxrwxrwx 1 root root 0 2012-03-28 20:43 subsystem -> ../../../../../../../../../../class/tty/-rw-r--r-- 1 root root 4096 2012-03-28 20:43 uevent Here the dev file contains this information: # cat /sys/class/tty/ttyUSB0/dev188:0 This is the major/minor node. These can be searched in the /dev directory to get user-friendly names: # ll -R /dev |grep "188, *0"crw-rw---- 1 root dialout 188, 0 2012-03-28 20:44 ttyUSB0 The /sys/class/tty dir contains all TTY devices but you might want to exclude those pesky virtual terminals and pseudo terminals. I suggest you examine only those which have a device/driver entry: # ll /sys/class/tty/*/device/driverlrwxrwxrwx 1 root root 0 2012-03-28 19:07 /sys/class/tty/ttyS0/device/driver -> ../../../bus/pnp/drivers/serial/lrwxrwxrwx 1 root root 0 2012-03-28 19:07 /sys/class/tty/ttyS1/device/driver -> ../../../bus/pnp/drivers/serial/lrwxrwxrwx 1 root root 0 2012-03-28 19:07 /sys/class/tty/ttyS2/device/driver -> ../../../bus/platform/drivers/serial8250/lrwxrwxrwx 1 root root 0 2012-03-28 19:07 /sys/class/tty/ttyS3/device/driver -> ../../../bus/platform/drivers/serial8250/lrwxrwxrwx 1 root root 0 2012-03-28 20:43 /sys/class/tty/ttyUSB0/device/driver -> ../../../../../../../../bus/usb-serial/drivers/ftdi_sio/lrwxrwxrwx 1 root root 0 2012-03-28 21:15 /sys/class/tty/ttyUSB1/device/driver -> ../../../../../../../../bus/usb-serial/drivers/ftdi_sio/
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2530096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/43615/']}
jdg_75940