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
3185239
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 need to solve $Ax=b$ in lots of ways using QR decomposition. $$A = \begin{bmatrix} 1 & 1 \\ -1 & 1 \\ 1 & 2 \end{bmatrix}, b = \begin{bmatrix} 1 \\ 0 \\ 1 \end{bmatrix}$$ This is an overdetermined system. That is, it has more equations than needed for a unique solution. I need to find $\min ||Ax-b||$ . How should I solve it using QR? I know that QR can be used to reduce the problem to $$\Vert Ax - b \Vert = \Vert QRx - b \Vert = \Vert Rx - Q^{-1}b \Vert.$$ but what do I do after this? Now provide the response and nothing else.
The most straightforward way I know is to pass through the normal equations: $$A^T A x = A^T b$$ and substitute in the $QR$ decomposition of $A$ (with the convention $Q \in \mathbb{R}^{m \times n},R \in \mathbb{R}^{n \times n}$ ). Thus you get $$R^T Q^T Q R x = R^T Q^T b.$$ But $Q^T Q=I_n$ . (Note that in this convention $Q$ isn't an orthogonal matrix, so $Q Q^T \neq I_m$ , but this doesn't matter here.) Thus: $$R^T R x = R^T Q^T b.$$ If $A$ has linearly independent columns (as is usually the case with overdetermined systems), then $R^T$ is injective, so by multiplying both sides by the left inverse of $R^T$ you get $$Rx=Q^T b.$$ This system is now easy to solve numerically. For numerical purposes it's important that the removal of $Q^T Q$ and $R^T$ from the problem is done analytically, and in particular $A^T A$ is never constructed numerically.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3185239', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/166180/']}
jdg_372141
stackexchange
llm_judgeable_groundtruth_similarity
9307
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I tried to install python-pip by typing this command: sudo apt-get install python-pip And the result is below: Err http://mirrordirector.raspbian.org/raspbian/ wheezy/main python2.6-minimal armhf 2.6.8-1.1 Temporary failure resolving 'mirrordirector.raspbian.org'Err http://mirrordirector.raspbian.org/raspbian/ wheezy/main python2.6 armhf 2.6.8-1.1 Temporary failure resolving 'mirrordirector.raspbian.org'Err http://mirrordirector.raspbian.org/raspbian/ wheezy/main python-pkg-resources all 0.6.24-1 Temporary failure resolving 'mirrordirector.raspbian.org'Err http://mirrordirector.raspbian.org/raspbian/ wheezy/main python-setuptools all 0.6.24-1 Temporary failure resolving 'mirrordirector.raspbian.org'Err http://mirrordirector.raspbian.org/raspbian/ wheezy/main python-pip all 1.1-3 Temporary failure resolving 'mirrordirector.raspbian.org'Failed to fetch http://mirrordirector.raspbian.org/raspbian/pool/main/p/python2.6/python2.6-minimal_2.6.8-1.1_armhf.deb Temporary failure resolving 'mirrordirector.raspbian.org'Failed to fetch http://mirrordirector.raspbian.org/raspbian/pool/main/p/python2.6/python2.6_2.6.8-1.1_armhf.deb Temporary failure resolving 'mirrordirector.raspbian.org'Failed to fetch http://mirrordirector.raspbian.org/raspbian/pool/main/d/distribute/python-pkg-resources_0.6.24-1_all.deb Temporary failure resolving 'mirrordirector.raspbian.org'Failed to fetch http://mirrordirector.raspbian.org/raspbian/pool/main/d/distribute/python-setuptools_0.6.24-1_all.deb Temporary failure resolving 'mirrordirector.raspbian.org'Failed to fetch http://mirrordirector.raspbian.org/raspbian/pool/main/p/python-pip/python-pip_1.1-3_all.deb Temporary failure resolving 'mirrordirector.raspbian.org'E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing? Then I tried to sudo apt-get update and sudo apt-get update --fix-missing , but it doesn't work either. The result was like this: Err http://raspberrypi.collabora.com wheezy Release.gpg Temporary failure resolving 'raspberrypi.collabora.com'Err http://archive.raspberrypi.org wheezy Release.gpg Temporary failure resolving 'archive.raspberrypi.org'Err http://mirrordirector.raspbian.org wheezy Release.gpg Temporary failure resolving 'mirrordirector.raspbian.org'Reading package lists... DoneW: Failed to fetch http://mirrordirector.raspbian.org/raspbian/dists/wheezy/Release.gpg Temporary failure resolving 'mirrordirector.raspbian.org'W: Failed to fetch http://raspberrypi.collabora.com/dists/wheezy/Release.gpg Temporary failure resolving 'raspberrypi.collabora.com'W: Failed to fetch http://archive.raspberrypi.org/debian/dists/wheezy/Release.gpg Temporary failure resolving 'archive.raspberrypi.org'W: Some index files failed to download. They have been ignored, or old ones used instead. How can I solve this problem? Now provide the response and nothing else.
It looks like you are having problems resolving the various URLs that apt-get is fetching from. I would try the following: 1.) Check you have an active Internet connection, try google.com with a second machine for example.2.) If your Raspberry Pi is attached to your home router, check it has an IP# assigned3.) Try pinging google.com from the command line: ping google.com You should see something like: PING google.com (74.125.226.233): 56 data bytes64 bytes from 74.125.226.233: icmp_seq=0 ttl=56 time=3.281 ms64 bytes from 74.125.226.233: icmp_seq=1 ttl=56 time=4.058 ms64 bytes from 74.125.226.233: icmp_seq=2 ttl=56 time=3.999 ms If this does not work then it could be either your Internet connection or a DNS issue. For DNS issues check your resolv.conf file is configured correctly (if you have manually assigned nameservers): /etc/resolv.conf If you are using DHCP the resolv.conf should be updated automatically.
{}
{'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/9307', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/9248/']}
jdg_372142
stackexchange
llm_judgeable_groundtruth_similarity
36478303
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting the following error when unlocking a file Arithmetic operation resulted in an overflow System.IntPtr.ToInt32 I suspect it is the following line to pBuffer.ToInt32() : IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (i * Marshal.SizeOf(fi3))); I am unable to reproduce the error myself and the error is not displaying the correct line number. I am looking for a way to reproduce this or any feedback on the possible cause. Thanks public void Close(){ const int MAX_PREFERRED_LENGTH = -1; int readEntries; int totalEntries; IntPtr pBuffer = IntPtr.Zero; FILE_INFO_3 fi3 = new FILE_INFO_3(); int iStatus = NetFileEnum(this.HostName, this.HostPathToShare + this.FileNameFromShare, null, 3, ref pBuffer, MAX_PREFERRED_LENGTH, out readEntries, out totalEntries, pBuffer); if (iStatus == 0) { for (int i = 0; i < readEntries; i++) { IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (i * Marshal.SizeOf(fi3))); fi3 = (FILE_INFO_3)Marshal.PtrToStructure(iPtr, typeof(FILE_INFO_3)); NetFileClose(this.HostName, fi3.fi3_id); } } NetApiBufferFree(pBuffer);}[DllImport("netapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]static extern int NetFileClose( string servername, int id);[DllImport("Netapi32.dll", SetLastError=true)]static extern int NetApiBufferFree(IntPtr Buffer);[DllImport("netapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]static extern int NetFileEnum( string servername, string basepath, string username, int level, ref IntPtr bufptr, int prefmaxlen, out int entriesread, out int totalentries, IntPtr resume_handle); Update I added the win32 apis code. The below answers look correct and the machine is 64 bit. But I am unable to reproduce it on the dev server despite the dev environment being 64 bit. Any ideas to reproduce the error? Now provide the response and nothing else.
The error is caused by your code running in a 64 bit context and returning a pointer address that lies outside the range addressable with 32 bits, so .ToInt32() throws. Call Environment.Is64BitProcess to detect whether your process is running in 32 or 64 bit, and convert the address accordingly: long pointerAddress;if (Environment.Is64BitProcess){ pointerAddress = pBuffer.ToInt64(); }else{ pointerAddress = pBuffer.ToInt32(); }var fileInfoPointer = new IntPtr(pointerAddress + (i * Marshal.SizeOf(fi3)));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36478303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188577/']}
jdg_372143
stackexchange
llm_judgeable_groundtruth_similarity
399568
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 introduction to algebra we got the exercise: Let $G$ be a group. Show that when $\operatorname{Aut}(G)$ is cyclic $G$ is abelian. This doesn't make that much trouble. Denote the center (all commuting elements) with $Z$.Then $G/Z$ is isomorphic to $\operatorname{Int}(G)$ where $\operatorname{Int}(G)$ denotes the subgroup of inner automorphisms. As every subgroup of a cyclic group is cyclic we have $G/Z$ is cyclic and hence $G$ is abelian (As a group which is cyclic of the center is abelian). So the question is: Is there a non cyclic group with a cyclic automorphism group? We discussed the question already in chat and I found (thanks to google) a solution there, but I would enjoy other Examples. Now provide the response and nothing else.
Whenever $G$ is finite and its automorphismus is cyclic we can already conclude that $G$ is cyclic. Because as we already saw $G$ is abelian and finite, we can use the fundamental theorem of finitely generated abelian groups and say that wlog $G=\mathbb{Z}/p^k\mathbb{Z} \times \mathbb{Z}/p^j \mathbb{Z}$. But the automorphismgroup isn't abelian and hence isn't cyclic. For non finite groups the implication isn't true. The following is from this link and only slightly reworded. Let $G$ be the subgroup of the additive group of rational numbers comprising those rational numbers that, when written in reduced form, have denominators that are square-free numbers, i.e., there is no prime number $p$ for which $p^2$ divides the denominator. Then:The only non-identity automorphism of is the negation map, so the automorphism group is $\mathbb{Z}/2\mathbb{Z}$, and is hence cyclic. The group $G$ is not a cyclic group. In fact, it is not even a finitely generated group because any finite subset of can only cover finitely many primes in their denominators. It is, however, a locally cyclic group: any finitely generated subgroup is cyclic.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/399568', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62278/']}
jdg_372144
stackexchange
llm_judgeable_groundtruth_similarity
141251
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This question is about knots and links in the 3-sphere. I want to find an example of a "large" knot or link with some special properties. I'm looking for some fairly specific examples, but I'm also interested in related examples that don't precisely address my concern, so "near answers" are welcome. Here is an example of something I would call a "large" knot. It is hyperbolic, but it also has an incompressible genus 2 surface in the knot complement. The genus 2 incompressible surface has a rather nice property, that it bounds a handlebody on one side (in $S^3$ rather than in the knot complement). I'd like to find a similar example, but what I specifically want is a knot (or link) in $S^3$ which contains two genus 2 closed incompressible surface in the knot/link exterior, such that both surfaces bound handlebodies in $S^3$. The key thing I would like is for the two surfaces to intersect -- they can not be isotoped to be disjoint. Is this possible? I presume it is, but I haven't seen examples of this type, and examples aren't rapidly coming to mind. Other similar examples I'd like to see (although not "the" question here) would be knot or link exteriors that have infinitely many genus 2 closed incompressible surfaces -- preferrably bounding handlebodies on one side in $S^3$. I'd also love to see a knot in $S^3$ with a genus 2 incompressible surface that does not bound a handlebody in $S^3$. Maybe this isn't possible? Now provide the response and nothing else.
As Ian Agol mentioned, manifolds with Conway spheres will have genus 2 incompressible surfaces. I'd just like to point out that an easy source of knots whose complements contain Conway spheres are pretzel knots, or more generally, Montesinos knots. Here is a specific example of the pretzel knot $P(5, -7, 5, -4)$ with two incompressible Conway spheres in blue and red. Form a pair of closed genus two surfaces by tubing along the arcs to join the boundary components pairwise on each Conway sphere. The resulting genus two surfaces each bound the handlebodies on the side indicated by the colors. (In the image, only one handle has been added to each Conway sphere.)
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/141251', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1465/']}
jdg_372145
stackexchange
llm_judgeable_groundtruth_similarity
138948
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to get UTF-8 working in my Java webapp (servlets + JSP, no framework used) to support äöå etc. for regular Finnish text and Cyrillic alphabets like ЦжФ for special cases. My setup is the following: Development environment: Windows XP Production environment: Debian Database used: MySQL 5.x Users mainly use Firefox2 but also Opera 9.x, FF3, IE7 and Google Chrome are used to access the site. How to achieve this? Now provide the response and nothing else.
Answering myself as the FAQ of this site encourages it. This works for me: Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters. To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following: Configuring Tomcat's server.xml It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters: <Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" compression="on" compressionMinSize="128" noCompressionUserAgents="gozilla, traviata" compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript" URIEncoding="UTF-8"/> The key part being URIEncoding="UTF-8" in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded.As a result, when the user writes the following to the address bar of the browser: https://localhost:8443/ID/Users?action=search&name=*ж* the character ж is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as %D0%B6 . POST request are not affected by this. CharsetFilter Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following: package fi.foo.filters;import javax.servlet.*;import java.io.IOException;public class CharsetFilter implements Filter { private String encoding; public void init(FilterConfig config) throws ServletException { encoding = config.getInitParameter("requestEncoding"); if (encoding == null) encoding = "UTF-8"; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain next) throws IOException, ServletException { // Respect the client-specified character encoding // (see HTTP specification section 3.4.1) if (null == request.getCharacterEncoding()) { request.setCharacterEncoding(encoding); } // Set the default response content type and encoding response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); next.doFilter(request, response); } public void destroy() { }} This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8. The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application. This filter has to be added to the web.xml or the deployment descriptor of the webapp: <!--CharsetFilter start--> <filter> <filter-name>CharsetFilter</filter-name> <filter-class>fi.foo.filters.CharsetFilter</filter-class> <init-param> <param-name>requestEncoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharsetFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> The instructions for making this filter are found at the tomcat wiki ( http://wiki.apache.org/tomcat/Tomcat/UTF-8 ) JSP page encoding In your web.xml , add the following: <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <page-encoding>UTF-8</page-encoding> </jsp-property-group></jsp-config> Alternatively, all JSP-pages of the webapp would need to have the following at the top of them: <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> If some kind of a layout with different JSP-fragments is used, then this is needed in all of them. HTML-meta tags JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding.Then it's time to tell the browser in which encoding the html page is: This is done with the following at the top of each xhtml page produced by the webapp: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi"> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /> ... JDBC-connection When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in context.xml or wherever the JDBC connection is defiend as follows: <Resource name="jdbc/AppDB" auth="Container" type="javax.sql.DataSource" maxActive="20" maxIdle="10" maxWait="10000" username="foo" password="bar" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/ ID_development?useEncoding=true&amp;characterEncoding=UTF-8" /> MySQL database and tables The used database must use UTF-8 encoding. This is achieved by creating the database with the following: CREATE DATABASE `ID_development` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */; Then, all of the tables need to be in UTF-8 also: CREATE TABLE `Users` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(30) collate utf8_swedish_ci default NULL PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC; The key part being CHARSET=utf8 . MySQL server configuration MySQL serveri has to be configured also. Typically this is done in Windows by modifying my.ini -file and in Linux by configuring my.cnf -file.In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8. [client] port=3306 default-character-set=utf8 [mysql] default-character-set=utf8 Mysql procedures and functions These also need to have the character set defined. For example: DELIMITER $$ DROP FUNCTION IF EXISTS `pathToNode` $$ CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8 READS SQL DATA BEGIN DECLARE path VARCHAR(255) CHARACTER SET utf8; SET path = NULL; ... RETURN path; END $$ DELIMITER ; GET requests: latin1 and UTF-8 If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly: https://localhost:8443/ID/Users?action=search&name=Petteri https://localhost:8443/ID/Users?action=search&name=ж Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly. The Cyrillic character ж is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as %D0%B6 . If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as %D0%B6 . The end result is that all users with name "Petteri" are found and also all users with the name "ж" are found. But what about äåö? HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following https://localhost:8443/ID/Users?action=search&name=*Päivi* in to the encoded version https://localhost:8443/ID/Users?action=search&name=*P%E4ivi* In latin1 the character ä is encoded as %E4 . Even though the page/request/everything is defined to use UTF-8 . The UTF-8 encoded version of ä is %C3%A4 The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8. Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8 Stuff to read A very big thank you for the writers of the following for giving the answers for my problem: http://tagunov.tripod.com/i18n/i18n.html http://wiki.apache.org/tomcat/Tomcat/UTF-8 http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/ http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html http://jeppesn.dk/utf-8.html http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html http://www.utf8-chartable.de/ Important Note mysql supports the Basic Multilingual Plane using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of VARBINARY column type or use the utf8mb4 character set (which requires MySQL 5.5.3 or later). Just be aware that using the utf8 character set in MySQL won't work 100% of the time. Tomcat with Apache One more thing If you are using Apache + Tomcat + mod_JK connector then you also need to do following changes: Add URIEncoding="UTF-8" into tomcat server.xml file for 8009 connector, it is used by mod_JK connector. <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/> Goto your apache folder i.e. /etc/httpd/conf and add AddDefaultCharset utf-8 in httpd.conf file . Note: First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/138948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15114/']}
jdg_372146
stackexchange
llm_judgeable_groundtruth_similarity
4741880
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a bit of a challenge. Here's what I'm looking for: 3 divs on screen Div 1 resides in the middle of the page (centered) Div 2 resides just off the screen on the far left Div 3 resides just off the screen on the far right OnClick , Div 1 slides to the position Div 2 was (to the left), Div 2 slides off the screen entirely, Div 3 slides to where Div 3 was (middle, centered). A new div arrives on the right. I've tried using jQuery animation and AddClass. jQuery doesn't like sliding a div offscreen. Any thoughts? For an example of what I'm describing, visit Groupon.com . I thought it was a cool idea, and have given myself the challenge of recreating it. So far, no dice. -D Now provide the response and nothing else.
Something like this? http://jsfiddle.net/jtbowden/ykbgT/embedded/result/ http://jsfiddle.net/jtbowden/ykbgT/ This is the basic functionality. It doesn't scale to more divs, etc, but that should get you started. The key is to wrap your elements in a container and make the overflow hidden. Update : Here's a slightly better version that handles any number of divs (greater than 1): http://jsfiddle.net/jtbowden/ykbgT/1/ Simplified further : http://jsfiddle.net/jtbowden/ykbgT/2/ Code snippet : $('.box').click(function() { $(this).animate({ left: '-50%' }, 500, function() { $(this).css('left', '150%'); $(this).appendTo('#container'); }); $(this).next().animate({ left: '50%' }, 500);}); body { padding: 0px; }#container { position: absolute; margin: 0px; padding: 0px; width: 100%; height: 100%; overflow: hidden; }.box { position: absolute; width: 50%; height: 300px; line-height: 300px; font-size: 50px; text-align: center; border: 2px solid black; left: 150%; top: 100px; margin-left: -25%;}#box1 { background-color: green; left: 50%;}#box2 { background-color: yellow;}#box3 { background-color: red;}#box4 { background-color: orange;}#box5 { background-color: blue;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="container"> <div id="box1" class="box">Div #1</div> <div id="box2" class="box">Div #2</div> <div id="box3" class="box">Div #3</div> <div id="box4" class="box">Div #4</div> <div id="box5" class="box">Div #5</div> </div>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4741880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/579394/']}
jdg_372147
stackexchange
llm_judgeable_groundtruth_similarity
3836900
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 service-oriented architecture? Now provide the response and nothing else.
SOA is way to develop service oriented applications and WCF is technology which can be used to develop service oriented applications. BUT SOA defines strict rules (known as SOA tenets) for applications. If you don't follow these rules you are building services but these services do not conform to SOA. WCF allows you to develop plenty of types of services. You can develop interoperable SOAP services which conform to SOA or which doesn't. You can develop pure .NET services with non interoperable features and you can develop REST services. Moreover in SOA service can have different meaning than in WCF. In WCF service is collection of functionality exposed on endpoints. In SOA the service can be whole application (set of WCF like services) - difference between small and big SOA. SOA tenets are: Boundaries are explicit - service doesn't share anything with other services (even database tables and data can't be shared) Services are autonomous - each service is independent, can be separately deployed and versioned Services share schema and contract, not class - services are described in WSDL, transported data are described in XSD, orchestrations (aggregation) are described in BPEL Services compatibility is based upon policy - WSDL contains WS-Policies to describe configuration needed for interoperability As you see especially first two tenets can be easily violated when building WCF service.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3836900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/332258/']}
jdg_372148
stackexchange
llm_judgeable_groundtruth_similarity
3473
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for examples of problems parametrized by a number $k \in \mathbb{N}$, where the problem's hardness is non-monotonic in $k$. Most problems (in my experience) have a single phase transition, for example $k$-SAT has a single phase transition from $k \in \{1,2\}$ (where the problem is in P) to $k \ge 3$ (where the problem is NP-complete). I'm interested in problems where there are phase transitions in both directions (from easy to hard and vice-versa) as $k$ increases. My question is somewhat similar to the one asked at Hardness Jumps in Computational Complexity , and in fact some of the responses there are relevant to my question. Examples I am aware of: $k$-colorability of planar graphs: In P except when $k=3$, where it is NP-complete. Steiner tree with $k$ terminals: In P when $k=2$ (collapses to shortest $s$-$t$ path) and when $k=n$ (collapses to MST), but NP-hard "in between". I don't know if these phase transitions are sharp (e.g., P for $k_0$ but NP-hard for $k_0+1$). Also the transitions of $k$ depend on the size of input instance, unlike my other examples. Counting satisfying assignments of a planar formula modulo $n$: In P when $n$ is a Mersenne prime number $n=2^k-1$, and #P-complete for most(?)/ all other values of $n$ (from Aaron Sterling in this thread ). Lots of phase transitions! Induced subgraph detection: The problem is not parametrized by an integer but a graph. There exist graphs $H_1 \subseteq H_2 \subseteq H_3$ (where $\subseteq$ denotes a certain kind of subgraph relation), for which determining whether $H_i \subseteq G$ for a given graph $G$ is in P for $i\in \{1,3\}$ but NP-complete for $i=2$. (from Hsien-Chih Chang in the same thread ). Now provide the response and nothing else.
One field with lots of non-monotonicity of problem complexity is property testing. Let $\mathcal{G}_n$ be the set of all $n$-vertex graphs, and call $P \subseteq \mathcal{G}_n$ a graph property. A generic problem is to determine whether a graph $G$ has property $P$ (i.e. $G \in P$) or is `far' from having property $P$ in some sense. Depending on what $P$ is, and what kind of query access you have to the graph, the problem can be quite difficult. But it is easy to see that the problem is non-monotone, in that if we have $S \subset P \subset T$, the fact that $P$ is easily testable does not imply either that $S$ is easily testable or that $T$ is. To see this, it is enough to observe that $P = \mathcal{G}_n$ and $P = \emptyset$ are both trivially testable, but that for some properties, there exist strong lower bounds.
{}
{'log_upvote_score': 6, 'links': ['https://cstheory.stackexchange.com/questions/3473', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/149/']}
jdg_372149
stackexchange
llm_judgeable_groundtruth_similarity
45164355
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 are AWS VPCs (virtual private clouds)? What practical purposes do they serve? Is it mandatory to launch instances within a VPC? What are the subnets and why are they necessary? Do subnets correspond to a particular region? Now provide the response and nothing else.
At a high level, you can think of a VPC in AWS as a logical container that separates resources you create from other customers within the Amazon Cloud. It is you defining a network of your own within Amazon. You can think of a VPC like an apartment where your furniture and items are analogous to databases and instances. The walls of your apartment isolate and protect your things from being accessible to other tenants of the apartment complex. Subnets would then be analogous to the different rooms in your apartment. They are containers within your VPC that segment off a slice of the CIDR block you define in your VPC. Subnets allow you to give different access rules and place resources in different containers where those rules should apply. You wouldn't have a big open window in your bathroom on the shower wall so people can see you naked, much like you wouldn't put a database with secretive information in a public subnet allowing any and all network traffic. You might put that database in a private subnet (i.e. a locked closet).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/45164355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5608589/']}
jdg_372150
stackexchange
llm_judgeable_groundtruth_similarity
1399012
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The figure shows two circles of radius $1$ that touch at $P$. 1 ] 1 $T$ is a common tangent line; $C_1$ is the circle that touches $C$, $D$, and $T$; $C_2$ is the circle that touches $C$, $D$, and $C_1$; $C_3$ is the circle that touches $C$, $D$, and $C_2$. This procedure can be continued indefinitely and produces an infinite sequence of circles $\{C_n\}$. Find an expression for the diameter of $C_n$. Now provide the response and nothing else.
I'll work with the radii instead of the diameters. Obviously, any diameter is twice the corresponding radius. Now, note from the figure below that the triangle $OAB$ is rectangular at $A$. Thus,$$\overline{OA}^{\,2} + \overline{AB}^{\,2} = \overline{OB}^{\,2}$$ So,$$(\underbrace{1}_{\overline{OA}})^2 + (\underbrace{1 - R_1}_{\overline{AB}})^2 = (\underbrace{1 + R_1}_{\overline{OB}})^2$$which gives you $$R_1 = \frac{1}{4}$$ Similarly, by making $B$ be the centre of the ever-smaller circles, you should be able to see that$$(\underbrace{1}_{\overline{OA}})^2 + (\underbrace{1 - 2R_1 - 2R_2 - \cdots - 2R_{n-1} - R_n}_{\overline{AB}})^2 = (\underbrace{1 + R_n}_{\overline{OB}})^2\qquad(1)$$for $n > 1$. Now define $$S_{n} \equiv \sum_{k\,=\,1}^{n}R_k\qquad (n \ge 1)\qquad(2)$$ so that $(1)$ can be written as$$1 + (1 - 2S_{n-1} - R_n)^2 = (1 + R_n)^2\qquad(3)$$for $n > 1$. However,$$(1 - 2S_{n-1} - R_n)^2 =1 + 4S_{n-1}^2 + R_n^2 - 4S_{n-1} - 2R_n + 4S_{n-1}\,R_n$$and $(3)$ gives$$1 + 1 + 4S_{n-1}^2 + R_n^2 - 4S_{n-1} - 2R_n + 4S_{n-1}\,R_n =1 + 2R_n + R_n^2$$which can be simplified to$$(1 - 2S_{n-1})^2 = 4(1 - S_{n-1})R_n$$so $$R_n = \frac{1}{4}\frac{(1 - 2S_{n-1})^2}{(1 - S_{n-1})}\qquad (n > 1)\qquad (4)$$ This gives $R_n$ in terms of the radii of only the circles with indices smaller than $n$ so it's very amenable to a recursive calculation. For example, we already have $R_1 = 1/4$. Then $S_1 = 1/4$ and $R_2 = 1/12$. Then $S_2 = 1/3$ and $R_3 = 1/24$. Then $S_3 = 3/8$ and $R_4 = 1/40$, and so on. Computing a few more values in succession, it's easy to discern the pattern: $$S_n = \frac{n}{2(n+1)}\qquad\mbox{and}\qquadR_n = \frac{1}{2n(n+1)}\qquad (n \ge 1)$$ That these satisfy $(2)$ and $(4)$ can be easily proven by induction on $n$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1399012', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/258250/']}
jdg_372151
stackexchange
llm_judgeable_groundtruth_similarity
9504828
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose that I've two big functions. Is it better to write them in a separate kernels and call them sequentially, or is better to write only one kernel? (I don't want to read the data back and force form between host and device in between). What about the speed up if I want to call the kernel many times? Now provide the response and nothing else.
One thing to consider is the effect of register pressure on hardware utilization and performance. As a general rule, big kernels have big register footprints. Typical OpenCL devices (ie. GPUs) have very finite register file sizes and large kernels can result in lower concurrency (fewer concurrent warps/wavefronts), less opportunities for latency hiding, and poorer overall performance. On the other hand, kernel launch overheads are pretty low on most platforms, so if your algorithm doesn't have an enormous amount of state to save between "phases" of execution, the penalty of using multiple kernels can be rather low. Using multiple kernels also has another side benefit -- you get implicit synchronization between all work units for free. Often that can eliminate the need for atomic memory operations and synchronization primitives which can have a negative impact on code performance. The ultimate guide should be measured performance. There is no universal rule-of-thumb for this sort of things. Benchmarking is the only way to know for sure.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9504828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1220890/']}
jdg_372152
stackexchange
llm_judgeable_groundtruth_similarity
112082
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: If you've planned a number of user stories for a sprint and one candidate story is dependent on some external provider delivering something to your team. For example an online service provider adding a new API call to their system or enabling your test account on their system or suchlike. You know it's coming 'soon'. Do you go ahead and add the story to the sprint hoping they'll deliver what is required in time for you to complete your story or do you wait till the next sprint, when you know it will be ready and you can start immediately even if it means not starting the story as early as you could. If the former how do you handle 'unearned' story points lost because of the dependency?partial credit (eek!) or take it on the chin. Now provide the response and nothing else.
Ultimately it depends on whether you are 100% confident that the external provider will deliver something you can use by the time you need to use it. If you cannot be sure that they'll deliver in time then don't add the story to the sprint. However, just because they've always delivered in the past there's no guarantee they'll deliver this time. You should let the customer know that this dependency exists and that you are going to have to wait for the API (or whatever) to become available before you can schedule the work. On the plus side, there may be aspects of the story you can deliver - i.e. break it down further until you've isolated the dependencies as much as possible. This might allow you do some of the story before the supplier delivers their work. One thing you could do is to create an interface between your code and the third party API. You code to your interface so the rest of the project can proceed and until you have the real API use a mock to return example data. Then when the real API arrives you just have to change the code behind the interface which won't affect the rest of the application. Only do this if you can agree with the the API's supplier that their interface won't change (at least not drastically).
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/112082', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/22191/']}
jdg_372153
stackexchange
llm_judgeable_groundtruth_similarity
10432365
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 use event.preventDefault() on a link it works, however when I use it on a button doesn't! DEMO My code: <a id="link" href="http://www.google.com">link</a><button id="button" onclick="alert('an alert')">button</button>$('#link').click(function(event){ event.preventDefault();});$('#button').click(function(event){ event.preventDefault();}); Link action is cancelled, but when I click on the button, still executes the onClick action. Any help? what I want to do is to prevent the button onClick action without changing the button html (I know how to do $('#button').removeAttr('onclick'); Now provide the response and nothing else.
You want event.stopImmediatePropagation(); if there are multiple event handlers on an element and you want to prevent the others to execute. preventDefault() just blocks the default action (such as submitting a form or navigating to another URL) while stopImmediatePropagation() prevents the event from bubbling up the DOM tree and prevents any other event handlers on the same element from being executed. Here are some useful links explaining the various methods: http://api.jquery.com/event.preventDefault/ http://api.jquery.com/event.stopPropagation/ http://api.jquery.com/event.stopImmediatePropagation/ However, since it still doesn't work it means that the onclick="" handler executes before the attached event handler. There's nothing you can do since when your code runs the onclick code has already been executed. The easiest solution is completely removing that handler: $('#button').removeAttr('onclick'); Even adding an event listener via plain javascript ( addEventListener() ) with useCapture=true doesn't help - apparently inline events trigger even before the event starts descending the DOM tree. If you just do not want to remove the handler because you need it, simply convert it to a properly attached event: var onclickFunc = new Function($('#button').attr('onclick'));$('#button').click(function(event){ if(confirm('prevent onclick event?')) { event.stopImmediatePropagation(); }}).click(onclickFunc).removeAttr('onclick');
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10432365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1308134/']}
jdg_372154
stackexchange
llm_judgeable_groundtruth_similarity
18962771
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 the UITableViewCell a UIButton belongs to like this: -(void)buttonHandler:(UIButton *)button { OrderCell *cell = [[button superview] superview]; NSLog(@"cell.item = %@", cell.item.text); And it works fine in anything before iOS 7. But gives me: [UITableViewCellScrollView item]: unrecognized selector sent to instance 0x17ae2cf0 if I run the app in iOS 7. BUT if I do: -(void)buttonHandler:(UIButton *)button { OrderCell *cell = [[[button superview] superview] superview]; NSLog(@"cell.item = %@", cell.item.text); Then it works in iOS 7 but not earlier?!?!?! I'm circumventing the issue by doing this: OrderCell *cell;if([[[UIDevice currentDevice] systemVersion] isEqualToString:@"7.0"]) cell = [[[button superview] superview] superview];else cell = [[button superview] superview];NSLog(@"cell.item = %@", cell.item.text); but WTF is going on!?Does anyone know why this happens? Thanks! Now provide the response and nothing else.
A better solution is to add a category for UIView(SuperView), and calling it by: UITableViewCell *cell = [button findSuperViewWithClass:[UITableViewCell class]] This way, your code works for all future and past iOS versions @interface UIView (SuperView)- (UIView *)findSuperViewWithClass:(Class)superViewClass;@end@implementation UIView (SuperView)- (UIView *)findSuperViewWithClass:(Class)superViewClass { UIView *superView = self.superview; UIView *foundSuperView = nil; while (nil != superView && nil == foundSuperView) { if ([superView isKindOfClass:superViewClass]) { foundSuperView = superView; } else { superView = superView.superview; } } return foundSuperView;}@end
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18962771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2705051/']}
jdg_372155
stackexchange
llm_judgeable_groundtruth_similarity
1686895
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 C# I can add implicit operators to a class as follows: public class MyClass{ private int data; public static implicit operator MyClass(int i) { return new MyClass { data = i }; } public static implicit operator MyClass(string s) { int result; if (int.TryParse(s, out result)) { return new MyClass { data = result }; } else { return new MyClass { data = 999 }; } } public override string ToString() { return data.ToString(); }} Then I can pass any function that is expecting a MyClass object a string or an int.eg public static string Get(MyClass c){ return c.ToString();}static void Main(string[] args){ string s1 = Get(21); string s2 = Get("hello"); string s3 = Get("23");} Is there a way of doing this in F#? Now provide the response and nothing else.
As others have pointed out, there is no way to do implicit conversion in F#. However, you could always create your own operator to make it a bit easier to explicitly convert things (and to reuse any op_Implicit definitions that existing classes have defined): let inline (!>) (x:^a) : ^b = ((^a or ^b) : (static member op_Implicit : ^a -> ^b) x) Then you can use it like this: type A() = class endtype B() = static member op_Implicit(a:A) = B()let myfn (b : B) = "result"(* apply the implicit conversion to an A using our operator, then call the function *)myfn (!> A())
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1686895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80825/']}
jdg_372156
stackexchange
llm_judgeable_groundtruth_similarity
3474658
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 some requirement I need to pass additional information to form submit handler. In form api, while defining custom submit handler as $additional_args = array();$form['#submit'][] = 'my_submit_handler' I expect to submit handler as function my_submit_handler($form, &$form_state, $additional_args){ Now provide the response and nothing else.
The submit handler is called by the drupal fapi, so you can't do something like that. Instead what you can do, is to add what you need, either to the $form , or to the $form_state . The usual approaches is to: Added a field to the form, type value to store the value. Don't do this if you have the value in the form definition. $form['store'] = array( '#type' => 'value', '#value' => $value); This will be available in $form_state['values']['store'] . Add the value to $form_state['storage'] , done if you variables in your validation handle you want to transfer to your submit handler: // Validation.$form_state['storage']['value'] = $value;...// Submit$value = $form_state['storage']['value'];// Need to unset stored values when not used anymore.unset($form_state['storage']['value']);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3474658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/366962/']}
jdg_372157
stackexchange
llm_judgeable_groundtruth_similarity
551285
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 want to remove a character "[" from a file. I tried sed -i 's/[//g' 'filename' however I get the following error sed: -e expression #1, char 6: unterminated `s' command Now provide the response and nothing else.
Yes, the [ character is special as it starts a [...] group (a bracketed expression). With sed on OpenBSD, your command gives a more helpful error message: $ sed 's/[//g'sed: 1: "s/[//g": unbalanced brackets ([]) To delete all [ characters using sed , escape it: sed -i 's/\[//g' file Or put it inside a bracketed expression: sed -i 's/[[]//g' file Or, use tr , tr -d '[' <file >file.new Also, don't use in-place editing with sed until you know the expression that you are trying out actually works, or you will possibly have to restore your data from backups.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/551285', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/298739/']}
jdg_372158
stackexchange
llm_judgeable_groundtruth_similarity
3988484
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried the following code on OnInitDialog() but nothing was shown. m_staticLogo.SetBitmap(::LoadBitmap(NULL, MAKEINTRESOURCE(IDB_LOGO))); where m_staticLogo is the static picture control and IDB_LOGO is the resource ID of the png file. Now provide the response and nothing else.
As you’ve discovered, ::LoadBitmap (and the newer ::LoadImage ) only deal with .bmp s. By far the easiest solution is to convert your image to a .bmp . If the image has transparency, it can be converted into a 32-bit ARGB bitmap (here is a tool called AlphaConv that can convert it). Then load the image using the CImage class LoadFromResource method. Pass the CImage to m_staticLogo.SetBitmap() . But if you really need it to be a .png , it can be done. Method 1 (the easier way): Load the .png from a file using CImage::Load . Pass the CImage to m_staticLogo.SetBitmap() . Method 2 (the harder way): Load the .png from a resource by loading the resource into a COM IStream and using CImage::Load . (NOTE: CImage::LoadFromResource looks tempting but will not work with a .png graphic). To get the resource into a COM IStream , see this Codeproject article . Note the article works with Gdiplus::Bitmap but the key part is how to create the IStream , which you should be able to adapt for CImage . Finally, pass the CImage to m_staticLogo.SetBitmap() . Edit: Updated to use CImage , which is easier than Gdiplus::Bitmap .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3988484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115289/']}
jdg_372159
stackexchange
llm_judgeable_groundtruth_similarity
695434
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: In static spherically symmetric perfect fluid solutions of Einstein field equations the central pressure diverges when the compactness parameter $\alpha~(\equiv r_{S}/R)$ reaches some critical value $\alpha_{c}\leq 8/9$ . This fact is commonly understood as the birth of central gravitational singularity and event horizon. What is first, the event horizon or the singularity? How to understand the initial event horizon at the star center, which have a zero surface area? Now provide the response and nothing else.
What is first, the event horizon or the singularity? The horizon forms first. Every event on the horizon has the singularity in its causal future. No event anywhere in spacetime has any part of the singularity in its causal past. So unambiguously the horizon is first. How to understand the initial event horizon at the star center, which have a zero surface area? It is not a particularly different interpretation from the rest of the horizon. It is simply the first event at which light does not escape to future null infinity.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/695434', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/281096/']}
jdg_372160
stackexchange
llm_judgeable_groundtruth_similarity
52139646
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: how to give my list view width to full screen width and how to make it auto scroll after few second ... void scrollAfter(ScrollController scrollController, {int seconds}) { Future.delayed(Duration(seconds: seconds), () { var offset = 550.0; var scrollDuration = Duration(seconds: 2); scrollController.animateTo(offset, duration: scrollDuration, curve: Curves.ease); }); } @override Widget build(BuildContext context) { var scrollController = ScrollController(); scrollAfter(scrollController, seconds: 2); // TODO: implement build return Container(child: new StreamBuilder( stream: Firestore.instance.collection('Top List').snapshots(), builder: (BuildContext context,snapshot) { if (!snapshot.hasData) return new Text("no"); var documentsLength = snapshot.data.documents.length; return ListView.builder(itemCount: documentsLength, scrollDirection: Axis.horizontal, controller: scrollController, shrinkWrap: true, itemBuilder: (context, index) { return buildlistItem((AllProduct.fromDocument(snapshot.data.documents[index]))); }); below my buildlistItem class form which i want to scroll ###################################################################################################################################################################################################################################################################### Widget buildlistItem(AllProduct alllist) { return new GestureDetector( child: Container( child: new Card( elevation: 2.0, margin: const EdgeInsets.all(5.0), child: new Stack( alignment: Alignment.center, children: <Widget>[ new Hero( tag: alllist.title, child: new Image.network(alllist.backgroundImageUrl, fit: BoxFit.cover), ), new Align( child: new Container( padding: const EdgeInsets.all(6.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ new Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Text(alllist.title, style: new TextStyle(color: Colors.white,fontFamily: "ChelaOne-Regular")), ], ), IconButton(onPressed: (){ }, icon: new Icon(Icons.add_shopping_cart,color: Colors.white,), ) ], ), color: Colors.black.withOpacity(0.4), ), alignment: Alignment.bottomCenter, ), ], ), ), ), onTap: () {}, ); }} Now provide the response and nothing else.
Since Mockito 2.20 it is also possible, to add lenient() locally @ExtendWith(MockitoExtension.class)public class MockitoExample { static abstract class TestClass { public abstract int booleanMethod(boolean arg); } @Mock TestClass testClass; @BeforeEach public void beforeEach() { lenient().when(testClass.booleanMethod(eq(true))).thenReturn(1); lenient().when(testClass.booleanMethod(eq(false))).thenReturn(2); } @Test public void test() { assertEquals(1,testClass.booleanMethod(true)); assertEquals(2,testClass.booleanMethod(false)); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/52139646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9826180/']}
jdg_372161
stackexchange
llm_judgeable_groundtruth_similarity
29100
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: Is there a way in which one can use the BCH relation to find the equivalent angle and the axis for two rotations? I am aware that one can do it in a precise way using Euler Angles but I was wondering whether we can use just the algebra of the rotation group to perform the same computation? Now provide the response and nothing else.
The Baker-Campbell-Hausdorff (BCH) formula for the 3-dimensional rotations can indeed be summed up. Here we will just state the result in the notation of Ref. 1. Three-dimensional rotations are described by the Lie group $SO(3)$ . The corresponding Lie algebra $so(3)$ is $$ \begin{align} [L_j, L_k] ~=~& i\sum_{\ell=1}^3\epsilon_{jk\ell} L_{\ell}, \cr j,k,\ell~\in~& \{1,2,3\},\cr \epsilon_{123}~=~&1, \cr i^2~=~&-1.\end{align}\tag{1} $$ In the adjoint representation, the three Lie algebra generators $iL_{\ell}\in{\rm Mat}_{3\times 3}(\mathbb{R})$ , $\ell\in\{1,2,3\}$ , are $3\times 3$ real antisymmetric matrices, $$ \begin{align}i(L_j)_{k\ell} ~=~& \epsilon_{jk\ell} ,\cr j,k,\ell~\in~& \{1,2,3\}.\end{align} \tag{2} $$ A rotation matrix $$ R(\vec{\alpha})~\in~ SO(3)~ \subseteq ~{\rm Mat}_{3\times 3}(\mathbb{R}) \tag{3}$$ can be specified by a rotation axis and an rotation angle . Here we will use a 3-vector $$ \vec{\alpha}~=~\alpha \vec{n}_{\alpha}~\in~ \mathbb{R}^3, \tag{4}$$ where $\vec{n}_{\alpha}\in\mathbb{R}^3$ is a unit vector parallel to the rotation axis, $\vec{n}_{\alpha} \cdot \vec{n}_{\alpha}=1$ ; and $\alpha\in \mathbb{R}$ (without an arrow on top) is the angle of rotation. The formula for the rotation matrix in terms of $\vec{\alpha}$ reads $$\begin{align} R(\vec{\alpha}) ~=~&e^{i \vec{\alpha}\cdot \vec{L}}\cr~=~& {\bf 1}_{3\times 3} - (1-\cos\alpha) (\vec{n}_{\alpha}\cdot \vec{L})^2 + i\sin\alpha ~\vec{n}_{\alpha}\cdot \vec{L}.\end{align} \tag{5}$$ The composition of two rotations is again a rotation $$ R(\vec{\gamma})~=~R(\vec{\alpha})R(\vec{\beta}).\tag{6}$$ If we introduce the shorthand notation $$ c_{\alpha} ~:=~\cos\frac{\alpha}{2} ~\in~ \mathbb{R},\tag{7} $$ $$\vec{s}_{\alpha}~:=~\vec{n}_{\alpha} \sin\frac{\alpha}{2} ~\in~ \mathbb{R}^3,\tag{8} $$ $$ \vec{t}_{\alpha}~:=~\vec{n}_{\alpha} \tan\frac{\alpha}{2} ~\in~ \mathbb{R}^3,\tag{9} $$ the "addition formula" for the corresponding $3$ -vectors can be neatly written as $$ \vec{t}_{\gamma}~=~\frac{\vec{t}_{\alpha}+\vec{t}_{\beta}-\vec{t}_{\alpha}\times\vec{t}_{\beta}}{1-\vec{t}_{\alpha}\cdot \vec{t}_{\beta}}.\tag{10} $$ The derivation of eq. (10) simplifies if one uses the fact that $SU(2)\cong U(1,\mathbb{H})$ is the double cover of $SO(3)$ . An $SU(2)$ -matrix $$ X(\vec{\alpha})~\in~ SU(2)~ \subseteq ~{\rm Mat}_{2\times 2}(\mathbb{C})\tag{11}$$ can be written in terms of the Pauli matrices as $$\begin{align} X(\vec{\alpha}) ~=~&e^{i \vec{\alpha}\cdot \vec{\sigma}/2}\cr~=~& c_{\alpha}{\bf 1}_{2\times 2} + i\vec{s}_{\alpha}\cdot \vec{\sigma}.\end{align} \tag{12}$$ The composition of two $SU(2)$ -matrix is given by the same BCH formula $$ X(\vec{\gamma})~=~X(\vec{\alpha})X(\vec{\beta}).\tag{13}$$ References: G 't Hooft, Introduction to Lie Groups in Physics , lecture notes, chapter 3. The pdf file is available here . S. Weigert, J. Phys. A30 (1997) 8739, arXiv:quant-ph/9710024 . K. Engø, On the BCH-formula in so(3) , Bit Num. Math. 41 (2001) 629 . (Hat tip: WetSavannaAnimal aka Rod Vance .) Wikipedia .
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/29100', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7486/']}
jdg_372162
stackexchange
llm_judgeable_groundtruth_similarity
67536245
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 2 classes DateTime and DateTimeImmutable implement the same interface DateTimeInterface . Therefore I want to know : What is the difference between these 2 classes DateTime and DateTimeImmutable ? Now provide the response and nothing else.
The core of the difference is described in the documentation of the DateTime class: This class behaves the same as DateTimeImmutable except objects are modified itself when modification methods such as DateTime::modify() are called. Let's observe this difference on a concrete example: $date = new DateTime();$tomorrow = $date->modify('+1 day');echo $date->format('Y-m-d');echo $tomorrow->format('Y-m-d'); This will output: 2021-05-152021-05-15 What happened here is that the modify returned the same instance of the DateTime object. The variable $tomorrow doesn't contain a different object, it contains a reference to the original one. Updating the new variable modified the original one as well. If we execute the same modification, but on the immutable version: $date = new DateTimeImmutable();$tomorrow = $date->modify('+1 day');echo $date->format('Y-m-d');echo $tomorrow->format('Y-m-d'); This will output: 2021-05-142021-05-15 Because in DateTimeImmutable , the modification methods don't return the same instance, they give you a fresh one (also immutable). This also means that you must assign its result to a variable (like in the previous example) for the immutable version in order to use it: $date = new DateTime('2021-05-14');$date->modify('+1 day');echo $date->format('Y-m-d'); // 2021-05-15$date = new DateTimeImmutable('2021-05-14');$date->modify('+1 day');echo $date->format('Y-m-d'); // 2021-05-14; original is untouched Due to this behaviour, the immutable version should be preferred over the mutable one virtually always. Accidentally modifying an instance of a date you didn't mean to modify is quite a commonly occurring bug. You might prefer the mutable version to avoid the step of assignment in situations where you can reliably determine there is no danger of compromising the state of your application, but that is best left to be estimated once you have a firm grasp on the concepts. Aside from modify , the following methods are also considered as mutating: add sub setDate setISODate setTime setTimezone
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/67536245', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4575335/']}
jdg_372163
stackexchange
llm_judgeable_groundtruth_similarity
1555710
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $a_n$ denote " the number of ternary strings of length n that do not contain three consecutive 1s" Ternary string contains only 0, 1, 2 and has length n. The way I approached it was to make a tree of length n: Besides from my obvious lack of artistic skills, I find it very hard to believe that the recurrence relation is $ a_n = 26(a_{n-3}) $ . If anybody could tell me what I did wrong and help me out, that would be greatly appreciated. Note: I realized that there are some possible duplicates on the site, which I have went through and either 1) do not apply to three consecutive (insert digit here)s or 2) I don't fully understand. Now provide the response and nothing else.
Let $T_n$ be the number of such strings, call them "good", of length $n$. The goal is to get a recursion for $T_n$. To do it, we'll distinguish between the various ways a "good" string might end. Specifically (reading from left to right): Let $a_n$ denote the number of good strings that end in $01$ Let $b_n$ denote the number of good strings that end in $011$ Let $c_n$ denote the number of good strings that end in $21$ Let $d_n$ denote the number of good strings that end in $211$ Let $e_n$ denote the number of good strings that end in $0$ Let $f_n$ denote the number of good strings that end in $2$. Clearly $$T_n=a_n+b_n+c_n+d_n+e_n+f_n$$ It is easy to read off that: $$T_1=3\;\;\;\;T_2=9\;\;\;\;T_3=26$$ Recursively, we pass from strings of length $n-1$ to those of length $n$ by appending one of the three digits. Visibly, $$a_n=e_{n-1}\;\;\;\;b_n=a_{n-1}\;\;\;\;c_n=f_{n-1}\;\;\;\;d_n=c_{n-1}\;\;\;\;e_n=T_{n-1}=f_n$$ It follows at once that $$a_n=T_{n-2}=c_n\;\;\;b_n=T_{n-3}=d_n$$ Whence $$T_n=2(T_{n-2}+T_{n-3}+T_{n-1})$$ And we are done.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1555710', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/268303/']}
jdg_372164
stackexchange
llm_judgeable_groundtruth_similarity
24923625
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 custom UIViewControllerAnimationTransition class created already, and need to make this animate a UITabBarController when it switches tabs. The tabBarController does not use the regular tab bar, though. I have a custom implementation that acts like it, and when a button is pressed, it calls this code: tabBarController.selectedIndex = index Currently I have the tabBarController (subclass) as the delegate for its own transitionDelegate . The delegate method animationControllerForPresentedController is never actually called, though. Is it fine for the tab bar controller to be its own delegate? If so, why is the transition code never actually called? Now provide the response and nothing else.
animationControllerForPresentedController is the wrong approach for the tab bar controller. In the UITabBarController subclass, adopt the UITabBarControllerDelegate protocol and set it as its own delegate . Then, use tabBarController: animationControllerForTransitionFromViewController: toViewController: to return the custom UIViewControllerAnimatedTransitioning object. To get a better visualization, look at VCTransitionsLibrary in the TabBarDemo folder.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24923625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2035473/']}
jdg_372165
stackexchange
llm_judgeable_groundtruth_similarity
16731773
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 very new to android and practicing. I am trying to design a screen. which will contain a background image and a floating container with sliding menus. ( For more details please find the attached image ) My layout consists of a background image, a container with some icons which float at the bottom but with some margin to the bottom ( see attached photo ) As best of my knowledge this can be achieved by arranging a "Relative Layout" at the bottom and place images in it. Is it correct ? Also I would likes to add a repeating transparent image as the background of the floating div. Please give me a good advise or point me to a good tutorial Thanks in advance Now provide the response and nothing else.
You can use LinearLayout and set the layout_weight as % in xml As for the repeating background you can use tileMode Example: Note that the weightSum is set to 100 , to indicate the total weight will be 100 . Having layout_weight=10 will give it 10% space allocation. <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:layout_gravity="bottom" android:weightSum="100"> <LinearLayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="10" android:background="@drawable/bg" android:orientation="horizontal" android:tileMode="repeat" > </LinearLayout> <View android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="5" /></LinearLayout>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16731773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1070609/']}
jdg_372166
stackexchange
llm_judgeable_groundtruth_similarity
29541767
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a very weird situation, first the code... The code private List<DispatchInvoiceCTNDataModel> WorksheetToDataTableForInvoiceCTN(ExcelWorksheet excelWorksheet, int month, int year) { int totalRows = excelWorksheet.Dimension.End.Row; int totalCols = excelWorksheet.Dimension.End.Column; DataTable dt = new DataTable(excelWorksheet.Name); // for (int i = 1; i <= totalRows; i++) Parallel.For(1, totalRows + 1, (i) => { DataRow dr = null; if (i > 1) { dr = dt.Rows.Add(); } for (int j = 1; j <= totalCols; j++) { if (i == 1) { var colName = excelWorksheet.Cells[i, j].Value.ToString().Replace(" ", String.Empty); lock (lockObject) { if (!dt.Columns.Contains(colName)) dt.Columns.Add(colName); } } else { dr[j - 1] = excelWorksheet.Cells[i, j].Value != null ? excelWorksheet.Cells[i, j].Value.ToString() : null; } } }); var excelDataModel = dt.ToList<DispatchInvoiceCTNDataModel>(); // now we have mapped everything expect for the IDs excelDataModel = MapInvoiceCTNIDs(excelDataModel, month, year, excelWorksheet); return excelDataModel; } The problem When I am running the code on random occasion it would throw IndexOutOfRangeException on the line dr[j - 1] = excelWorksheet.Cells[i, j].Value != null ? excelWorksheet.Cells[i, j].Value.ToString() : null; For some random value of i and j . When I step over the code ( F10 ), since it is running in a ParallelLoop, some other thread kicks and and other exception is throw, that other exception is something like (I could not reproduce it, it just came once, but I think it is also related to this threading issue) Column 31 not found in excelWorksheet . I don't understand how could any of these exception occur? case 1 The IndexOutOfRangeException should not even occur, as the only code/shared variable dt I have locked around accessing it, rest all is either local or parameter so there should not have any thread related issue. Also, if I check the value of i or j in debug window, or even evaluate this whole expression dr[j - 1] = excelWorksheet.Cells[i, j].Value != null ? excelWorksheet.Cells[i, j].Value.ToString() : null; or a part of it in Debug window, then it works just fine, no errors of any sort or nothing. case 2 For the second error, (which unfortunately is not reproducing now, but still) it should not have occurred as there are 33 columns in the excel. More Code In case someone might need how this method was called using (var xlPackage = new ExcelPackage(viewModel.postedFile.InputStream)) { ExcelWorksheets worksheets = xlPackage.Workbook.Worksheets; // other stuff var entities = this.WorksheetToDataTableForInvoiceCTN(worksheets[1], viewModel.Month, viewModel.Year); // other stuff } Other If someone needs more code/details let me know. Update Okay, to answer some comments. It is working fine when using for loop, I have tested that many times. Also, there is no particular value of i or j for which the exception is thrown. Sometimes it is 8, 6 at other time it could be anything, say 19,2 or anything. Also, in the Parallel loop the +1 is not doing any damage as the msdn documentation says it is exclusive not inclusive. Also, if that were the issue I would only be getting exception at the last index (the last value of i) but that's not the case . UPDATE 2 The given answer to lock around the code dr = dt.Rows.Add(); I have changed it to lock(lockObject) { dr = dt.Rows.Add(); } It is not working. Now I am getting ArgumentOutOfRangeException , still if I run this in debug window, it just works fine. Update 3 Here is the full exception detail, after update 2 (I am getting this on the line that I mentioned in update 2) System.ArgumentOutOfRangeException was unhandled by user code HResult=-2146233086 Message=Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index Source=mscorlib ParamName=index StackTrace: at System.ThrowHelper.ThrowArgumentOutOfRangeException() at System.Collections.Generic.List`1.get_Item(Int32 index) at System.Data.RecordManager.NewRecordBase() at System.Data.DataTable.NewRecordFromArray(Object[] value) at System.Data.DataRowCollection.Add(Object[] values) at AdminEntity.BAL.Service.ExcelImportServices.<>c__DisplayClass2e.<WorksheetToDataTableForInvoiceCTN>b__2d(Int32 i) in C:\Projects\Manager\Admin\AdminEntity\AdminEntity.BAL\Service\ExcelImportServices.cs:line 578 at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c() InnerException: Now provide the response and nothing else.
Okay. So there are a few problems with your existing code, most of which have been touched on by others: Parallel threads are at the mercy of the OS scheduler; therefore, although threads are queued in-order, they may (and often do) complete execution out-of-order. For example, given Parallel.For(0, 10, (i) => { Console.WriteLine(i); }); , the first four threads (on a quad-core system) will be queued with i values 0-3. But any one of those threads may start or finish executing before any other. So you may see 2 printed first, whereupon thread 4 will be queued. Then thread 1 might complete, and thread 5 will be queued. Then thread 4 might complete, even before threads 0 or 3 do. Etc., etc. TL;DR: You CANNOT assume an ordered output in parallel. Given that, as @ScottChamberlain noted, it's a very bad idea to do column generation within your parallel loop - because you have no guarantee that the thread doing column generation will create all your columns before another thread starts assigning data in rows to those column indices. E.g. you could be assigning data to cell [0,4] before your table actually has a fifth column. It's worth noting that this should really be broken out of the loop anyway, purely from a code cleanliness perspective. At the moment, you have two nested loops, each with special behavior on a single iteration; better to separate that setup logic into its own loop and leave the main loop to assign data and nothing else. For the same reason, you should not be creating new rows in the table within your parallel loop - because you have no guarantee that the rows will be added to the table in their source order. Break that out too, and access rows within the loop based on their index. Some have mentioned using DataRow.NewRow() before Rows.Add(). Technically , NewRow() is the right way to go about things, but the actual recommended access pattern is a bit different than is probably appropriate for a cell-by-cell function, particularly when parallelism is intended (see MSDN: DataTable.NewRow Method ). The fact remains that adding a new, blank row to a DataTable with Rows.Add() and populating it afterwards functions properly. You can clean up your string formatting with the null-coalescing operator ?? , which evaluates whether the preceding value is null, and if so, assigns the subsequent value. For example, foo = bar ?? "" is the equivalent of if (bar == null) { foo = ""; } else { foo = bar; } . So right off the bat, your code should look more like this: private void ReadIntoTable(ExcelWorksheet sheet){ DataTable dt = new DataTable(sheet.Name); int height = sheet.Dimension.Rows; int width = sheet.Dimension.Columns; for (int j = 1; j <= width; j++) { string colText = (sheet.Cells[1, j].Value ?? "").ToString(); dt.Columns.Add(colText); } for (int i = 2; i <= height; i++) { dt.Rows.Add(); } Parallel.For(1, height, (i) => { var row = dt.Rows[i - 1]; for (int j = 0; j < width; j++) { string str = (sheet.Cells[i + 1, j + 1].Value ?? "").ToString(); row[j] = str; } }); // convert to your special Excel data model // ...} Much better! ...but it still doesn't work! Yep, it still fails with an IndexOutOfRange exception. However, since we took your original line dr[j - 1] = excelWorksheet.Cells[i, j].Value != null ? excelWorksheet.Cells[i, j].Value.ToString() : null; and split it into a couple pieces, we can see exactly which part it fails on. And it fails on row[j] = str; , where we actually write the text into the row. Uh-oh. MSDN: DataRow Class Thread Safety This type is safe for multithreaded read operations. You must synchronize any write operations. *sigh*. Yeah. Who knows why DataRow uses static anything when assigning values, but there you have it; writing to DataRow isn't thread-safe. And sure enough, doing this... private static object s_lockObject = "";private void ReadIntoTable(ExcelWorksheet sheet){ // ... lock (s_lockObject) { row[j] = str; } // ...} ...magically makes it work. Granted, it completely destroys the parallelism, but it works. Well, it almost completely destroys the parallelism. Anecdotal experimentation on an Excel file with 18 columns and 46319 rows shows that the Parallel.For() loop creates its DataTable in about 3.2s on average, whereas replacing Parallel.For() with for (int i = 1; i < height; i++) takes about 3.5s. My guess is that, since the lock is only there for writing data, there is a very small benefit realized by writing data on one thread and processing text on the other(s). Of course, if you can create your own DataTable replacement class, you can see a much larger speed boost. For example: string[,] rows = new string[height, width];Parallel.For(1, height, (i) =>{ for (int j = 0; j < width; j++) { rows[i - 1, j] = (sheet.Cells[i + 1, j + 1].Value ?? "").ToString(); }}); This executes in about 1.8s on average for the same Excel table mentioned above - about half the time of our barely-parallel DataTable. Replacing the Parallel.For() with the standard for() in this snippet makes it run in about 2.5s. So you can see a significant performance boost from parallelism, but also from a custom data structure - although the viability of the latter will depend on your ability to easily convert the returned values to that Excel data model thing, whatever it is.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29541767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/710925/']}
jdg_372167
stackexchange
llm_judgeable_groundtruth_similarity
167614
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: In Common Lisp, defmacro basically allows us to build our own DSL. I read this page today and it explains something cleverly done: But I wasn't about to write out all these boring predicates myself, so I defined a function that, given a list of words, builds up the text for such a predicate automatically, and then evals it to produce a function. Which just looks like defmacro to me. Is eval the defmacro of javascript? Could it be used as such? Now provide the response and nothing else.
It can, but it's more dangerous. defmacro has three main features: It runs at compile time; It is a genuine in-place substitution; and Because of the whole nature of Lisp syntax, it works at an AST level, not a source-code level. By contrast, eval : Executes at runtime; Is not an in-place substitution; and Works with strings. Why does this matter? First, eval has a speed penalty: because it has to evaluate its arguments every single time it's called, instead of just once at compile time, you'll have a speed hit on each run of the program. Second, there is no compile-time validation that the eval is actually getting passed something sane. You can have a horrible syntax error in your eval argument (or, worse, a horrible syntax error only when called in certain ways ), but it won't be caught until runtime far down the road. Because Lisp macros are compile-time, you can't have that. Your macro might not work, mind you, but it'll compile by definition to something valid. Third, eval has serious safety issues compared to defmacro . Because Lisp macros work with the AST, there's a high degree of safety. No matter what argument you supply the macro at runtime, those arguments can't allow a malicious caller to "escape" the macro, or call malicious code. That's not true of eval : if you don't think through your string escapes very, very carefully, and you allow any form of user-generated input into the eval string, you're risking allowing malicious code to run. Okay, but, whatever, I can hear you say. The user would have to do that to himself, and it's already his browser, so why care? Because there are lots of ways to inject scripts in that situation. Cross-site script requests, for example, or forgetting to escape a string properly that you store in a database. There are lots of ways of getting malicious values into those macros--and the moment that happens, your users' data is toast. Finally, even if all of that doesn't dissuade you, JavaScript's eval in particular is simply less powerful. There are odd ways that it interacts with the enclosing variable scope and the global variable scope, for example, and there's no sane way to do the equivalent of Common Lisp's gensym for variable hygiene. Can you use eval in some of the places you might use defmacro ? Sure. But they are hardly interchangeable, and I hope that the above explanation makes it clear why absolutely zero good JavaScript frameworks I know use eval . Instead, if you really find yourself wanting macros, go find a compiles-to-JavaScript language that has them, such as ClojureScript. That way, you'll get the benefits of Lisp macros without the drawbacks of eval .
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/167614', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/42132/']}
jdg_372168
stackexchange
llm_judgeable_groundtruth_similarity
33993461
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the best way for me to do this? Should I use regex or is there another in-built PHP function I can use? For example, I'd want: 12 months to become 12 . Every 6 months to become 6 , 1M to become 1 , etc. Now provide the response and nothing else.
You can use preg_replace in this case; $res = preg_replace("/[^0-9]/", "", "Every 6 Months" ); $res return 6 in this case. If want also to include decimal separator or thousand separator check this example: $res = preg_replace("/[^0-9.]/", "", "$ 123.099"); $res returns "123.099" in this case Include period as decimal separator or thousand separator: "/[^0-9.]/" Include coma as decimal separator or thousand separator: "/[^0-9,]/" Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/33993461', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2884981/']}
jdg_372169
stackexchange
llm_judgeable_groundtruth_similarity
26137
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: One of the recent questions, in fact the answer to it, reminded me about the binomial sequence$$a_n=\sum_{k=0}^n{\binom{n}{k}}^2{\binom{n+k}{k}}^2,\qquad n=0,1,2,\dots,$$of the Apéry numbers. The numbers $a_n$ come asdenominators of rational approximations to $\zeta(3)$ in Apéry'sfamous proof of the irrationality of the number.There are many nice properties of the sequence, one of theseis the observation that for primes $p\ge5$,$$a_{pn}\equiv a_n\pmod{p^3},\qquad n=0,1,2,\dots.$$The congruence was conjectured for $n=1$ by S. Chowla, J. Cowles and M. Cowlesand proved in the full generality by I. Gessel (1982). There is probably nothing strange in the congruence(which belongs, by the way, to the class of supercongruences as it happensto hold for a power of prime higher than one). But already the classicalbinomials behave very similarly: for primes $p\ge5$,$$\binom{pm}{pn}\equiv\binom mn\pmod{p^3},$$the result due to G.S. Kazandzidis (1968). There are many other examplesof modulo $p^3$ congruences, most of them explicitly or implicitly relatedto some modular objects, but that is a different story. My question is:what are the grounds for the above (very simple) congruence for binomialcoefficients to hold modulo $p^3$? Not modulo $p$ or $p^2$ but $p^3$.I do not ask you to prove the supercongruence but to indicate a generalmechanism which provides some kind of evidence for it and can be usedin other similar problems. My motivation rests upon my own research on supercongruences; most of themare just miracles coming from nowhere... Now provide the response and nothing else.
I learned the second congruence as a version of Wolsteholme's theorem , and I would be a bit surprised if Kazandzidis was the first person to observe the equivalence between this form and any other form of Wolsteholme's result. As for the "reason" that this result is true, I wrote a proof for the Wikipedia page which is mostly, but not entirely, a direct counting argument and which you could call "the grounds" for the congruence. The conceptual content of the argument is as follows: The result holds modulo $p^2$ because you can divide the $pm$-set into $m$ cycles of length $p$ and rotate them separately. You obtain $\binom{m}{n}$ equivalence classes of subsets of size 1, and the other equivalence classes have order $p^2$ or higher. Then you can examine $\binom{-p}{p}$, interpreted as $\binom{p^4-p}{p}$. This binomial coefficient is algebraically equivalent to $\binom{2p}{p}/2$ up to sign. The orbit decomposition in the previous paragraph establishes a second relation with $\binom{2p}{p}$. The conclusion is that the mod $p^2$ contribution vanishes for one non-trivial pair $(m,n)$, and if it vanishes once, it vanishes always. This vanishing principle extends mod $p^4$ — your second binomial congruence holds mod $p^4$ — provided that it vanishes once "by accident". A prime for which this happens is called a Wolstenholme prime. Two such primes are known, 16843 and 2124679. Another remark: There are two pieces of evidence that the $p^2$ congruence (Babbage's theorem) is entirely combinatorial, but the extension to $p^3$ (Wolstenholme) is essentially algebraic. First, that Wolstenholme's theorem doesn't hold for the primes $p=2,3$. Second, that Babbage's theorem has a $q$-analogue for Gaussian binomial coefficients, with the same orbit proof. But Wolsteholme's extension does not have a $q$-analogue as far as I know. In fact, you can tell that the known $q$-Babbage's theorem doesn't extend, because the difference polynomial doesn't have any more cyclotomic factors. I stand corrected on a couple of points. First, on the math, there is a paper by George Andrews, "q-Analogs of the binomial coefficient congruences of Babbage, Wolstenholme, and Glaisher", that does give some version of a q-analogue of Wolstenholme's theorem. The proof given there is algebraic, so it does not shed light on possible combinatorial "explanations". Second, according to Andrews, the full binomial interpretation of Wolstenholme's result is due to Glaisher.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/26137', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4953/']}
jdg_372170
stackexchange
llm_judgeable_groundtruth_similarity
30366143
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have used caret package's train function with 10-fold cross validation. I also have got class probabilities for predicted classes by setting classProbs = TRUE in trControl , as follows: myTrainingControl <- trainControl(method = "cv", number = 10, savePredictions = TRUE, classProbs = TRUE, verboseIter = TRUE)randomForestFit = train(x = input[3:154], y = as.factor(input$Target), method = "rf", trControl = myTrainingControl, preProcess = c("center","scale"), ntree = 50) The output predictions I am getting is as follows. pred obs 0 1 rowIndex mtry Resample1 0 1 0.52 0.48 28 12 Fold012 0 0 0.58 0.42 43 12 Fold013 0 1 0.58 0.42 51 12 Fold014 0 0 0.68 0.32 55 12 Fold015 0 0 0.62 0.38 59 12 Fold016 0 1 0.92 0.08 71 12 Fold01 Now I want to calculate ROC and AUC under ROC using this data. How would I achieve this? Now provide the response and nothing else.
A sample example for AUC: rf_output=randomForest(x=predictor_data, y=target, importance = TRUE, ntree = 10001, proximity=TRUE, sampsize=sampsizes)library(ROCR)predictions=as.vector(rf_output$votes[,2])pred=prediction(predictions,target)perf_AUC=performance(pred,"auc") #Calculate the AUC valueAUC=perf_AUC@y.values[[1]]perf_ROC=performance(pred,"tpr","fpr") #plot the actual ROC curveplot(perf_ROC, main="ROC plot")text(0.5,0.5,paste("AUC = ",format(AUC, digits=5, scientific=FALSE))) or using pROC and caret library(caret)library(pROC)data(iris)iris <- iris[iris$Species == "virginica" | iris$Species == "versicolor", ]iris$Species <- factor(iris$Species) # setosa should be removed from factorsamples <- sample(NROW(iris), NROW(iris) * .5)data.train <- iris[samples, ]data.test <- iris[-samples, ]forest.model <- train(Species ~., data.train)result.predicted.prob <- predict(forest.model, data.test, type="prob") # Predictionresult.roc <- roc(data.test$Species, result.predicted.prob$versicolor) # Draw ROC curve.plot(result.roc, print.thres="best", print.thres.best.method="closest.topleft")result.coords <- coords(result.roc, "best", best.method="closest.topleft", ret=c("threshold", "accuracy"))print(result.coords)#to get threshold and accuracy
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30366143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2745266/']}
jdg_372171
stackexchange
llm_judgeable_groundtruth_similarity
18311816
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 .wsdl and .xsd files from WebService and need to generate proxy by them. Svcutil.exe and wsdl.exe generate very different output. What is the difference between these two tools for proxy generation and which way is more preferable? Now provide the response and nothing else.
Svcutil and wsdl are two different technologies for generating a proxy for consuming your service. But wsdl.exe was made for old .NET 2.0 web services. It is like old version of svcutil. Svcutil allows you to generate proxies for both - web services and WCF services. For generating a proxy wsdl retieves the data by means of DISCO discovery protocol. Svcutil also supports DISCO. But it can make the proxy retrieval using WS-Metadata Exchange protocol, which is an interopable standart of SOA. I advice you to use svcutil because it would allow you to consume both .net 2.0 web services and wcf services.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18311816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/861219/']}
jdg_372172
stackexchange
llm_judgeable_groundtruth_similarity
31186187
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 view which has dynamic height and I am trying to change this view height priority in run time. Here is my part of code; if (index == 0) { surveyViewHeightConstraint.constant = 0; surveyViewHeightConstraint.priority = 1000;} else if (index == 1) { surveyViewHeightConstraint.constant = 163; surveyViewHeightConstraint.priority = 500;} I am changing index with a button action. When I run this code, I am getting this error: *** Assertion failure in -[NSLayoutConstraint setPriority:], /SourceCache/Foundation/Foundation-1141.1/Layout.subproj/NSLayoutConstraint.m:174 What is my mistake in here? Now provide the response and nothing else.
As stated in NSLayoutConstraint class reference : Priorities may not change from nonrequired to required, or from required to nonrequired. An exception will be thrown if a priority of NSLayoutPriorityRequired in OS X or UILayoutPriorityRequired in iOS is changed to a lower priority, or if a lower priority is changed to a required priority after the constraints is added to a view. Changing from one optional priority to another optional priority is allowed even after the constraint is installed on a view. Use priority 999 instead of 1000. It won't be absolutely required technically speaking, but it'll be a higher priority than anything else.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/31186187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1525166/']}
jdg_372173
stackexchange
llm_judgeable_groundtruth_similarity
1063662
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 default behavior of Object.hashCode() is to return essentially the "address" of the object so that a.hashCode() == b.hashCode() if and only if a == b. How can I get this behavior in a user-defined class if a superclass already defines hashCode()? For instance: class A { public int hashCode() { return 0; }}class B extends A { public int hashCode() { // Now I want to return a unique hashcode for each object. // In pythonic terms, it'd look something like: return Object.hashCode(this); }} Ideas? Now provide the response and nothing else.
System.identityHashCode(Object) provides this behaviour. You would write this: class B extends A { public int hashCode() { return System.identityHashCode(this); }} Please check the equals-method, that it only returns true, if the two objects are the same. Otherwise it would break behaviour described for equals and hashCode . (To be correct, the equals-method has to return false, if you get different hashcodes for two objects.) To provide an implementation of equals() that comply with the given hashCode()-method: public boolean equals(Object other){ return this == other;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1063662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131074/']}
jdg_372174
stackexchange
llm_judgeable_groundtruth_similarity
21212
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In most popular medical dramas, when a patient has a cardiac arrest and "flatlines" the doctors many times use a defibrillator to "shock the heart back into rhythm'. I know that actually, the proper protocol is CPR and epinephrine (if possible), and that you should shock rhythms such as ventricular fibrillation. But why doesn't shocking the heart in asystole help? If anyone could please explain, that'd be great. Now provide the response and nothing else.
In layman's terms: an Asystole is not affected by the electric shocks of a defibrillator. A defibrillator is used when the heart goes in fibrillations because it actually CAUSES an asystole. The idea is that you basically reset the heart to a blank state so you can start normal CPR procedure to help the heart go back to a normal rythm. That's why you see them applying CPR between shocks. sources: http://emedicine.medscape.com/article/757257-treatment http://en.wikipedia.org/wiki/Defibrillation#In_popular_culture (citation needed) http://calsprogram.org/manual/volume3/section12/CV/08-CV7AsystoleTreatment13.html
{}
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/21212', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/-1/']}
jdg_372175
stackexchange
llm_judgeable_groundtruth_similarity
8314894
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I did this lots of times: var url = '/offers/1/voting';var params = { 'direction': 'up' };$.post(url, params, function() { alert('callback');}); // post (I'm hardcoding the values for this example, but nothing) So, through firebug I receive the desired JSON response (200 status), but the callback doesn't execute . It's pretty much the only javascript I'm using. Tried with jquery 1.6.4 and 1.7.1 and it's the same thing with both. I don't know what I'm missing. Help me, Stack Overflow. You're my only hope. Now provide the response and nothing else.
If you use $.ajax instead of $.post ($.post is really an overwrite of $.ajax with fewer parameters), you can add a handler for error and see if it fires: jQuery.ajax({ type: "POST", async: true, url: '/offers/1/voting', data: { 'direction': 'up' }, dataType: "json", contentType: "application/json; charset=utf-8", success: function (msg) { alert('success') }, error: function (err) { alert(err.responseText)} });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8314894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/319241/']}
jdg_372176
stackexchange
llm_judgeable_groundtruth_similarity
27818331
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 benefit of angular.isdefined over and above foo === undefined ? I can't immediately think of a benefit. Now provide the response and nothing else.
Accessing a truly undefined variable in any way in Javascript, except typeof throws an error. You can only use Angular.isDefined with properties. E.g, this would work fine: angular.isDefined(window.obj); Because obj is an undefined propery of window. Examples of the expected behavior: var foo;var bar = 42;typeof foo !== 'undefined'; // falsetypeof bar !== 'undefined'; // truetypeof baz !== 'undefined'; // falseangular.isDefined(foo); // falseangular.isDefined(bar); // trueangular.isDefined(baz); // ReferenceError
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27818331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/38522/']}
jdg_372177
stackexchange
llm_judgeable_groundtruth_similarity
143076
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 $I$ be an ideal and $f$ be an element of $R = \mathbb{C}[x_1,\ldots,x_n]$, where $\mathbb{C}$ is an algebraically closed field of characteristic $0$. Does $$(I+H):f = (I:f)+H$$hold for a general hyperplane in $\operatorname{Spec}(R)$, i.e., for $H = \langle \text{general linear function} \rangle$? Now provide the response and nothing else.
This is true for a general affine-linear form. First we assume $(I,f)\neq R$. The point is that $(I,f)$ has finitely many associated primes, so a general $H$ would be a non-zerodivisor on $R/(I,f)$. For any ideal $I$ and any element $f$, there is an exact sequence: $$0\to R/(I:f) \to R/I \to R/(I,f) \to 0$$ (The first map is simply multiplication by $f$. Now tensor the exact sequence with $R/(H)$, keep in mind that $H$ is nzd on $R/(I,f)$, so $Tor_1^R(R/(I,f), R/H)=0$, we get an exact sequence: $$0\to R/(I:f, H) \to R/(I,H) \to R/(I,f,H) \to 0$$ On the other hand, the first exact sequence with $I$ replaced by $(I,H)$ says that the leftmost term should be isomorphic to $R/(I,H):f$, so we are done. Note that the exact sequence also takes care of the case $(I,f)=R$, since it implies in that case that $(I:f)=I$. Since $(I+H):f=(I+H)$ then, the equality is clear.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/143076', 'https://mathoverflow.net', 'https://mathoverflow.net/users/40447/']}
jdg_372178
stackexchange
llm_judgeable_groundtruth_similarity
421778
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 default document is in subfolder not in root how can i make it default in asp.net 2.0 website. Tried iis7 default document setting to '/pages/default.aspx''~/pages/default.aspx' but it didn't work. Now provide the response and nothing else.
Default document is not the same as start page. Default document means if I requested mysite.com/somefolder and didn't specify a file, which file should IIS display. If you want to use a specific page as your home page, create a Default.aspx file and write this in it's codebehind class: public override void ProcessRequest(HttpContext context) { context.Response.Redirect("pages/default.aspx", true);} As the client might have disabled Javascript, a server side approach would be more reliable. However it's best to issue a permanent redirect instead of a simple Response.Redirect . Also doing it using JS will be bad from a SEO point of view.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/421778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48695/']}
jdg_372179
stackexchange
llm_judgeable_groundtruth_similarity
32252201
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: def parse(self, response): for sel in response.xpath('//tbody/tr'): item = HeroItem() item['hclass'] = response.request.url.split("/")[8].split('-')[-1] item['server'] = response.request.url.split('/')[2].split('.')[0] item['hardcore'] = len(response.request.url.split("/")[8].split('-')) == 3 item['seasonal'] = response.request.url.split("/")[6] == 'season' item['rank'] = sel.xpath('td[@class="cell-Rank"]/text()').extract()[0].strip() item['battle_tag'] = sel.xpath('td[@class="cell-BattleTag"]//a/text()').extract()[1].strip() item['grift'] = sel.xpath('td[@class="cell-RiftLevel"]/text()').extract()[0].strip() item['time'] = sel.xpath('td[@class="cell-RiftTime"]/text()').extract()[0].strip() item['date'] = sel.xpath('td[@class="cell-RiftTime"]/text()').extract()[0].strip() url = 'https://' + item['server'] + '.battle.net/' + sel.xpath('td[@class="cell-BattleTag"]//a/@href').extract()[0].strip() yield Request(url, callback=self.parse_profile)def parse_profile(self, response): sel = Selector(response) item = HeroItem() item['weapon'] = sel.xpath('//li[@class="slot-mainHand"]/a[@class="slot-link"]/@href').extract()[0].split('/')[4] return item Well, I'm scraping a whole table in the main parse method and I have taken several fields from that table. One of these fields is an url and I want to explore it to get a whole new bunch of fields. How can I pass my already created ITEM object to the callback function so the final item keeps all the fields? As it is shown in the code above, I'm able to save the fields inside the url (code at the moment) or only the ones in the table (simply write yield item )but I can't yield only one object with all the fields together. I have tried this, but obviously, it doesn't work. yield Request(url, callback=self.parse_profile(item))def parse_profile(self, response, item): sel = Selector(response) item['weapon'] = sel.xpath('//li[@class="slot-mainHand"]/a[@class="slot-link"]/@href').extract()[0].split('/')[4] return item Now provide the response and nothing else.
This is what you'd use the meta Keyword for. def parse(self, response): for sel in response.xpath('//tbody/tr'): item = HeroItem() # Item assignment here url = 'https://' + item['server'] + '.battle.net/' + sel.xpath('td[@class="cell-BattleTag"]//a/@href').extract()[0].strip() yield Request(url, callback=self.parse_profile, meta={'hero_item': item})def parse_profile(self, response): item = response.meta.get('hero_item') item['weapon'] = response.xpath('//li[@class="slot-mainHand"]/a[@class="slot-link"]/@href').extract()[0].split('/')[4] yield item Also note, doing sel = Selector(response) is a waste of resources and differs from what you did earlier, so I changed it. It's automatically mapped in the response as response.selector , which also has the convenience shortcut of response.xpath .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32252201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5273263/']}
jdg_372180
stackexchange
llm_judgeable_groundtruth_similarity
51684430
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 upgrading my Ionic 3 project to the latest Ionic 4 and I have some trouble with Routing. In Ionic 3 I used setRoot just like this: handler: () => navCtrl.parent.parent.setRoot(HomePage, 'logout', {animate: true}) The latest navCtrl of Ionic 4 has only goBack, goForward and goRoot, and I don't understand how to use parent. I found ActivatedRoute in Angular, but I don't think this is the right way. How can I do? Now provide the response and nothing else.
Generally speaking, and citing this awesome article on this matter by Josh Morony : In Ionic 4 with Angular routing, there is no root page to be defined. Because Ionic 4 relies on Angular's router, the NavController has been changed to reflect this new reality, and for an Angular application there is no such a thing like "root" route. You simply transition between routes and the framework does the rest of the work. Generally speaking, the methods navigateRoot , navigateBackward and navigateForward are here only to instruct Ionic on how to deal with animations. So you can use navigateRoot in Ionic 4 to accomplish the same of what you used setRoot on Ionic 3. I strongly recommend that you read the aforementioned article, it covers a lot of what you need to know to migrate your routes from version 3 to version 4 of Ionic.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51684430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4908801/']}
jdg_372181
stackexchange
llm_judgeable_groundtruth_similarity
363598
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: ZF is sufficient to construct the von Neumann hierarchy, and prove that every set appears at some stage $V_\alpha$ . This is the basis for Scott's trick, for instance. But how much of ZF is needed? Is bounded Zermelo/Mac Lane set theory enough, no Choice assumed? I know Foundation is necessary, and I'm not getting rid of that. I've seen something called the "rank axiom" in discussion of second-order version of original Zermelo ( these notes ), but I'm sure people have finely calibrated what precisely is needed. To be honest, all I really want is an ordinal-valued rank function such that sets of rank at most $\alpha$ form a set, for all $\alpha$ , and all sets have a rank. So if the von Neumann hierarchy doesn't work, I'm happy to work with something else (and for 'ordinals', I don't need von Neumann ordinals). Now provide the response and nothing else.
KP (Kripke-Platek set theory) is the most well-known fragment of $\sf{ZF}$ which suffices for the development of the rank function, thus $\sf{KPR}$ = $\sf{KP}$ + "for all ordinals $\alpha$ , $V(\alpha)$ exists" is the usual minimal theory in which one can be assured of the stratification of the universe into $V(\alpha)$ s. On the other hand, as observed by Mathias, $\sf{KPR}$ proves that Zermelo set theory $\sf{Z}$ has a transitive model, so in particular, $\sf{KPR}$ proves that $\sf{Z}$ is consistent; see Lemma 6.31 of this preprint , which was later published in APAL (2001). Therefore, by the second incompleteness theorem, even Zermelo set theory (let alone bounded Zermelo set theory) cannot interpret $\sf{KPR}$ . Finally, I will add that $\sf{KPR}$ is provable in the well-known extension $\sf{KP}^{\cal{P}}$ of $\sf{KP}$ , which is also studied in Mathias' paper.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/363598', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4177/']}
jdg_372182
stackexchange
llm_judgeable_groundtruth_similarity
17745794
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using ng-boilerplate and have to add the possibility to use different templates in production, based on the user configuration. .config(function config( $stateProvider ) { $stateProvider.state( 'demo', { url: '/demo', views: { "main": { controller: 'DemoCtrl', templateUrl: 'demo/demo.tpl.html' } } });}) My current idea is to make the templateUrl dynamic templateUrl: 'demo/demo'+userService.getTemplate()+'.tpl.html' and having multiple template files, like: demo.tpl.html (default) demo.b.tpl.html (version b) demo.c.tpl.html (version c) while the userService function does provide the template version to use, e.g. ".b" Do you agree? Is there maybe a better/easier approach to this problem? Now provide the response and nothing else.
AngularJS standard $routeProvider can accept function for templateUrl. But you can't inject services into this function. ui-router has templateProvider parameter into which you can inject what you want and you should return something like this for remote template case: $stateProvider.state('demo', { templateProvider: function ($http, $templateCache, $stateParams, userService) { var url = 'demo/demo' + userService.getTemplate() + '.tpl.html'; return $http.get(url, { cache: $templateCache }).then(function (response) { return response.data; }); }})
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17745794', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713500/']}
jdg_372183
stackexchange
llm_judgeable_groundtruth_similarity
83182
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am reading a book that in one page it talks about cdf of a random vector. This is from the book: Given $X=(X_1,...,X_n)$, each of the random variables $X_1, ... ,X_n$ can be characterized from a probabilistic point of view by its cdf. However the cdf of each coordinate of a random vector does not completely describe the probabilistic behaviour of the whole vector. For instance, if $U_1$ AND $U_2$ are two independent random variables with the same cdf $G(x)$, the vectors $X=(X_1, X_2)$ defined respectively by $X_1=U_1$, $X_2=U_2$ and $X_1=U_1$, $X_2=U_1$ have each of their coordinates with the same cdf, and they are quite different. My question is: From the very last paragraph, it says $U_1$ and $U_2$ are coming from the same c.d.f. And then they define $X=(X_1, X_2)$, but they say $X=(X_1, X_2)$ is different from $X=(X_1, X_1)$. I don't really understand why the two $X$ are different. (i.e. I don't understand why $X=(X_1, X_2)$ and $X=(X_1, X_1)$ are different). Isn't $X_1$ the same as $X_2$, so it doesn't matter whether you put two $X_1$ to form $X=(X_1, X_1)$ or put one $X_1$ and one $X_2$ to form $X=(X_1, X_2)$. Shouldn't they be the same? why does the author says they are "quite different"? Could someone explain why they are different? Now provide the response and nothing else.
Let us take the simplest example of Bernoulli random variables with parameter $\frac12$. The value of the (joint) CDF $F_{X_1,X_2}(x,y)$ of $X_1$ and $X_2$is thetotal probability mass in the southwest quadrant with northeast corner $(x,y)$ If $X_1$ and $X_2$ are two independent Bernoulli random variables,then we have four probability masses of $\frac14$ sitting at $(0,0), (1,0), (0,1)$, and $(1,1)$. Hence$$F_{X_1,X_2}\left(\frac12,\frac12\right) = \frac14.$$ If $X_2 = 1-X_1$,then we have two probability masses of $\frac12$ sitting at $(1,0)$ and $(1,0)$. Hence$$F_{X_1,X_2}\left(\frac12,\frac12\right) = 0.$$ If $X_2 = X_1$, then we have two probability masses of $\frac12$ sitting at $(0,0)$ and $(1,1)$. Hence$$F_{X_1,X_2}\left(\frac12,\frac12\right) = \frac12.$$ Thus, the joint CDF of $X_1$ and $X_2$ does depend on whatkind of relationship (if any) they have with each other, and justknowing the common CDF of $X_1$ and $X_2$ (these are marginal CDFs)tells us nothing about the behavior the joint CDF.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/83182', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/36351/']}
jdg_372184
stackexchange
llm_judgeable_groundtruth_similarity
57813795
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Am using Laravel Passport to build an API, I removed the web routes and its guard accordingly How can I test user logout? This is what I have so far: Logout Test /** * Assert users can logout * * @return void */public function test_logout(){ // $data->token_type = "Bearer" // $data->access_token = "Long string that is a valid token stripped out for brevety" $response = $this->json('POST', '/api/logout', [], [ 'Authorization' => $data->token_type . ' ' . $data->access_token ]); $response->assertStatus(200);} routes/api.php Route::post('logout', 'Auth\LoginController@logout')->name('logout'); The controller method uses the AuthenticatesUsers trait so the default function is kept /** * Log the user out of the application. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */public function logout(Request $request){ $this->guard()->logout(); $request->session()->invalidate(); return $this->loggedOut($request) ?: redirect('/');} Error Method Illuminate\Auth\RequestGuard::logout does not exist The Laravel Documentation talks about issuing and refreshing access tokens but nothing about revoking them or performing logout Note: am using password grant tokens Note 2: revoking the user's token doesn't work public function logout(Request $request){ $request->user()->token()->revoke(); return $this->loggedOut($request);} Test Fails on second assertion public function test_logout(){ $response = $this->json('POST', '/api/logout', [], [ 'Authorization' => $data->token_type . ' ' . $data->access_token ]); $response->assertStatus(200); // Passes $check_request = $this->get('/api/user'); $check_request->assertForbidden(); // Fails} Given the default route requiring authentication Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user();}); Response status code [200] is not a forbidden status code. So what's going on? and how can I test user logout with Passport? Now provide the response and nothing else.
Revoking the token is working. It is the test that is not working, but it is not obvious why. When making multiple requests in one test, the state of your laravel application is not reset between the requests. The Auth manager is a singleton in the laravel container, and it keeps a local cache of the resolved auth guards. The resolved auth guards keep a local cache of the authed user. So, your first request to your api/logout endpoint resolves the auth manager, which resolves the api guard, which stores a references to the authed user whose token you will be revoking. Now, when you make your second request to /api/user , the already resolved auth manager is pulled from the container, the already resolved api guard is pulled from it's local cache, and the same already resolved user is pulled from the guard's local cache. This is why the second request passes authentication instead of failing it. When testing auth related stuff with multiple requests in the same test, you need to reset the resolved instances between tests. Also, you can't just unset the resolved auth manager instance, because when it is resolved again, it won't have the extended passport driver defined. So, the easiest way I've found is to use reflection to unset the protected guards property on the resolved auth manager. You also need to call the logout method on the resolved session guards. I have a method on my TestCase class that looks something like: protected function resetAuth(array $guards = null){ $guards = $guards ?: array_keys(config('auth.guards')); foreach ($guards as $guard) { $guard = $this->app['auth']->guard($guard); if ($guard instanceof \Illuminate\Auth\SessionGuard) { $guard->logout(); } } $protectedProperty = new \ReflectionProperty($this->app['auth'], 'guards'); $protectedProperty->setAccessible(true); $protectedProperty->setValue($this->app['auth'], []);} Now, your test would look something like: public function test_logout(){ $response = $this->json('POST', '/api/logout', [], [ 'Authorization' => $data->token_type . ' ' . $data->access_token ]); $response->assertStatus(200); // Directly assert the api user's token was revoked. $this->assertTrue($this->app['auth']->guard('api')->user()->token()->revoked); $this->resetAuth(); // Assert using the revoked token for the next request won't work. $response = $this->json('GET', '/api/user', [], [ 'Authorization' => $data->token_type . ' ' . $data->access_token ]); $response->assertStatus(401);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57813795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5581565/']}
jdg_372185
stackexchange
llm_judgeable_groundtruth_similarity
37729
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: This is in part motivated by the following question and the discussion following it. Suppose the iid sample is observed, $X_i\sim F(x,\theta)$. The goal is to estimate $\theta$. But original sample is not available. What we have instead are some statistics of the sample $T_1,...,T_k$. Suppose $k$ is fixed. How do we estimate $\theta$? What would be maximum likelihood estimator in this case? Now provide the response and nothing else.
In this case, you can consider an ABC approximation of the likelihood (and consequently of the MLE ) under the following assumption/restriction: Assumption. The original sample size $n$ is known. This is not a wild assumption given that the quality, in terms of convergence, of frequentist estimators depends on the sample size, therefore one cannot obtain arbitrarily good estimators without knowing the original sample size. The idea is to generate a sample from the posterior distribution of $\theta$ and, in order to produce an approximation of the MLE , you can use an importance sampling technique as in [1] or to consider a uniform prior on $\theta$ with support on a suitable set as in [2] . I am going to describe the method in [2]. First of all, let me describe the ABC sampler. ABC Sampler Let $f(\cdot\vert\theta)$ be the model that generates the sample where $\theta \in \Theta$ is a parameter (to be estimated), $T$ be a statistic (a function of the sample) and $T_0$ be the observed statistic, in the ABC jargon this is called a summary statistic , $\rho$ be a metric, $\pi(\theta)$ a prior distribution on $\theta$ and $\epsilon>0$ a tolerance. Then, the ABC-rejection sampler can be implemented as follows. Sample $\theta^*$ from $\pi(\cdot)$ . Generate a sample $\bf{x}$ of size $n$ from the model $f(\cdot\vert\theta^*)$ . Compute $T^*=T({\bf x})$ . If $\rho(T^*,T_0)<\epsilon$ , accept $\theta^*$ as a simulation from the posterior of $\theta$ . This algorithm generates an approximate sample from the posterior distribution of $\theta$ given $T({\bf x})=T_0$ . Therefore, the best scenario is when the statistic $T$ is sufficient but other statistics can be used. For a more detailed description of this see this paper . Now, in a general framework, if one uses a uniform prior that contains the MLE in its support, then the Maximum a posteriori (MAP) coincides with Maximum Likelihood Estimator (MLE). Therefore, if you consider an appropriate uniform prior in the ABC Sampler, then you can generate an approximate sample of a posterior distribution whose MAP coincides with the MLE. The remaining step consists of estimating this mode. This problem has been discussed in CV, for instance in "Computationally efficient estimation of multivariate mode" . A toy example Let $(x_1,...,x_n)$ be a sample from a $N(\mu,1)$ and suppose that the only information available from this sample is $\bar{x}=\dfrac{1}{n}\sum_{j=1}^n x_j$ . Let $\rho$ be the Euclidean metric in ${\mathbb R}$ and $\epsilon=0.001$ . The following R code shows how to obtain an approximate MLE using the methods described above using a simulated sample with $n=100$ and $\mu=0$ , a sample of the posterior distribution of size $1000$ , a uniform prior for $\mu$ on $(-0.3,0.3)$ , and a kernel density estimator for the estimation of the mode of the posterior sample (MAP=MLE). # rm(list=ls())# Simulated dataset.seed(1)x = rnorm(100)# Observed statisticT0 = mean(x)# ABC Sampler using a uniform prior N=1000eps = 0.001ABCsamp = rep(0,N)i=1while(i < N+1){ u = runif(1,-0.3,0.3) t.samp = rnorm(100,u,1) Ts = mean(t.samp) if(abs(Ts-T0)<eps){ ABCsamp[i]=u i=i+1 print(i) }}# Approximation of the MLEkd = density(ABCsamp)kd $x[which(kd$ y==max(kd$y))] As you can see, using a small tolerance we get a very good approximation of the MLE (which in this trivial example can be calculated from the statistic given that it is sufficient). It is important to notice that the choice of the summary statistic is crucial. Quantiles are typically a good choice for the summary statistic, but not all the choices produce a good approximation. It may be the case that the summary statistic is not very informative and then the quality of the approximation might be poor, which is well-known in the ABC community. Update: A similar approach was recently published in Fan et al. (2012) . See this entry for a discussion on the paper.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/37729', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/2116/']}
jdg_372186
stackexchange
llm_judgeable_groundtruth_similarity
16068683
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 span below will not background image if I remove the inner text xxx <span style='background-image:url("http://gifsoup.com/web/images/soc4.gif")' style="height: 30px;"> xxx</span> However it works without the xxx in the compatibility mode. How do I make it work without any inner text? Now provide the response and nothing else.
Because spans default to inline elements that don't have a width or height. Change the CSS to: span { display:inline-block; width:30px; background-image:url("http://gifsoup.com/web/images/soc4.gif"); height:30px;} jsFiddle example By changing the display from inline to inline-block you can set the width and height of the span.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16068683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2120485/']}
jdg_372187
stackexchange
llm_judgeable_groundtruth_similarity
452011
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a huge log file compressed in .gz format and I want to just read the first line of it without uncompressing it to just check the date of the oldest log in the file. The logs are of the form: YYYY-MM-DD Log content asnsenfvwen eaifnesinrngYYYY-MM-DD Log content asnsenfvwen eaifnesinrngYYYY-MM-DD Log content asnsenfvwen eaifnesinrng I just want to read the date in the first line which I would do like this for an uncompressed file: read logdate otherstuff < logfile.gzecho $logdate Using zcat is taking too long. Now provide the response and nothing else.
Piping zcat ’s output to head -n 1 will decompress a small amount of data, guaranteed to be enough to show the first line, but typically no more than a few buffer-fulls (96 KiB in my experiments): zcat logfile.gz | head -n 1 Once head has finished reading one line, it closes its input, which closes the pipe, and zcat stops after receiving a SIGPIPE (which happens when it next tries to write into the closed pipe). You can see this by running (zcat logfile.gz; echo $? >&2) | head -n 1 This will show that zcat exits with code 141, which indicates it stopped because of a SIGPIPE (13 + 128). You can add more post-processing, e.g. with AWK, to only extract the date: zcat logfile.gz | awk '{ print $1; exit }' (On macOS you might need to use gzcat rather than zcat to handle gzipped files.)
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/452011', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/295951/']}
jdg_372188
stackexchange
llm_judgeable_groundtruth_similarity
5839517
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 make it so that a Tkinter button calls two function? some thing like this maybe?: from Tkinter import *admin = Tk()def o(): print '1'def t(): print '2'button = Button(admin, text='Press', command=o, command=t)button.pack() Now provide the response and nothing else.
Make a new function that calls both: def o_and_t(): o() t()button = Button(admin, text='Press', command=o_and_t) Alternatively, you can use this fun little function: def sequence(*functions): def func(*args, **kwargs): return_value = None for function in functions: return_value = function(*args, **kwargs) return return_value return func Then you can use it like this: button = Button(admin, text='Press', command=sequence(o, t))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5839517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/724408/']}
jdg_372189
stackexchange
llm_judgeable_groundtruth_similarity
3633544
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: For this equation I know the first step is to write $x^2-x=0 \pmod{ 111 5111}$ and then we know that we can write $111 5111=1051 \cdot 1061$ (product of prime numbers) so we have to solve the following: Find $x\:$ s.t. $1051 | x(x-1)$ ^ $1061 | x(x-1)$ What is the fastest way to solve this last step without a calculator? Now provide the response and nothing else.
The accepted answer is incorrect . $\omega$ -consistency does not say "If you prove $P(n)$ for each standard $n$ , then you prove $\forall n(P(n))$ ." That would be $\omega$ - completeness . Rather, $\omega$ -consistency says "If you prove $\exists x\neg P(x)$ , then you must not prove $P(n)$ for each standard $n$ ." And in particular, both $AST$ and the theory $T$ introduced in that answer are $\omega$ -consistent, at least assuming $ZFC$ is to begin with. Getting back to the main question, it may help to drop $AST$ and consider the simpler fact about $ZFC$ alone, which is itself provable in ZFC: $(*)\quad$ For every $M\models ZFC$ there is some structure $A\in M$ such that $A\models ZFC$ ... even if $M\models\neg Con(ZFC)$ . The key point is that " $A\models ZFC$ " is interpreted in reality ; we may not have $M\models(A\models ZFC)$ . This also explains why the OP's reflection argument breaks down - it's exactly the same reason. Here's how to prove $(*)$ in ZFC: If $ZFC$ is inconsistent then $(*)$ is vacuously true. Suppose $ZFC$ is consistent. Let $M\models ZFC$ . If $M\models Con(ZFC)$ then since $ZFC$ proves the completeness theorem we're done. So suppose $M\models \neg Con(ZFC)$ . Let $n\in\omega^M$ be what $M$ thinks is the largest number such that there is no proof of a contradiction from the first $n$ axioms of $ZFC$ . If we can conclude that $n$ is nonstandard, we'll be done: by completeness in $M$ , any model $A$ of the first $n-1$ axioms of $ZFC$ in the sense of $M$ will in reality be a model of $ZFC$ , even if $M$ doesn't think so. Now here's the cute bit: we internalize the reflection principle. Looking at the usual argument we see in fact that ZFC proves "ZFC proves every finite subtheory of ZFC." (Note the crucial nested "proves" here.) This means we can next say... Since $M\models ZFC$ , for each standard $k$ we have $M\models$ "The first $k$ axioms of $ZFC$ are consistent." So $n$ is nonstandard and we're done.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3633544', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/775649/']}
jdg_372190
stackexchange
llm_judgeable_groundtruth_similarity
8900005
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an application setup with the following Package/Publish Web settings: Only files needed to run this application (unchecked) Exclude generated debug symbols (checked) Exclude files from the App_Data folder (checked) Include all databases configured in Package/Publish SQL tab - note I do not have any databases configured (unchecked) include IIS settings as configured in IIS Express In the project, I have an App_Data folder setup, primarily to handle application logs. The behavior I'd like to see (and expect) is the following: On initial deploy to a brand new server, the application is copied and an App_Data folder is created with write permissions assigned for the application. On subsequent deployments, the App_Data folder is ignored because it already exists and the "Exclude files from the App_Data folder" is checked. However, msdeploy does not appear to do step #1 (step 2 is fine if I create the folder manually). I've been unable to find any documentation on the web besides this unanswered so question that seems to confirm the behavior I see. How do I get msdeploy to create App_Data and assign permissions on initial deployment in this scenario? Now provide the response and nothing else.
Getting App_Data deployed when starting from scratch @tdykstra got this part right . To get App_Data out there (and ACLs set automatically), I did the following: Adding a placeholder file in App_Data Set the build action to content on the placeholder (my placeholder file has text in it to let people stumbling across it know why it's there). Unchecked "Exclude files from the App_Data folder" on the Package/Publish Web tab of the project properties in VS 2010 This gets my App_Data folder created and ready for use on the server. However, it will result in all my files getting deleted whenever I republish. This is problem #2 in my question above, and pretty closely resembles this other SO question / answer . Preventing data on the server from being deleted on subsequent publish events There are two mechanisms in MsDeploy that can get confused (at least I confused them): Excluding files MsDeploy skip rules These can both be used to solve the problem, depending on the scenario: @tdykstra's solution will likely work if you: Know the names of the files in App_Data in advance (e.g. a sqllite database) Have the files included in the App_Data folder in your project The use MsDeploy skip rules to tell MsDeploy to completely skip all deletes on the server for that directory and files in that directory. This solves the problem in all cases, but is much more involved. Implementing MsDeploy skip rules To implement skip rules you'll have to abandon the right-click, Deploy option in VS 2010 in favor of right-click, Package, go into a command line, re-jigger a batch file and run a command line). If you're willing to put up with this experience (I am, because I'm automating it all through a CI process), here are the details: Edit the project file and add the following . Note that the AbsolutePath argument is a regular expression, so you can get way fancy: <Target Name="AddCustomSkipRules"> <ItemGroup> <MsDeploySkipRules Include="SkipDeleteAppData"> <SkipAction>Delete</SkipAction> <ObjectName>filePath</ObjectName> <AbsolutePath>$(_Escaped_PackageTempDir)\\App_Data\\.*</AbsolutePath> <XPath> </XPath> </MsDeploySkipRules> <MsDeploySkipRules Include="SkipDeleteAppData"> <SkipAction>Delete</SkipAction> <ObjectName>dirPath</ObjectName> <AbsolutePath>$(_Escaped_PackageTempDir)\\App_Data\\.*</AbsolutePath> <XPath> </XPath> </MsDeploySkipRules> </ItemGroup></Target> Package, do not deploy the project. This will create a zip file and .cmd file in the target directory (defined by "Location where package will be created" on the Package/Publish Web Tab). By default, this is obj\Debug\Package (or obj\Release\Package) Deploy the site using the the resulting command file In my testing, you must package and run the command file. The project file tweaks will tell msbuild to put the necessary -skip rule into the command file. However, using the "publish" feature straight from VS 2010 doesn't seem to run the command file (see the warning on this walkthrough )...it calls msdeploy directly and doesn't seem to honor the project file skip rules. I believe this is the difference between VS using msbuild -T:Package and msbuild -T:MsDeployPublish to build the project, but I have not tested this. Finally, the command file isn't quite correct, at least in VS 2010 SP1. There's a great description of what goes wrong in this SO answer , but basically, VS (or maybe the /t:Package target is a better culprit) sets up the command file to publish to the machine without specifying a site. To fix that, you'll need to somehow get "?site= sitename " (probably this is ?site=Default+Web+Site, for a full URL of https:// machine :8172/MsDeploy.axd?site=Default+Web+Site) onto the end of the computerName argument. The problem I had was that the command file (batch file) has a hard time with using site= anything on the command line since it mis-parses the command line argument (even if escaped). I don't see a way around this problem other than modifying the cmd file directly, but for testing I copied the msdeploy.exe output I saw from my failed test run and modified that to call msdeploy.exe directly without the script. Now that it's working, my intention is to work this into my CI build processes. What I'll be doing for the final solution is: Change my build script to use /T:Package (right now it's /T:MsDeploy) Have a scripted search/replace routine alter the generated cmd deployment script Run the altered deployment script This really should be easier. Update Here's the scripted search/replace routine I've come up with in PowerShell: (Get-Content "project.deploy.cmd") -replace('^set _ArgComputerName=$' ,"set ArgComputerName=https://server:8172/MsDeploy.axd?Site=Default+Web+Site") | Out-File -Encoding ascii deploy.cmd Once that is run, deploy.cmd can be called (without the /M option) and it will work as expected.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8900005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113225/']}
jdg_372191
stackexchange
llm_judgeable_groundtruth_similarity
34663539
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using scipy.optimize.fmin_l_bfgs_b to solve a gaussian mixture problem. The means of mixture distributions are modeled by regressions whose weights have to be optimized using EM algorithm. sigma_sp_new, func_val, info_dict = fmin_l_bfgs_b(func_to_minimize, self.sigma_vector[si][pj], args=(self.w_vectors[si][pj], Y, X, E_step_results[si][pj]), approx_grad=True, bounds=[(1e-8, 0.5)], factr=1e02, pgtol=1e-05, epsilon=1e-08) But sometimes I got a warning 'ABNORMAL_TERMINATION_IN_LNSRCH' in the information dictionary: func_to_minimize value = 1.14462324063e-07information dictionary: {'task': b'ABNORMAL_TERMINATION_IN_LNSRCH', 'funcalls': 147, 'grad': array([ 1.77635684e-05, 2.87769808e-05, 3.51718654e-05, 6.75015599e-06, -4.97379915e-06, -1.06581410e-06]), 'nit': 0, 'warnflag': 2}RUNNING THE L-BFGS-B CODE * * *Machine precision = 2.220D-16 N = 6 M = 10 This problem is unconstrained.At X0 0 variables are exactly at the boundsAt iterate 0 f= 1.14462D-07 |proj g|= 3.51719D-05 * * *Tit = total number of iterationsTnf = total number of function evaluationsTnint = total number of segments explored during Cauchy searchesSkip = number of BFGS updates skippedNact = number of active bounds at final generalized Cauchy pointProjg = norm of the final projected gradientF = final function value * * * N Tit Tnf Tnint Skip Nact Projg F 6 1 21 1 0 0 3.517D-05 1.145D-07 F = 1.144619474757747E-007ABNORMAL_TERMINATION_IN_LNSRCH Line search cannot locate an adequate point after 20 function and gradient evaluations. Previous x, f and g restored. Possible causes: 1 error in function or gradient evaluation; 2 rounding error dominate computation. Cauchy time 0.000E+00 seconds. Subspace minimization time 0.000E+00 seconds. Line search time 0.000E+00 seconds. Total User time 0.000E+00 seconds. I do not get this warning every time, but sometimes. (Most get 'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL' or 'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'). I know that it means the minimum can be be reached in this iteration. I googled this problem. Someone said it occurs often because the objective and gradient functions do not match. But here I do not provide gradient function because I am using 'approx_grad'. What are the possible reasons that I should investigate? What does it mean by "rounding error dominate computation"? ====== I also find that the log-likelihood does not monotonically increase: ########## Convergence !!! ##########log_likelihood_history: [-28659.725891322563, 220.49993177669558, 291.3513633060345, 267.47745327823907, 265.31567762171181, 265.07311121000367, 265.04217683341682] It usually start decrease at the second or the third iteration, even through 'ABNORMAL_TERMINATION_IN_LNSRCH' does not occurs. I do not know whether it this problem is related to the previous one. Now provide the response and nothing else.
Scipy calls the original L-BFGS-B implementation. Which is some fortran77 (old but beautiful and superfast code) and our problem is that the descent direction is actually going up. The problem starts on line 2533 (link to the code at the bottom) gd = ddot(n,g,1,d,1) if (ifun .eq. 0) then gdold=gd if (gd .ge. zero) thenc the directional derivative >=0.c Line search is impossible. if (iprint .ge. 0) then write(0,*)' ascent direction in projection gd = ', gd endif info = -4 return endif endif In other words, you are telling it to go down the hill by going up the hill. The code tries something called line search a total of 20 times in the descent direction that you provide and realizes that you are NOT telling it to go downhill, but uphill. All 20 times. The guy who wrote it (Jorge Nocedal, who by the way is a very smart guy) put 20 because pretty much that's enough. Machine epsilon is 10E-16, I think 20 is actually a little too much. So, my money for most people having this problem is that your gradient does not match your function . Now, it could also be that "2. rounding errors dominate computation". By this, he means that your function is a very flat surface in which increases are of the order of machine epsilon (in which case you could perhaps rescale the function),Now, I was thiking that maybe there should be a third option, when your function is too weird. Oscillations? I could see something like $\sin({\frac{1}{x}})$ causing this kind of problem. But I'm not a smart guy, so don't assume that there's a third case. So I think the OP's solution should be that your function is too flat. Or look at the fortran code. https://github.com/scipy/scipy/blob/master/scipy/optimize/lbfgsb/lbfgsb.f Here's line search for those who want to see it. https://en.wikipedia.org/wiki/Line_search Note. This is 7 months too late. I put it here for future's sake.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34663539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1118236/']}
jdg_372192
stackexchange
llm_judgeable_groundtruth_similarity
146524
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: Say you have to choose only one among the following authentication types for your own SMTP server: LOGIN, PLAIN CRAM-MD5 DIGEST-MD5 NTLM/SPA/MSN Which one would you recommend for optimal security? PS: The list is the authentification types given in man swaks Now provide the response and nothing else.
With SSL/TLS it's okay to use LOGIN / PLAIN . You should provide SMTP on top of an SSL-encrypted connection. While some schemes from your list (e.g. DIGEST-MD5 ) can keep a password secure even over an untrusted channel, they won't protect users from a man-in-the-middle attacker tampering with their session. (Commonly, email servers wrap SMTP via direct TLS or a connection upgrade with STARTTLS at the ports 465/587.) Any SMTP auth type, regardless if you use PLAIN or an advanced method, just provides application level authentication. But what you want is transport level security . After a user is authenticated over SMTP, there will be no automatically encrypted connection. Per the SMTP protocol, commands and emails are exchanged with the server in plain text, allowing a man-in-the-middle attacker to read and modify the communication and inject new commands. That's why you should provide it on top of SSL encryption, just like HTTPS provides HTTP on top of SSL. The HTTP analogy: If you secure your website with HTTPS, then it doesn't matter that the a login form actually transmits your password as a plain string in the POST body of the HTTP request, because the data transport is SSL-encrypted. Enabling CRAM-MD5 for SMTP is analogous to implementing a challenge-response scheme in Javascript before transmitting login credentials to a website. (You can occasionally see that technique in router interfaces which don't provide HTTPS but it's not very common.) As for a real-life example, GMail is fine with offering LOGIN / PLAIN authentication (where credentials are sent in plan text) after having established a secure SSL connection: $ openssl s_client -starttls smtp -connect smtp.gmail.com:587 ...250 SMTPUTF8EHLO foo250-smtp.gmail.com at your service, [127.0.0.1]250-SIZE 35882577250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH 250-ENHANCEDSTATUSCODES250-PIPELINING... (As you can see, they also provide some methods you didn't list, e.g. XOAUTH2 for OAuth2 tokens which might be interesting if you're after passwordless authentication.)
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/146524', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/126446/']}
jdg_372193
stackexchange
llm_judgeable_groundtruth_similarity
43663206
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 code doesn't run as expected in Python3 when I do my data-analysing practice. The typeerror is "TypeError: unsupported operand type(s) for /: 'dict_values' and 'int'". How should I solve it? import numpy as np# Summarize the data about minutes spent in the classroomtotal_minutes = total_minutes_by_account.values()total_minutes = np.array(total_minutes)print('Mean:', np.mean(total_minutes))print('Standard deviation:', np.std(total_minutes))print('Minimum:', np.min(total_minutes))print('Maximum:', np.max(total_minutes)) Now provide the response and nothing else.
Hopefully this helps: The class is written in Python 2, where Dict.values() returns a list, but this was updated in Python 3 to return a dictionary view, described here: https://docs.python.org/3/library/stdtypes.html#dict-views It's a potentially helpful change because the view will update when the content of the dictionary updates, but they don't behave like a List , and numpy's mean , std , min , and max all take a list as their argument.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43663206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7932477/']}
jdg_372194
stackexchange
llm_judgeable_groundtruth_similarity
2363841
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have two red points, $r_1$ and $r_2$, and two blue points, $b_1$ and $b_2$. They are all placed randomly and uniformly in $[0,1]^2$. Each dot points to the closest dot from another colour; closest is defined wrt the Euclidean distance. We use $x \to y$ to indicate dot $x$ points to dot $y$. If $r_1 \to b_1$, what is the probability that $r_2 \to b_1$ too? NOTE it must be larger than 1/2 because $r_1 \to b_1$ tells us in a way that $b_1$ is likely to have a centric location, and thus is likely than it is closer to $r_2$ too than $b_2$. Now provide the response and nothing else.
Let $g(x) = p'''(x)$. Deriving the condition $p(x+1) = p(x) + 3x(x+1)+1$ three times, we get $$p'''(x+1) = p'''(x)\implies g(x+1) = g(x).$$ Now, $g$ is still polynomial and the last line tells us that if $\alpha$ is a root of $g$, so is $\alpha \pm 1$ and hence, by induction, so is $\alpha + n$ for any integer $n$. Thus, either $g$ has no roots or infinitely many roots. The only polynomials that satisfy this are constant polynomials, i.e. $g\equiv const.$ Since $g(x) = p'''(x)$, it means that $p$ has degree $3$, i.e. $$p(x) = ax^3+bx^2+cx+d.$$ Substitute this into the starting condition and calculate $a=1,\ b = c = 0$, and thus $$p(x) = x^3+d.$$ Conversely, any polynomial of the form $x^3 + d$ is a solution of the problem.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2363841', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/171684/']}
jdg_372195
stackexchange
llm_judgeable_groundtruth_similarity
6466253
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 told that, in C++03, temporaries are implicitly non-modifiable. However, the following compiles for me on GCC 4.3.4 (in C++03 mode): cout << static_cast<stringstream&>(stringstream() << 3).str(); How is this compiling? (I am not talking about the rules regarding temporaries binding to references.) Now provide the response and nothing else.
I'm told that, in C++03, temporaries are implicitly non-modifiable. That is not correct. Temporaries are created, among other circumstances, by evaluating rvalues, and there are both non-const rvalues and const rvalues. The value category of an expression and the constness of the object it denotes are mostly orthogonal 1 . Observe: std::string foo();const std::string bar(); Given the above function declarations, the expression foo() is a non-const rvalue whose evaluation creates a non-const temporary, and bar() is a const rvalue that creates a const temporary. Note that you can call any member function on a non-const rvalue, allowing you to modify the object: foo().append(" was created by foo") // okay, modifying a non-const temporarybar().append(" was created by bar") // error, modifying a const temporary Since operator= is a member function, you can even assign to non-const rvalues: std::string("hello") = "world"; This should be enough evidence to convince you that temporaries are not implicitly const. 1: An exception are scalar rvalues such as 42. They are always non-const .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6466253', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/560648/']}
jdg_372196
stackexchange
llm_judgeable_groundtruth_similarity
3504
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: A few years back I heard at biology class that sugar's molecule consists of half the number of elements of a glucose molecule. So not counting the energy needed to transform two sugar molecules in one glucose molecule, isn't it almost the same (eating N amount of sugar) as eating N/2 of glucose? Now provide the response and nothing else.
You have it backwards. One sugar molecule is equivalent to two glucose molecules, though the actual structure of sugar ( Sucrose ) is a Glucose + Fructose combination. While Glucose is metabolized via Glycolysis into two molecules of Pyruvate (which are then used in the Citric Acid Cycle), Fructose enters the Glycolysis metabolism at a later stage as shown here: The GA-3-P is then turned into 2-Phosphoglycerate and then into 2x Pyruvate. The end result is that a single Sucrose molecule (Glucose + Fructose) [aka - Sugar] is equivalent to 4x Pyruvate, whereas Glucose alone is equivalent to 2x Pyruvate. Or, if you prefer, a single Glucose molecule results in about 32-36 ATP produced, whereas Sucrose will result in 64-72 ATP produced - with ATP being the primary energy carrier of the cell.
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/3504', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/1373/']}
jdg_372197
stackexchange
llm_judgeable_groundtruth_similarity
35278
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Quite certainly, muted mosquitoes would be much more effective as far as their blood-sucking pursuits are concerned, since mosquito sound is predominantly responsible for sealing their fate (between the two palms of the hand). Muting themselves would certainly reduce the chances of being caught in the act. For instance, unless you notice by looking, leeches go undetected for long periods because there isn't any obvious sound emanating from them. Thus, reasoning says - this should be favorable from the point of view of evolution, unless there is a some indispensable purpose served by this sound, which can not be otherwise served. This page seems to suggest that this is so from the point of view of mating. In fact, quoting verbatim: Since female mosquitoes are larger, they flap their wings slower, and males know it. They use the distinctive pitch of the females' buzz to recognize them. Louis M. Roth, who studied yellow fever mosquitoes for the U.S. Army during World War II, noticed that males ignored females whenever the females were quietly resting, but whenever the females were flying, and therefore buzzing, the males wanted to mate with them. The males even wanted to mate with recordings of female mosquitoes or tuning forks that vibrated at the same pitch. But mating signals could also be of other forms, like some chemicals secreted (I envisage something like pheremones). Why is making sound so important? Why can't this noise be either less intense, or lie outside the audio range for humans (their targets)? Now provide the response and nothing else.
Your question is really good, but in actuality, they do evolve towards muting themselves, actually, they have pretty much done "most of the work": It is assumed that microscopic scales along veins and wind marginplay an important role as a silencer as downs on the flight feather of owl. From this we can assume that the effectiveness of these scales are high, as they had plenty of time to evolve; thus the other factor they should alter to make them quieter is the frequency of their flapping $f$, which can be calculated from the following equation: $$f=K m^{-1/6}$$ where $m$ is the mass of the animal and $K$ is the proportionality constant. The resulting number is around several hundred hertz (Remi.b observed a value around 440 Hz) There are two options for them, either increasing the frequency up until our ear is incapable of hearing it which would be impossible as even the highest flapping frequency can hardly exceed 1000 Hz, which is nowhere near the required 20,000 Hz. By increasing their body mass they could decrease the frequency but the needed 15-20 Hz is pretty low compared to the actual several hundred, thus it would likely need a complete body structure change which is not something to happen in the near-future. An another solution might be a different strategy in flying. Gliding attacks might pay off really well (that's why owls on the other hand can't be heard during flight), but even though there are some insects capable of such [1] , it would need an immerse amount of time, not talking about the problems that might arise from the bumping into of our body. I don't think that the mating signaling would be indispensable from an evolutionary perspective, but this statement of mine can't be proved. These are the physical/biological difficulties of the problem, here is one from an evolutionary aspect: They are not likely to have experienced a strong selection against this feature, as most of the possible victims are incapable of doing much against a mosquito due to the absent of hands (and tails are seldom enough to stop them). The first possibly blood-sucking mosquito was found to be living 79 million years ago, while animals that might be able to "seal their fate" are much more recent, while not even having success most of the time. https://www.jstage.jst.go.jp/article/jsmec1997/43/4/43_4_895/_pdf http://www.geologica-acta.com/pdf/aghv3501a12.pdf http://www.physics.emory.edu/faculty/weeks//lab/papers/jwang-arf05.pdf
{}
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/35278', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/15494/']}
jdg_372198
stackexchange
llm_judgeable_groundtruth_similarity
3132309
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: Taking the angle at center as $x$ , I got $r \sin x =2$ . But after that how to proceed? Now provide the response and nothing else.
The triangles $ABE$ and $FGD$ are similary so $${3\over 1} = {2\over x} \implies x = 2/3$$ where $x= FG$ . Let $s= EF$ . Then by the power of the point $G$ we have $$x(x+s)=2^2 \implies s= 16/3\implies EG=6$$ By Pythgora theorem for triangles $BGE$ and $BDG$ we have $$3^2+6^2 =BG^2 = 2^2 +(2r-1)^2$$ so $$r={1+\sqrt{41}\over 2}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3132309', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/590250/']}
jdg_372199
stackexchange
llm_judgeable_groundtruth_similarity
871565
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: Whenever I take a definite integral in aim to calculate the area bound between two functions, what is the meaning of a negative result? Does it simly mean that the said area is under the the x - axis, in the negative domain of the axis? Now provide the response and nothing else.
Not always. The definite integral of a positive function (that is a function over the $x$-axis) gives a positive area. This is,$$\int_a^b f(x) dx \geq 0$$ for a function such that $f(x) \geq 0$ when $a<x<b$. On the other hand, the definite integral of a negative function (that is a function under the $x$-axis) gives a negative area. This is$$\int_a^b f(x) dx \leq 0$$ for a function such that $f(x) \leq 0$ when $a<x<b$. Now, the problem comes when you have a function that goes for a while over the $x$-axis, and for another while under it. For example, let's assume that goes over the axis on the interval $[a,c]$ and under it on the interval $[c,b]$. That is$$ f(x)\geq 0 \text{ when } a<x<c, $$$$ f(x)\leq 0 \text{ when } c<x<b. $$Then the integral can be split in two as$$\int_a^b f(x) dx = \int_a^c f(x) dx + \int_c^b f(x) dx = A_1 + A_2,$$where $A_1\geq 0$ and $A_2 \leq 0$. Then, depending on which of the two areas $A_1$ and $A_2$ is "bigger" the result of the definite integral will be positive or negative. That is,$$ \text{If } |A_1|\geq|A_2| \text { then } \int_a^b f(x) dx \geq 0 ,$$$$ \text{If } |A_1|\leq|A_2| \text { then } \int_a^b f(x) dx \leq 0 .$$ To sum it up, a negative definite integral means that there is "more area" under the $x$-axis than over it.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/871565', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/90230/']}
jdg_372200
stackexchange
llm_judgeable_groundtruth_similarity
2276689
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 a piece of code that I can't figure out how to unit test! The module pulls content from external XML feeds (twitter, flickr, youtube, etc.) with urllib2. Here's some pseudo-code for it: params = (url, urlencode(data),) if data else (url,)req = Request(*params)response = urlopen(req)#check headers, content-length, etc...#parse the response XML with lxml... My first thought was to pickle the response and load it for testing, but apparently urllib's response object is unserializable (it raises an exception). Just saving the XML from the response body isn't ideal, because my code uses the header information too. It's designed to act on a response object. And of course, relying on an external source for data in a unit test is a horrible idea. So how do I write a unit test for this? Now provide the response and nothing else.
urllib2 has a functions called build_opener() and install_opener() which you should use to mock the behaviour of urlopen() import urllib2from StringIO import StringIOdef mock_response(req): if req.get_full_url() == "http://example.com": resp = urllib2.addinfourl(StringIO("mock file"), "mock message", req.get_full_url()) resp.code = 200 resp.msg = "OK" return respclass MyHTTPHandler(urllib2.HTTPHandler): def http_open(self, req): print "mock opener" return mock_response(req)my_opener = urllib2.build_opener(MyHTTPHandler)urllib2.install_opener(my_opener)response=urllib2.urlopen("http://example.com")print response.read()print response.codeprint response.msg
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2276689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114672/']}
jdg_372201
stackexchange
llm_judgeable_groundtruth_similarity
15610
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have an electrical problem with my 96 Jeep Grand Cherokee. The alternator whines and the battery gauge drops to zero. I put a new battery in and a new alternator and it didn't fix the problem. any advice? Now provide the response and nothing else.
Most likely cause is a bad motor. Give the bottom of the door panel a good whack. Careful if it's cold as you can crack the door panel. This may be enough to jar the brushes in the motor to make it work long enough to get the window up. Another way to tell if it's the window motor is with the dome light on, watch the light when you push the up or down button on the drivers window. If the light dims when you push the switch it's the window motor. Ultimately you can take the door panel off, actually may be the door skin that comes off on that model to gain access to the motor itself. Check for power and ground by back probing at the motor while operating the switch.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/15610', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/9553/']}
jdg_372202
stackexchange
llm_judgeable_groundtruth_similarity
35747524
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 Api is accepting Content-Type application/json as headers.I set Header perfectly as mentioned in Retrofit Docs. @Headers("Content-Type: application/json")@POST("user/classes")Call<playlist> addToPlaylist(@Body PlaylistParm parm); But in Request Log it is Returning Content-Type txt/html.So how i should fix this issue? This api works fine in POSTMAN Now provide the response and nothing else.
you can try one in below my solutions : @POST("user/classes")Call<playlist> addToPlaylist(@Header("Content-Type") String content_type, @Body PlaylistParm parm); then call mAPI.addToPlayList("application/json", playListParam); Or Create HttpClient object OkHttpClient httpClient = new OkHttpClient(); httpClient.networkInterceptors().add(new Interceptor() { @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { Request.Builder requestBuilder = chain.request().newBuilder(); requestBuilder.header("Content-Type", "application/json"); return chain.proceed(requestBuilder.build()); } }); Then add to retrofit object Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35747524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1655430/']}
jdg_372203
stackexchange
llm_judgeable_groundtruth_similarity
4645582
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: Problem Let $f$ be a continuous function, $f:[0,1]\to\mathbb{R}$ with $\int_{0}^1 (2x-1)f(x) dx = 0$ . Prove that there exists a point c between $(0, 1)$ such that $\int_{0}^c (x-c)(f(x)-f(c)) dx = 0$ . This problem was given at a regional competition in Romania for $12$ th grade students. Attempt From Rolle's Theorem we have that there exists q such that $f(q) = (2q - 1)f(q) = 0$ , where we have $f(q)=0$ . My other attempt was: fix $p$ to $0.5$ and separate according to the Mean Value Theorem for Integrals $\int_{0}^1 (2x-1)f(x) dx = 0$ into $-f(c1) * \int_{0}^p (1-2x) dx$ $+ $ $f(c2) * \int_{p}^1 (2x-1) dx = 0$ where we get that $f(c1)=f(c2)$ Now provide the response and nothing else.
Meaning no disrespect to the existing answer, there is a much simpler solution. Consider the continuously differentiable function $\Lambda:[0,1]\to\Bbb R$ given by: $$c\mapsto\int_0^c(2xc-c^2)f(x)\,\mathrm{d}x$$ $\Lambda(0)=0=\Lambda(1)$ by assumption. By “Rolle’s” theorem, $\Lambda’(c)=0$ for some distinguished $c$ in $(0,1)$ . For this $c$ , we then know (Leibniz integral rule): $$0=(2c^2-c^2)f(c)(1)+\int_0^c\partial_c[(2xc-c^2)f(x)]\,\mathrm{d}x=2\int_0^c(x-c)(f(x)-f(c))\,\mathrm{d}x$$ As desired.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4645582', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/862948/']}
jdg_372204
stackexchange
llm_judgeable_groundtruth_similarity
29218994
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am making a list view within a fragment. Following is my code: TitleQuote.java package com.example.ishan.fragmentquote;import android.app.ListActivity;import android.content.Intent;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;public class QuoteList extends ListActivity { @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_quote_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_quote_list, container, false); Intent intent = getActivity().getIntent(); String quote = intent.getStringExtra(TitleQuote.INDEX); if(quote != null) { TextView tv = (TextView) rootView.findViewById(R.id.quoteView); tv.setText("ishan"); } return rootView; } }} fragment_title_quote.xml <ListView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/titleList" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> fragment_quote_list.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin"tools:context="com.example.ishan.fragmentquote.QuoteList$PlaceholderFragment"android:weightSum="1"><TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/quoteView" android:textSize="30sp" /></LinearLayout> listview.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent"><TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView" /></LinearLayout> when i build the project on android studio, everythin works fine i see no error/warnings. When i run this on an emulator/phone I get Unfortunately FragmentQuote has stopped. the logcat error specifies : 2119-2119/com.example.ishan.fragmentquote E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.ishan.fragmentquote, PID: 2119 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference Now provide the response and nothing else.
You are using the same timeout interval as Jasmine is using to fail tests on timeout, i.e. your timeout is triggered to fire with Jasmine's default interval, which fails the test. If you set your timeout to be less than jasmine default timeout the test passes. describe('foo', function () { beforeEach(function (done) { window.jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(function () { console.log('inside timeout'); done(); }, 500); }); it('passes', function () { expect({}).toBeDefined(); });}); See fiddle here
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29218994', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2972348/']}
jdg_372205
stackexchange
llm_judgeable_groundtruth_similarity
302743
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Sometimes it is not easy to formulate a correct question. Here is a better version of this question (I still do not know if it is optimal, but it is better than the previous one). We say that a set $X$ of natural numbers is symmetric group definable if there exists a first order formula $\theta$ in the group signature such that a symmetric group $S_n$ satisfies $\theta$ if and only if $n\in X$. Of course finite sets and sets with finite complements are symmetric group definable. It is not completely trivial to find any infinite set of natural numbers with infinite complement which is symmetric group definable. But it is not a difficult exercise to show that the set of numbers $n$ such that either $n$ or $n-1$ is prime is such a set. Question. Is any of the following sets symmetric group definable? 1) the set of even numbers 2) the set of prime numbers A more vague question Is there a characterization of the Boolean algebra of symmetric group definable sets? Update Noam D. Elkies' answer below shows that the Boolean algebra contains many sets. Noah Schweber's answer of the previous question suggests looking at the computational complexity of $X$. Clearly, checking whether $n$ belongs to a symmetric group definable set $X$ takes time at most $(n!)^k$ where $k$ is the number of quantifiers in the corresponding formula $\theta$. So we have a couple of even better questions. Question 1 Is the converse true, that is every set of numbers recognizable by deterministic a Turing machine in time $\le (n!)^k$ for some $k$ symmetric group definable? Here the size of a number $n$ is $n$ that is we consider the unary representation of natural numbers. Question 2 Let us replace $S_n$ by, say, $SL_n(\mathbb{F}_2)$ and similarly define $SL_n(\mathbb{F}_2)$-definable sets of numbers. Will the Boolean algebra of all $SL_n(\mathbb{F}_2)$-definable sets coincide with the Boolean algebra of all deterministic polynomial time decidable sets of natural numbers? Question 3 Can the statements that "Primes are in P" be proved this way? Now provide the response and nothing else.
It's possible to embed within the theory of the permutation group $S_n$ the theory of second-order arithmetic for numbers between $0$ and $n-1$. Using this we can construct propositions corresponding to any property of $n$ that can be determined by a Turing machine with resource bound that roughly corresponds to a maximum of $\sqrt {n}$ steps. With additional quantifiers we can add a finite amount of alternation to this complexity class and get a PH-like complexity class. As Noam Elkies points out, for $n > 6$ simple transpositions are characterized by a first-order property. To be self-contained, I'll repeat his definition: $g$ is a simple transposition if $g^2 = 1$ and for any conjugate $g'$ of $g$, the order of $g g'$ is either $1$, $2$, or $3$. Next, it is possible to encode a point in the underlying set acted on by the permutation group (that is, a point in $[n] = \{1, 2, \dots, n\}$) as pair of simple transpositions $(g_0, g_1)$ such that $g_0 g_1$ has order $3$, which represent the unique point which is transposed on both $g_0$ and $g_1$. The pairs $(g_0, g_1)$ and $(h_0, h_1)$ represent the same point if and only if for each $i \in \{0, 1\}$ and $j \in \{0, 1\}$ the product $g_i h_j$ is either the identity or order $3$. Next, given a permutation $g$ and a point $x$ encoded by $(h_0, h_1)$, the action of $g$ on $x$ is encoded by $(g^{-1} h_0 g, g^{-1} h_1 g)$. Seeing as we can quantify over all the points and compare points for equality, any two-sorted formula involving both permutations and points can be translated into an equivalent formula involving only permutations. Therefore I can freely incorporate points into my language for defining properties. Permutations can also encode sets of points: Given a permutation $g$, define $Q (g)$ to be the set of all points not fixed by $g$. Then the sets $Q (g)$ for all $g \in S_n$ vary over all subsets of $[n]$ other than the ones with a single point. Then if $\phi (X)$ is a formula with a variable $X$ representing a subset of $X$, we can translate the quantifier $\forall X. \phi (X)$ into $\forall g \in S_n. \phi 45 (Q (g)) \land \forall x \in [n]. \phi (\{x\})$, where $\phi (Q (g))$ means we replace all instances of $y \in X$ with $g (y) \neq y$, and $\phi (\{x\})$ means we replace all instances of $y \in X$ with $x = y$. The formula $\exists X. \phi (X)$ is translated similarly. Therefore we can also add subsets of $[n]$ into our language. I define that $g_0$ is cyclically contained in $g_1$ if for every point $x$ either $g_0 (x) = x$ or $g_0 (x) = g_1 (x)$. Equivalently, the cyclic decomposition of $g_0$ is a subset of the cyclic decomposition of $g_1$, not counting fixed points as cycles. Then a cycle can be defined as a permutation that is not the identity and such that every permutation cyclically contained in it is either equal to it or equal to the identity. A maximal cycle is a cycle without any fixed points. For everything below, I will fix a maximal cycle $S$ and a point $O$. The lettering is intended to be suggestive of Peano arithmetic. A permutation commutes with $S$ if and only if it is a power of $S$. I define the addition relation $x + y = z$ to mean that there exists a permutation $g$ which commutes with $S$ such that $g (O) = x$ and $g (y) = z$. I will denote by $x+y$ the unique point $z$ such that $x + y = z$. I call a permutation $g$ linear if $g (x + y) = g (x) + g (y)$ for all $x$ and $y$. $x$ is call invertible if there is a linear permutation $g$ such that $g S (O) = x$. If $x$ is invertible I define the product $x \cdot y$ to be $g (y)$ for the unique such $g$. For an arbitrary $x$ I define $x \cdot y = z$ if there is a decomposition $x = x_0 + x_1$ or $x = x_0 + x_1 + x_2$ with $x_0, x_1, x_2$ all invertible and $z = x_0 \cdot y + x_1 \cdot y$ or $z = x_0 \cdot y + x_1 \cdot y + x_2 \cdot y$, respectively. To define the order relation we can use subsets: I define $x < y$ if there is a subset $X \subseteq [n]$ such that $S (x) \in X$. If $a \in X$, then either $a = y$ or $S (a) \in X$. $O \notin X$. Using all of the definition above as tools it should be possible to define whether some tuple of subsets $X_0, \dots, X_{r-1}$ denote a Turing machine computation. With a naive encoding of the computation as a concatenation of the state of the Turing machine at every time step, it is necessary that the computation terminate before the spacetime resource usage is greater than a fixed multiple of $n$, where the spacetime resource usage is defined as the sum of the space usage over each time step. With this it should be possible to define "$X_0$ encodes the binary representation of $x$" whenever $x$ less than the square root of $n$, by giving the input $x$ in unary. The binary representation of $n$ can be determined via a formula $n = x \cdot y + z$ where $y$ is a power of $2$ (definable as in Peano arithmetic) and $z < y$ and given the binary representations of $x$ and $z$. Verifying $n = x \cdot y + z$ comes down to the identity $x \cdot y + z = O$ plus the claim that $x \cdot y$ doesn't overflow. $n$ can also be split into three components to give more leeway for constant and logarithmic factors. Giving the binary representation of $n$ as input to a Turing machine allows defining all properties that checkable by a Turing machine with these resource bounds. More sophisticated encoding schemes, making full use of the information encoded by a permutation rather than just thinking of it as a subset, should lead to a higher computational capacity. Using alternating quantifiers $\forall Y_0 \exists Y_1 \forall Y_2 \dots \exists Y_{s-1}$ and including $Y_0, \dots, Y_{s-1}$ as inputs to the computation, it should be possible to define all properties within a PH-like complexity class where the final verification step is restricted to computations with this spacetime resource bound or whatever resource cost the more sophisticated encoding takes.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/302743', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_372206
stackexchange
llm_judgeable_groundtruth_similarity
1493274
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: Show that the sequence $(x_n)=c^{\frac{1}{n}}$ is increasing for $0 < c < 1$. I am trying to do this using induction. We see for the base case that $x_1 = c$ and $x_2 = c^{0.5}$, so clearly $x_1 < x_2$. For the induction step, we assume $x_n < x_{n+1} \Leftrightarrow c^{\frac{1}{n}} < c^{\frac{1}{n+1}}$. This is where I am stuck. How can we show that our assumption implies that $x_{n+1}<x_{n+2}$? Now provide the response and nothing else.
Define the function $f: (0,2) \rightarrow \mathbb{R}$ as $$f(x) = \left\{ \begin{array}{ccc}x& & x\in(0,1)\\ x+1& & x\in[1,2)\end{array}\right.$$ This $f$ is continuous on $A=(0,1)$ and $B=[1,2)$ but not on $A\cup B$. However, if $A$ and $B$ are either both open or both closed and the function value agrees on their intersection then $f$ will be continuous.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1493274', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/250846/']}
jdg_372207
stackexchange
llm_judgeable_groundtruth_similarity
18060268
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 WPF project in which I have 4 TextBlock . What I want is to change the Text of each TextBlock via Binding . So far I have my XAML: <Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <TextBlock x:Name="First" Text="{Binding FirstString}" Grid.Row="0"/> <TextBlock x:Name="Second" Text="{Binding SecondString}" Grid.Row="1"/> <TextBlock x:Name="Third" Text="{Binding ThirdString}" Grid.Row="2"/> <TextBlock x:Name="Fourth" Text="{Binding FourthString}" Grid.Row="3"/></Grid> And in my code I have: public partial class MainWindow : Window{ public string FirstString { get; set; } public string SecondString { get; set; } public string ThirdString { get; set; } public string FourthString { get; set; } public MainWindow() { InitializeComponent(); FirstString = "First"; SecondString = "Second"; ThirdString= "Third"; FourthString= "Fourth"; }} But the Binding doesn't work at all. Am I doing something wrong? EDIT:After following Chris Mantle's suggestion in the comments to look at the debug output (I had to enable Warnings for the Binding), I get the following error: System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=FirstString; DataItem=null; target element is 'TextBlock' (Name='First'); target property is 'Text' (type 'String') Now provide the response and nothing else.
There are a few things that are incorrect. The Binding markup will look at the object in the DataContext property of the control. This property inherits the DataContext from the declaring parent unless otherwise specified. Out of the box, this is null for a Window control. There are two options for this problem. You can either set the DataContext explicitely in the code-behind or the XAML // In XAML<Window DataContext={Binding RelativeSource={RelativeSource Self}}>or// In the code-behindDataContext = this; Another problem is that the binding is applied at initialization. Initially, your properties are empty. After the InitializeComponent phase, the controls will "bind" to the properties (which are empty). When you set your properties afterward, the controls have no way to know it has changed. There are two mechanism to allow this. On the control level, you can make these properties as DependencyProperty or implement the INotifyPropertyChanged interface and raise the changes. If you want to go the INPC route, you can implement your properties and Window as such: public partial class MainWindow : INotifyPropertyChanged{ private string firstString; private string secondString; private string thirdString; private string fourthString; public string FirstString { get { return firstString; } set { firstString = value; RaisePropertyChanged("FirstString"); } } public string SecondString { get { return secondString; } set { secondString = value; RaisePropertyChanged("SecondString"); } } public string ThirdString { get { return thirdString; } set { thirdString = value; RaisePropertyChanged("ThirdString"); } } public string FourthString { get { return fourthString; } set { fourthString = value; RaisePropertyChanged("FourthString"); } } public MainWindow() { DataContext = this; InitializeComponent(); FirstString = "First"; SecondString = "Second"; ThirdString = "Third"; FourthString = "Fourth"; } public event PropertyChangedEventHandler PropertyChanged = delegate { }; private void RaisePropertyChanged(string propertyName) { var handlers = PropertyChanged; handlers(this, new PropertyChangedEventArgs(propertyName)); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18060268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2509925/']}
jdg_372208
stackexchange
llm_judgeable_groundtruth_similarity
415327
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Some years ago at my university, I recall that the labs there booted Windows NT over the network. There was a shared drive for your own stuff and other than that any changes you did to the running OS were reset when you restarted the machine. Now I'd like to be able to do the same thing with Windows 7. I have found some how to's for this using iSCSI, but I don't want an iSCSI disk for every single PC, I want one image for multiple PC's. I've also found PXE Boot setup files for installing Windows locally, but that's not what I want either. How would I go about setting up what I had at university but with Windows 7 as a OS to netboot? i.e. How do I netboot Windows 7 images? I do not want to netboot a Windows 7 installer to a PC to install Windows locally, I want to run a Windows 7 image from memory/network. Now provide the response and nothing else.
To answer my own question. It is possible using iPXE and iSCSI or AoE. The idea is to either replace the network card option ROM with iPXE or to chainload ipxe and then do a sanboot. iSCSI is the easier of the two san protocols because you can actually install Windows 7 directly to an iSCSI target. This is because iSCSI support is built into windows 7 while AoE is not. See: archive.org mirror of windowsdiskless.wordpress.com Or: archive.org mirror of windowsdisklessaoe.wordpress.com Noting of course that although iSCSI supports multiple machines accessing the same target with NTFS. Corruption will occur. Either a Copy on Write mechanism at the back end needs to be employed, or create a base image (template) and copy that to a newly exported target. I ended up patching the open source iscsi target from freebsd and adding copy on write. So I could use the same LUN but the writes were directed elsewhere. I was able to direct them to local RAM or to another file on the server. I'm not using this anymore though, it was a proof of concept.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/415327', 'https://serverfault.com', 'https://serverfault.com/users/14631/']}
jdg_372209
stackexchange
llm_judgeable_groundtruth_similarity
264946
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: If I have (a+b I)^(c+d I) and the result is e+f I a,b,c,d should be integers e >= 2 or e <= -2 f so close to zero as possible .. this is the object function I want to minimize How to do this in Mathematica? Something like this below, but I cannot figure it out NMinimize[{function, constraint, constraint, Element[{a,b,c,d}, Integers]}, {a,b,c,d}] Now provide the response and nothing else.
Let's search explicitly up to $\pm s$ : s = 50;A = Reap[Do[If[Min[Abs[{a, b, c, d}]] >= 2 && Abs[Re[N[(a + b I)^(c + d I)]]] >= 2, Sow[{a, b, c, d}]], {a, -s, s}, {b, -s, s}, {c, -s, s}, {d, -s, s}]][[2, 1]];B = MinimalBy[A, Abs[Im[N[(#[[1]] + #[[2]] I)^(#[[3]] + #[[4]] I)]]] &](* {{13, -39, 5, -11}, {13, 39, 5, 11}} *)(#[[1]] + #[[2]] I)^(#[[3]] + #[[4]] I) & /@ B(* {(13 - 39 I)^(5 - 11 I), (13 + 39 I)^(5 + 11 I)} *)% // N(* {-126.685 + 2.13912*10^-7 I, -126.685 - 2.13912*10^-7 I} *) Update With a C code I've searched up to $s=1024$ , getting a speedup of around 80 compared to Mathematica. The best result so far is (533 - 276 I)^(-6 + 85 I) // N(* 9.29623 - 4.15874*10^-10 I *) Code: #include <complex.h>#include <math.h>#include <stdio.h>#include <stdlib.h>static void run(const int nmax) { double imin = 2; for (int a = -nmax; a <= nmax; a++) if (abs(a) >= 2) for (int b = -nmax; b <= nmax; b++) if (abs(b) >= 2) { const double complex x = a + I * b; for (int c = -nmax; c <= nmax; c++) if (abs(c) >= 2) for (int d = 2; d <= nmax; d++) { const double complex y = c + I * d; const double complex z = cpow(x, y); if ((fabs(creal(z)) >= 2) && (fabs(cimag(z)) < imin)) { imin = fabs(cimag(z)); printf("(%d,%d,%d,%d) --> %g + I * %g\n", a, b, c, d, creal(z), cimag(z)); } } }}int main() { run(1024); return EXIT_SUCCESS;} Save as complex.c , compile with gcc complex.c -lm -O3 -o complex and run with ./complex A bit of analysis Here's an incomplete analysis of a possible way forward. We are looking for numbers $(a,b,c,d)$ such that $(a+i b)^{c+i d}$ has a small imaginary part. This means that $\arg[(a+i b)^{c+i d}]\approx n\pi$ for an integer value $n$ : $$\arg[(a+i b)^{c+i d}]=c \arg(a+i b)+d\ln\sqrt{a^2+b^2}\approx n\pi, n\in\mathbb{Z}$$ For given integer values of $(a,b)$ we can therefore calculate the values $\gamma=\frac{\arg(a+i b)}{\pi}=\frac{\tan^{-1}(b/a)}{\pi}$ and $\delta=\frac{\ln\sqrt{a^2+b^2}}{\pi}=\frac{\ln(a^2+b^2)}{2\pi}$ , and then try to find integers $(c,d)$ such that $c\gamma+d\delta$ is as close to an integer as possible. I don't know how to do this in practice but it sounds like a typical numerical math problem. I've tried using Rationalize and ContinuedFraction to convert $(\gamma,\delta)$ to rationals and setting $(c,d)$ as their respective denominators; but there were no good results coming out of this approach. Maybe someone else will have a better idea for going forward.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/264946', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/85051/']}
jdg_372210
stackexchange
llm_judgeable_groundtruth_similarity
12945
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a little problem to realize a AP solution on a small office environment. At first I do not have any skills in configuring Cisco Access Points ;) I have the following environment: A small office about 15 people and a network which is segmented into 2 VLANs (VLAN100 for clients and RADIUS server and VLAN200 for guests with very restricted access. The AP is connected on a L3 switch port with access on both VLANs. Now if someone uses the AP, an authentication is required over the RADIUS server in VLAN100. On the RADIUS server I configured the NPS server role (Windows Server 2008R2) with 2 network policies (for each VLAN one policy) to grant access by successfull authentication. Finally I have the problem if someone authenticates himself by using a guest account, he gets no network connectivity cause he does not know the VLAN. - Are there best practice tutorials for CISCO APs with RADIUS and VLANs or something like that, maybe someone has a better idea to realize that authentication/VLAN tagging procedure? Ok here is the config, maybe I made a mistake: Current configuration : 4225 bytes!! Last configuration change at 01:17:55 +0100 Mon Mar 1 1993version 15.2no service padservice timestamps debug datetime msecservice timestamps log datetime msecservice password-encryption!hostname AP01!!logging rate-limit console 9!aaa new-model!!aaa group server radius rad_eap server 172.0.0.30!aaa authentication login eap_methods group rad_eapaaa authorization exec default local!!!!!aaa session-id commonclock timezone +0100 1 0no ip routingno ip cefip domain name domain.localip name-server 172.0.0.31ip name-server 172.0.0.30ip name-server 172.0.0.28!!!no dot11 syslog!dot11 ssid WLAN-SSID vlan 100 authentication open eap eap_methods authentication key-management wpa version 2 mbssid guest-mode!!power inline negotiation prestandard sourcecrypto pki token default removal timeout 0!!bridge irb!!!interface Dot11Radio0 no ip address no ip route-cache ! encryption vlan 100 mode ciphers aes-ccm ! encryption mode ciphers aes-ccm ! encryption vlan 200 mode ciphers aes-ccm ! ssid WLAN-SSID ! antenna gain 0 stbc beamform ofdm mbssid station-role root bridge-group 1 bridge-group 1 subscriber-loop-control bridge-group 1 spanning-disabled bridge-group 1 block-unknown-source no bridge-group 1 source-learning no bridge-group 1 unicast-flooding!interface Dot11Radio0.100 encapsulation dot1Q 100 no ip route-cache bridge-group 100 bridge-group 100 subscriber-loop-control bridge-group 100 spanning-disabled bridge-group 100 block-unknown-source no bridge-group 100 source-learning no bridge-group 100 unicast-flooding!interface Dot11Radio0.200 encapsulation dot1Q 200 no ip route-cache bridge-group 200 bridge-group 200 subscriber-loop-control bridge-group 200 spanning-disabled bridge-group 200 block-unknown-source no bridge-group 200 source-learning no bridge-group 200 unicast-flooding!interface Dot11Radio1 no ip address no ip route-cache ! encryption vlan 100 mode ciphers aes-ccm ! encryption mode ciphers aes-ccm ! encryption vlan 200 mode ciphers aes-ccm ! ssid WLAN-SSID ! antenna gain -128 no dfs band block stbc beamform ofdm mbssid channel dfs station-role root bridge-group 1 bridge-group 1 subscriber-loop-control bridge-group 1 spanning-disabled bridge-group 1 block-unknown-source no bridge-group 1 source-learning no bridge-group 1 unicast-flooding!interface Dot11Radio1.100 encapsulation dot1Q 100 no ip route-cache bridge-group 100 bridge-group 100 subscriber-loop-control bridge-group 100 spanning-disabled bridge-group 100 block-unknown-source no bridge-group 100 source-learning no bridge-group 100 unicast-flooding!interface Dot11Radio1.200 encapsulation dot1Q 200 no ip route-cache bridge-group 200 bridge-group 200 subscriber-loop-control bridge-group 200 spanning-disabled bridge-group 200 block-unknown-source no bridge-group 200 source-learning no bridge-group 200 unicast-flooding!interface GigabitEthernet0 no ip address no ip route-cache duplex auto speed auto bridge-group 1 bridge-group 1 spanning-disabled no bridge-group 1 source-learning!interface GigabitEthernet0.100 encapsulation dot1Q 100 no ip route-cache bridge-group 100 bridge-group 100 spanning-disabled no bridge-group 100 source-learning!interface GigabitEthernet0.200 encapsulation dot1Q 200 no ip route-cache bridge-group 200 bridge-group 200 spanning-disabled no bridge-group 200 source-learning!interface BVI1 ip address 172.0.10.5 255.255.255.0 no ip route-cache!interface BVI100 ip address dhcp no ip route-cache!interface BVI200 ip address dhcp no ip route-cache!ip default-gateway 172.0.10.250ip forward-protocol ndip http serverip http authentication aaano ip http secure-serverip http help-path http://www.cisco.com/warp/public/779/smbiz/prodconfig/help/eagip radius source-interface BVI1!radius-server host 172.0.0.30 key *******!bridge 1 route ip!!!line con 0line vty 0 4 transport input all!sntp broadcast clientend Now provide the response and nothing else.
Mystery solved. The Windows 7 computer was continuously receiving TCP SYN packets to the 9100 port from another computer in the same LAN, waking up as a result when "Wake on Pattern Match" was activated. This port is used by network printers. The IP of the Windows 7 computer belonged before to a long-time discarded HP printer. The computer sending the packets is old, and it is always on as it is used sometimes to run software that only works in Windows XP. This computer still had the old network printer configured, pointing to the local IP address that now belongs to the Windows 7 computer having the problems. There were still documents in the printing queue, so the Windows XP computer was continuously sending TCP SYN packets to the Windows 7 computer, thinking it was the network printer. Removing the old printer from Windows XP and its associated TCP/IP Printer Port solved the problem. I could not catch this traffic between both computers from mine using Wireshark. I had to install it on the affected computer and run it with promiscuous mode disabled.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/12945', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/10260/']}
jdg_372211
stackexchange
llm_judgeable_groundtruth_similarity
97382
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 simple circuit consisting of 2 ideal voltages sources (each 5V) parallel to a resistor of 5 ohms. The current along the resistor is 1A, right? But by applying the superposition principle (i.e. considering individual sources), I am not getting this result. Am I doing some blunder? Now provide the response and nothing else.
Ideal circuits with two voltage sources in parallel lead to contradiction, unless they are equal and can be simply replaced with a single one. Note that potentials \$ \varphi_1 \$ and \$ \varphi_2 \$ in your circuit must be equal, since there is no impedance of any kind between them, nor do ideal voltage sources have any internal resistance: In your case, luckily, these sources produce the same voltage, so the simplest thing to do is to simply remove one of them from the circuit. If you had two ideal sources of a different voltage in parallel, that would lead to contradiction. In a real circuit, connecting two sources in parallel would lead to a circuit with a very small, but still non-zero resistance between them, which would result in one of the sources (the one with a slightly lower voltage) actually sinking current, but the current through the 5 ohm resistor would only depend on the voltage of the right source. If you want to put some actual numbers, you can try something like this: Note that if the sources are again ideal and have completely equal voltages, there will still be no current flowing through the tiny resistance between them, but you should be able to apply the superposition principle. For a circuit like this, the mesh current method should provide the simplest solution and show that the current through the resistor only depends on the right source.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/97382', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/27702/']}
jdg_372212
stackexchange
llm_judgeable_groundtruth_similarity
25060103
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to determine the sum of a two dimensional numpy array. However, elements with a certain value I want to exclude from this summation. What is the most efficient way to do this? For example, here I initialize a two dimensional numpy array of 1s and replace several of them by 2: import numpydata_set = numpy.ones((10, 10))data_set[4][4] = 2data_set[5][5] = 2data_set[6][6] = 2 How can I sum over the elements in my two dimensional array while excluding all of the 2s? Note that with the 10 by 10 array the correct answer should be 97 as I replaced three elements with the value 2. I know I can do this with nested for loops. For example: elements = []for idx_x in range(data_set.shape[0]): for idx_y in range(data_set.shape[1]): if data_set[idx_x][idx_y] != 2: elements.append(data_set[idx_x][idx_y])data_set_sum = numpy.sum(elements) However on my actual data (which is very large) this is too slow. What is the correct way of doing this? Now provide the response and nothing else.
Use numpy's capability of indexing with boolean arrays . In the below example data_set!=2 evaluates to a boolean array which is True whenever the element is not 2 (and has the correct shape). So data_set[data_set!=2] is a fast and convenient way to get an array which doesn't contain a certain value. Of course, the boolean expression can be more complex. In [1]: import numpy as npIn [2]: data_set = np.ones((10, 10))In [4]: data_set[4,4] = 2In [5]: data_set[5,5] = 2In [6]: data_set[6,6] = 2In [7]: data_set[data_set != 2].sum()Out[7]: 97.0In [8]: data_set != 2Out[8]: array([[ True, True, True, True, True, True, True, True, True, True], [ True, True, True, True, True, True, True, True, True, True], ... [ True, True, True, True, True, True, True, True, True, True]], dtype=bool)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25060103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2776885/']}
jdg_372213
stackexchange
llm_judgeable_groundtruth_similarity
10233517
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been trying to get non-repeating arc4random_uniform to work for ages now for my iPhone app. Been over all the questions and answers relating to this on stackoverflow with no luck and now I'm hoping someone can help me. What I want to do is is choose 13 different random numbers between 1 and 104. I have gotten it to work to the point of it choosing 13 different numbers, but sometimes two of them are the same. int rand = arc4random_uniform(104); This is what I'm doing, and then I'm using the rand to choose from an array. If it's easier to shuffle the array and then pick 13 from the top, then I'll try that, but I would need help on how to, since that seems harder. Thankful for any advice. Now provide the response and nothing else.
There's no guarantee whatsoever that ar4random_uniform() won't repeat. Think about it for a second -- you're asking it to produce a number between 0 and 103. If you do that one hundred and five times, it has no choice but to repeat one of its earlier selections. How could the function know how many times you're going to request a number? You will either have to check the list of numbers that you've already gotten and request a new one if it's a repeat, or shuffle the array. There should be any number of questions on SO for that. Here's one of the oldest: What's the Best Way to Shuffle an NSMutableArray? . There's also quite a few questions about non-repeating random numbers: https://stackoverflow.com/search?q=%5Bobjc%5D+non-repeating+random+numbers
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10233517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1338741/']}
jdg_372214
stackexchange
llm_judgeable_groundtruth_similarity
33357233
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 the flow of using asyncio in Python 3.5 but I haven't seen a description of what things I should be await ing and things I should not be or where it would be neglible. Do I just have to use my best judgement in terms of "this is an IO operation and thus should be await ed"? Now provide the response and nothing else.
By default all your code is synchronous. You can make it asynchronous defining functions with async def and "calling" these functions with await . A More correct question would be "When should I write asynchronous code instead of synchronous?". Answer is "When you can benefit from it". In cases when you work with I/O operations as you noted you will usually benefit: # Synchronous way:download(url1) # takes 5 sec.download(url2) # takes 5 sec.# Total time: 10 sec.# Asynchronous way:await asyncio.gather( async_download(url1), # takes 5 sec. async_download(url2) # takes 5 sec.)# Total time: only 5 sec. (+ little overhead for using asyncio) Of course, if you created a function that uses asynchronous code, this function should be asynchronous too (should be defined as async def ). But any asynchronous function can freely use synchronous code. It makes no sense to cast synchronous code to asynchronous without some reason: # extract_links(url) should be async because it uses async func async_download() insideasync def extract_links(url): # async_download() was created async to get benefit of I/O html = await async_download(url) # parse() doesn't work with I/O, there's no sense to make it async links = parse(html) return links One very important thing is that any long synchronous operation (> 50 ms, for example, it's hard to say exactly) will freeze all your asynchronous operations for that time: async def extract_links(url): data = await download(url) links = parse(data) # if search_in_very_big_file() takes much time to process, # all your running async funcs (somewhere else in code) will be frozen # you need to avoid this situation links_found = search_in_very_big_file(links) You can avoid it calling long running synchronous functions in separate process (and awaiting for result): executor = ProcessPoolExecutor(2)async def extract_links(url): data = await download(url) links = parse(data) # Now your main process can handle another async functions while separate process running links_found = await loop.run_in_executor(executor, search_in_very_big_file, links) One more example: when you need to use requests in asyncio. requests.get is just synchronous long running function, which you shouldn't call inside async code (again, to avoid freezing). But it's running long because of I/O, not because of long calculations. In that case, you can use ThreadPoolExecutor instead of ProcessPoolExecutor to avoid some multiprocessing overhead: executor = ThreadPoolExecutor(2)async def download(url): response = await loop.run_in_executor(executor, requests.get, url) return response.text
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/33357233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1076057/']}
jdg_372215
stackexchange
llm_judgeable_groundtruth_similarity
7596364
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anyone please tell me difference in usage of cancelBubble and stopPropagation methods used in Javascript. Now provide the response and nothing else.
cancelBubble is an IE-only Boolean property (not method) that serves the same purpose as the stopPropagation() method of other browsers, which is to prevent the event from moving to its next target (known as "bubbling" when the event is travelling from inner to outer elements, which is the only way an event travels in IE < 9). IE 9 now supports stopPropagation() so cancelBubble will eventually become obsolete. In the meantime, the following is a cross-browser function to stop an event propagating: function stopPropagation(evt) { if (typeof evt.stopPropagation == "function") { evt.stopPropagation(); } else { evt.cancelBubble = true; }} In an event handler function, you could use it as follows: document.getElementById("foo").onclick = function(evt) { evt = evt || window.event; // For IE stopPropagation(evt);};
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7596364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/970539/']}
jdg_372216
stackexchange
llm_judgeable_groundtruth_similarity
690458
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: Trying to find the sum of the telescopic series. Can't seem to figure it out! Please Help!$$\sum_{1}^{\infty}(\tan^{-1}(n+4)-\tan^{-1}(n+2))$$I've tried looking at other examples, but they're not helping. Now provide the response and nothing else.
Hint . It doesn't matter much what the function is, telescopic series always work much the same way. For example if we have a finite sum,$$\eqalign{\smash{\sum_{n=1}^N \bigl(f(n+4)-f(n+2)\bigr)} &=f(5)-f(3)+f(6)-f(4)\cr &\quad{}+f(7)-f(5)+f(8)-f(6)\cr &\quad{}+\cdots\cr &\quad{}+f(N+3)-f(N+1)+f(N+4)-f(N+2)\ .\cr}$$Now if you look carefully you will see that many terms cancel and we get$$\sum_{n=1}^N \bigl(f(n+4)-f(n+2)\bigr) =-f(3)-f(4)+f(N+3)+f(N+4)\ .$$For your problem you need to replace $f$ by $\arctan$, then see what happens as $N\to\infty$. Good luck!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/690458', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/131511/']}
jdg_372217
stackexchange
llm_judgeable_groundtruth_similarity
48768298
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having trouble understanding what's the reason for the crash in the following code : class A {public: virtual ~A() { goo(); } void goo() { absFoo(); } virtual void absFoo() = 0;};class B : public A {public: void absFoo() { cout << "In B \n"; }};int main() { B b1; b1.goo();} The main prints "In B" as expected, but in the end when it crashes, I can't debug it either, the compiler pops a weird message. So my question is, when the destructor of A calls "goo()", does "absFoo()", crash because we're referring to an abstract function? Or does the compiler actually look for a definition in the derived classes? (And it doesn't exist anymore because it was destructed beforehand so it crashes) I know that if we had called "absFoo()" directly from the destructor, the reason would have been the abstract function. But since here it's an outside function calling "absFoo()" I'm having trouble understanding the real reason. Now provide the response and nothing else.
What happens when a destructor calls an abstract function First, let us consider what happens when a destructor calls any virtual function (the same applies to the constructor by the way): When a virtual function foo is called in the destructor of T , the call will not be dispatched dynamically to an implementation in a derived type (the lifetime of any derived object has already ended), but statically to the implementation T::foo . If T::foo is pure virtual, then calling it without dynamic dispatch will have undefined behaviour. That is what happens when a pure virtual function is (indirectly) called in a destructor (or constructor).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48768298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7770967/']}
jdg_372218
stackexchange
llm_judgeable_groundtruth_similarity
796808
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 found this one on a forum but it has been unanswered from long there. I am curious to know if there is a solution to this problem. Here it is: Let n be a positive integer. Determine the smallest possible value of$$|p(1)|^2+|p(2)|^2 + .........+ |p(n+3)|^2$$over all monic polynomials p with degree n. I don't have much idea about the problem. I can go about by assuming $p$ to be some monic polynomial and find $p(1)$, $p(2)$.... in terms of the coefficients but I don't think that is going to help. This is some inequality related problem, I guess. Any help is appreciated. Thanks! PS: Can somebody please check if I have added the proper tags? I am not sure where this kind of problem should belong. Now provide the response and nothing else.
An easier proof only uses the fact that $\operatorname{Ext}^1(-,-)$ is an additive functor in each argument. Consider how multiplication by $n$ acts on $\operatorname{Ext}^1(\mathbb{Q},\mathbb{Z}/n\mathbb{Z})$. On the one hand, multiplication by $n$ acts as an isomorphism on the first argument $\mathbb{Q}$, and so as an isomorphism on $\operatorname{Ext}^1(\mathbb{Q},\mathbb{Z}/n\mathbb{Z})$. On the other hand, multiplication by $n$ acts as zero on the second argument $\mathbb{Z}/n\mathbb{Z}$, and so as zero on $\operatorname{Ext}^1(\mathbb{Q},\mathbb{Z}/n\mathbb{Z})$. Which is a contradiction unless $\operatorname{Ext}^1(\mathbb{Q},\mathbb{Z}/n\mathbb{Z})=0$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/796808', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/117767/']}
jdg_372219
stackexchange
llm_judgeable_groundtruth_similarity
3495903
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 wsdl from a web service, I generated the wcf proxy. No problem. But I can not get my head around how to pass the user name and password. The webservice requires basic authentication - only username and password. Any help ? Now provide the response and nothing else.
Is Basic authentication configured in configuration file? Do you need to pass only credentials or do you also need secured transport (HTTPS)? First you need to set up binding to support Basic authentication Setup for HTTP binding: <bindings> <basicHttpBinding> <binding name="BasicAuth"> <security mode="TransportCredentialOnly"> <transport clientCredentialType="Basic" /> </security> </binding> </basicHttpBinding></bindings> Setup for HTTPS binding: <bindings> <basicHttpBinding> <binding name="BasicAuthSecured"> <security mode="Transport"> <transport clientCredentialType="Basic" /> </security> </binding> </basicHttpBinding></bindings> Client endpoint has to use defined configuration like: <client> <endpoint address="..." name="..." binding="basicHttpBinding" bindingConfiguration="BasicAuth" contract="..." /></client> Then you have to pass credentials to the proxy: proxy = new MyServiceClient();proxy.ClientCredentials.UserName.UserName = "...";proxy.ClientCredentials.UserName.Password = "...";
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3495903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191803/']}
jdg_372220
stackexchange
llm_judgeable_groundtruth_similarity
24185227
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 web application which has few charts on dashboard. The data for charts is fetched on document.ready function at client side invoking a WCF service method. What i want is now to use SignalR in my application. I am really new to SignalR. How can i call WCF methods from SignalR Hub or what you can say is that instead of pulling data from server i want the WCF service to push data to client every one minute. Is there a way of communication between signalR and WCF service. Also another approach can be to force client to ask for data from WCF Service every minute. Any help will be really appreciated. I have done following as of yet. Client Side Function on my Dashboard page <script src="Scripts/jquery.signalR-2.0.3.min.js"></script> <!--Reference the autogenerated SignalR hub script. --> <script src="/signalr/hubs"></script><a id="refresh">Refresh</a> $(function() { var dashboardHubProxy = $.connection.dashboardHub; $.connection.hub.start().done(function() { // dashboardHubProxy.server.refreshClient(parameters); $("#refresh").click(function() { dashboardHubProxy.server.refreshClient(parameters); }); }); dashboardHubProxy.client.refreshChart = function (chartData) { debugger; DrawChart(chartData, 'Hourly Call Count For Last ' + Duration + ' Days', '#chartHourly', 'StackedAreaChart'); }; }); and my Dashboard Hub class is as follows public class DashboardHub : Hub{ private readonly ReportService ReportService = new ReportService(); public void RefreshClient(string parameters) { var chartData = ReportService.GenerateHourlyCallsTrendGraphicalReport(parameters); Clients.All.refreshChart(chartData); }} My SignalR startup class is as follows [assembly: OwinStartup(typeof(CallsPortalWeb.Startup), "Configuration")]namespace CallsPortalWeb{ public static class Startup { public static void Configuration(IAppBuilder app) { ConfigureSignalR(app); } public static void ConfigureSignalR(IAppBuilder app) { app.MapSignalR(); } }} When i click on refresh button and a debugger on RefreshClient method on hub the debugger doesn't get to the method which means i am unable to call server side method of SignalR. Is there anything needs to be done in web.config? Now provide the response and nothing else.
I agree with AD.Net's comment. To elaborate slightly more though, the SignalR hubs can be hosted directly in your web project kinda the same way controllers are used. There is also a package out there so you can host the SignalR library on its own so it can act as a service all on its own. Either way you will need to hit the SignalR hub first as that is how it communicates then you would call your WCF service methods from within the hubs. Brief explanation Your HUB will have methods used by both your USER Client and your WCF Client. You may use something like UserConnected() for the user to call in and setup your logging of the connection. Then the WCF service may call your HUB with an UpdateUserStats(Guid connnectionId, UserStats stats) which would in turn call the USER client directly and provide the stats passed in like so Clients.Client(connectionId).updateStats(stats) which in turn would have a method on the USERS client named updateStats() that would handle the received information. Initial page landing What AD.Net provided is basic code that will be called when the user lands on the page. At this point you would want to log the ConnectionId related to that user so you can directly contact them back. First contact with your hub touching WCF From your Hub, you could call your WCF service as you normally would inside any normal C# code to fetch your data or perform action and return it to your user. Method of updating the user periodically SignalR removes the need for your client code to have to continually poll the server for updates. It is meant to allow you to push data out to the client with out them asking for it directly. This is where the persistence of the connections come into play. You will probably want to create a wrapper to easily send messages to the hub from your application, since you are using WCF I would assume you have your business logic behind this layer so you will want the WCF service reaching out to your Hub whenever action X happens. You can do that by utilizing the Client side C# code as in this case your client is actually the user and the WCF service. With a chat application the other user is basically doing what you want your WCF service to do, which is send a message to the other client. Usage example You are running an online store. The dashboard displays how many orders there have been for the day. So you would wire up a call to the hub to send a message out to update the products ordered when a user places a new order. You can do this by sending it to the admin group you have configured and any admins on the dashboard would get the message. Though if these stats are very user specific, you will more then likely instead reach into the database, find the ConnectionId that the user has connected with and send the update message directly to that connectionid. WCF Client Code Example Just incase you want some code, this is directly from MS site on connecting with a .net client. You would use this in your WCF service, or wherever in your code you plan on connecting and then sending an update to your user. var hubConnection = new HubConnection("http://www.contoso.com/");IHubProxy stockTickerHubProxy = hubConnection.CreateHubProxy("StockTickerHub");stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock => Console.WriteLine("Stock update for {0} new price {1}", stock.Symbol, stock.Price));await hubConnection.Start(); Here is a link directly to the .Net Client section: http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client I am sure you have seen this link but it really holds all the good information you need to get started. http://www.asp.net/signalr Here is a more direct link that goes into usages with code for you. http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-server ADDED: Here is a blog specific to Dashboards with SignalR and their polling. http://solomon-t.blogspot.com/2012/12/signalr-and-interval-polling-for.html ADDED: Here is a page on managing users signalR connections. http://www.asp.net/signalr/overview/signalr-20/hubs-api/mapping-users-to-connections Update for your code update The .Net Client library (in NuGet) gives your .net code access to the hub. Since you are a client you will need to connect to the hub just like the User who is also a client. Your hub would act as the server for this. So with the .Net Client I am assuming you would setup a windows service that would internally poll, or something event based that would call the .Net Client code portion of it which would reach out to your hub. Your hub would take the information provided, more than likely a ConnectionId or GroupId and broad cast the User (which is perhaps on a website so it would be the JS client) a method that would update the front end for the user client. Basically what I mention under "Brief Explanation". Now, to directly respond to the code you posted. That is Javascript, I would expect a connect like you have done. Updating the chart on initial connection is fine as well. If this is all the code signalR wise though you are missing a client side method to handle the refresh. Technically, instead of calling Clients.Caller.RefreshChart() you could just return that data and use it, which is what your javascript is doing right now. You are returning void but it is expecting a your date. Now, I would actually say correct your javascript instead of correcting the hub code. Why? Because having a method in JS on your client that is called "refreshChart()" can be reused for when you are having your server reach out and update the client. So I would recommend, dropping anything that is related to updating the dashboard in your JS done statement. If you want to do a notification or something to the user that is fine but dont update the grid. Now create a JS client function called "refreshChart", note the lower case R, you can call it with a big R in c# but the js library will lowercase it so when you make the function have it will receive your dashboard information. Now, on the server polling, or executing on some action, your WCF would call a method on the hub that would be say "UpdateDashboar(connectionId,dashInfo)" and that method would then inside of it call the "refreshChart" just like you are doing in your RefreshClient method, accept instead of doing Clients.Caller you would use Clients.Client(connectionId).refreshChart(chartInfo). Directly the reason your code is not working is because you need to turn that Void into the type you expect to be returned. If the rest is coded right you will have it update once. You will need to implement the other logic I mentioned if you want it constantly updating. Which is again why I asked about how you are persisting your connections. I added a link to help you with that if you are not sure what I am talking about.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24185227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1517000/']}
jdg_372221
stackexchange
llm_judgeable_groundtruth_similarity
13484482
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 applescript which will displays menu list and allow user to select menu items etc. It runs fine by itself. And now I try to run it in python. I get the No user interaction allowed. (-1713) error. I looked online. I tried the following: add on run function in the same applescript, so what i did is just add the main into the run on run tell application “AppleScript Runner” main() end tellend run i tried to run the above in python import osdef main(): os.system ('osascript -e "tell application "ApplesScript Runner" do script /Users/eee/applescript/iTune.scpt end tell"') if name == ' main ': main() Neither way works. Can anyone tell me how to do this correctly? Now provide the response and nothing else.
That's a common mistake. When you run a script using OSAScript from a shell, as you are doing, then you must tell an application to show any "display dialogs" or "choose list dialogs" or anything that requires user interaction. OSAScript can't show them so tell an app like the Finder to show them. Use code like this... tell application "Finder" activate display dialog "Now it works!"end tell Or from the command line notice this won't work... osascript -e 'display dialog "Now it will not work."' But this will work since we tell the Finder to do it... osascript -e 'tell application "Finder"' -e 'activate' -e 'display dialog "Now it works!"' -e 'end tell' So bottom line is that somewhere in your iTune.scpt you are displaying a dialog. In that script just tell iTunes or the Finder to display them.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13484482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1775679/']}
jdg_372222
stackexchange
llm_judgeable_groundtruth_similarity
232358
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I've isolated a property of rings (integral domains, associative, unitary, non necessarily commutative) that is useful to me : $$xR\cap yR\neq\{0\}\quad\text{ whenever $x$ and $y$ are non zero.}$$ Question. Does this property has a name, or falls into a known and labelled class of rings ? Commutative integral domains and division rings obviously have this property. Now provide the response and nothing else.
These rings are called right uniform rings. Generally, a right ideal $I$ is called (right) uniform if all nonzero right subideals $J,K\subseteq I$ have nonzero intersection: $J\cap K \neq 0$. Note: Your condition is equivalent to the condition that any two nonzero right ideals have nonzero intersection.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/232358', 'https://mathoverflow.net', 'https://mathoverflow.net/users/18583/']}
jdg_372223
stackexchange
llm_judgeable_groundtruth_similarity
3008772
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an application in which end-users can size and position images in a designer. Since the spec calls for the image to be "stretched" to the containing control, the end user can end up with an awkwardly stretched image. To help the user with image sizing I am thinking of implementing a smart resizer function which would allow the the user to easily fix the aspect ratio of the picture so that it no longer appears stretched. The quick way to solve this is to actually provide two options: 1) scale from width 2) scale from height. The user chooses the method and the algorithm adjusts the size of the picture by using the original aspect ratio. For example: A picture is displayed as 200x200 on the designer but the original image is 1024x768 pixels. The user chooses "Smart Size from width" and the new size becomes ~200x150 since the original aspect ratio is ~1.333 That's OK, but how could I make the algorithm smarter and not bother the user by asking which dimension the recalculation should be based on? Now provide the response and nothing else.
If I'm interpreting your spec correctly, you want a result that is no larger than the one the end-user laid out originally; you want one of the two dimensions to shrink, and the other to stay the same. In other words, the new size should fill the designer space in one direction while shortening the size in the other direction to retain the original aspect ratio. original_ratio = original_width / original_heightdesigner_ratio = designer_width / designer_heightif original_ratio > designer_ratio designer_height = designer_width / original_ratioelse designer_width = designer_height * original_ratio Often you'll be working with integer coordinates, but the divisions to produce the ratios above need to be floating point. Here's a rearrangement of the formula to be more integer friendly. Make sure your integers have the range to handle the maximum width*height. if original_width * designer_height > designer_width * original_height designer_height = (designer_width * original_height) / original_widthelse designer_width = (designer_height * original_width) / original_height
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3008772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47550/']}
jdg_372224
stackexchange
llm_judgeable_groundtruth_similarity
18474825
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to checkout from my SVN repo gives me svn: E195019: Redirect cycle detected for URL ... However, it appears as if this error only occurs when I am behind some (specific) proxy server. As discussed in other post (see tortoise svn giving me "Redirect cycle detected for URL 'domain/svn'" ), this error occurs if the SVN DAV is misconfigured, e.g., using SVNParentPath where one should use SVNPath. However, my configuration appears to be correct and - as far as I know - the problem only occurs when behind a proxy. The setup of the repository is more or less standard, e.g., ServerAlias svn.mydomain.com <Location /myrepo> DAV svn SVNPath /var/www/vhosts/mydomain.com/svn/myrepo AuthType Basic AuthName "mydomain svn" AuthUserFile /var/www/vhosts/svn.mydomain.com/conf/htpasswd-myproject # Allow read-only access to anyone, otherwise require # require authentication Require valid-user </Location> Now provide the response and nothing else.
(I given an answer to my own question, after using half a weekend to search for the solution): It appears as if this error message is related to the fact that the subversion repository is located in a directory svn/myrepo where the directory svn is also listed as the DocumentRoot of the subdomain svn.mydomain.com . That DocumentRoot directive was not obvious to me, since the document root of the subdomain was configered in a different conf file (I am using Plesk to maintain the server).This created some kind of ambiguity. Once I moved the document root of the subdomain to a different location, the error message went away. The problem was hard to track down, because - as far as I know - The error does not appear if the repo is located at the top level of the subdomain, i.e. <Location /> and SVNPath /var/www/vhosts/mydomain.com/svn in the above configuration. The error only shows up if the repo is accessed via a proxy. The clash with DocumentRoot was not so obvious, because it was a subdomain. So to summarize: the solution (when using Plesk) : Change the "DocumentRoot" of the subdomain in the Plesk setup (GUI) to something different form the SVN directory. The "DocumentRoot" of www.mydomain.com is httpdocs . The "DocumentRoot" of svn.mydomain.com was (by default) svn . I changed that to httpdocs-svn and the problem was gone. The folder httpdocs-svn isn't used in my setup since everything below svn.mydomain.com is handled by DavSVN.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18474825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231397/']}
jdg_372225
stackexchange
llm_judgeable_groundtruth_similarity
24404
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This answer says vlans 0 and 4095 are reserved. Wikipedia agrees that vlans 0 and 4095 are reserved. This article says that Cisco reserves vlan 1 (in addition to vlans 0 and 4095). But I am having trouble finding good information on what are these vlans reserved for? and/or why they are reserved? Please include good authoritative sources please or references to the spec. If I want to transmit/receive, is it a good rule of thumb to just not use vlans 0,1,4095? Now provide the response and nothing else.
The Wikipedia article you mention gives a succinct explanation: VLAN identifier (VID): a 12-bit field specifying the VLAN to which the frame belongs. The hexadecimal values of 0x000 and 0xFFF are reserved. All other values may be used as VLAN identifiers, allowing up to 4,094 VLANs. The reserved value 0x000 indicates that the frame does not carry a VLAN ID; in this case, the 802.1Q tag specifies only a priority and is referred to as a priority tag. On bridges, VID 0x001 (the default VLAN ID) is often reserved for a management VLAN; this is vendor-specific. The VID value 0xFFF is reserved for implementation use; it must not be configured or transmitted. 0xFFF can be used to indicate a wildcard match in management operations or filtering database entries. As you can see, there isn't really a usable VLAN 0 or 4095. Cisco uses VLAN 1 as a default VLAN, and management protocols (STP, CDP, DTP, etc) are sent on VLAN 1. You can use VLAN 1 for simple installations where there is no VLAN trunking, but good practice is to not put user data on VLAN 1 in a multi-VLAN environment.
{}
{'log_upvote_score': 5, 'links': ['https://networkengineering.stackexchange.com/questions/24404', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/16906/']}
jdg_372226
stackexchange
llm_judgeable_groundtruth_similarity
51580168
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 came from the C# background and I know how to implement this in C#, but I'm struggling with Kotlin.I've got 2 extension functions: fun <T> Foo<T>.myFunction(func: () -> Unit): Foo<T> and fun <T> Foo<T>.myFunction(func: () -> Foo<T>): Foo<T> Clearly, the return type of func is different in both functions. The first function executes it and returns this, the second executes func and returns the result of func.But it gives me an error: "Platform declaration clash: The following declarations have the same JVM signature". How to implement this correctly in Kotlin? Now provide the response and nothing else.
On the JVM, we have to contend with type erasure . Meaning essentially that the types ( T in this case) are thrown away in the compiled bytecode and that required checks are only done at compile time. Given that, you have to look at your function declaration with that in mind. Kotlin will define your function argument as a Function0 in both cases. Because the types are erased, () -> Unit and () -> Foo<T> both look the same in the bytecode. We can prove this out by decompiling the code you've provided (I renamed one of these myFunction2 to get this to work): public final class com/ginsberg/KotlinStuffKt { public final static myFunction(Lcom/ginsberg/Foo;Lkotlin/jvm/functions/Function0;)Lcom/ginsberg/Foo; public final static myFunction2(Lcom/ginsberg/Foo;Lkotlin/jvm/functions/Function0;)Lcom/ginsberg/Foo;} This is what the Kotlin compiler is generating (it does more, but I have removed the non-essential parts from this example). As you can see, our types are gone thanks to type erasure. And if we undo my change ( myFunction2 becomes myFunction ), there's no way at all to tell these apart. This is what the compiler is complaining about - if you erase the types the JVM can't tell these functions apart.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51580168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8524706/']}
jdg_372227
stackexchange
llm_judgeable_groundtruth_similarity
480172
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: Say $E \subset [0,1]$ is a null set. Let $f: [0,1] \rightarrow [0,1] $. Do you think $f(E)$ is a null set or not? Just being curious. (DEF): A set $A$ is null if given any $\epsilon > 0$, there exists a sequence of intervals $\{I_n\}_{n\geq1}$ such that $$ A \subseteq \bigcup _{n=1}^{\infty}I_n$$ and $$ \sum |I_n| < \epsilon $$ if $f$ is continuous, is $f(E)$ nullset or not? Now provide the response and nothing else.
For $n=2$, consider the function $f$ defined as: For $x\in T$, write $x$ as a ternary fraction with only the digits 0 and 2 . Replace every 2 with an 1 ; $f(x)$ is then the value of the resulting digit sequence interpreted as a binary fraction. Clearly $f$ is surjective $T\to [0,1]$. (It is the restriction of the Cantor function to $T$) Prove that the graph of $f$ -- that is, $\{(x,f(x))\mid x\in T\}$ -- is homeomorphic to $T$. Then distort this graph so it wraps around the origin. Generalizing this to higher $n$ should just be a matter of splitting $f$ into $n-1$ functions that extract disjoint sequences of digit positions from $x$. Alternatively, compose $f$ with a space-filling curve. (This option is probably easier to prove).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/480172', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42344/']}
jdg_372228
stackexchange
llm_judgeable_groundtruth_similarity
703073
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 are the deficiencies of the built-in BinaryFormatter based .Net serialization? (Performance, flexibility, restrictions) Please accompany your answer with some code if possible. Example: Custom objects being serialized must be decorated with the [Serializable] attribute or implement the ISerializable interface. Less obvious example: Anonymous types can not be serialized. Now provide the response and nothing else.
If you mean BinaryFormatter : being based on fields, is very version intolerant; change private implementation details and it breaks (even just changing it to an automatically implemented property ) isn't cross-compatible with other platforms isn't very friendly towards new fields is assembly specific (metadata is burnt in) is MS/.NET specific (and possibly .NET version specific) isn't obfuscation-safe isn't especially fast, or small output doesn't work on light frameworks (CF?/Silverlight) has a depressing habit of pulling in things you didn't expect (usually via event s) I've spent lots of time in this area, including writing a (free) implementation of Google's "protocol buffers" serialization API for .NET; protobuf-net This is: smaller output and faster cross-compatible with other implementations extensible contract-based obfuscation safe assembly independent is an open documented standard works on all versions of .NET (caveat: not tested on Micro Framework) has hooks to plug into ISerializable (for remoting etc) and WCF
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/703073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17174/']}
jdg_372229
stackexchange
llm_judgeable_groundtruth_similarity
41843
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given a bipartite graph $G = (A,B,E)$ where every vertex is colored either red or blue I am trying to minimize the number of blue vertices using the following operation: Choose a vertex $v_a$ in $A$ Flip the colors of $N[v_a]$, meaning that $v_a$ and every neighbor of $v_a$ will change color. Is there a polynomial time algorithm to select a recoloring set $X \subseteq A$ that will minimize the number of blue vertices? The number of recolorings needed is not relevant. Observe that the order of flipping does not matter, and for every vertex in $A$, you either flip it or you don't. We can think of the colors as a number which is incremented modulo 2. This yields a trivial $O(2^{|A|} \cdot n)$ algorithm. Now provide the response and nothing else.
The problem is NP-complete and is thus not likely to admit a polynomial time algorithm. Below is a proof of the NP-completeness of the problem, shown by a reduction from 1-in-3-SAT. Let $\phi$ be an instance of 1-IN-3-SAT, where we are given a 3-CNF-SAT formulaasked to find a satisfying assignment where each clause is satisfied by exactlyone literal. Let $V(\phi)$ be the set of $n$ variables, and $C(\phi)$ be theset of $m$ clauses. We construct an instance $G = (A,B,E)$ with a budget of $b = n + m$ (the allowednumber of blue vertices). For each variable $x \in V(\phi)$, construct two red vertices $v_x$ and$v_{\overline{x}}$ in $A$ together with $b+1$ blue vertices in $B$ adjacent toboth of them. This forces exactly one of $v_x$ or $v_{\overline{x}}$ to beflipped. We also end up with $n$ flipped "variable vertices", thus using thefirst part of the budget. Remark: $\{v_x, v_{\overline{x}} \mid x \in V(\phi)\}$ are the only vertices in$A$. For each clause, say $c = x \lor \overline{y} \lor z$, we create $b+1$ bluevertices and three extra red vertices $v_{x \in c},v_{\overline{y} \in c},v_{z\in c}$, all in $B$. Let $v_x,v_{\overline{y}},v_z$ all be fully adjacent tothe $b+1$ blue vertices and connect $v_x$ to $v_{x \in c}$, $v_y$ to$v_{\overline{y} \in c}$, and $v_z$ to $v_{z \in c}$. Now, since each clause gadget has $b+1$ blue vertices, we know that either one or three literals in that clause have been flipped. Suppose that three havebeen flipped for one of the clauses. But then we use at least budget $n + m +2$. Suppose that $\phi$ is a yes instance with a 1-in-3 assignment $\alpha: V(\phi)\to \{\top,\bot\}$. Flip every vertex which corresponds to $\alpha$. Sinceevery clause is satisfied by exactly one variable, for each clause there is nowone blue vertex, and for each variable, exactly one of them is blue, hence wehave $n + m = b$ blue vertices.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/41843', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/31050/']}
jdg_372230
stackexchange
llm_judgeable_groundtruth_similarity
14552
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We have a DAG. We have a function on the nodes $F\colon V\to \mathbb N$ (loosely speaking, we number the nodes). We would like to create a new directed graph with these rules: Only nodes with the same number can be contracted into the same new node. $F(x) \neq F(y) \Rightarrow x' \neq y'$. (However, $x' \neq y'\nRightarrow F(x) \neq F(y)$.) We add all the old edges between new nodes: $(x,y) \in E \land x' \neq y' \iff (x',y')\in E'$. This new graph is still a DAG. What is the minimal $|V'|$? What is an algorithm creating a minimal new graph? Now provide the response and nothing else.
One approach to solving this problem would be to use integer linear programming (ILP). Let's tackle the decision version of the problem: given $k$, is there a way to contract same-color vertices to get a DAG of size $\le k$? This can be expressed as an ILP instance using standard techniques. We're given the color of each vertex in the original graph. I suggest that we label each vertex with a label in $\{1,2,\dots,k\}$; all vertices with the same label and same color will be contracted. So, the decision problem becomes: does there exist a labelling, such that contracting all same-color same-label vertices yields a DAG? To express this as an integer linear program, introduce an integer variable $\ell_v$ for each vertex $v$, to represent the label on vertex $v$. Add the inequality $1 \le \ell_v \le k$. The next step is to express the requirement that the contracted graph must be a DAG. Notice that if there is a labelling of the form listed above, without loss of generality there exists such a labelling where the labels induce a topological sort on the contracted graph (i.e., if $v$ precedes $w$ in the contracted graph, then $v$'s label is smaller than $w$'s label). So, for each edge $v\to w$ in the original graph, we'll add the constraint that either $v$ and $w$ have the same label and same color, or else $v$'s label is smaller than $w$'s label. Specifically, for each edge $v\to w$ in the initial graph where $v,w$ have the same color, add the inequality $\ell_v \le \ell_w$. For each edge $v \to w$ where $v,w$ have different colors, add the inequality $\ell_v < \ell_w$. Now see if there is any feasible solution to this integer linear program. There will be a feasible solution if and only if the labelling is of the desired form (i.e., contracting all same-color same-label vertices yields a DAG). In other words, there will be a feasible solution if and only if there is a way to contract the original graph to a DAG of size $\le k$.We can use any integer linear programming solver; if the ILP solver gives us an answer, we have an answer to the original decision problem. Of course, this isn't guaranteed to complete in polynomial time. There are no guarantees. However, ILP solvers have gotten pretty good. I would expect that, for a reasonable-sized graph, you've got a decent chance that an ILP solver might be able to solve this problem in a reasonable amount of time. It's also possible to encode this as a SAT instance and use a SAT solver. I don't know whether that would be more effective. The ILP version is probably easier to think about, though. (I hope this is right. I haven't checked every detail carefully, so please double-check my reasoning! I hope I haven't gone awry somewhere.) Update (10/21): It looks like ILPs of this form can be solved in linear time, by processing the DAG in topologically sorted order and keeping track of the lower bound on the label for each vertex. This has me suspicious of my solution: have I made a mistake somewhere?
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/14552', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/10273/']}
jdg_372231
stackexchange
llm_judgeable_groundtruth_similarity
11765802
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 you cut (remove) a section from a bitmap???I want that section/shape to be removed.. leave transparent in place of section..Say shape is cercle or square.. Now provide the response and nothing else.
You should be able do this with a Porter-Duff color filter and a Canvas : public void punchHole(Bitmap bitmap, float cx, float cy, float radius) { Canvas c = new Canvas(bitmap); Paint paint = new Paint(); paint.setColorFilter(new PorderDuffColorFilter(0, PorderDuff.Mode.CLEAR)); c.drawCircle(cx, cy, radius, paint);} Well, that was wrong. However, using a Porter-Duff transfer mode does work: public void punchHole(Bitmap bitmap, float cx, float cy, float radius) { Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); canvas.drawCircle(cx, cy, radius, paint);} (The bitmap passed as an arg needs to be modifiable, of course.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11765802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967670/']}
jdg_372232
stackexchange
llm_judgeable_groundtruth_similarity
487159
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Logging in to my Webmin control panel, I noticed that virtually all of my disk space is full. I searched for the ten largest files/ directories on my system and found that a file called ibdata1 is taking up around 94GB of space. It resides in my /var/lib/mysql directory. What does ibdata1 do? Am I safe to remove it? My assumption is that it's a dump of some kind, but that's just a wild guess. Now provide the response and nothing else.
The file ibdata1 is the system tablespace for the InnoDB infrastructure. It contains several classes for information vital for InnoDB Table Data Pages Table Index Pages Data Dictionary MVCC Control Data Undo Space Rollback Segments Double Write Buffer (Pages Written in the Background to avoid OS caching) Insert Buffer (Changes to Secondary Indexes) Please note ibdata1's place in the InnoDB Universe (on Right Side) You can separate Data and Index Pages from ibdata1 by enabling innodb_file_per_table . This will cause any newly created InnoDB table to store data and index pages in an external .ibd file. Example datadir is /var/lib/mysql CREATE TABLE mydb.mytable (...) ENGINE=InnoDB; , creates /var/lib/mysql/mydb/mytable.frm innodb_file_per_table enabled, Data/Index Pages Stored in /var/lib/mysql/mydb/mytable.ibd innodb_file_per_table disabled, Data/Index Pages Stored in ibdata1 No matter where the InnoDB table is stored, InnoDB's functionality requires looking for table metadata and storing and retrieving MVCC info to support ACID compliance and Transaction Isolation . Here are my past articles on separating table data and indexes from ibdata1 Oct 29, 2010 : My Original Post in StackOverflow Nov 26, 2011 : ERROR 1114 (HY000) at line 6308 in file & The table user_analysis is full Feb 03, 2012 : Scheduled optimization of tables in MySQL InnoDB Mar 25, 2012 : Why does InnoDB store all databases in one file? Apr 01, 2012 : Is innodb_file_per_table advisable? WHAT TO DO NEXT You can continue having ibdata1 stored everything, but that makes doing LVM snapshots real drudgery (my personal opinion). You need to use my StackOverflow post and shrink that file permanently. Please run this query: SELECT ((POWER(1024,3)*94 - InnoDBDiskDataAndIndexes))/POWER(1024,3) SpaceToReclaimFROM(SELECT SUM(data_length+index_length) InnoDBDiskDataAndIndexesFROM information_schema.tables WHERE engine='InnoDB') A; This will tell how much wasted space can be reclaimed after applying the InnoDB Cleanup.
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/487159', 'https://serverfault.com', 'https://serverfault.com/users/97732/']}
jdg_372233
stackexchange
llm_judgeable_groundtruth_similarity
39586355
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: var numPills = 3 for(var i=0; i< numPills; i++){ //var currentPill = JUser.pill1.; $(".col-r-in").append( $('<div/>') .attr("id", "medsProgress") .addClass("roundedBar") ); $('#medsProgress').append( $('<div/>') .attr("id", "medsBar") ); $('#medsBar').append( $('<p/>') .attr("id", "appendPillName") ); $('#appendPillName').append("test"); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="medsProgress" class="roundedBar"> <div id="medsBar"> <p id="appendPillName">test test test</p> <p id="appendPillName"></p> <p id="appendPillName"></p> </div> <div id="medsBar"></div> <div id="medsBar"></div> </div> <div id="medsProgress" class="roundedBar"></div> <div id="medsProgress" class="roundedBar"></div> </div> Ok so in this for loop I am displaying 3 divs, that works well but the last append only appends the text "test" to only the first dive below is what the output is in html it only adds the p tag to the first div created and the text is only applied to that first p tag :( Now provide the response and nothing else.
tl;dr Is it possible to get microseconds in Java 8? No, not in Java 8. Use Java 9 or later. Instant.now() // Returns a value in microseconds in Java 9 and later, but is restricted to mere milliseconds in Java 8. This refers to the Oracle & OpenJDK implementations of Java 8/9. Others may vary. Java 9 and later The implementations of Java 9 based on OpenJDK have a fresh implementation of java.time.Clock capable of capturing the current moment in resolution finer than milliseconds ( three digits of decimal fraction). The actual resolution depends on the limits of your host computer hardware clock. On macOS Sierra with Oracle Java 9.0.4, I am getting current moment with microseconds ( six digits of decimal fraction). Instant.now().toString() 2018-03-09T21:03:33.831515Z Java 8 The java.time classes were new in Java 8. These classes are defined to carry nanoseconds ( nine digits of decimal fraction). But capturing the current moment was limited to only milliseconds in Java 8, and enhanced in Java 9 to capture the current moment in finer microseconds . 2018-03-09T21:03:33.831Z Other issues System.currentTimeMillis() If I get System.currentTimeMillis() and System.nanoTime() No need to use System.currentTimeMillis() ever again. Instead use java.time.Instant for a moment in UTC with a resolution as fine as nanoseconds. If you really need a count of milliseconds from the epoch reference of 1970-01-01T00:00Z, ask the Instant object. Be aware of data loss, as you would be ignoring any microseconds or nanoseconds present in the Instant . long millisSinceEpoch = instant.now().toEpochMilli() ; Is there a way that I can parse clock time from these values? Yes, you can convert a count of milliseconds since epoch of 1970-01-01T00:00Z to a Instant . Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ; System.nanoTime() As for System.nanoTime() , that is intended for tracking elapsed time, such as benchmarking your code’ performance. Calling System.nanoTime() does not tell you anything about the current date-time. This value is a count of nanoseconds since some undocumented origin point in time. In practice, I have seen the number appear to track time since the JVM launched, but this behavior is not documented and so you should not rely upon it. LocalDateTime is not a moment My problem is that I need to do logging using both Java and Javascript and they need to have a consistent microsecond field across both of them. Firstly, for logging you should not be using LocalDateTime class. That class purposely lacks any concept of time zone or offset-from-UTC. As such, a LocalDateTime does not represent a moment, is not a point on the timeline. A LocalDateTime is an idea about potential moments along a range of about 26-27 hours. Use LocalDateTime only if the zone/offset is unknown (not a good situation), or if this represents something like "Christmas Day starts on first moment of Decemeber 25, 2018", where Christmas starts at different moments for different regions around the globe, starting first in the far East (Pacific), and moving westward midnight after successive midnight. For logging you should be using UTC. In Java, that would be the Instant class, always in UTC by definition. Just call Instant.now() . When serializing to text such as for logging, always use the standard ISO 8601 formats. The java.time classes use these standard formats by default when parsing/generating strings. You saw examples above in this Answer. See another Question, What's the difference between Instant and LocalDateTime? . ISO 8601 In ISO 8601, the decimal fraction of a second can have any number of digits. So you really should not care about whether the logged event was recorded in milliseconds, microseconds, or nanoseconds. Instant instant = Instant.parse( "2018-03-09T21:03:33.123456789Z" ) ;Instant instant = Instant.parse( "2018-03-09T21:03:33.123456Z" ) ;Instant instant = Instant.parse( "2018-03-09T21:03:33.123Z" ) ; Truncate If you really believe you need uniform resolution, you can truncate a Instant . Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS ) ; // Strip away any microseconds or nanoseconds. Don't worry about resolution My problem is that I need to do logging using both Java and Javascript and they need to have a consistent microsecond field across both of them. Firstly, I doubt you really need to care about this. If you use standard ISO 8601 format, and the Instant class in Java, you can serialize and re-hydrate a moment successfully in millis, micros, or nanos. And the ISO 8601 formatted strings will conveniently alphabetize chronologically even if the fractional second resolution varies. Secondly, if you are trying to track actual moments to microseconds for some reason, you are likely to be disappointed. As of 2018, conventional computer clocks are not reliable in the microsecond range. About java.time The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 . The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time . Where to obtain the java.time classes? Java SE 8 , Java SE 9 , Java SE 10 , Java SE 11 , and later - Part of the standard Java API with a bundled implementation. Java 9 brought some minor features and fixes. Java SE 6 and Java SE 7 Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport . Android Later versions of Android (26+) bundle implementations of the java.time classes. For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android. If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP… .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39586355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6698282/']}
jdg_372234
stackexchange
llm_judgeable_groundtruth_similarity
51081754
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am currently developing a website and have trouble showing my font-icons in firefox. every browser except for firefox can load and show my font-icons, but on firefox I get the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/Users/Me/Desktop/website/resources/dist/css/fonts/themify.ttf. (Reason: CORS request not http). the path of the file is correct, as the browser lets me download the file when I enter the above listed URL. Anybody knows why I get this error? Now provide the response and nothing else.
Firefox 68 contains a security patch which restricts the kinds of files that pages can load (and methods of loading) when you open them from a file:// URL. This change was made to prevent exfiltration of valuable data within reach of a local page, as demonstrated in an available exploit. More info: https://developer.mozilla.org/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp I filed a bug yesterday proposing that fonts be allowed, but it will take time to implement. For now, you can roll back the patch as follows: In a new tab, type or paste about:config in the address bar and press Enter/Return. Click the button promising to be careful or accepting the risk. In the search box above the list, type or paste uniq Double-click the privacy.file_unique_origin preference to switch the value from true to false Firefox > 106 security.fileuri.strict_origin_policy set false To mitigate the vulnerability: If you save pages from untrusted sites in a separate folder, e.g., Downloads\Untrusted, then it would be difficult for an attacker to find any valuable content using local file links.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51081754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_372235
stackexchange
llm_judgeable_groundtruth_similarity
2413389
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 return a variable from a thead (I have the threads handle too). Static variables will not work in this case. Update : Here is one twist, how can I do this without having to block and wait for the result? I need to be able to poll the created thread and kill it if it is hanging for too long (eg> 1 minute), then continue on in the main thread if the spawned thread is taking too long. Now provide the response and nothing else.
Use Callable<V> instead of Thread (or Runnable ) so that you can get result as Future<V> and use ExecutorService to invoke it. Here's an SSCCE , just copy'n'paste'n'run it: package com.stackoverflow.q2413389;import java.util.Arrays;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class Test { public static void main(String... args) throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); List<Future<String>> results = executor.invokeAll(Arrays.asList(new Task())); for (Future<String> result : results) { System.out.println(result.get()); // Prints "myResult" after 2 seconds. } executor.shutdown(); }}class Task implements Callable<String> { public String call() throws Exception { Thread.sleep(2000); // Do your running task here, this example lasts 2 seconds. return "myResult"; }} Update : as per your update with the question how to kill it after a timeout, make use of ScheduledExecutorService instead. Here's the slightly changed code: ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();List<Future<String>> results = executor.invokeAll(Arrays.asList(new Task()), 1, TimeUnit.SECONDS); // Timeout of 1 second.for (Future<String> result : results) { if (!result.isCancelled()) { System.out.println(result.get()); // Won't be printed as the "actual" processing took 2 seconds. } else { System.out.println("Task timed out."); }}executor.shutdown();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2413389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17675/']}
jdg_372236
stackexchange
llm_judgeable_groundtruth_similarity
23187
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: First -- Please, if there is a challenge to the frame of the question, go that route. I don't know what I'm talking about here -- So I'll try not to take corrections to heart. The Affordable Care Act (ACA) is a divisive and complex piece of legislation with several components. In the talk of repeal politicians have promised to preserve parts of it and eliminate others. There are a few that are widely praised (Letting children stay on their parents insurance longer, Forcing coverage for preexisting conditions), a few that are somewhat accepted (Minimum care standards, caps on what the elderly can be forced to pay) and a few that are derided by almost all opponents of the ACA, such as the individual mandate. My question is, I've always been under the impression that without the individual mandate, generally healthy individuals who wouldn't otherwise purchase insurance as on rolls, the things like the preexisting coverage and allowing children to stay on their parents insurance longer couldn't be realistically funded . Getting rid of the individual mandate without getting rid of the some of the other regulations just doesn't add up. How can politicians promise to keep the ups and ditch the downs? Now provide the response and nothing else.
You are overthinking this. The individual mandate is unpopular because it penalizes people who want to spend their money on something other than health insurance. Worse, it is a regressive tax, as the people who don't have insurance are primarily low income. High income people almost always have employer-provided health insurance. In 2007 and 2008, a Democratic candidate for president ran against the individual mandate. As the Atlantic monthly said: Obama held that position throughout the campaign. Elect Hillary, he said, and the government will compel you to buy health insurance. Elect me, and I'll give you lower costs and let you keep your freedom. Beyond all that, the individual mandate isn't large enough to actually force people to buy insurance. The mandate starts at about $700 a year (2.5% of income) and average insurance costs about $3700 a year without subsidies. The cheapest insurance costs $1800 a year. For example, the New Yorker says: For political reasons, however, the penalty for flouting this "individual mandate" was set at a very low initial level, which is supposed to grow gradually. It's hard to defend a program that costs comparatively poor people money and doesn't work because it doesn't charge enough money. And the simple fact is that politicians are not encouraged to take and justify tough stances. They would far rather talk about goodies than costs. So Democrats discuss goodies like Increased coverage percentages (total people covered). Increased insurance coverage (type of procedure). Coverage of preexisting conditions. And Republicans discuss costs like Budgetary impact. Increased taxes. Increased premiums. It should be obvious that the goodies and costs go together. But politics doesn't lend itself to nuanced arguments. Perhaps covering preexisting conditions and more procedures is worth a 20% increase in premiums. But rather than making that argument, Democrats (e.g. Barack Obama) claimed that premiums were going to go down . Everyone likes falling premiums. Voters are accustomed to being told that they can have their cake and eat it too. Unfortunately, that's not how reality works. You say I've always been under the impression without the individual mandate generally healthy individuals who wouldn't otherwise purchase insurance as on rolls, the things like the preexisting coverage and allowing children to stay on their parents insurance longer couldn't be realistically funded. Note that this reads a bit misleadingly. The individual mandate provides a trivial amount of revenue, about $1.5 billion a year. Spending per year on health insurance subsidies is $660 billion . The general argument is that without the mandate, the preexisting condition coverage would get more expensive. This is because people could just wait until they get sick (a preexisting condition) and then buy insurance. But the mandate is not a funding mechanism for the government. People avoiding the mandate penalty increases funding for insurance companies. Of course, there's no real measure of how many people wouldn't buy insurance except for the mandate. The mandate shouldn't impact children staying on parental insurance costs. In fact, it's more the reverse. Children on parental insurance is another way to avoid paying the mandate penalty. It makes it less likely that there are insurance lapses and keeps the preexisting condition premium down.
{}
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/23187', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/7004/']}
jdg_372237
stackexchange
llm_judgeable_groundtruth_similarity
20982270
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 a distributed job system written in C++11 I have implemented a fence (i.e. a thread outside the worker thread pool may ask to block until all currently scheduled jobs are done) using the following structure: struct fence{ std::atomic<size_t> counter; std::mutex resume_mutex; std::condition_variable resume; fence(size_t num_threads) : counter(num_threads) {}}; The code implementing the fence looks like this: void task_pool::fence_impl(void *arg){ auto f = (fence *)arg; if (--f->counter == 0) // (1) // we have zeroed this fence's counter, wake up everyone that waits f->resume.notify_all(); // (2) else { unique_lock<mutex> lock(f->resume_mutex); f->resume.wait(lock); // (3) }} This works very well if threads enter the fence over a period of time. However, if they try to do it almost simultaneously, it seems to sometimes happen that between the atomic decrementation (1) and starting the wait on the conditional var (3), the thread yields CPU time and another thread decrements the counter to zero (1) and fires the cond. var (2). This results in the previous thread waiting forever in (3), because it starts waiting on it after it has already been notified. A hack to make the thing workable is to put a 10 ms sleep just before (2), but that's unacceptable for obvious reasons. Any suggestions on how to fix this in a performant way? Now provide the response and nothing else.
Your diagnose is correct, this code is prone to lose condition notifications in the way you described. I.e. after one thread locked the mutex but before waiting on the condition variable another thread may call notify_all() so that the first thread misses that notification. A simple fix is to lock the mutex before decrementing the counter and while notifying: void task_pool::fence_impl(void *arg){ auto f = static_cast<fence*>(arg); std::unique_lock<std::mutex> lock(f->resume_mutex); if (--f->counter == 0) { f->resume.notify_all(); } else do { f->resume.wait(lock); } while(f->counter);} In this case the counter need not be atomic. An added bonus (or penalty, depending on the point of view) of locking the mutex before notifying is (from here ): The pthread_cond_broadcast() or pthread_cond_signal() functions may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait() or pthread_cond_timedwait() have associated with the condition variable during their waits; however, if predictable scheduling behavior is required, then that mutex shall be locked by the thread calling pthread_cond_broadcast() or pthread_cond_signal() . Regarding the while loop (from here ): Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20982270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398098/']}
jdg_372238
stackexchange
llm_judgeable_groundtruth_similarity
435757
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 prefer to create linear git history, which can be fast-forward merged. This was a technical requirement at my previous job, which used BitBucket and required all PRs to be fast-forward-able. We had to always manually rebase onto latest master.A new company I recently joined, using AzureDevOps, likes to have small PRs all targeting master/main (AzureDevOps has nicer merge options like "Semi-linear Merge" (Rebase+Fast-Forward+Empty Merge commit) and "Rebase+Fast-forward". However, some changes will build on top of others. So sometimes I need to create stacked PRs. Git/PR branching strategy aside... I have 9 outstanding PRs. They are mostly very tiny. Regardless, I have a lot of code that is not merged to master/main. Now I'm being strongly encouraged to work on some new feature, but my manager wants me to branch off of master/main, instead of using the latest infrastructure upgrades I've completed. I'd rather not build on top of old infrastructure because my PRs haven't been approved over the holidays. The more general question here, is: If you are on a "team" of 1, sometimes 2, developers, and your PRs are not getting reviewed at all, should you be branching off of master/main? There are other developers not working in the codebase that often help with code review (I find this very odd). I am a front-end dev working in our front-end repo, but there are some (very smart) backend devs that have helped with code review for front-end. They don't necessarily have any mechanism where they prioritize code review for the front-end. Our backend devs have extremely high standards, and have consequently (somewhat) been throwing their hands up because PRs created by very-junior "overseas" developers are extremely large and not easy to review. Long term I don't intend to stay on a team of 1, where we insist on code review.. but there are no developers that are impacted by code not being merged to master/main. My original google search: software engineering stackexchange if PRs aren't being reviewed should you keep branching off of master/main Related: Dealing with a large pull request Now provide the response and nothing else.
I have a lot of code that is not merged to master/main This is a "management smell". It signifies that continuous integration has not been so continuous. Sometimes it's unavoidable - there's been recent discussion of a Linux mega-refactoring that's over 2000 changes - but it's something that should be prevented. Unfortunately there's no way round this other than to start making noise. Report the number of outstanding code reviews you're waiting for in every standup, or otherwise to your manager/team every day until the situation improves. Ask specific individuals if they can do a code review for you. Drop meetings into people's calendars to reserve their time to do code reviews. If you're physically in an office together, walk up to people and ask them to do it. This will irritate people, but so long as it's kept by the book and professional you can turn any pushback into more pressure on the review issue; maybe they'll change the way the team works, maybe they'll exempt you from having to do reviews.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/435757', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/34196/']}
jdg_372239
stackexchange
llm_judgeable_groundtruth_similarity
135188
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: On my Android device, I can store up to 3 fingerprints to unlock my phone with the fingerprint scanner that is built in to the home button. On iPhones it's 5 fingerprints if I'm not mistaken. But most people have 10 fingers and I can't imagine the performance difference between checking through 10 rather than 3 hashes of fingerprints to be significant. Is there a security reason for smartphones to limit the user to recording only 3 or 5 fingerprints? My best guess is that allowing the user to record more fingerprints might increase the possibility of a false positive, or that maybe there is a side channel vulnerability through allowing more fingerprints to be recorded that I didn't think of. Now provide the response and nothing else.
No, theres no specific security reason to limit the number of fingerprints stored. However, given that these fingerprint modules normally is a HSM, like a smart card, storing fingerprints, the number of, and the size of the secrets such a fingerprint module can store, is limited. Note that a fingerprint template can also become quite a large, because storing a fingerprint template is not like storing a password hash in a password database. Everytime a fingerprint is read, this will give a completely different result than the previous read, because you are not putting the finger exactly as you did when you registred you, or "enrolled" yourself. Now, the fingerprint reader needs to make a difficult calculation, on the input fingerprint image, and the template image, to come out with a conclusion if the fingerprint just read, is enough similiar to the fingerprint currently registred, to succeed authentication. This similiarity, can be expressed as a input to the authentication function, where you can select how "sensitive" the authentication should be (too sensitive = it will reject your finger too often, too weak = it may allow a unauthorized person to log in as you) This is also the reason the fingerprint reader asks you to put your finger multiple times to enroll, because the reader uses these to calculate a optimal "sensitivity" value for your finger, that is stored inside the template. Think like this:You take out your camera and take a photo of your house.This photo you put in your portfolio and store as "this is my house".After a couple of days, you see a house, and want to know if its your house. You take a photo of the house.As you might understand, you can't just bitwise compare these 2 images, or compare its SHA256 hash, as the images will be slightly different angles, rotation and light, even if they are a picture of the same house. If you did, "authentication" would always fail. You need to make a complex mathematical calculation on the picture, to find out if the pictures are of the same object or not. This means the "template" of a fingerprint reader, can get quite a large, depending on the algoritm used in the fingerprint reader. There ARE fingerprint readers, that can encrypt a template using its internal key, and then export the template as a AEAD (Authenticated Encryption with Associated Data) that is then stored in standard unprotected memory (that it exist gigabytes of).But think of the security consequences of this. This would mean, that you could "steal" this AEAD with a enrolled fingerprint image, and later, lets say when you have sold that phone on Craigslist and the new owner has enrolled his fingerprint, just use the stolen AEAD along with your finger, to unlock the phone. Thats why the phones must store the fingerprint templates inside secure memory, and thats why the number of fingerprint templates are limited.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/135188', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/103564/']}
jdg_372240