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
2652331
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 the group presentation $$ G := \langle a,b |a^8=b^8=1,a^{-1}ba=b^{-1},b^{-1}ab=a^{-1} \rangle. $$ Which group is it? Notably, what about its order? Now provide the response and nothing else.
This is the quaternion group, of order $8$. First, note that $a^2=b^{-2}$, as you've noticed. In particular, $a^2$ is centralised by $b$, but $b$ also inverts $a$ by conjugation, so we find $a^2=(a^2)^b=a^{-2}$, and so $a^4=1$. Now, $\langle a\rangle$ is normal in $G$, has order at most $4$, and the quotient has order at most $2$ (since $b^2\in\langle a\rangle$). This shows the group has order at most $8$, but $Q_8$ clearly satisfies the presentation (with $a=i$ and $b=j$, for example). Note that we never use the first two relations! Indeed, $\langle a,b\mid a^b=a^{-1}, b^a=b^{-1}\rangle$ is already the quaternion group! (This is often useful to remember.) (I'm using $a^b$ throughout to denote the conjugate of $a$ under $b$, that is $a^b=b^{-1}ab$.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2652331', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/531915/']}
jdg_80541
stackexchange
llm_judgeable_groundtruth_similarity
9539633
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 may sound stupid but how do I define a global variable in Go? const myglobalvariable = "Hi there!" doesn't really work... I just want to get the command line argument and after this I want to print it. I do this using this code snippet: package mainimport ( "flag" "fmt")func main() { gettext(); fmt.Println(text)}func gettext() { flag.Parse() text := flag.Args() if len(text) < 1 { fmt.Println("Please give me some text!") }} The problem is that it just prints an empty line so I thought about declaring a global variable using const myglobalvariable = "Hi there!" but I just get the error cannot use flag.Args() (type []string) as type ideal string in assignment ......I know this is a noob question so I hope you can help me... Now provide the response and nothing else.
I see at least two questions here, maybe three. How do you declare a global variable? How do you declare a global constant? How do you parse command line options and arguments? I hope the code below demonstrates this in a helpful way. The flag package was one of the first packages I had to cut my teeth on in Go. At the time it wasn't obvious, though the documentation is improving. FYI, at the time of this writing I am using http://weekly.golang.org as a reference. The main site is far too out of date. package mainimport ( "flag" "fmt" "os")//This is how you declare a global variablevar someOption bool//This is how you declare a global constantconst usageMsg string = "goprog [-someoption] args\n"func main() { flag.BoolVar(&someOption, "someOption", false, "Run with someOption") //Setting Usage will cause usage to be executed if options are provided //that were never defined, e.g. "goprog -someOption -foo" flag.Usage = usage flag.Parse() if someOption { fmt.Printf("someOption was set\n") } //If there are other required command line arguments, that are not //options, they will now be available to parse manually. flag does //not do this part for you. for _, v := range flag.Args() { fmt.Printf("%+v\n", v) } //Calling this program as "./goprog -someOption dog cat goldfish" //outputs //someOption was set //dog //cat //goldfish}func usage() { fmt.Printf(usageMsg) flag.PrintDefaults() os.Exit(1)}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9539633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1111794/']}
jdg_80542
stackexchange
llm_judgeable_groundtruth_similarity
3919
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: To defend versus Remote File Inclusion where attackers try to abuse image files, I usually recommend to never use include to include image files into PHP code. Sometimes though, the avoidance of image include s may be not possible at all (for whatever reasons, doesn't matter). In such case I usually pickup the images somewhere in the upload process and convert them to another image format (sometimes im combination with a lossy compression) to hopefully destroy any malicious code possibly contained in the original image. This works, but I'm not quite satisfied with it. Mainly because of the additional server load such processing produces and possible image quality decreases that sometimes may happen. Are the any smarter ways or best practices on that? EDIT To clarify: I'm talking about a siutation where the attacker injects PHP code into an image file to get the injected code executed on server side after uploading the image. Forums for example allow users to upload avatars (small image files) for personalisation. Now provide the response and nothing else.
Using GD functions to convert is a nice way to solve the problem, but adds overhead as you noticed. Also why do you use include? I guess you have done all the usual mitigations: Only allow certain extensions and check against them Use random file names use getimagesize() Check content-type Other things you may try disable execution of php files in the image upload directory use a separate domain to upload the images or store them outside the webroot
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/3919', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/2491/']}
jdg_80543
stackexchange
llm_judgeable_groundtruth_similarity
27401247
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 got this warning when I added share extension to my project and archiving it warning: skipping copy phase strip, binary is code signed: /Users/xxxx/xxx/xxxx/Build/xxxx/Build/Intermediates/ArchiveIntermediates/xxxx/IntermediateBui ldFilesPath/UninstalledProducts/XXX.appex/XXXX The old question does not provide and insight to correct this . So I decided to ask again. Warning during archive App with iOS 8 Extension in Xcode 6 Can someone please explain why this is happening ? Is it because the extension target is already code signed? If so, how to solve it ? I knew that setting "Strip debug symbols during copy" to "NO" can clear this warning . But it is not actually solve the problem. And what is the drawback of not "stripping debug symbol"? Because my archive size is still the same whether I set this to YES or NO Now provide the response and nothing else.
Do not disable Strip Debug Symbols During Copy in your application project. This will bloat your app (if you have other unsigned dependencies). It occurs because building the application project attempts to strip the framework but it can't since the framework is already codesigned. However the framework has already been stripped during it's build, so the warning is harmless. Xcode isn't doesn't seem to detect that the codesigned framework has already been stripped. You should leave it as is.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27401247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1626220/']}
jdg_80544
stackexchange
llm_judgeable_groundtruth_similarity
32062
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm a programmer and have recently played around a bit with rendering Mandelbrot fractals / zooming into them. What I can't grasp: How can such infinite, complex shapes come out of somewhat 10 lines of deterministic code? How is it possible that when zooming ever deeper and deeper, there are still completely new shapes coming up, while the algorithm remains the same? Does the set maybe give us some deep insight into our universe or even other dimensions, as it involves complex numbers? Now provide the response and nothing else.
Let $m(z,c) = z^2 + c$, consider the sequence of polynomials: $m(z,z),\,$ $m(m(z,z),z)$, ... , which are $$z^2+z,\quad z^4 + 2z^3 + z^2 + z,\quad z^8 + 4z^7 + 6z^6 + 6z^5 + 5z^4 + 2z^3 + z^2 + z,\quad...\quad.$$ Note that in terms of complex numbers the transformation $z \mapsto m(z,c)$ can be seen a way of twisting and squashing the sphere over itself.. if you keep kneading something you are bound to get tearing and crumpled filaments and such like. Here are graphs of the first seven (produced by the software here ):
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/32062', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9391/']}
jdg_80545
stackexchange
llm_judgeable_groundtruth_similarity
50123742
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 do I need to insert into TextField(inputFormatters: ? I want to disallow \ and / in one TextField and only allow a to Z in another. Now provide the response and nothing else.
Formatters In the services library you will find the TextInputFormatter abstract class (this means that you have to import package:flutter/services.dart ). It already has implementations, which are FilteringTextInputFormatter (formerly BlacklistingTextInputFormatter and WhitelistingTextInputFormatter ) and LengthLimitingTextInputFormatter . If you want to implement your own formatter, you can do so by extending TextInputFormatter itself and implementing formatEditUpdate in there. I will show how to apply the premade FilteringTextInputFormatter with given context. Examples disallow \ and / For this we are going to use the FilteringTextInputFormatter.deny constructor : TextField( inputFormatters: [ FilteringTextInputFormatter.deny(RegExp(r'[/\\]')), ],) For the Pattern , which needs to be supplied to the formatter, I will be using RegExp , i.e. regular expressions. You can find out more about that here, which also links you to the features I will be using in my examples . Pay attention to the double backslash \\ and the raw string ( r'' ) in this example . This represents only a single backslash in reality. The reason for this is that backslashes are escape keys in RegExp , so we need to use two backslashes if we want to match the \ character. We would even need quadruple backslashes( \\\\ ) without the raw string ( r'…' ) because Dart also uses backslashes as escape keys. Using a raw string will ensure that Dart does not unescape characters. If we were to block a , b , F , ! , and . , we would also put it in a list […] like this: FilteringTextInputFormatter.deny(RegExp('[abF!.]')) This translates to " deny/blacklist all 'a', 'b', 'F', '!' and '.' ". only allow a to Z This time we use the FilteringTextInputFormatter.allow constructor : TextField( inputFormatters: [ FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')), ],) For this, we are specifying two ranges of characters: a-z and A-Z , which will also accept all the characters (here all the letters) in-between those two specified. This will also work for 0-9 and you can append any character to that list, e.g. a-zA-Z0-9!. will also take ! and . into account. We can combine this TextField( inputFormatters: [ FilteringTextInputFormatter.allow(RegExp('[a-zA-Z]')), FilteringTextInputFormatter.deny(RegExp('[abFeG]')), ],) This is only to show that inputFormatters takes a List<InputFormatter> and multiple formatters can be combined. In reality, you can solve this with one allow/whitelist and a regular expression, but this does work as well. digitsOnly There are also already included static properties in the FilteringTextInputFormatter class : one of these is FilteringTextInputFormatter.digitsOnly . It will only accept/allow digits and is equivalent to an .allow(RegExp('[0-9]')) formatter.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/50123742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6509751/']}
jdg_80546
stackexchange
llm_judgeable_groundtruth_similarity
49094502
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 create the database schema and include it in my software requirements specification for my school project, however, when I try to create a relationship between 2 tables, I get Error: Missing index on column(s). Now provide the response and nothing else.
I think @HazarathChillara has this right; you need to create primary, unique, or index keys. You said every table has an primary key, but did you make each foreign and referenced key an index as well? It sounds like you neglected to properly set up your table structure; I only get the error when I don't have a primary key or index on the particular columns I'm working with. " MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan " You can just put an INDEX on the foreign key (often my referenced key is a primary key anyway, so I don't need any additional key on that column).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49094502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8618818/']}
jdg_80547
stackexchange
llm_judgeable_groundtruth_similarity
4084972
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my example below, why do I have to fully qualify the name of the free function in the cpp to avoid linker errors and why does it work for the class function without? Can you explain the difference? ctest.h: namespace Test{ int FreeFunction(); class CTest { public: CTest(); ~CTest(); };} ctest.cpp: #include "ctest.h"using namespace Test;// int FreeFunction() -> undefined reference errorint Test::FreeFunction() -> works just fine{ return 0;}CTest::CTest() -> no need to fully qualify name, i.e. Test::CTest{}CTest::~CTest(){} Thanks for your time & help. Now provide the response and nothing else.
int FreeFunction(void); is just a declaration whereas the below is a definition. class CTest { public: CTest(); ~CTest(); }; If you want to provide definition for an already declared entity in a namespace (e.g. in an enclosing namespace), it has to be fully qualified name. EDIT2: Here is something that would give you some more clarity. Note no using directive in this code. namespace Test { int FreeFunction(void); // declare class CTest; // declare} int Test::FreeFunction(){return 0;} // defineclass Test::CTest{ // define};int main(){} EDIT 3: Declaration vs Definition (C++0x)$3.1/2- A declaration is a definition unless it declares a function without specifying the function’s body (8.4) , it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function-body, it declares a static data member in a class definition (9.4), it is a class name declaration (9.1) , it is an opaque-enum-declaration (7.2), or it is a typedef declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute-declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4084972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/220636/']}
jdg_80548
stackexchange
llm_judgeable_groundtruth_similarity
24808660
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 HTML form with multiple inputs named like this: <input name="hello[]" type="text" /><input name="hello[]" type="text" /><input name="hello[]" type="text" /> In PHP you get this as an array but is it the same way in Python, using Flask? I have tried this: hello = request.form['hello']print(hello) But that did not work, I got a 400 Bad Request : Bad RequestThe browser (or proxy) sent a request that this server could not understand. How do I do it in Flask? Now provide the response and nothing else.
You are following a PHP convention of adding brackets to the field names . It's not a web standard, but because PHP supports it out of the box it is popular; Ruby on Rails also uses it. If you do use that convention, to get the POST data on the Flask side you need to include the square brackets in the field name. You can retrieve all values of the list using MultiDict.getlist() : hello = request.form.getlist('hello[]') You don't have to use the [] convention at all, of course. Not appending the [] to the hello name will work perfectly fine, at which point you'd use request.form.getlist('hello') in Flask.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24808660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1221132/']}
jdg_80549
stackexchange
llm_judgeable_groundtruth_similarity
884759
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following example. string s = "The man is old. Them is not bad."; If I use s = s.Replace("The", "@@"); Then it returns "@@ man is old. @@m is not bad." But I want the output to be "@@ man is old. Them is not bad." How can I do this? Now provide the response and nothing else.
Here's how you'd use a regex, which would handle any word boundaries: Regex r = new Regex(@"\bThe\b");s = r.Replace(s, "@@");
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/884759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_80550
stackexchange
llm_judgeable_groundtruth_similarity
18795453
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'd like to understand better why choose int over unsigned ? Personally, I've never liked signed values unless there is a valid reason for them. e.g. count of items in an array, or length of a string, or size of memory block, etc., so often these things cannot possibly be negative. Such a value has no possible meaning. Why prefer int when it is misleading in all such cases? I ask this because both Bjarne Stroustrup and Chandler Carruth gave the advice to prefer int over unsigned here (approx 12:30') . I can see the argument for using int over short or long - int is the "most natural" data width for the target machine architecture. But signed over unsigned has always annoyed me. Are signed values genuinely faster on typical modern CPU architectures? What makes them better? Now provide the response and nothing else.
Let me paraphrase the video, as the experts said it succinctly. Andrei Alexandrescu : No simple guideline. In systems programming, we need integers of different sizes and signedness. Many conversions and arcane rules govern arithmetic (like for auto ), so we need to be careful. Chandler Carruth : Here's some simple guidelines: Use signed integers unless you need two's complement arithmetic or a bit pattern Use the smallest integer that will suffice. Otherwise, use int if you think you could count the items, and a 64-bit integer if it's even more than you would want to count. Stop worrying and use tools to tell you when you need a different type or size. Bjarne Stroustrup : Use int until you have a reason not to. Use unsigned only for bit patterns. Never mix signed and unsigned Wariness about signedness rules aside, my one-sentence take away from the experts: Use the appropriate type, and when you don't know, use an int until you do know.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18795453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112755/']}
jdg_80551
stackexchange
llm_judgeable_groundtruth_similarity
3022713
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 difference between a FULL JOIN and an INNER JOIN ? When I do a FULL JOIN , I get 832 records and with an INNER JOIN , I get 830 records. Now provide the response and nothing else.
NOTE : All of these can be found on Wikipedia: Join (SQL) . There are three types of OUTER joins: LEFT OUTER JOIN RIGHT OUTER JOIN FULL OUTER JOIN The keyword OUTER is optional in all implementations that follow the standard, so FULL JOIN is the same as FULL OUTER JOIN. ( I've omitted the word OUTER from the SQL in the rest of this answer .) Let's look at what each does. Consider the following two input data sets: Set "A" Set "B" AA BB-------- -------- Item 1 Item 3 Item 2 Item 4 Item 3 Item 5 Item 4 Item 6 Notice that there are some items in A that aren't in B, and vice versa. Now, if we write an SQL statement like this, using LEFT join: SELECT * FROM A LEFT JOIN B ON AA = BB You'll get the following result (the empty holes are actually NULL marks): AA BB-------- -------- Item 1 Item 2 Item 3 Item 3 Item 4 Item 4 Notice that you'll get all the rows from AA, or rather, all the rows from the left part of the join clause. If you switch to using a RIGHT join: SELECT * FROM A RIGHT JOIN B ON AA = BB AA BB-------- -------- Item 3 Item 3 Item 4 Item 4 Item 5 Item 6 Notice that you get all the rows from the right part of the join clause. However, if you want all the rows of both, you'll use a FULL join: SELECT * FROM A FULL JOIN B ON AA = BB AA BB-------- -------- Item 1 <-----+ Item 2 | Item 3 Item 3 | Item 4 Item 4 | Item 5 +--- empty holes are NULL's Item 6 | ^ | | | +---------------------+ As suggested in a comment, let me complete the other different ways to join. With INNER join: SELECT * FROM A INNER JOIN B ON AA = BB AA BB-------- -------- Item 3 Item 3 Item 4 Item 4 With INNER join we only get the rows that actually match up, no holes because of joining. A CROSS join produces a cartesian product, by matching up every row from the first set with every row from the second set: SELECT * FROM A CROSS JOIN B AA BB-------- -------- Item 1 Item 3 ^ Item 1 Item 4 +--- first item from A, repeated for all items of B Item 1 Item 5 | Item 1 Item 6 v Item 2 Item 3 ^ Item 2 Item 4 +--- second item from A, repeated for all items of B Item 2 Item 5 | Item 2 Item 6 v Item 3 Item 3 ... and so on Item 3 Item 4 Item 3 Item 5 Item 3 Item 6 Item 4 Item 3 Item 4 Item 4 Item 4 Item 5 Item 4 Item 6 Also note that we don't specify which columns that match, since there is no matching done. Finally, NATURAL join, in this syntax we don't specify which columns that match, but matches on column names. In our contrived example, no column names are the same, but let's say for this specific example that the column names was XX in both tables, then we would get the following result: SELECT * FROM A NATURAL JOIN B +----------+------- matches on the names, and then the data | | v v XX XX-------- -------- Item 3 Item 3 Item 4 Item 4 As you can see, you get the same as a INNER join, but don't have to type out the match part of the join clause.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3022713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/364529/']}
jdg_80552
stackexchange
llm_judgeable_groundtruth_similarity
2487922
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: That's x \ y using mathematical notation. Suppose x <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,1,1,1,3) y <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1) How can I get a vector with ALL the values in x that are not in y. i.e the result should be: 2,1,1,3 There is a similar question here . However, none of the answers returns the result that I want. Now provide the response and nothing else.
Here a solution using pmatch (this gives the "complement" as you require): x <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,1,1,1,3)y <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1)res <- x[is.na(pmatch(x,y))] From pmatch documentation: "If duplicates.ok is FALSE, values of table once matched are excluded from the search for subsequent matches."
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2487922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170792/']}
jdg_80553
stackexchange
llm_judgeable_groundtruth_similarity
5346859
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 these text in my db, categories_postscategories_newsposts_addnews_add And I don't want to select the rows with categories , I use a query something like this, SELECT * FROM developer_configurations_cms WHERE developer_configurations_cms.cat_id = '1' AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%' AND developer_configurations_cms.cfg_name_unique NOT LIKE '%categories%' but it returns these two in the output as well... categories_postscategories_news How can I ignore them in my query? Thanks. Now provide the response and nothing else.
categories_posts and categories_news start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique starts with 'categories' instead of check if it contains the given substring. Translating all that into a query: SELECT * FROM developer_configurations_cms WHERE developer_configurations_cms.cat_id = '1' AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%' AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5346859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/413225/']}
jdg_80554
stackexchange
llm_judgeable_groundtruth_similarity
38820
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Which class design is better and why? public class User{ public String UserName; public String Password; public String FirstName; public String LastName;}public class Employee : User{ public String EmployeeId; public String EmployeeCode; public String DepartmentId;}public class Member : User{ public String MemberId; public String JoinDate; public String ExpiryDate;} OR public class User{ public String UserId; public String UserName; public String Password; public String FirstName; public String LastName;}public class Employee{ public User UserInfo; public String EmployeeId; public String EmployeeCode; public String DepartmentId;}public class Member{ public User UserInfo; public String MemberId; public String JoinDate; public String ExpiryDate;} Now provide the response and nothing else.
The question is simply answered by recognising that inheritance models an "IS-A" relationship, while membership models a "HAS-A" relationship. An employee IS A user An employee HAS A userinfo Which one is correct? This is your answer.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191/']}
jdg_80555
stackexchange
llm_judgeable_groundtruth_similarity
421892
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I find the arc sine of a sine without using a calculator? Thank you. Now provide the response and nothing else.
To compute $\arcsin(x)$ we might need to use a bit of calculus. Note that$$\arcsin(x)=\int_0^x\frac{\mathrm{d}t}{\sqrt{1-t^2}}$$Using the binomial theorem, we get that$$\frac1{\sqrt{1-x^2}}=\sum_{k=0}^\infty\binom{2k}{k}\left(\frac{x}{2}\right)^{2k}$$Integrating term by term, we get$$\arcsin(x)=\sum_{k=0}^\infty\frac2{2k+1}\binom{2k}{k}\left(\frac{x}{2}\right)^{2k+1}$$ Iterative Method Requiring Square Roots We can use the identity$$\begin{align}\sin^2(x/2)&=\frac{1-\sqrt{1-\sin^2(x)}}{2}\\[6pt]&=\frac{\sin^2(x)}{2+2\sqrt{1-\sin^2(x)}}\end{align}$$and the limit$$\lim_{n\to\infty}2^n\sin(x/2^n)=x$$to compute $x$ from $\sin(x)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/421892', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/81240/']}
jdg_80556
stackexchange
llm_judgeable_groundtruth_similarity
358532
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Is there for every infinite cardinal $\kappa$ a connected Hausdorff space $(X,\tau)$ with $|X| = \kappa$ and a collection ${\cal D}$ of mutually disjoint open sets with $|{\cal D}| = \kappa$ ? Now provide the response and nothing else.
An easy way to see this is by using the Lebesgue density theorem. Any set of positive measure has a density point $t$ (indeed, almost every element of the set is a density point). This means that for any $\epsilon > 0$ there is an interval $I$ containing $t$ such that $m(E \cap I) > (1-\epsilon)m(I)$ . This pretty much immediately implies that $m(\Gamma E) > (1-\epsilon)2\pi$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/358532', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8628/']}
jdg_80557
stackexchange
llm_judgeable_groundtruth_similarity
9028029
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: DataTable Table = new DataTable;SqlConnection = new System.Data.SqlClient.SqlConnection("Data Source=" + ServerName + ";Initial Catalog=" + DatabaseName + ";Integrated Security=SSPI; Connect Timeout=120");SqlDataAdapter adapter = new SqlDataAdapter("Select * from " + TableName, Connection);adapter.FillSchema(Table, SchemaType.Source);adapter.Fill(Table);DataColumn column = DataTable.Columns[0]; What I want to do is: Assume currently column.DataType.Name is "Double" . I want it to become "Int32" . How do I achieve this? Now provide the response and nothing else.
You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below. DataTable dtCloned = dt.Clone();dtCloned.Columns[0].DataType = typeof(Int32);foreach (DataRow row in dt.Rows) { dtCloned.ImportRow(row);}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9028029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1037008/']}
jdg_80558
stackexchange
llm_judgeable_groundtruth_similarity
5901706
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to PEP 358 , a bytes object is used to store a mutable sequence of bytes (0-255), raising if this is not the case. However, my python 2.7 says otherwise >>> bytes([1,2,3])'[1, 2, 3]'>>> bytes([280])'[280]'>>> bytes is strTrue>>> bytes<type 'str'> Does anyone have a clue on the reason why the PEP is declared Final, but the implementation does not conform ? Now provide the response and nothing else.
The new bytes type is 3.x only . The 2.x bytes built-in is just an alias to the str type. There is no new type called bytes in 2.x; Just a new alias and literal syntax for str . Here's the documentation snippet everybody loves: Python 2.6 adds bytes as a synonym for the str type, and it also supports the b'' notation. The 2.6 str differs from 3.0’s bytes type in various ways; most notably, the constructor is completely different. In 3.0, bytes([65, 66, 67]) is 3 elements long, containing the bytes representing ABC ; in 2.6, bytes([65, 66, 67]) returns the 12-byte string representing the str() of the list. The primary use of bytes in 2.6 will be to write tests of object type such as isinstance(x, bytes) . This will help the 2to3 converter, which can’t tell whether 2.x code intends strings to contain either characters or 8-bit bytes; you can now use either bytes or str to represent your intention exactly, and the resulting code will also be correct in Python 3.0.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5901706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/78374/']}
jdg_80559
stackexchange
llm_judgeable_groundtruth_similarity
35272832
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 JSPM , AngularJS , TypeScript , SystemJS and ES6 and my project is running pretty well... unless I try to use momentJS. This is the error I get: TypeError: moment is not a function This is part of the code: import * as moment from 'moment'; More: var momentInstance = moment(value); If I debug it, moment is an object not a function: This is what my moment.js JSPM package looks like: module.exports = require("npm:[email protected]/moment.js"); I've read a lot and couldn't find a way to solve this... any ideas? Some things I've read/tried: How to use momentjs in TypeScript with SystemJS? https://github.com/angular-ui/ui-calendar/issues/154 https://github.com/jkuri/ng2-datepicker/issues/5 Typescript module systems on momentJS behaving strangely https://github.com/dbushell/Pikaday/issues/153 Thanks! Now provide the response and nothing else.
Simply remove the grouping ( * as ) from your import statement: import moment from 'moment'; Without digging too deeply in to the source code , it looks like moment usually exports a function, that has all kinds of methods and other properties attached to it. By using * as , you're effectively grabbing all those properties and attaching them to a new object, destroying the original function. Instead, you just want the chief export ( export default in ES6, module.exports object in Node.js). Alternatively, you could do import moment, * as moments from 'moment'; to get the moment function as moment , and all the other properties on an object called moments . This makes a little less sense when converting ES5 exports like this to ES6 style, because moment will retain the same properties.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/35272832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/578808/']}
jdg_80560
stackexchange
llm_judgeable_groundtruth_similarity
6271947
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to test a function that takes input from stdin , which I'm currently testing with something like this: cat /usr/share/dict/words | ./spellchecker.py In the name of test automation, is there any way that pyunit can fake input to raw_input() ? Now provide the response and nothing else.
The short answer is to monkey patch raw_input() . There are some good examples in the answer to How to display the redirected stdin in Python? Here is a simple, trivial example using a lambda that throws away the prompt and returns what we want. System Under Test cat ./name_getter.py#!/usr/bin/env pythonclass NameGetter(object): def get_name(self): self.name = raw_input('What is your name? ') def greet(self): print 'Hello, ', self.name, '!' def run(self): self.get_name() self.greet()if __name__ == '__main__': ng = NameGetter() ng.run()$ echo Derek | ./name_getter.py What is your name? Hello, Derek ! Test case: $ cat ./t_name_getter.py#!/usr/bin/env pythonimport unittestimport name_getterclass TestNameGetter(unittest.TestCase): def test_get_alice(self): name_getter.raw_input = lambda _: 'Alice' ng = name_getter.NameGetter() ng.get_name() self.assertEquals(ng.name, 'Alice') def test_get_bob(self): name_getter.raw_input = lambda _: 'Bob' ng = name_getter.NameGetter() ng.get_name() self.assertEquals(ng.name, 'Bob')if __name__ == '__main__': unittest.main()$ ./t_name_getter.py -vtest_get_alice (__main__.TestNameGetter) ... oktest_get_bob (__main__.TestNameGetter) ... ok----------------------------------------------------------------------Ran 2 tests in 0.000sOK
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6271947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/677903/']}
jdg_80561
stackexchange
llm_judgeable_groundtruth_similarity
14685417
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 i know, when the user authorize the app, or not, and the SDK goes back to my app?Theres any event to know that? Now provide the response and nothing else.
Error handling Suppose there is an error deep down in a function nested in many other functions and error handling makes sense only in the top level function. It would be very tedious and awkward if all the functions in between had to return normally and evaluate return values or a global error variable to determine that further processing doesn't make sense or even would be bad. That's a situation where setjmp/longjmp makes sense.Those situations are similar to situation where exception in other langages (C++, Java) make sense. Coroutines Besides error handling, I can think also of another situation where you need setjmp/longjmp in C: It is the case when you need to implement coroutines . Here is a little demo example.I hope it satisfies the request from Sivaprasad Palas for some example code and answers the question of TheBlastOne how setjmp/longjmp supports the implementation of corroutines (as much as I see it doesn't base on any non-standard or new behaviour). EDIT: It could be that it actually is undefined behaviour to do a longjmp down the callstack (see comment of MikeMB; though I have not yet had opportunity to verify that). #include <stdio.h>#include <setjmp.h>jmp_buf bufferA, bufferB;void routineB(); // forward declaration void routineA(){ int r ; printf("(A1)\n"); r = setjmp(bufferA); if (r == 0) routineB(); printf("(A2) r=%d\n",r); r = setjmp(bufferA); if (r == 0) longjmp(bufferB, 20001); printf("(A3) r=%d\n",r); r = setjmp(bufferA); if (r == 0) longjmp(bufferB, 20002); printf("(A4) r=%d\n",r);}void routineB(){ int r; printf("(B1)\n"); r = setjmp(bufferB); if (r == 0) longjmp(bufferA, 10001); printf("(B2) r=%d\n", r); r = setjmp(bufferB); if (r == 0) longjmp(bufferA, 10002); printf("(B3) r=%d\n", r); r = setjmp(bufferB); if (r == 0) longjmp(bufferA, 10003);}int main(int argc, char **argv) { routineA(); return 0;} Following figure shows the flow of execution: Warning note When using setjmp/longjmp be aware that they have an effect on the validity of local variables often not considered. Cf. my question about this topic .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14685417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1520936/']}
jdg_80562
stackexchange
llm_judgeable_groundtruth_similarity
10084224
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to confirm if a value returned from the scanf() function is a floating number or not. How can I do that? My code is not running as it should if the wrong data types are supplied to the scanf() function. Similarly, how would I confirm if a value returned is a character string or not? Now provide the response and nothing else.
scanf() et al return the number of successful conversions. If you have: scanf("%f", &f); you should test: if (scanf("%f", &f) == 1) ...all OK...else ...EOF or conversion failure... If you have several conversions, check that they all completed. If you're using %n 'conversions', they aren't counted. Although scanf() does return EOF on EOF, you should not test for that — you should always check primarily that you got the number of conversions you expected. For example, consider the buggy code: while (scanf("%f %d %s", &f, &i, s) != EOF) // Here be BUGS! ...loop body... If you type 3.14 x23 yes , then you will have an infinite loop because scanf() will return 1 on the first iteration (it successfully converted 3.14), and 0 thereafter (not EOF). You might be OK with: while ((rc = scanf("%f %d %s", &f, &i, s)) != EOF){ if (rc != 3) ...oops data problems... else ...all OK...} Judging from previous questions, you should be looking at using fgets() (or possibly POSIX getline() ) to read lines of data, and then using sscanf() or even functions like strtol() and strtod() to read particular values from the line. If you use sscanf() , the comments made above about checking the number of successful conversions still apply. I don't use scanf() in production code; it is just too damn hard to control properly. I regard it as almost suitable for beginning programs — except that it causes lots of confusion. On the whole, the best advice is 'stay clear of scanf() and fscanf() '. Note that that does not mean you have to stay clear of sscanf() , though some caution is needed even with sscanf() .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10084224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/597858/']}
jdg_80563
stackexchange
llm_judgeable_groundtruth_similarity
28226408
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the following function I define all the necessary characteristics of a UIView: func OpenController() { var gameOverView: UIView = UIView() gameOverView.center = super.view.center gameOverView.frame.size = CGSize(width: 200, height: 300) gameOverView.backgroundColor = UIColor.grayColor() self.view.addSubview(gameOverView)} Even though I define the center of the UIView "gameOverView" as that of the the viewcontroller it resides in, it appears with a corner in the center of the viewcontroller and not centered in the viewcontroller. I have tried various other ways of defining the position (NSLayoutConstraints, frame.x, frame.y etc.) but all have this result. If anyone can tell me why this happens and how to center the UIView within its parent view controller I would greatly appreciate it! Now provide the response and nothing else.
Your issue here is that your center is being set before the frame. Since you are creating the view without the frame argument your frame is {0, 0}. So you are currently centering the subview then resizing it, so this is happening: What you need to do is resize the subview then center it, like this: So you can just swap your centering and framing logic: gameOverView.frame.size = CGSize(width: 200, height: 300)gameOverView.center = super.view.center Otherwise even easier just pass the frame when creating the view (you could even pass in the proper x, y coordinates to center it here too): var gameOverView: UIView = UIView(frame: CGRectMake(0, 0, 200, 300))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28226408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4480763/']}
jdg_80564
stackexchange
llm_judgeable_groundtruth_similarity
22190885
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 doubt about R-Tree data structure. What is fan-out in R-Tree. Is it a Maximum number of entries? How can we determine the minimum and maximum number of entries in R-Tree? Let say if i have 10000 points and my page size i 8kb. Thanks Now provide the response and nothing else.
Fan-out, in any tree, is number of pointers to child nodes in a node. Different trees have different fan-out. A binary tree has fanout 2. A B-tree has a fan-out B , with all nodes except leaves having between B/2 and B children. External (on-disk) implementation often relax the minimal number of children restriction to save some updates. In databases, B-trees or their variant called B+-trees is often used so that each node has size of 1 page and the fan out determined by number of sort keys and pointers that fit in that space. An R-tree is a search tree where indices are multi-dimensional intervals. These may possibly overlap. It may have any fan-out. Usual is number of 2 to number of dimensions (so 4 for 2-dimensional, 8 for 3-dimensional etc.). But it may have higher fanout too and organizing it similar to B-tree is certainly possible. How can we determine the minimum and maximum number of entries in R-Tree? Let say if I have 10000 points and my page size is 8KiB. The size of the tree node does not have to match page size. If it does (usually used for external, i.e. on disk, implementations), you still need to know how large the sort key is and how large the pointer is. An R-tree needs 2 coordinate values, minimum and maximum, per dimension. So a 2-dimensional R-tree with double precision coordinates (the common case appearing in mapping applications) will have four 64 bit values describing the rectangle plus a child pointer, for which an external implementation probably wants to use 64 bits as well. That is 20 B per child and you can squeeze 409 of these in an 8 KiB page. The number of points does not matter. Dimension and precision of coordinate system does. In memory, trees with low fanout are more efficient, because though they are deeper, they need fewer comparisons per search. However on disk (in databases) the slow operation is reading and since that can only be done in blocks, it is faster to reduce number of nodes by having each node fill whole block and have correspondingly higher fanout.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22190885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3030823/']}
jdg_80565
stackexchange
llm_judgeable_groundtruth_similarity
3272889
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On one hand, I know that the advisable usage of Properties is to have a backing field, like in the following example: private int m_Capacity; public int Capacity { get { return m_Capacity > 0 ? m_Capacity : -666; } set { m_Capacity = value; } } On the other hand, what benefit do I get from using the above example over discarding the field and using only the property for all purposes, like in the following example: public int Capacity { get { return Capacity > 0 ? Capacity : -666; } set { Capacity = value; } } What is good about using a backing field for regular (non-auto-implemented) properties? Now provide the response and nothing else.
If you do this: public int Capacity { get { return Capacity > 0 ? Capacity : -666; } set { Capacity = value; } } then your code will have an infinite recursion. It will never work. That's because the getter for Capacity is referencing itself. Same thing goes for the setter. Unless you are using automatic properties, you need a backing field
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3272889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/394646/']}
jdg_80566
stackexchange
llm_judgeable_groundtruth_similarity
17713412
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 a lot of trouble getting a cross domain POST request to hit an Api controller in the latest beta 2 release. Chrome (and other browsers) spit out: OPTIONS http://api.hybridwebapp.com/api/values 400 (Bad Request)POST http://api.hybridwebapp.com/api/values 404 (Not Found) It may be related to this issue but I have applied that workaround and several other fixes such as web.config additions here I've been banging my head with this for a while so I created a solution to reproduce the problem exactly. Load the web app there will be 2 buttons one for GET one for POST and the response will appear next to the button. GET works. Cannot get POST to return successfully. I'm able to get a hint at the cause from Fiddler but it makes no sense because if you look at the response it DOES include the domain in the Access-Controll-Allow-Origin header: There is a folder in the solution called "ConfigurationScreenshots" with a few screenshots of the IIS configuration (website bindings) and Project properties configurations to make it as easy as possible to help me :) EDIT: Don't forget to add this entry to host file (%SystemRoot%\system32\drivers\etc): 127.0.0.1 hybridwebapp.com api.hybridwebapp.com **STATUS: ** It seems that some browsers like Chrome allow me to proceed with the POST regardless of the error message in the OPTIONS response (while others like Firefox don't). But I don't consider that solved. Look at the Fidler screenshots of the OPTIONS request it has Access-Control-Allow-Origin: http://hybridwebapp.com And yet the error: The origin http://hybridwebapp.com is not allowed That is completely contradictory it's as if it's ignoring the header. Now provide the response and nothing else.
Ok I got past this. This has got to be the strangest issue I've ever encountered. Here's how to "solve" it: Continue on with life as usual until suddenly out of no where OPTIONS requests to this domain begin returning 200 OK (instead of 400 Bad Request) and POST never happens (or at least seems like it doesn't because the browser swallows it) Realize that Fiddler's OPTIONS response mysteriously contains duplicates for "Access-Control-Allow-XXX". Try removing the following statement from you web.config even though you clearly remember trying that to fix the previous issue and it not working: Remove this: <httpProtocol> <customHeaders> <remove name="X-Powered-By" /> <add name="Access-Control-Allow-Origin" value="http://mydomain.com" /> <add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" /> <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" /> </customHeaders> </httpProtocol> Because you already have this: var enableCorsAttribute = new EnableCorsAttribute("http://mydomain.com", "Origin, Content-Type, Accept", "GET, PUT, POST, DELETE, OPTIONS"); config.EnableCors(enableCorsAttribute); Moral: You only need one.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17713412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1267778/']}
jdg_80567
stackexchange
llm_judgeable_groundtruth_similarity
14673
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to generate text files with the following name format: YYYYY-MM-DD--hh-mm-ss.org . How can I use the capture funtionality for this? That is, instead of making one entry per capture in a single file, the function should make one single file per capture, and hopefully with all the possibilities within the capture mechanism. Now provide the response and nothing else.
You should be able to use the function target form to do this: (defun my/org-file-by-date () "Create an Org file with current time as name." (find-file (format-time-string "~/org/%Y-%m-%d--%H-%M-%S.org")))(add-to-list 'org-capture-templates '("x" "Template Name" plain (function my/org-file-by-date) "Capture template contents")) Edit 2 : As it turns out, code passed to a file form or the like isn't evaluated until capture time, so there's a more compact way to do this. See Erik Sjöstrand's answer for an example. Edit 1 : To get similar functionality without going through the capture interface, you can use functions similar to these. (defun my/org-file-by-date-with-inline-skeleton () "Create Org file from skeleton with current time as name." (interactive) (find-file (format-time-string "~/org/%Y-%m-%d--%H-%M-%S.org")) (insert "Skeleton contents"))(defun my/org-file-by-date-with-file-skeleton () "Create Org file from skeleton file with current time as name." (interactive) (let ((filename (format-time-string "~/org/%Y-%m-%d--%H-%M-%S.org"))) (copy-file "path/to/skeleton/file" filename) (find-file filename)))
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/14673', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/8348/']}
jdg_80568
stackexchange
llm_judgeable_groundtruth_similarity
35459392
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 using a form building library calledEureka( https://github.com/xmartlabs/Eureka ) and for some reasonwhenever I build a form,the navigation bar is not appearing eventhoughmy view controller is embedded in a navigation controller and it isset to visible.Any help? Here's my repo: https://github.com/ariff20/iTutor Code class SignUpViewController: FormViewController ,UINavigationBarDelegate{override func viewDidLoad() { super.viewDidLoad() let logButton : UIBarButtonItem = UIBarButtonItem(title: "RightButtonTitle", style: UIBarButtonItemStyle.Done, target: self,action: "multipleSelectorDone") self.navigationController?.navigationBar.hidden = false self.navigationItem.rightBarButtonItem = logButton form +++ Section("Your Basic Details") <<< NameRow() { $0.placeholder = "Your Name" } <<< EmailRow() { $0.placeholder = "Email" } <<< PasswordRow() { $0.placeholder = "Password" } <<< PhoneRow() { $0.placeholder = "Your phone no,Customers will see this" } +++ Section("Select your Expertise") <<< MultipleSelectorRow<String> { $0.title = "Choose your Subjects" $0.options = ["English","Mandarin","Maths","Science","Bahasa Malaysia"] } .onPresent { from, to in to.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: from, action:"multipleSelectorDone:") } <<< MultipleSelectorRow<String> { $0.title = "Choose your levels" $0.options = ["Standard 1-3","Standard 4-6","Form 1-3","Form 4-5"] } .onPresent { from, to in to.navigationItem.rightBarButtonItem = logButton} <<< MultipleSelectorRow<String> { $0.title = "Choose your pricing range" $0.options = ["RM30-RM40","RM40-RM60","RM60-RM80","RM80-RM100"] } .onPresent { from, to in to.navigationItem.rightBarButtonItem = logButton} +++ Section("Where can you teach?") <<< TextRow() { $0.placeholder = "State" } <<< TextRow() { $0.placeholder = "Town,ex:Near Shah Alam" } }override func viewWillAppear(animated: Bool){ super.viewWillAppear(true) self.navigationController?.navigationBarHidden=false}func multipleSelectorDone(item:UIBarButtonItem){ navigationController?.popViewControllerAnimated(true)} OUTPUT 1 2 3 Now provide the response and nothing else.
You're presenting your ViewController like this: let vc = storyboard!.instantiateViewControllerWithIdentifier("TutorSignUp") as! SignUpViewControllerself.presentViewController(vc, animated: true, completion: nil) so your SignUpViewController doesn't actually have a UINavigationController as a parent. This will fix that: let vc = storyboard!.instantiateViewControllerWithIdentifier("TutorSignUp") as! SignUpViewControllerlet navigationController = UINavigationController(rootViewController: vc)self.presentViewController(navigationController, animated: true, completion: nil)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35459392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3879598/']}
jdg_80569
stackexchange
llm_judgeable_groundtruth_similarity
49196979
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 I could append an element to an array like that: Using this code I'm overriding the old data: let toUpdate = [book.id]self.refUsers.child(localUser.key!).child("booksPurchased").setValue(toUpdate, withCompletionBlock: { (error, _) in Now provide the response and nothing else.
In this case, you will have to read the existing data, then write it back with the new value added. Arrays like this are not always the best way to store lists of data if you want to perform a lot of append operations. For that, you're better off pushing data into a location using childByAutoId .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49196979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7127472/']}
jdg_80570
stackexchange
llm_judgeable_groundtruth_similarity
19393774
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 clicked on the maximize button the window is maximized but the controls are not resized proportionally. What is the best way to make the controls resize accordingly? I am using MVVM. Here is my code. <Window x:Class="DataTransfer.View.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Icon="/DataTransfer;component/View/Images/ms_msnexplore.gif" ResizeMode="CanResizeWithGrip" Title="Window1" Height="500" Width="600"> <!--Style="{DynamicResource OfficeStyle}"--> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!--<ResourceDictionary Source="/DataTransfer;component/View/WindowBase.xaml" />--> <!--<ResourceDictionary Source="/DataTransfer;component/Themes/WPFThemes/CalendarResource.xaml" />--> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width ="*" /> </Grid.ColumnDefinitions> <Button Content="Button" HorizontalAlignment="Left" Margin="52,28,0,0" VerticalAlignment="Top" Width="75" Height="22" /> <DatePicker Name="dp" HorizontalAlignment="Left" Margin="175,25,0,0" VerticalAlignment="Top" Width="123" Text="aaa" GotFocus="DateGotFocused" LostFocus="OnLeaveArchiveDate"/> <Calendar HorizontalAlignment="Left" Margin="47,162,0,0" VerticalAlignment="Top"/> <TextBox Name="t1" HorizontalAlignment="Left" Height="23" Margin="337,23,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" LostFocus="LeaveField" /> <RadioButton Content="RadioButton" HorizontalAlignment="Left" Margin="88,92,0,0" VerticalAlignment="Top"/> <CheckBox Content="CheckBox" HorizontalAlignment="Left" Margin="252,96,0,0" VerticalAlignment="Top"/> <ComboBox Name="combo" IsEditable="False" Text="aaa" IsReadOnly="True" HorizontalAlignment="Left" Margin="337,89,0,0" VerticalAlignment="Top" Width="120" Focusable="True" GotFocus="ComboBoxGotFocused" > <ComboBoxItem>January</ComboBoxItem> <ComboBoxItem>February</ComboBoxItem> </ComboBox> <TextBlock HorizontalAlignment="Left" Height="40" Margin="260,184,0,0" TextWrapping="Wrap" Text="Text_Block" VerticalAlignment="Top" Width="257"/> </Grid></Window> Now provide the response and nothing else.
In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't. Here are some that do not resize their contents (I'm guessing that you are using one or more of these): StackPanelWrapPanelCanvasTabControl Here are some that do resize their contents: GridUniformGridDockPanel Therefore, it is almost always preferable to use a Grid instead of a StackPanel unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid to not size its inner controls... it all depends on your Grid.RowDefinition and Grid.ColumnDefinition settings: <Grid> <Grid.RowDefinitions> <RowDefinition Height="100" /> <!--<<< Exact Height... won't resize --> <RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents --> <RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space --> </Grid.RowDefinitions></Grid> You can find out more about the Grid control from the Grid Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN. Further resizing can be achieved using the FrameworkElement.HorizontalAlignment and FrameworkElement.VerticalAlignment properties. The default value of these properties is Stretch which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch. UPDATE >>> In response to the questions in your comment: Use the Grid.RowDefinition and Grid.ColumnDefinition settings to organise a basic structure first... it is common to add Grid controls into the cells of outer Grid controls if need be. You can also use the Grid.ColumnSpan and Grid.RowSpan properties to enable controls to span multiple columns and/or rows of a Grid . It is most common to have at least one row/column with a Height / Width of "*" which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be. There is no Auto setting that you can use on the controls in the cells, but this is just as well, because we want the Grid to size the controls for us... therefore, we don't want to set the Height or Width of these controls at all. The point that I made about the FrameworkElement.HorizontalAlignment and FrameworkElement.VerticalAlignment properties was just to let you know of their existence... as their default value is already Stretch , you don't generally need to set them explicitly. The Margin property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin property to suit your needs.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19393774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1794925/']}
jdg_80571
stackexchange
llm_judgeable_groundtruth_similarity
45183875
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 STS and now I am using IntelliJ Ultimate Edition but I am still getting the same output. My controller is not getting mapped thus showing 404 error. I am completely new to Spring Framework. DemoApplication.java package com.webservice.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.ComponentScan;@SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }} HelloController.java package com.webservice.demo;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class HelloController { @RequestMapping("/hello") public String sayHello(){ return "Hey"; }} Console Output com.webservice.demo.DemoApplication : Starting DemoApplication on XFT000159365001 with PID 11708 (started by Mayank Khursija in C:\Users\Mayank Khursija\IdeaProjects\demo) 2017-07-19 12:59:46.150 INFO 11708 --- [ main] com.webservice.demo.DemoApplication : No active profile set, falling back to default profiles: default 2017-07-19 12:59:46.218 INFO 11708 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@238e3f: startup date [Wed Jul 19 12:59:46 IST 2017]; root of context hierarchy 2017-07-19 12:59:47.821 INFO 11708 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8211 (http) 2017-07-19 12:59:47.832 INFO 11708 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2017-07-19 12:59:47.832 INFO 11708 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15 2017-07-19 12:59:47.944 INFO 11708 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2017-07-19 12:59:47.944 INFO 11708 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1728 ms 2017-07-19 12:59:47.987 INFO 11708 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2017-07-19 12:59:48.510 INFO 11708 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-07-19 12:59:48.519 INFO 11708 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0 2017-07-19 12:59:48.634 INFO 11708 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8211 (http) 2017-07-19 12:59:48.638 INFO 11708 --- [ main] com.webservice.demo.DemoApplication : Started DemoApplication in 2.869 seconds (JVM running for 3.44) Now provide the response and nothing else.
I too had the similar issue and was able to finally resolve it by correcting the source package structure following this Your Controller classes are not scanned by the Component scanning. Your Controller classes must be nested below in package hierarchy to the main SpringApplication class having the main() method, then only it will be scanned and you should also see the RequestMappings listed in the console output while Spring Boot is getting started. Tested on Spring Boot 1.5.8.RELEASE But in case you prefer to use your own packaging structure, you can always use the @ComponentScan annotation to define your basePackages to scan.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/45183875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6154775/']}
jdg_80572
stackexchange
llm_judgeable_groundtruth_similarity
33575419
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried to follow this tutorial: http://t4-editor.tangible-engineering.com/blog/how-to-generate-multiple-output-files-from-a-single-t4-template.html with visual studio 2015 (.Net 4.5) Sample project with error: http://www.filedropper.com/t4fail I created the Template1.tt with the following source: <#@ include file="TemplateFileManagerV2.1.ttinclude" #><#@ Assembly Name="System.Core" #><#@ Assembly Name="System.Windows.Forms" #><#@ import namespace="System" #><#@ import namespace="System.IO" #><#@ import namespace="System.Diagnostics" #><#@ import namespace="System.Linq" #><#@ import namespace="System.Collections" #><#@ import namespace="System.Collections.Generic" #> <# var manager = TemplateFileManager.Create(this);#> I added TemplateFileManagerV2.1.ttinclude from template gallery to my project. Then I got an error: 'Microsoft.VisualStudio.TextTemplating.IDebugTextTemplatingEngine' is defined in an assembly that is not referenced. You must add a reference to assembly 'Microsoft.VisualStudio.TextTemplating.Interfaces.11.0, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. So I added references to C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.VisualStudio.TextTemplating.11.0\v4.0_11.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.TextTemplating.11.0.dll and C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.VisualStudio.TextTemplating.Interfaces.11.0\v4.0_11.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.TextTemplating.Interfaces.11.0.dll to my project, but nothing changed. The error was in the following method inside .ttinclude public string GetTemplateContent(string templateName, TextTemplatingSession session) { string fullName = this.Host.ResolvePath(templateName); string templateContent = File.ReadAllText(fullName); var sessionHost = this.Host as ITextTemplatingSessionHost; sessionHost.Session = session; Engine engine = new Engine(); return engine.ProcessTemplate(templateContent, this.Host); } I replaced it with public string GetTemplateContent(string templateName, TextTemplatingSession session) { string fullName = this.Host.ResolvePath(templateName); string templateContent = File.ReadAllText(fullName); var sessionHost = this.Host as ITextTemplatingSessionHost; sessionHost.Session = session; //Engine engine = new Engine(); return "";//engine.ProcessTemplate(templateContent, this.Host); } to check if the problem is indeed in dll and got: 'Microsoft.VisualStudio.TextTemplatingA30AC8B57EFC4307E43667FCD72F5E4857F498C5224AE0D43FFC74B3A98D4FA090794EF196648D62B1BC664AFBA5EDE831067D7D1768A759EBBE83426975F7AA.GeneratedTextTransformation' does not contain a definition for 'Host' and no extension method 'Host' accepting a first argument of type 'Microsoft.VisualStudio.TextTemplatingA30AC8B57EFC4307E43667FCD72F5E4857F498C5224AE0D43FFC74B3A98D4FA090794EF196648D62B1BC664AFBA5EDE831067D7D1768A759EBBE83426975F7AA.GeneratedTextTransformation' could be found (are you missing a using directive or an assembly reference?) It seems, that it's not. Now provide the response and nothing else.
I remember I found an easier way to do it back in 2010, but now, after looking across the web for that method, I couldn't find it again. So, after some digging, I managed to find it in an old source code repository. Here's how I did it back then, without making use of any external file or dependency: <#@ template debug="false" hostspecific="true" language="C#" #><#@ assembly name="System.Core" #><#@ import namespace="System" #><#@ import namespace="System.IO" #><#@ output extension=".txt" #><#for (Int32 i = 0; i < 10; ++i) {#>Content <#= i #><# // End of file. SaveOutput("Content" + i.ToString() + ".txt");}#><#+private void SaveOutput(string outputFileName) { string templateDirectory = Path.GetDirectoryName(Host.TemplateFile); string outputFilePath = Path.Combine(templateDirectory, outputFileName); File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);}#> Please note that I don't know who the original author of this method is. If you happen to know who he or she is, please leave a comment.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33575419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136963/']}
jdg_80573
stackexchange
llm_judgeable_groundtruth_similarity
13654401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on some shaders, and I need to transform normals. I read in few tutorials the way you transform normals is you multiply them with the transpose of the inverse of the modelview matrix . But I can't find explanation of why is that so, and what is the logic behind that? Now provide the response and nothing else.
Take a look at this tutorial: https://paroj.github.io/gltut/Illumination/Tut09%20Normal%20Transformation.html You can imagine that when the surface of a sphere stretches (so the sphere is scaled along one axis or something similar) the normals of that surface will all 'bend' towards each other. It turns out you need to invert the scale applied to the normals to achieve this. This is the same as transforming with the Inverse Transpose Matrix . The link above shows how to derive the inverse transpose matrix from this. Also note that when the scale is uniform, you can simply pass the original matrix as normal matrix. Imagine the same sphere being scaled uniformly along all axes, the surface will not stretch or bend, nor will the normals.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13654401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1796942/']}
jdg_80574
stackexchange
llm_judgeable_groundtruth_similarity
299120
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 certain bash script, which wants to preserve original /dev/stdout location before replacing 1st file descriptor with other location. So, naturally, I wrote something like old_stdout=$(readlink -f /dev/stdout) And it didn't work. Very quickly I understand what the problem was: test@ubuntu:~$ echo $(readlink -f /dev/stdout)/proc/5175/fd/pipe:[31764]test@ubuntu:~$ readlink -f /dev/stdout/dev/pts/18 Obvioulsly, $() runs in a subshell, which is piped to the parent shell. So the question is: is there a reliable (scoped to portability between Linux distributions) way to save /dev/stdout location as a string in a bash script? Now provide the response and nothing else.
To save a file descriptor, you duplicate it on another fd. Saving a path to the corresponding file is not enough, you'd need to save the opening mode, the opening flags, the current position within the file and so on. And of course, for anonymous pipes, or sockets, that wouldn't work as those have no path. What you want to save is the open file description that the fd refers to, and duplicating an fd is actually returning a new fd to the same open file description . To duplicate a file descriptor onto another, with Bourne-like shell, the syntax is: exec 3>&1 Above, fd 1 is duplicated onto fd 3. Whatever fd 3 was already open to before would be closed, but note that fds 3 to 9 (usually more, up to 99 with yash ) are reserved for that purpose (and have no special meaning contrary to 0, 1, or 2), the shell knows not to use them for its own internal business. The only reason fd 3 would have been open beforehand is because you did it in the script 1 , or it was leaked by the caller. Then, you can change stdout to something else: exec > /dev/null And later, to restore stdout: exec >&3 3>&- ( 3>&- being to close the file descriptor which we no longer need). Now, the problem with that is that except in ksh, every command you run after that exec 3>&1 will inherit that fd 3. That's a fd leak. Generally not a big deal, but that can cause problem. ksh sets the close-on-exec flag on those fds (for fds over 2), but not other shells and other shells don't have any way to set that flag manually. The work around for other shell is to close the fd 3 for each and every command, like: exec 3>&-exec > file.logls 3>&-uname 3>&-exec >&3 3>&- Cumbersome. Here, the best way would be to not use exec at all, but redirect command groups: { ls uname} > file.log There, it's the shell that takes care to save stdout and restore it afterwards (and it does do it internally by duplicating it on a fd (above 9, above 99 for yash ) with the close-on-exec flag set). Note 1 Now, the management of those fds 3 to 9 can be cumbersome and problematic if you use them extensively or in functions, especially if your script uses some third party code that may in turn use those fds. Some shells ( zsh , bash , ksh93 , all added the feature ( suggested by Oliver Kiddle of zsh ) around the same time in 2005 after it was discussed among their developers) have an alternative syntax to assign the first free fd above 10 instead which helps in this case: myfunction() { local fd exec {fd}>&1 # stdout was duplicated onto a new fd above 10, whose actual value # is stored in the fd variable ... # it should even be safe to re-enter the function here ... exec >&"$fd" {fd}>&-}
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/299120', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/101764/']}
jdg_80575
stackexchange
llm_judgeable_groundtruth_similarity
60852911
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to pass HTML string as argument in javascript, in django template.Here it is:I have bunch of links, which they are in my database.I can access these links via {% for link in links %} {{ link }} {% endfor %} in my django template.for example, I can access a certain link name with using {{ link.name }} , but I also have content specified to every links; like {{ link.content }} . the problem is; in my template I have a sidebar nav which contains several link's urls, and I want to display the content of clicked link in that page. for that, I wrote a javascript function named display: <script> function display(str){ document.getElementById('cont').innerHTML = str: }</script> which will access: <div id="cont"> </div> here it is: <a class="nav-link active" href="{{ link.link }}" onclick="display('{{ link.content }}')">{{ link.name }}</a> in the code above, the display function doesn't work.I mean, when I click the link in sidebar, it doesn't show any content, literally nothing.but for test, when I changed the display argument {{ link.content }} to something else like '<h1>hello<h1>' , it worked. p.s: my link's content is an inline html tags like: '<h1><strong>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp' and note that I put my <script> ... at bottom of the <body> .I will be very thankful for any helps and guides. Now provide the response and nothing else.
You can copy paste run full code below, full code fix this issue Reason: This line userProfile.user = snapshot.data; cause error FutureBuilder is build data, and receive notifyListeners() From Flutter team's suggestion, https://github.com/flutter/flutter/issues/16218#issuecomment-403995076 The FutureBuilder 's builder should only build widgets, it shouldn't have any logic. Builders can get called arbitrarily. Solution: In user case, after getUser() you can directly set UserProfile.user Step 1: remove final userProfile = Provider.of<UserProfile>(context); Step 2: move userProfile.user = snapshot.data; logic to futureBuilder 's future FutureBuilder<User>( future: _future.then((value) => Provider.of<UserProfile>(context, listen: false).user = value), full code import 'package:flutter/material.dart';import 'package:provider/provider.dart';void main() { runApp( ChangeNotifierProvider( create: (context) => UserProfile(), child: MyApp(), ), );}class StatefulWrapper extends StatefulWidget { final Function onInit; final Widget child; const StatefulWrapper({@required this.onInit, @required this.child}); @override _StatefulWrapperState createState() => _StatefulWrapperState();}class _StatefulWrapperState extends State<StatefulWrapper> { @override void initState() { if (widget.onInit != null) { widget.onInit(); } super.initState(); } @override Widget build(BuildContext context) { return widget.child; }}class User { String name; User({this.name});}Future<User> getUser() async { print("getUser"); return User(name: "test");}class UserProfile with ChangeNotifier { User _user = User(); get user { return _user; } set user(User user) { this._user = user; notifyListeners(); }}class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { //final authService = Provider.of<AuthService>(context); //final userProfile = Provider.of<UserProfile>(context, listen: false); Future _future = getUser(); return StatefulWrapper( onInit: () { //FirebaseNotifications().setUpFirebase(); }, child: FutureBuilder<User>( future: _future.then((value) => Provider.of<UserProfile>(context, listen: false).user = value), builder: (context, AsyncSnapshot<User> snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.error != null) { return Text(snapshot.error.toString()); } if (snapshot.hasData) { return ListScreen(); } else { return LoginScreen(); } } else { return Scaffold( appBar: AppBar(), body: Container(), ); } }, )); }}class ListScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Text("ListScreen"); }}class LoginScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Text("LoginScreen"); }}class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: HomePage(), ); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60852911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10762930/']}
jdg_80576
stackexchange
llm_judgeable_groundtruth_similarity
18980925
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 migrating my application to iOS 7. For handing the status bar issue I have added this code if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f){ CGRect frame = self.navigationController.view.frame; if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { frame.origin.y = 20; } else { frame.origin.x = 20; } [self.navigationController.view setFrame:frame];} This is working fine in normal case. If I am changing orientation (app supports only landscape orientation) or presenting any view controller and dismissing model view controller my view controller alignment changed. The status bar again overlaps my view controller. This piece of code is not working at all. Please guide me to fix this status bar issue. Case 2: This is how I am presenting my view controller ZBarReaderViewController *reader = [ZBarReaderViewController new];reader.readerDelegate = self;if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) reader.supportedOrientationsMask = ZBarOrientationMaskLandscape;else reader.supportedOrientationsMask = ZBarOrientationMaskPortrait; [self presentModalViewController:reader animated:YES]; Ref: Thanks in advance. Now provide the response and nothing else.
Fix for status bar issue in IOS 7 Finally I fixed the status bar over lap issue using the delta value property in xcode5. First I have increased origin - y 20pxl to all the controller used in the Xib (it seams to be working fine only in IOS 7), after that I set the delta value for all the view controller origin -y to -20 it works fine in both iOS 6 and iOS 7. Steps to do that. Xcode 5 provide preview option to view the appearance of the xib in different view based on the OS version. Choose preview option from assistant editor Click assistant editor and choose preview option to preview selected view controller in different version. view controller view preview option. in preview you can find the toggle option to preview view in different version. In preview u can feel the status bar issue clearly if its not fixed properly by toggle the version. Three steps to fix the status bar issue: step 1: Make sure the view target us 7.0 and later in File inspector . Step 2 : Increase the origin - y with 20 pixel (exactly the size of the status bar) for all the controls added in the view controller. Step 3 : Set the delta value of origin y to -20 for all the controls then only it will adjust automatically based on the version. Use preview now and feel the differ that the controls automatically adjust because of the delta value. Once the status bar issue fixed, issue while presenting the model view (ZbarSDk controller) is also fixed automatically. Preview screen :
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18980925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1545180/']}
jdg_80577
stackexchange
llm_judgeable_groundtruth_similarity
6884609
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 seen a lot of people do the former, is there any performance benefit doing one vs the other? Or is it just an eye candy? I personally use the latter every time as it is shorter and personally more readable to me. Now provide the response and nothing else.
The other responses focus on the differences between the two functions. This is true, but if the source array does not contain null or 0 or "" , ... (empty values) values you can benchmark the speed of the two functions: <?phpfunction makeRandomArray( $length ) { $array = array(); for ($i = 0; $i < $length; $i++) { $array[$i] = rand(1, $length); } return $array;}function benchmark( $count, $function ) { $start = microtime(true); for ($i = 0; $i < $count; $i++) { $function(); } return microtime(true) - $start;}$runs = 100000;$smallLength = 10;$small = makeRandomArray($smallLength);var_dump(benchmark($runs, function() { global $small, $smallLength; array_key_exists(rand(0, $smallLength), $small);}));var_dump(benchmark($runs, function() { global $small, $smallLength; !empty($small[rand(0, $smallLength)]);})); Which gave me the following results: For a small array: array_key_exists : float(0.18357992172241) empty : float(0.072798013687134) isset : float(0.070242881774902) For a relative big array: array_key_exists : float(0.57489585876465) empty : float(0.0068421363830566) isset : float(0.0069410800933838) So if it's possible it's faster to use empty or isset .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6884609', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135448/']}
jdg_80578
stackexchange
llm_judgeable_groundtruth_similarity
26445894
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to add a dashed border using CALayer on a UIImageView . I've found a method, but is that working in swift and how can i convert it to swift? o have another imageView which has a border so would be the best solution to use CALayer , so they look similar? How can i obtain this obj-c code to swift? - (CAShapeLayer *) addDashedBorderWithColor: (CGColorRef) color { CAShapeLayer *shapeLayer = [CAShapeLayer layer]; CGSize frameSize = self.size; CGRect shapeRect = CGRectMake(0.0f, 0.0f, frameSize.width, frameSize.height); [shapeLayer setBounds:shapeRect]; [shapeLayer setPosition:CGPointMake( frameSize.width/2,frameSize.height/2)]; [shapeLayer setFillColor:[[UIColor clearColor] CGColor]]; [shapeLayer setStrokeColor:color]; [shapeLayer setLineWidth:5.0f]; [shapeLayer setLineJoin:kCALineJoinRound]; [shapeLayer setLineDashPattern: [NSArray arrayWithObjects:[NSNumber numberWithInt:10], [NSNumber numberWithInt:5], nil]]; UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:shapeRect cornerRadius:15.0]; [shapeLayer setPath:path.CGPath]; return shapeLayer;} Now provide the response and nothing else.
Ok, I would do simply like this in the custom view class: Updated for Swift 4 class DashedBorderView: UIView { let _border = CAShapeLayer() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } init() { super.init(frame: .zero) setup() } func setup() { _border.strokeColor = UIColor.black.cgColor _border.fillColor = nil _border.lineDashPattern = [4, 4] self.layer.addSublayer(_border) } override func layoutSubviews() { super.layoutSubviews() _border.path = UIBezierPath(roundedRect: self.bounds, cornerRadius:10).cgPath _border.frame = self.bounds }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26445894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4034437/']}
jdg_80579
stackexchange
llm_judgeable_groundtruth_similarity
56187371
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 created a form using reactive forms and angular material mat-select which I use to create an object called " core ". The core object has 2 properties: "name" and "owners". The "owners" property is an array of IUser objects. The core object: export interface ICore { id?: number; name: string; owners: IUser[];} The form: <form [formGroup]="parentForm"> <mat-form-field class="example-full-width"> <input matInput formControlName="name" placeholder="Name"> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>Users</mat-label> <mat-select formControlName="owners" multiple> <mat-option *ngFor="let user of users" [value]="user"> {{ user.username }}</mat-option> </mat-select> </mat-form-field> </form> The " users " variable is an array of all available users that can be selected. users: IUser[]; The form works great but now I want to use the same form to edit a core object and for that I need to display the core owners in the "owners" form control when the page is loaded. Form creation: createForm() { this.coreForm = this.formBuilder.group({ name: ['', [Validators.required]], owners: ['', [Validators.required]] }); } How I get the core: getCore() { this.coreService.getCore(this.route.snapshot.params['id']) .subscribe( res => { this.core = res; this.updateForm(); }, err => this.toastr.error('Core has not been received!', 'Error!') ); } Form update(it works for the name property): updateForm() { this.coreForm.patchValue({ name: this.core.name, owners: this.core.owners }); } But the owners list is not added. The strange thing is that if I update the form with the users it works: getUsers() { this.usersService.getUsers() .subscribe( res => { this.users = res; this.coreForm.patchValue({ owners: res }); }, err => this.toastr.error('User could not be received!', 'Error!') ); } This way all the users are added as the default value. But for the core owners it's not working. Any idea what I do wrong here? Thanks in advance! Now provide the response and nothing else.
You need to define the criteria based on which an object becomes considered as selected using the [compareWith] directive as follows: <form [formGroup]="parentForm"> <mat-form-field class="example-full-width"> <input matInput formControlName="name" placeholder="Name"> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>Users</mat-label> <mat-select [compareWith]="compareFunction" formControlName="owners" multiple> <mat-option *ngFor="let user of users" [value]="user"> {{ user.username }}</mat-option> </mat-select> </mat-form-field></form> and define your compareFunction: compareFunction(o1: any, o2: any) { return (o1.name == o2.name && o1.id == o2.id);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56187371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3018671/']}
jdg_80580
stackexchange
llm_judgeable_groundtruth_similarity
59179
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 there is a submatrix, let's call $P$: $P=\begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}$ And I want to have $n$, let's say $n=2$, such submatrices placed on the diagonal. The result is expected to look like: $Q=\begin{pmatrix} 1 & 1 & 0 & 0 \\ 1 & 1 & 0 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 0 & 1 & 1 \end{pmatrix}$ How do I write the code in Mathematica? Now provide the response and nothing else.
f1 = KroneckerProduct[IdentityMatrix[#], #2]& f2 = SparseArray[{Band[{1, 1}, # Dimensions@#2] -> {#2}}] &f3 = SparseArray[{Band[{1, 1}] -> ConstantArray[#2, #]}] &f4 = ArrayFlatten[IdentityMatrix[#] /. 1 -> #2 ] &p = Table[1, {2}, {2}];f1[3, p]f2[3, p] // Normalf3[3, p] // Normalf4[3, p] all give (* {{1,1,0,0,0,0},{1,1,0,0,0,0}, {0,0,1,1,0,0},{0,0,1,1,0,0}, {0,0,0,0,1,1},{0,0,0,0,1,1}} *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/59179', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/19630/']}
jdg_80581
stackexchange
llm_judgeable_groundtruth_similarity
1209893
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 shortest distance between the parabolas $y^2=x-1$ and $x^2=y-1$ is. Attempt: The shortest distance is along the common normal of the two curves. Now provide the response and nothing else.
Hope a bit of calculus is allowed. Primes are with respect to x. Notice that they are inverse functions of each other, you can swap $ x,y$ to get to the second parabola. They are mirror images with respect to line $ x=y$ . Required point should have this slope $y^{'} =1 $ for its tangent at point of tangency at ends of common normal. Take the parabola with its symmetry axis coinciding with axis. Differentiating $ 2 y y'= 1 , 2 y = 1, $ and the $x,y$ coordinates are $$ (\dfrac54,\dfrac12)$$ and the other point of tangency is again swapped to $$ (\dfrac12,\dfrac54); $$ Now use distance formula between the tangent points to get $ d = \dfrac{3 \sqrt{2}}{4}. $
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1209893', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/226511/']}
jdg_80582
stackexchange
llm_judgeable_groundtruth_similarity
13540661
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using CONNECT BY LEVEL seems to return too many rows when performed on a table. What is the logic behind what's happening? Assuming the following table: create table a ( id number );insert into a values (1);insert into a values (2);insert into a values (3); This query returns 12 rows ( SQL Fiddle ). select id, level as lvl from aconnect by level <= 2 order by id, level One row for each in table A with the value of column LVL being 1 and three for each in table A where the column LVL is 2, i.e.: ID | LVL ---+----- 1 | 1 1 | 2 1 | 2 1 | 2 2 | 1 2 | 2 2 | 2 2 | 2 3 | 1 3 | 2 3 | 2 3 | 2 It is equivalent to this query, which returns the same results. select id, level as lvl from dual cross join aconnect by level <= 2 order by id, level I don't understand why these queries return 12 rows or why there are three rows where LVL is 2 and only one where LVL is 1 for each value of the ID column. Increasing the number of levels that are "connected" to 3 returns 13 rows for each value of ID. 1 where LVL is 1, 3 where LVL is 2 and 9 where LVL is 3. This seems to suggest that the rows returned are the number of rows in table A to the power of the value of LVL minus 1. I would have though that these queries would be the same as the following, which returns 6 rows select id, lvl from ( select level as lvl from dual connect by level <= 2 ) cross join a order by id, lvl The documentation isn't particularly clear, to me, in explaining what should occur. What's happening with these powers and why aren't the first two queries the same as the third? Now provide the response and nothing else.
In the first query, you connect by just the level. So if level <= 1, you get each of the records 1 time. If level <= 2, then you get each level 1 time (for level 1) + N times (where N is the number of records in the table). It is like you are cross joining, because you're just picking all records from the table until the level is reached, without having other conditions to limit the result. For level <= 3, this is done again for each of those results. So for 3 records: Lvl 1: 3 record (all having level 1) Lvl 2: 3 records having level 1 + 3*3 records having level 2 = 12 Lvl 3: 3 + 3*3 + 3*3*3 = 39 (indeed, 13 records each). Lvl 4: starting to see a pattern? :) It's not really a cross join. A cross join would only return those records that have level 2 in this query result, while with this connect by, you get the records having level 1 as well as the records having level 2, thus resulting in 3 + 3*3 instead of just 3*3 record.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13540661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/458741/']}
jdg_80583
stackexchange
llm_judgeable_groundtruth_similarity
223972
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: It is known that there are limited read and write cycles for EEPROM. Suppose I keep writing some important information in EEPROM and read it after power off to ON. Suppose at some point of time the EEPROM fails, how to know this condition? What are the checks I can put? Another question is checking one byte ofEEPROM memory like writing known value and reading the same value is equivalent to checking the complete EEPROM memory say 4K. Now provide the response and nothing else.
There are various strategies to detect such failures. A simple one works and even catches cases where your device gets powered off during a write: Let's say you have a n byte block that you want to write: [ xx xx xx xx xx xx ] Instead of just writing that block you encapsulate it with two counters an a checksum (crc for example) like this: [ counter1 xx xx xx xx xx xx checksum counter2] Write algorithm: Before you write data, first read out the old value of counter1: a = eeprom_read_read (counter1_offset) Now you overwrite the data with incremented counters and a checksum: eeprom_write(counter1_offset, a+1); eeprom_write(data_offset, data); eeprom_write(checksum_offset, calc_checksum...); eeprom_write(counter2_offset, a+1); Read algorithm: If you want to access your data in the eeprom, always read the counters and the checksum along with the data. If counter1 differs from counter2 you likely had a power failure during the write operation. If the counters are the same but the checksum does not match you have a bad eeprom cell.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/223972', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/51619/']}
jdg_80584
stackexchange
llm_judgeable_groundtruth_similarity
23021457
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 wanting to stop a System.Timers.Timer that is running in a SignalR hub after a client closes a window/tab containing the active connection. I have tried sending a bool value to the server by calling server code to notify the server the client is still connected or not, but it's not currently working. window.onbeforeunload = function () { profile.server.setIsConnected(false);}; Server Side: public ProfileHub(){ timer = new Timer(15000); timer.Elapsed += (sender, e) => { timer_Elapsed(sender, e, _isActive); }; timer.AutoReset = false;}[Authorize]private void timer_Elapsed(object sender, ElapsedEventArgs e, bool active){ timer.Stop(); if (active) { System.Diagnostics.Debug.WriteLine("Timer Started"); timer.Start(); } else { System.Diagnostics.Debug.WriteLine("Timer Stopped"); return; } // process code}[Authorize]public void SetIsActive(bool isActive){ _isActive = isActive;} Is this possible and am I on the right track? I suspect it has something to do with the anonymous delegate for timer.Elapsed , but I'm not entirely sure. Now provide the response and nothing else.
SignalR has OnConnected, OnDisconnected, and OnReconnected that are called every time the client does one of those actions. You can simply override them: public override Task OnConnected(){ return base.OnConnected();}public override Task OnDisconnected(){ //custom logic here return base.OnDisconnected();}public override Task OnReconnected(){ return base.OnReconnected();} I've found them to be extremely useful also for debugging purposes. If you're wanting to set a timer for each person, you should use some sort of connectionMapping along with the above functions to keep track of your users.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23021457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541404/']}
jdg_80585
stackexchange
llm_judgeable_groundtruth_similarity
3750109
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use some arguments for an Instrumentation test. I noticed that I can read system properties with System.getProperty() function. So I use setprop command to set a system property. For example: adb shell setprop AP 123 .Inside my Test code I try to read this AP property with : tmp = System.getProperty("AP"); Log.d("MyTest","AP Value = " + tmp); Then I use logcat to view this debug message but I get a null value for this property. Any ideas on what could be wrong? Note that I can still read the system property with adb shell getprop AP command. Now provide the response and nothing else.
To get the property set by 'setprop', there are two options: One. use android.os.SystemProperties, this is a hide API. use it like this: Class clazz = null;clazz = Class.forName("android.os.SystemProperties");Method method = clazz.getDeclaredMethod("get", String.class);String prop = (String)method.invoke(null, "AP");Log.e("so_test", "my prop is: <" + prop + ">"); Two. use 'getprop' utility: Process proc = Runtime.getRuntime().exec(new String[]{"/system/bin/getprop", "AP"});BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));Log.e("so_test", "my prop is: " + reader.readLine()); Maybe using functions availble in NDK is an option too, but why bother?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3750109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342863/']}
jdg_80586
stackexchange
llm_judgeable_groundtruth_similarity
213285
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 some help understanding this proof: Prove: If a sequence converges, then every subsequence converges to the same limit. Proof: Let $s_{n_k}$ denote a subsequence of $s_n$. Note that $n_k \geq k$ for all $k$. This easy to prove by induction: in fact, $n_1 \geq 1$ and $n_k \geq k$ implies $n_{k+1} > n_k \geq k$ and hence $n_{k+1} \geq k+1$. Let $\lim s_n = s$ and let $\epsilon > 0$. There exists $N$ so that $n>N$ implies $|s_n - s| < \epsilon$. Now $k > N \implies n_k > N \implies |s_{n_k} - s| < \epsilon$. Therefore: $\lim_{k \to \infty} s_{n_k} = s$. What is the intuition that each subsequence will converge to the same limit I do not understand the induction that claims $n_k \geq k$ Now provide the response and nothing else.
A sequence converges to a limit $L$ provided that, eventually, the entire tail of the sequence is very close to $L$. If you restrict your view to a subset of that tail, it will also be very close to $L$. An example might help. Suppose your subsequence is to take every other index: $n_1 = 2$, $n_2 = 4$, etc. In general, $n_k = 2k$. Notice $n_k \geq k$, since each step forward in the sequence makes $n_k$ increase by $2$, but $k$ increases only by $1$. The same will be true for other kinds of subsequences (i.e. $n_k$ increases by at least $1$, while $k$ increases by exactly $1$).
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/213285', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38879/']}
jdg_80587
stackexchange
llm_judgeable_groundtruth_similarity
590533
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 often come across figures like this on the net, or as contest problems, asking to find the number of a specific type of polygon in the figure (triangles, in this case). But I've never really found a method for solving it, rather than blindly counting and hoping it's the right answer. For complete graphs, the problem is trivial:- ${n \choose k} \times (n-k)$, where $n$ is the number of vertices of the complete graph, and $(k+1)$ is the number of sides of the polygon in question. But I was wondering if there was a general algorithm for going about these problems. Any ideas? DISCUSSION SO FAR : My above answer obtained for the complete graph is incorrect, as I hadn't considered the possibility of collinear vertices, and hence degenerate polygons (Thanks to Carl's brilliant answer, for pointing this out!). So here's the discussion so far: One can obtain the number of triangles (including degenerate) in any graph from the trace of its adjacency matrix $A$, by the formula $\text{Tr}(A^3)/3!$ (read Carl's post for the explanation). Unfortunately, this cannot be used for higher polygons, since cycles of path lengths $k$, $ k>3$ are attainable in less than $k$ vertices. So, focusing for now on obtaining the number of triangles in a graph, the algorithm is to compute $\text{Tr}(A^3)/3!$, and then to subtract the number of degenerate triangles from it. So now, the essential question is: Is there is a method for systematically enumerating distinct sets of collinear nodes in a graph? Now provide the response and nothing else.
This post illustrates why $\text{Tr}(A^k)$ gives the number of cycles of length $k$ in the graph with adjacency matrix $A$. We have to be careful since a cycle is not the same thing as a polygon. For example, we can make a 4-cycle by moving between two nodes only: XYXY is a 4-cycle, but not a quadrilateral. For triangles it turns out that this is not a problem since you can't form a 3-cycle that isn't also a triangle. (Caveat: you might form a degenerate (flat) triangle if three nodes are colinear. There is no way of detecting whether points are colinear using an abstract graph, represented as an adjacency matrix.) Even with triangles, we still have to be careful of double counting. $\text{Tr}(A^3)$ is the number of 3-cycles in an undirected graph, but this gives 6 for the simple case of a 3-node graph that is itself triangle.$$A=\left(\begin{array}{ccc}0&1&1\\1&0&1\\1&1&0\end{array}\right) \Rightarrow \text{Tr}(A^3)=6$$This is because all of the following cycles are triangles, even though they all form the same triangle: XYZ, XZY, YXZ, YZX, ZXY, ZYX. Since each triangle gets counted 6 times, the total number of triangles in a graph with adjacency matrix $A$ is $$\text{Tr}(A^3)/6 = \text{Tr}(A^3)/3!$$ The example in the original question will have quite a few degenerate triangles since there are so many colinear vertices, making this method less than ideal. You can however compute all the triangles using the trace of the adjacency matrix and then try to count and subtract the number of degenerate triangles.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/590533', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51731/']}
jdg_80588
stackexchange
llm_judgeable_groundtruth_similarity
14587290
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 found some workaround for floating point problem in PHP: php.ini setting precision = 14 342349.23 - 341765.07 = 584.15999999992 // floating point problem php.ini setting, let's say precision = 8 342349.23 - 341765.07 = 584.16 // voila! Demo: http://codepad.org/r7o086sS How bad is that? 1. Can I rely on this solution if I need just precise 2 digits calculations (money)? 2. If not can you provide me a clear example when this solutions fails? Edit: 3. Which php.ini.precision value suits best two digits, money calculations Please mind I can't use integer calculations (float*100 = cents), it's far too late for that. I am not going to work on numbers higher than 10^6 I don't need to compare numbers UPDATE @Baba answer is good, but he used precision=20 , precision=6 in his tests... So still i am not sure is it gonna work or not. Please consider following: Let's say precision = 8 and only thing I do is addition + and subtraction - A + B = C A - B = C Question 1: Is precision workaround gonna fail for numbers between 0..999999.99, where A and B is a number with decimal places? If so please provide me an example. Simple test would do the job: // if it fails what if I use 9,10,11 ???// **how to find when it fails??? **ini_set('precision', 8); for($a=0;$a<999999.99;$a+=0.01) { for($b=0;$b<999999.99;$b+=0.01) { // mind I don't need to test comparision (round($a-$b,2) == ($a-$b)) echo ($a + $b).','.($a - $b)." vs "; echo round($a + $b, 2).','.round($a - $b, 2)."\n"; }} but obviously 99999999 * 2 is too big job so I can't run this test Question 2: How to estimate/calculate when precision workaround fails? Without such crazy tests? Is there any mathematicial*, straight answer for it? How to calculate is gonna to fail or not? *i don't need to know floating point calculations works, but when workaround fails if you know precision, and range of A and B Please mind I really know cents and bcmath are best solution. But still I am not sure is workaround gonna fails or not for substraction and addition Now provide the response and nothing else.
Introduction Floating-point arithmetic is considered an esoteric subject by many people. This is rather surprising because floating-point is ubiquitous in computer systems. Most fractional numbers don't have an exact representation as a binary fraction, so there is some rounding going on. A good start is What Every Computer Scientist Should Know About Floating-Point Arithmetic Questions Question 1 Can I rely on this solution if I need just precise 2 digits calculations (money)? Answer 1 If you need need precise 2 digits then the answer is NO you can not use the php precision settings to ascertain a 2 digit decimal all the time even if you are not going to work on numbers higher than 10^6 . During calculations there is possibility that the precision length can be increased if the length is less than 8 Question 2 If not can you provide me a clear example when this solutions fails? Answer 2 ini_set('precision', 8); // your precision$a = 5.88 ; // cost of 1kg$q = 2.49 ;// User buys 2.49 kg$b = $a * 0.01 ; // 10% Discount only on first kg ;echo ($a * $q) - $b; Output 14.5824 <---- not precise 2 digits calculations even if precision is 8 Question 3 Which php.ini.precision value suits best two digits, money calculations? Answer 3 Precision and Money calculation are 2 different things ... it's not a good idea to use PHP precision for as a base for your financial calculations or floating point length Simple Test Lest Run some example together using bcmath , number_format and simple minus Base $a = 342349.23;$b = 341765.07; Example A ini_set('precision', 20); // set to 20 echo $a - $b, PHP_EOL;echo floatval(round($a - $b, 2)), PHP_EOL;echo number_format($a - $b, 2), PHP_EOL;echo bcsub($a, $b, 2), PHP_EOL; Output 584.15999999997438863584.15999999999996817 <----- Round having a party 584.16584.15 <-------- here is 15 because precision value is 20 Example B ini_set('precision', 14); // change to 14 echo $a - $b, PHP_EOL;echo floatval(round($a - $b, 2)), PHP_EOL;echo number_format($a - $b, 2), PHP_EOL;echo bcsub($a, $b, 2), PHP_EOL; Output 584.15999999997584.16584.16584.16 <-------- at 14 it changed to 16 Example C ini_set('precision', 6); // change to 6 echo $a - $b, PHP_EOL;echo floatval(round($a - $b, 2)), PHP_EOL;echo number_format($a - $b, 2), PHP_EOL;echo bcsub($a, $b, 2), PHP_EOL; Output 584.16584.16584.16584.00 <--- at 6 it changed to 00 Example D ini_set('precision', 3); // change to 3echo $a - $b, PHP_EOL;echo floatval(round($a - $b, 2)), PHP_EOL;echo number_format($a - $b, 2), PHP_EOL;echo bcsub($a, $b, 2), PHP_EOL; Output 584584584.16 <-------------------------------- They only consistent value 0.00  <--- at 3 .. everything is gone Conclusion Forget about floating point and just calculate in cents then later divided by 100 if that is too late just simply use number_format it looks consistent to me . Update Question 1: Is precision workaround gonna fail for numbers between 0..999999.99, where A and B is a number with decimal places? If so please provide me an example Form 0 to 999999.99 at increment of of 0.01 is about 99,999,999 the combination possibility of your loop is 9,999,999,800,000,000 I really don't think anyone would want to run such test for you. Since floating point are binary numbers with finite precision trying to set precision would have limited effect to ensure accuracy Here is a simple test : ini_set('precision', 8);$a = 0.19;$b = 0.16;$c = 0.01;$d = 0.01;$e = 0.01;$f = 0.01;$g = 0.01;$h = $a + $b + $c + $d + $e + $f + $g;echo "Total: " , $h , PHP_EOL;$i = $h-$a;$i = $i-$b;$i = $i-$c;$i = $i-$d;$i = $i-$e;$i = $i-$f;$i = $i-$g;echo $i , PHP_EOL; Output Total: 0.41.0408341E-17 <--- am sure you would expect 0.00 here ; Try echo round($i,2) , PHP_EOL;echo number_format($i,2) , PHP_EOL; Output 00.00 <------ still confirms number_format is most accurate to maintain 2 digit Question 2: How to estimate/calculate when precision workaround fails? Without such crazy tests? Is there any mathematical*, straight answer for it? How to calculate is gonna to fail or not? The fact sill remains Floating Point have Accuracy Problems but for mathematical solutions you can look at Machine precision and backward error analysis Minimizing the effect of accuracy problems i don't need to know floating point calculations works, but when workaround fails if you know precision, and range of A and B Not sure what that statement means :)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14587290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/994054/']}
jdg_80589
stackexchange
llm_judgeable_groundtruth_similarity
28301636
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 tried lot of combination both with xml and programmatically but nothing to do yet.This is the scenario (pay attention to the small red arrow): I have some RadioButtons inside a radio group, in xml this scenario could be represented as: <RadioGroup android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:id="@+id/radiobuttons" android:paddingBottom="@dimen/activity_vertical_margin" android:dividerPadding="30dp"> <RadioButton android:id="@+id/radio_blue" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="How to set the padding on the left of radio pin" android:background="@drawable/container_dropshadow"/> <!-- other radio buttons... --></RadioGroup> My problem is that I didn't find a way to set the left padding of the circle pin neither in xml nor programmatically (I'm interested in both).In fact each padding that I tried to modify in a RadioButton object seems to refer only to the text inside of it (i.e. java functions setPadding and setCompoundDrawablePadding, or xml android:paddingLeft and android:drawablePadding don't work). My container_dropshadow.xml is: <?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Drop Shadow Stack --> <item> <shape> <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" /> <solid android:color="#00CCCCCC" /> </shape> </item> <item> <shape> <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" /> <solid android:color="#10CCCCCC" /> </shape> </item> <item> <shape> <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" /> <solid android:color="#20CCCCCC" /> </shape> </item> <item> <shape> <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" /> <solid android:color="#30CCCCCC" /> </shape> </item> <item> <shape> <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" /> <solid android:color="#50CCCCCC" /> </shape> </item> <!-- Background --> <item> <shape> <solid android:color="@android:color/white" /> <corners android:radius="3dp" /> </shape> </item></layer-list> Now provide the response and nothing else.
I found a way, by using an inset drawable: First, create a new inset drawable (e.g. radio_button_inset.xml) with your desired padding and a link to the theme radio button drawable like this: <inset xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="?android:attr/listChoiceIndicatorSingle" android:insetLeft="@dimen/your_padding_value"/> Second, use this new drawable for your radio button: <RadioButton android:id="@+id/radio_blue" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="How to set the padding on the left of radio pin" android:background="@drawable/container_dropshadow" android:button="@drawable/radio_button_inset"/>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28301636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3138238/']}
jdg_80590
stackexchange
llm_judgeable_groundtruth_similarity
435553
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does creating an object using reflection rather than calling the class constructor result in any significant performance differences? Now provide the response and nothing else.
Yes - absolutely. Looking up a class via reflection is, by magnitude , more expensive. Quoting Java's documentation on reflection : Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications. Here's a simple test I hacked up in 5 minutes on my machine, running Sun JRE 6u10: public class Main { public static void main(String[] args) throws Exception { doRegular(); doReflection(); } public static void doRegular() throws Exception { long start = System.currentTimeMillis(); for (int i=0; i<1000000; i++) { A a = new A(); a.doSomeThing(); } System.out.println(System.currentTimeMillis() - start); } public static void doReflection() throws Exception { long start = System.currentTimeMillis(); for (int i=0; i<1000000; i++) { A a = (A) Class.forName("misc.A").newInstance(); a.doSomeThing(); } System.out.println(System.currentTimeMillis() - start); }} With these results: 35 // no reflection465 // using reflection Bear in mind the lookup and the instantiation are done together, and in some cases the lookup can be refactored away, but this is just a basic example. Even if you just instantiate, you still get a performance hit: 30 // no reflection47 // reflection using one lookup, only instantiating Again, YMMV.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/435553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4316/']}
jdg_80591
stackexchange
llm_judgeable_groundtruth_similarity
24612374
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 regex which matches to a standard html structure: <(.*)html(.*)>(.*)<head(.*)>(.*)</head>(.*)<body(.*)>(.*)<body(.*)>(.*)</body> which works fine for my node.js / express / jade generated sites. However, if I try to match the following website, I got no match: <HTML><HEAD><TITLE>IPWEBS - 400 Bad Request</TITLE></HEAD><BODY><H2>400 Bad Request</H2><P>The request generated an error response.</P></BODY></HTML> Any idea where I've gone wrong? Case sensitivity is not the problem , I've already checked that. UPDATE: Still with the following updated regex no match: /i<(.*)html(.*)>(.*)<head(.*)>(.*)</head>(.*)<body(.*)>(.*)</body>(.*)</html> (Sorry, tested the new regex already, but during trial with upper case a did some copy/paste errors ;)) COMMENT: I just want to test basic availability and correct html structure with jasmine-node under node.js. I don´t want to parse the DOM or walk through. If anyone has a better idea i´m really happy for suggestions. Now provide the response and nothing else.
There are several ways to do this. send_file and then immediately delete (Linux only) Flask has an after_this_request decorator which could work for this use case: @app.route('/files/<filename>/download')def download_file(filename): file_path = derive_filepath_from_filename(filename) file_handle = open(file_path, 'r') @after_this_request def remove_file(response): try: os.remove(file_path) file_handle.close() except Exception as error: app.logger.error("Error removing or closing downloaded file handle", error) return response return send_file(file_handle) The issue is that this will only work on Linux (which lets the file be read even after deletion if there is still an open file pointer to it). It also won't always work (I've heard reports that sometimes send_file won't wind up making the kernel call before the file is already unlinked by Flask). It doesn't tie up the Python process to send the file though. Stream file, then delete Ideally though you'd have the file cleaned up after you know the OS has streamed it to the client. You can do this by streaming the file back through Python by creating a generator that streams the file and then closes it, like is suggested in this answer : def download_file(filename): file_path = derive_filepath_from_filename(filename) file_handle = open(file_path, 'r') # This *replaces* the `remove_file` + @after_this_request code above def stream_and_remove_file(): yield from file_handle file_handle.close() os.remove(file_path) return current_app.response_class( stream_and_remove_file(), headers={'Content-Disposition': 'attachment', 'filename': filename} ) This approach is nice because it is cross-platform. It isn't a silver bullet however, because it ties up the Python web process until the entire file has been streamed to the client. Clean up on a timer Run another process on a timer (using cron , perhaps) or use an in-process scheduler like APScheduler and clean up files that have been on-disk in the temporary location beyond your timeout (e. g. half an hour, one week, thirty days, after they've been marked "downloaded" in RDMBS) This is the most robust way, but requires additional complexity (cron, in-process scheduler, work queue, etc.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24612374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1361017/']}
jdg_80592
stackexchange
llm_judgeable_groundtruth_similarity
40897966
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Objects are not valid as a React child (found: object with keys {$$typeof, type, key, ref, props, _owner, _store}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of App . AppContainer : const mapDispatchToProps = (dispatch) => { return { } } }} Component: class App extends Component { render() { return ( ); }} Above is my render function for app.js. This Code is working fine in google chrome, but when coming to Internet explorer It is not working and it is throwing the above error. Now provide the response and nothing else.
A problem since React 15.4 with IE11 If you still have this issue, you may have a look at this react issue #8379 about React 15.4 and IE11 .I had the same problem with webpack dev mode / IE11 / React 15.4, and it seems that React and ReactDom each use their version of a Symbol polyfill (this is new with 15.4): Somehow react and react-dom no longer "agree" on the $$typeof value which should be typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103 . Solution I've resolved this issue by reordering polyfill and react / react-dom to be sure that the polyfill Symbol is loaded before React and ReactDom's Symbol... Now they "agree" on $$typeof value. Example solution for webpack: entry: [ 'babel-polyfill', // Load this first 'react-hot-loader/patch', // This package already requires/loads react (but not react-dom). It must be loaded after babel-polyfill to ensure both react and react-dom use the same Symbol. 'react', // Include this to enforce order 'react-dom', // Include this to enforce order './index.js' // Path to your app's entry file]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40897966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7232799/']}
jdg_80593
stackexchange
llm_judgeable_groundtruth_similarity
9635939
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 upgraded my OSX from Snow Leopard to Lion and I downloaded Xcode 4.3.1Now when I try to validate and publish my app I get the first screenshot.If I click on Download Identifier button I get the second screenshot. Any suggest? Now provide the response and nothing else.
I had this same exact error after upgrading my Xcode from 4.2.x? to 4.3.1 via the app store. I did not upgrade my OS or any hardware, and my certificates were only about 2 months old. I has submitted an app update just days before this starting happening and I feel 100% sure that something in the Xcode upgrade caused it to happen. After a few days fiddling with it by rejecting my developer certificates and updating all the apps and provisions profiles, as well as distribution profiles. I noticed something.. See screen shot. The certificate that I was signing the app with was in the group "Identities with out Provisioning Profiles" I went back into the developer provisioning portal and downloaded the distribution certificate for my app, and added to my system, then updated the code signing identity with the correct certificate and I was able to get past this issue. In short this message may suggest, you signed the archive with the wrong certificate. check it and make sure its the one for your app for distribution and it should work. Happy Programing!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9635939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/536926/']}
jdg_80594
stackexchange
llm_judgeable_groundtruth_similarity
1616603
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 PHP, how would one check to see if a specified item (by name, I think - number would probably also work) in an array is empty? Now provide the response and nothing else.
Types of empty (from PHP Manual). The following are considered empty for any variable: "" (an empty string) 0 (0 as an integer) "0" (0 as a string) NULL FALSE array() (an empty array) var $var; (a variable declared, but without a value in a class) So take the example below: $arr = array( 'ele1' => 'test', 'ele2' => false ); 1) $arr['ele3'] is not set. So: isset($arr['ele3']) === false && empty($arr['ele3']) === true it is not set and empty. empty() checks for whether the variable is set and empty or not. 2) $arr['ele2'] is set, but empty. So: isset($arr['ele2']) === true && empty($arr['ele2']) === true 1) $arr['ele1'] is set and not empty: isset($arr['ele1']) === true && empty($arr['ele1']) === false if you wish to check whether is it empty, simply use the empty() function.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1616603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/163905/']}
jdg_80595
stackexchange
llm_judgeable_groundtruth_similarity
47426786
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 passing times in JSON to/from a web API, why would I choose to use an ISO8601 string instead of simply the UTC epoch value? For example, both of these are the same: Epoch = 1511324473iso8601 = 2017-11-22T04:21:13Z The epoch value is obviously shorter in length, which is always good for mobile data usage, and it's pretty simple to convert between epoch values and the language's local Date type variable. I'm just not seeing the benefit to using an ISO string value. Now provide the response and nothing else.
Both are unambiguous and easy to parse in programs. The benefit of epoch like you have mentioned is that it is smaller and will be faster to process in your program. The downside is it means nothing to humans. iso8901 dates are easy to read on their own and don't require the user to translate a number in to a recognizable date. The size increase in iso8601 is unnoticeable when compared to much much larger things like images. Personally I would pick ease of reading over speed for an API as it will cut down on debugging time while inspecting values sent and received. In another situation such as passing times around internally you may wish to choose the speed of an integer over text so it depends which you think will be more useful.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47426786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1455351/']}
jdg_80596
stackexchange
llm_judgeable_groundtruth_similarity
34245932
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 searching a []interface{} slice for a given interface{} value: var v interface{}for i := 0; i < len(A); i++ { if (A[i] == v) { fmt.Println("Gotcha!") break }} In the trivial case the types are int . However what should I do if, for example, the types are some custom struct ? Now provide the response and nothing else.
Thanks to @CodingPickle comment, I provide the following from the Go Programming Language Specification The equality operators == and != apply to operands that are comparable. Regarding interface{} s and structs : Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil. A value x of non-interface type X and a value t of interface type T are comparable when values of type X are comparable and X implements T. They are equal if t's dynamic type is identical to X and t's dynamic value is equal to x. Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal. You can also try this playground https://play.golang.org/p/bgO1_V87v9k In other words, handling equality seems easy in Go!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34245932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2399935/']}
jdg_80597
stackexchange
llm_judgeable_groundtruth_similarity
46987928
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my app, I am using an UICollectionView. Now I want to develop an UIAlertController, when clicking onto any cell of the collection view.I started with following code: extension HomeViewController: UICollectionViewDataSource {func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { …}// specify cellsfunc collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { ….}// called when widget is movedfunc collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { …}// called when clickedfunc collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { print("Got clicked!")}} But somehow, "Got clicked!" is never printed. Now provide the response and nothing else.
try next: extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate {} or func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { ... cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap(_:))))}func tap(_ sender: UITapGestureRecognizer) { let location = sender.location(in: self.collectionView) let indexPath = self.collectionView.indexPathForItem(at: location) if let index = indexPath { print("Got clicked on index: \(index)!") } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46987928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7087118/']}
jdg_80598
stackexchange
llm_judgeable_groundtruth_similarity
30052710
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 question is, I don't quite get why double can store bigger numbers than unsigned long long. Since both of them are 8 bytes long, so 64 bits. Where in unsigned long long, all 64 bits are used in order to store a value, on the other hand double has 1 for sign, 11 for exponent and 52 for mantissa. Even if 52 bits, which are used for mantissa, will be used in order to store decimal numbers without floating point, it still has 63 bits ... BUT LLONG_MAX is significantly smaller than DBL_MAX ... Why? Now provide the response and nothing else.
The reason is that unsigned long long will store exact integers whereas double stores a mantissa (with limited 52-bit precision) and an exponent. This allows double to store very large numbers (around 10 308 ) but not exactly. You have about 15 (almost 16) valid decimal digits in a double , and the rest of the 308 possible decimals are zeroes (actually undefined, but you can assume "zero" for better understanding). An unsigned long long only has 19 digits, but every single of them is exactly defined. EDIT: In reply to below comment "how does this exactly work" , you have 1 bit for the sign, 11 bits for the exponent, and 52 bits for the mantissa. The mantissa has an implied "1" bit at the beginning, which is not stored, so effectively you have 53 mantissa bits. 2 53 is 9.007E15, so you have 15, almost 16 decimal digits to work with. The exponent has a sign bit, and can range from -1022 to +1023, which is used to scale (binary shift left or right) the mantissa (2 1023 is around 10 307 , hence the limits on range), so very small and very large numbers are equally possible with this format. But, of course, all numbers that you can represent only have as much precision as will fit into the matissa. All in all, floating point numbers are not very intuitive, since "easy" decimal numbers are not necessarily representable as floating point numbers at all. This is due to the fact that the mantissa is binary. For example, it is possible (and easy) to represent any positive integer up to a few billion, or numbers like 0.5 or 0.25 or 0.0125, with perfect precision. On the other hand, it is also possible to represent a number like 10 250 , but only approximately. In fact, you will find that 10 250 and 10 250 +1 are the same number (wait, what???). That is because although you can easily have 250 digits, you do not have that many significant digits (read "significant" as "known" or "defined"). Also, representing something seemingly simple like 0.3 is also only possible approximately, even though 0.3 isn't even a "big" number. However, you can't represent 0.3 in binary, and no matter what binary exponent you attach to it, you will not find any binary number that results in exactly 0.3 (but you can get very close). Some "special values" are reserved for "infinity" (both positive and negative) as well as "not a number", so you have very slightly less than the total theoretical range. unsigned long long on the other hand, does not interprete the bit pattern in any way. All numbers that you can represent are simply the exact number that is represented by the bit pattern. Every digit of every number is exactly defined, no scaling happens.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30052710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1446139/']}
jdg_80599
stackexchange
llm_judgeable_groundtruth_similarity
25289231
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following code: public static void main(String args[]){ try { //String ticket = "Negotiate YIGCBg...=="; //byte[] kerberosTicket = ticket.getBytes(); byte[] kerberosTicket = Base64.decode("YIGCBg...=="); GSSContext context = GSSManager.getInstance().createContext((GSSCredential) null); context.acceptSecContext(kerberosTicket, 0, kerberosTicket.length); String user = context.getSrcName().toString(); context.dispose(); } catch (GSSException e) { e.printStackTrace(); } catch (Base64DecodingException e) { e.printStackTrace(); }} Of course it fails. Here's the exception: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag) I don't know what I'm supposed to do to solve this. Honestly, I don't really understand Kerberos. I got this ticket by sending a 401 with the appropriate header WWW-Authenticate with 'Negotiate' as the value. The browser immediately issued the same request again with an authorization header containing this ticket. I was hoping I could validate the ticket and determine who the user is. Do I need a keytab file? If so, what credentials would I run this under? I'm trying to use the Kerberos ticket for auth for a web-site. Would the credentials be the credentials from IIS? What am I missing? Update 1 From Michael-O's reply, I did a bit more googling and found this article , which led me to this article . On table 3 , I found 1.3.6.1.5.5.2 SPNEGO . I have now added that to my credentials following the example from the first article. Here's my code: public static void main(String args[]){ try { Oid mechOid = new Oid("1.3.6.1.5.5.2"); GSSManager manager = GSSManager.getInstance(); GSSCredential myCred = manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, mechOid, GSSCredential.ACCEPT_ONLY); GSSContext context = manager.createContext(myCred); byte[] ticket = Base64.decode("YIGCBg...=="); context.acceptSecContext(ticket, 0, ticket.length); String user = context.getSrcName().toString(); context.dispose(); } catch (GSSException e) { e.printStackTrace(); } catch (Base64DecodingException e) { e.printStackTrace(); }} But now the code is failing on createCredential with this error: GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos credentails) Here's the entire ticket: YIGCBgYrBgEFBQKgeDB2oDAwLgYKKwYBBAGCNwICCgYJKoZIgvcSAQICBgkqhkiG9xIBAgIGCisGAQQBgjcCAh6iQgRATlRMTVNTUAABAAAAl7II4g4ADgAyAAAACgAKACgAAAAGAbEdAAAAD0xBUFRPUC0yNDVMSUZFQUNDT1VOVExMQw== Now provide the response and nothing else.
Validating an SPNEGO ticket from Java is a somewhat convoluted process. Here's a brief overview but bear in mind that the process can have tons of pitfalls. You really need to understand how Active Directory, Kerberos, SPNEGO, and JAAS all operate to successfully diagnose problems. Before you start, make sure you know your kerberos realm name for your windows domain. For the purposes of this answer I'll assume it's MYDOMAIN . You can obtain the realm name by running echo %userdnsdomain% from a cmd window. Note that kerberos is case sensitive and the realm is almost always ALL CAPS. Step 1 - Obtain a Kerberos Keytab In order for a kerberos client to access a service, it requests a ticket for the Service Principal Name [SPN] that represents that service. SPNs are generally derived from the machine name and the type of service being accessed (e.g. HTTP/www.my-domain.com ). In order to validate a kerberos ticket for a particular SPN, you must have a keytab file that contains a shared secret known to both the Kerberos Domain Controller [KDC] Ticket Granting Ticket [TGT] service and the service provider (you). In terms of Active Directory, the KDC is the Domain Controller, and the shared secret is just the plain text password of the account that owns the SPN . A SPN may be owned by either a Computer or a User object within the AD. The easiest way to setup a SPN in AD if you are defining a service is to setup a user-based SPN like so: Create an unpriviledged service account in AD whose password doesn't expire e.g. SVC_HTTP_MYSERVER with password ReallyLongRandomPass Bind the service SPN to the account using the windows setspn utility. Best practice is to define multiple SPNs for both the short name and the FQDN of the host: setspn -U -S HTTP/myserver@MYDOMAIN SVC_HTTP_MYSERVERsetspn -U -S HTTP/myserver.my-domain.com@MYDOMAIN SVC_HTTP_MYSERVER Generate a keytab for the account using Java's ktab utility. ktab -k FILE:http_myserver.ktab -a HTTP/myserver@MYDOMAIN ReallyLongRandomPassktab -k FILE:http_myserver.ktab -a HTTP/myserver.my-domain.com@MYDOMAIN ReallyLongRandomPass If you are trying to authenticate a pre-existing SPN that is bound to a Computer account or to a User account you do not control, the above will not work. You will need to extract the keytab from ActiveDirectory itself. The Wireshark Kerberos Page has some good pointers for this. Step 2 - Setup your krb5.conf In %JAVA_HOME%/jre/lib/security create a krb5.conf that describes your domain. Make sure the realm you define here matches what you setup for your SPN. If you don't put the file in the JVM directory, you can point to it by setting -Djava.security.krb5.conf=C:\path\to\krb5.conf on the command line. Example: [libdefaults] default_realm = MYDOMAIN[realms] MYDOMAIN = { kdc = dc1.my-domain.com default_domain = my-domain.com }[domain_realm] .my-domain.com = MYDOMAIN my-domain.com = MYDOMAIN Step 3 - Setup JAAS login.conf Your JAAS login.conf should define a login configuration that sets up the Krb5LoginModule as a acceptor. Here's an example that assumes that the keytab we created above is in C:\http_myserver.ktab . Point to the JASS config file by setting -Djava.security.auth.login.config=C:\path\to\login.conf on the command line. http_myserver_mydomain { com.sun.security.auth.module.Krb5LoginModule required principal="HTTP/myserver.my-domain.com@MYDOMAIN" doNotPrompt="true" useKeyTab="true" keyTab="C:/http_myserver.ktab" storeKey="true" isInitiator="false";}; Alternatively, you can generate a JAAS config at runtime like so: public static Configuration getJaasKrb5TicketCfg( final String principal, final String realm, final File keytab) { return new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { Map<String, String> options = new HashMap<String, String>(); options.put("principal", principal); options.put("keyTab", keytab.getAbsolutePath()); options.put("doNotPrompt", "true"); options.put("useKeyTab", "true"); options.put("storeKey", "true"); options.put("isInitiator", "false"); return new AppConfigurationEntry[] { new AppConfigurationEntry( "com.sun.security.auth.module.Krb5LoginModule", LoginModuleControlFlag.REQUIRED, options) }; } };} You would create a LoginContext for this configuration like so: LoginContext ctx = new LoginContext("doesn't matter", subject, null, getJaasKrbValidationCfg("HTTP/myserver.my-domain.com@MYDOMAIN", "MYDOMAIN", new File("C:/path/to/my.ktab"))); Step 4 - Accepting the ticket This is a little off-the-cuff, but the general idea is to define a PriviledgedAction that performs the SPNEGO protocol using the ticket. Note that this example does not check that SPNEGO protocol is complete. For example if the client requested server authentication, you would need to return the token generated by acceptSecContext() in the authentication header in the HTTP response. public class Krb5TicketValidateAction implements PrivilegedExceptionAction<String> { public Krb5TicketValidateAction(byte[] ticket, String spn) { this.ticket = ticket; this.spn = spn; } @Override public String run() throws Exception { final Oid spnegoOid = new Oid("1.3.6.1.5.5.2"); GSSManager gssmgr = GSSManager.getInstance(); // tell the GSSManager the Kerberos name of the service GSSName serviceName = gssmgr.createName(this.spn, GSSName.NT_USER_NAME); // get the service's credentials. note that this run() method was called by Subject.doAs(), // so the service's credentials (Service Principal Name and password) are already // available in the Subject GSSCredential serviceCredentials = gssmgr.createCredential(serviceName, GSSCredential.INDEFINITE_LIFETIME, spnegoOid, GSSCredential.ACCEPT_ONLY); // create a security context for decrypting the service ticket GSSContext gssContext = gssmgr.createContext(serviceCredentials); // decrypt the service ticket System.out.println("Entering accpetSecContext..."); gssContext.acceptSecContext(this.ticket, 0, this.ticket.length); // get the client name from the decrypted service ticket // note that Active Directory created the service ticket, so we can trust it String clientName = gssContext.getSrcName().toString(); // clean up the context gssContext.dispose(); // return the authenticated client name return clientName; } private final byte[] ticket; private final String spn;} Then to authenticate the ticket, you would do something like the following. Assume that ticket contains the already-base-64-decoded ticket from the authentication header. The spn should be derived from the Host header in the HTTP request if the format of HTTP/<HOST>@<REALM> . E.g. if the Host header was myserver.my-domain.com then spn should be HTTP/myserver.my-domain.com@MYDOMAIN . public boolean isTicketValid(String spn, byte[] ticket) { LoginContext ctx = null; try { // this is the name from login.conf. This could also be a parameter String ctxName = "http_myserver_mydomain"; // define the principal who will validate the ticket Principal principal = new KerberosPrincipal(spn, KerberosPrincipal.KRB_NT_SRV_INST); Set<Principal> principals = new HashSet<Principal>(); principals.add(principal); // define the subject to execute our secure action as Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); // login the subject ctx = new LoginContext("http_myserver_mydomain", subject); ctx.login(); // create a validator for the ticket and execute it Krb5TicketValidateAction validateAction = new Krb5TicketValidateAction(ticket, spn); String username = Subject.doAs(subject, validateAction); System.out.println("Validated service ticket for user " + username + " to access service " + spn ); return true; } catch(PriviledgedActionException e ) { System.out.println("Invalid ticket for " + spn + ": " + e); } catch(LoginException e) { System.out.println("Error creating validation LoginContext for " + spn + ": " + e); } finally { try { if(ctx!=null) { ctx.logout(); } } catch(LoginException e) { /* noop */ } } return false;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25289231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/918608/']}
jdg_80600
stackexchange
llm_judgeable_groundtruth_similarity
7096670
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 Handlebars.js as a templating tool for my Backbone.js app. My render functions in my views usually look like the following: var source = $("#round").html(); var template = Handlebars.compile(source); var context = JSON.parse(JSON.stringify(this.model)); var html = template(context); $(this.el).html(html); return this; The above is appended to the main app view through the following code(this is the code that calls the above code): $('div#round-container', this.el).append(roundView.render().el); My Handlebars template handles all of the styling and layout, so I leave the "el" element of a view blank. Backbone.js automatically adds surrounding div tags around the Handlebars template. I assume this is because the "el" element is blank. Is there a way to prevent the addition of the surrounding div tags? Thanks! Now provide the response and nothing else.
What's happening is this.el is created on the fly because it was never explicitly set by you. You have two options: You should specify the element you want to create with tagName , className and/or id and let backbone create that for you. In render you should set this.el to the contents of your handlebars template. So you would have this.el = $(template(context)) . The docs have an expanded explanation - http://documentcloud.github.com/backbone/#View-el
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7096670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/897069/']}
jdg_80601
stackexchange
llm_judgeable_groundtruth_similarity
3434440
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to add a custom throws clause to a method definied by an interface. This is not possible. How could I bypass it? Here is some code: private void sendRequestToService(final ModuleRequest pushRequest) { ServiceConnection serviceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder service) { try { //some lines.. } catch (RemoteException e) { throw new RuntimeException(new UnavailableDestException()) ; } } };} Any idea how I could throw my custom exception? Now provide the response and nothing else.
There are two types of exceptions, checked and unchecked . Any Throwable is either one or the other. An example of a checked exception is IOException ; probably the most (in)famous unchecked exception is NullPointerException . Any checked exceptions that a method may throw must be declared in its throws clause. When you @Override a method (either implementing an interface method or overriding an inherited method from a superclass), certain requirements must be met, and one of them is that the throws clause must not cause a conflict. Simplistically speaking, subclasses/implementations can throw LESS , not MORE checked exceptions. An unchecked exception is defined as RuntimeException and its subclasses, and Error and its subclasses. They do not have to be declared in a method's throws clause. So in this particular case, if you want to throw a CustomException in an implementation of an interface method that does not list it in its throws clause, you can make CustomException extends RuntimeException , making it unchecked . (It can also extends any subclass of RuntimeException , e.g. IllegalArgumentException or IndexOutOfBoundsException may be more appropriate in some cases). This will allow you to compile the code as you desire, but note that the choice between choosing checked vs unchecked exception should not be taken too lightly. This is a contentious issue for many, and there are many factors to consider other than just getting the code to compile the way you want it. You may want to consider a redesign of the interface rather than having implementors throwing various undocumented unchecked exceptions not specified by the interface contract. References JLS 11.2 Compile-Time Checking of Exceptions JLS 8.4.6 Method Throws A method that overrides or hides another method, including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method. Related questions In Java, when should I create a checked exception, and when should it be a runtime exception? When to choose checked and unchecked exceptions The case against checked exceptions See also Effective Java 2nd Edition Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors Item 59: Avoid unnecessary use of checked exceptions Item 60: Favor the use of standard exceptions Item 61: Throw exceptions appropriate to the abstraction Item 62: Document all exceptions thrown by each method Workaround "solution" If a redesign is impossible, then wrapping your CustomException in a RuntimeException (or its subclass) will "work". That is, instead of: // ideal solution, not possible without redesign@Override public static void someMethod() throws CustomException { throw new CustomException();}//...try { someMethod();} catch (CustomException e) { handleCustomException(e);} You can, should you insist, do the following: // workaround if redesign is not possible// NOT RECOMMENDED!@Override public static void someMethod() { throw new RuntimeException(new CustomException());}//...try { someMethod();} catch (RuntimeException e) { // not catch(CustomException e) if (e.getCause() instanceof CustomException) { handleCustomException((CustomException) e.getCause()); } else { throw e; // preserves previous behavior }} It needs to be reiterated that this is NOT a recommendable technique in general. You should fix the problem at the design level if at all possible, but barring that, this is indeed a possible workaround.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3434440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260511/']}
jdg_80602
stackexchange
llm_judgeable_groundtruth_similarity
6112710
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 Lua, there seem to be two ways of appending an element to an array: table.insert(t, i) and t[#t+1] = i Which should I use, and why? Now provide the response and nothing else.
Which to use is a matter of preference and circumstance: as the # length operator was introduced in version 5.1, t[#t+1] = i will not work in Lua 5.0, whereas table.insert has been present since 5.0 and will work in both. On the other hand, t[#t+1] = i uses exclusively language-level operators, wheras table.insert involves a function (which has a slight amount of overhead to look up and call and depends on the table module in the environment). In the second edition of Programming in Lua (an update of the Lua 5.0-oriented first edition), Roberto Ierusalimschy (the designer of Lua) states that he prefers t[#t+1] = i , as it's more visible. Also, depending on your use case, the answer may be "neither". See the manual entry on the behavior of the length operator : If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array). As such, if you're dealing with an array with holes, using either one ( table.insert uses the length operator ) may "append" your value to a lower index in the array than you want. How you define the size of your array in this scenario is up to you, and, again, depends on preference and circumstance: you can use table.maxn (disappearing in 5.2 but trivial to write), you can keep an n field in the table and update it when necessary, you can wrap the table in a metatable, or you could use another solution that better fits your situation (in a loop, a local tsize in the scope immediately outside the loop will often suffice).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6112710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102441/']}
jdg_80603
stackexchange
llm_judgeable_groundtruth_similarity
29148544
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 initial problem was to convert a tuple of different types to a string. In Python, this would be something like: >> a = ( 1.3, 1, 'c' )>> b = map( lambda x: str(x), a )['1.3', '1', 'c']>> " ".join(b)'1.3 1 c" Yet, Rust doesn't support map on tuples -- only on vector-like structures. Obviously, this is due to being able to pack different types into a tuple and the lack of function overloading. Also, I couldn't find a way to get the tuple length at runtime. So, I guess, a macro would be needed to do the conversion. As a start, I tried to match the head of an tuple, something like: // doesn't workmatch some_tuple { (a, ..) => println!("{}", a), _ => ()} So, my question: Is it possible, using library functions, to convert a tuple to a string, specifying an arbitrary separator? How to write a macro to be able to map functions to arbitrary sized tuples? Now provide the response and nothing else.
Here's an overly-clever macro solution: trait JoinTuple { fn join_tuple(&self, sep: &str) -> String;}macro_rules! tuple_impls { () => {}; ( ($idx:tt => $typ:ident), $( ($nidx:tt => $ntyp:ident), )* ) => { impl<$typ, $( $ntyp ),*> JoinTuple for ($typ, $( $ntyp ),*) where $typ: ::std::fmt::Display, $( $ntyp: ::std::fmt::Display ),* { fn join_tuple(&self, sep: &str) -> String { let parts: &[&::std::fmt::Display] = &[&self.$idx, $( &self.$nidx ),*]; parts.iter().rev().map(|x| x.to_string()).collect::<Vec<_>>().join(sep) } } tuple_impls!($( ($nidx => $ntyp), )*); };}tuple_impls!( (9 => J), (8 => I), (7 => H), (6 => G), (5 => F), (4 => E), (3 => D), (2 => C), (1 => B), (0 => A),);fn main() { let a = (1.3, 1, 'c'); let s = a.join_tuple(", "); println!("{}", s); assert_eq!("1.3, 1, c", s);} The basic idea is that we can take a tuple and unpack it into a &[&fmt::Display] . Once we have that, it's straight-forward to map each item into a string and then combine them all with a separator. Here's what that would look like on its own: fn main() { let tup = (1.3, 1, 'c'); let slice: &[&::std::fmt::Display] = &[&tup.0, &tup.1, &tup.2]; let parts: Vec<_> = slice.iter().map(|x| x.to_string()).collect(); let joined = parts.join(", "); println!("{}", joined);} The next step would be to create a trait and implement it for the specific case: trait TupleJoin { fn tuple_join(&self, sep: &str) -> String;}impl<A, B, C> TupleJoin for (A, B, C)where A: ::std::fmt::Display, B: ::std::fmt::Display, C: ::std::fmt::Display,{ fn tuple_join(&self, sep: &str) -> String { let slice: &[&::std::fmt::Display] = &[&self.0, &self.1, &self.2]; let parts: Vec<_> = slice.iter().map(|x| x.to_string()).collect(); parts.join(sep) }}fn main() { let tup = (1.3, 1, 'c'); println!("{}", tup.tuple_join(", "));} This only implements our trait for a specific size of tuple, which may be fine for certain cases, but certainly isn't cool yet. The standard library uses some macros to reduce the drudgery of the copy-and-paste that you would need to do to get more sizes. I decided to be even lazier and reduce the copy-and-paste of that solution! Instead of clearly and explicitly listing out each size of tuple and the corresponding index/generic name, I made my macro recursive. That way, I only have to list it out once, and all the smaller sizes are just part of the recursive call. Unfortunately, I couldn't figure out how to make it go in a forwards direction, so I just flipped everything around and went backwards. This means there's a small inefficiency in that we have to use a reverse iterator, but that should overall be a small price to pay.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29148544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4690345/']}
jdg_80604
stackexchange
llm_judgeable_groundtruth_similarity
70809480
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to make a navigation bar with dropdowns when you hover. I got this from w3schools.com, but I wanted to have multiple drop downs next to each other. I have 2 of them next to each other, but when I hover over either of them, it shows the same dropdown menu. How do I fix this? Sorry if this seems obvious, I'm a beginner. .navbar { overflow: hidden; background-color: red; width: 620px; box-shadow: 0 2px 2px #FF0000, -2px 1px 0 #D30000, -4px 2px 0 #FE471E, -8px 3px 0 #FEF100, -12px 4px 0 #00A500, -16px 5px 0 #0080F6, -20px 6px 0 #20007D;}.navbar a { float: left; font-size: 16px; color: white; text-align: center; padding: 14px 16px; text-decoration: none;}.dropdown { float: left; text-align: center; overflow: hidden;}.dropdown .dropbtn { font-size: 16px; border: none; color: white; padding: 14px 16px; background-color: inherit; font-family: inherit; margin: 0;}.navbar a:hover,.dropdown:hover .dropbtn { background-color: red;}.dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 80px; box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); z-index: 10;}.dropdown-content a { float: none; color: black; padding: 12px 16px; text-decoration: none; display: block; text-align: center;}.dropdown-content a:hover { background-color: #ddd;}.dropdown:hover .dropdown-content { display: block;} <div class="navbar"> <a href="#home">Home</a> <a href="#news">Blog</a> <div class="dropdown"> <button class="dropbtn">Projects ▼ </button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> <div class="dropdown"> <button class="dropbtn">Archives ▼ </button> <div class="dropdown-content"> <a href="#">Hello</a> <a href="#">hi</a> <a href="#">how are you</a> </div> </div> </div> <a href="#guestbook">Guestbook</a> <a href="#about">About Me</a></div> Now provide the response and nothing else.
It's not possible to use a dataclass to make an attribute that sometimes exists and sometimes doesn't because the generated __init__ , __eq__ , __repr__ , etc hard-code which attributes they check. However, it is possible to make a dataclass with an optional argument that uses a default value for an attribute (when it's not provided). from dataclasses import dataclassfrom typing import Optional@dataclassclass CampingEquipment: knife: bool fork: bool missing_flask_size: Optional[int] = None kennys_stuff = { 'knife':True, 'fork': True}print(CampingEquipment(**kennys_stuff)) And it's possible to make a dataclass with an argument that's accepted to __init__ but isn't an actual field .So you could do something like this: from dataclasses import dataclass, InitVarfrom typing import Optional@dataclassclass CampingEquipment: knife: bool fork: bool missing_flask_size: InitVar[Optional[int]] = None def __post_init__(self, missing_flask_size): if missing_flask_size is not None: self.missing_flask_size = missing_flask_size If you really want classes to either to have that attribute present or not have it at all, you could subclass your dataclass and make a factory function that creates one class or the other based on whether that missing_flask_size attribute is present: from dataclasses import dataclass@dataclassclass CampingEquipment: knife: bool fork: bool@dataclassclass CampingEquipmentWithFlask: missing_flask_size: intdef equipment(**fields): if 'missing_flask_size' in fields: return CampingEquipmentWithFlask(**fields) return CampingEquipment(**fields) kennys_stuff = { 'knife':True, 'fork': True}print(CampingEquipment(**kennys_stuff)) If you really wanted to (I wouldn't recommend it though), you could even customize the __new__ of CampingEquipment to return an instance of that special subclass when that missing_flask_size argument is given (though then you'd need to set init=False and make your own __init__ as well on that class).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70809480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17998642/']}
jdg_80605
stackexchange
llm_judgeable_groundtruth_similarity
20116791
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering if in F# there is some sugar for cloning a class instance changing just one or a few of the properties. I know in F# it is possible with records: let p2 = {p1 with Y = 0.0} Now provide the response and nothing else.
One way to simulate copy-and-update expressions for classes is with a copy constructor taking optional args. type Person(first, last, age) = new (prototype: Person, ?first, ?last, ?age) = Person(defaultArg first prototype.First, defaultArg last prototype.Last, defaultArg age prototype.Age) member val First = first member val Last = last member val Age = agelet john = Person("John", "Doe", 45)let jane = Person(john, first="Jane") EDIT You didn't ask for this, but in many cases making the class mutable results in clearer code: type Person(first, last, age) = member val First = first with get, set member val Last = last with get, set member val Age = age with get, set member this.Clone() = this.MemberwiseClone() :?> Personlet john = Person("John", "Doe", 45)let jane = john.Clone() in jane.First <- "Jane"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20116791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2085376/']}
jdg_80606
stackexchange
llm_judgeable_groundtruth_similarity
4793490
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I sort a map of this kind: "01" -> List(34,12,14,23), "11" -> List(22,11,34) by the beginning values? Now provide the response and nothing else.
One way is to use scala.collection.immutable.TreeMap, which is always sorted by keys: val t = TreeMap("01" -> List(34,12,14,23), "11" -> List(22,11,34))//If you have already a map...val m = Map("01" -> List(34,12,14,23), "11" -> List(22,11,34))//... use thisval t = TreeMap(m.toSeq:_*) You can convert it to a Seq or List and sort it, too: //by specifying an element for sortingm.toSeq.sortBy(_._1) //sort by comparing keysm.toSeq.sortBy(_._2) //sort by comparing values//by providing a sort functionm.toSeq.sortWith(_._1 < _._1) //sort by comparing keys There are plenty of possibilities, each more or less convenient in a certain context.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4793490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587731/']}
jdg_80607
stackexchange
llm_judgeable_groundtruth_similarity
2028
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 three Computers. PC1 and PC2 is on a private LAN, where PC1 is known to PC2 as 192.168.0.2 PC2 and PC3 is on a another LAN, where PC2 is known to PC3 as 192.168.123.101 How can I connect to PC1 from PC3 with SSH. Is there something like: ssh [email protected] -via [email protected] Now provide the response and nothing else.
ssh -o 'ProxyCommand ssh -W %h:%p [email protected]' Then you can simply run ssh PC1 . Best used through an alias in ~/.ssh/config : Host PC1HostName 192.168.0.2User userProxyCommand ssh -W %h:%p [email protected] For older versions of OpenSSH that don't have the -W option (I think this means ≤5.4), make sure that netcat is available on PC2 and use Host PC1HostName 192.168.0.2User userProxyCommand ssh [email protected] nc %h %p
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/2028', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/1327/']}
jdg_80608
stackexchange
llm_judgeable_groundtruth_similarity
9712416
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 below query. When type_id is null I want it to be grouped by the name "unknown". How can I do it. I know there is a decode function but I'm not sure how to use it. select type_id, name from test_table group by decode(type_id,'Unknown'), name; how can I do it? Now provide the response and nothing else.
select decode(type_id, null, 'Unknown', type_id), name, count(*)from( select 'asdf' type_id, 'name1' name from dual union all select 'asdf' type_id, 'name2' name from dual union all select null type_id, 'name3' name from dual) test_tablegroup by type_id,name; I agree with @sql_mommy that CASE would probably look better. But I disagree about using TechOnTheNet as your primary source of information. You are usually better off with the official documentation, and the page for DECODE is a good example of why. DECODE has some strange behavior: "In a DECODE function, Oracle considers two nulls to be equivalent." That behavior is not mentioned in the TechOnTheNet article.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9712416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/273212/']}
jdg_80609
stackexchange
llm_judgeable_groundtruth_similarity
6796896
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 noticed that the C# compiler doesn't infer second generic parameter. Example: C++ template code: (yea I know that templates don't work like generics) class Test {public:template <class T,class V> T test(V v) { //do something with v return T(); }};int i = 0;Test t = new Test();double j = t.test<double>(i); //infers V as int The templates (and generics) can't infer return type, so in C++ I give it the first template parameter, and the second template parameter is inferred from the variable type. Now, same example in C#: class Test { public T test<T,V>(V v) where T: new() { //do something with v return new T(); }};int i = 0;Test t = new Test();double j = t.test<double>(i); //Error Using the generic method 'Test.test<T,V>(V)' requires '2' type arguments But if i use 1 type, I don't have to explicitly specify the type: class Test { public V test<V>(V v) where V: new() { return new V(); }};int i = 0;Test t = new Test();int j = t.test(i); //OK infers V as int. So, why can't C# generics infer the second type (while in c++ templates it clearly can) ? I'm sure it's designed that way (I doubt they the .Net team overlooked this), so why is it designed this way that I must explicitly specify both types? Edit: From the discussions we had in the answers so far, both languages support overloading by number of template parameters. So again, why is C# designed this way ? What's different in the language implementation that doesn't allow to explicitly declare only one parameter ? Now provide the response and nothing else.
C# has been designed to be a slightly less brain-bending language than C++. In particular, I don't think it's a great idea to compare C# generics to C++ templates for various reasons - they're fundamentally two really quite different approaches to accomplishing similar things in some situations. The C++ approach is certainly flexible in some ways - although it doesn't allow (as I understand it) templates which only exist in binary form, or new template specializations to be created at execution time. Basically the C++ templating approach doesn't sit well with the rest of how .NET fits together. Now as for why you can't specify some type arguments and allow others to be inferred (which is a language decision rather than a platform decision; I'm sure it would be feasible as far as .NET itself is concerned) - again, I believe this is for the sake of simplicity. Choosing the exact right method and the right type arguments is already extremely complicated in C# - more complicated than most C# developers can get their heads round. It involves: Potentially considering methods up the type hierarchy from the compile-time type of the target Overloading by number of parameters Overloading by the number of type parameters The effect of named arguments The effect of optional parameters The effect of generic type parameter constraints on parameter types ( not constraints specified by the target method, note) Method group to delegate conversions Anonymous function conversions Type inference for type arguments Dynamic typing Generic covariance and contravariance Personally, I think that's enough to get my head around, without allowing yet more possiblities via "M can still be a candidate if it has at least as many type parameters as specified type arguments". Would you also want named type arguments and optional type parameters? ;) I've looked at overloading quite a lot, following the spec thoroughly etc. I've found areas which make the language designers scratch their heads and try to work out what the compiler should do. I've found areas which the compiler definitely gets wrong. I wouldn't want to add any more complexity here without a really good reason. So yes, it's basically for the sake of simplicity, and sometimes that's a pain - but often you can work around it. For every potential feature, you need to consider: The benefit of the feature to end developers The cost of the feature to end developers in terms of time spent understanding it The cost to the language designers in designing and specifying it thoroughly The cost to the compiler writers in implementing it correctly The cost to the test team in testing it thoroughly (in conjunction with everything else around overloading) The cost to future potential features (if this one makes the language more complicated, that leaves less "potentially grokable" additional complexity for other features)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6796896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/536086/']}
jdg_80610
stackexchange
llm_judgeable_groundtruth_similarity
421479
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm guessing this is a pretty basic question, but I am having a hard time wrapping my head around it. So my understanding with linear regression, is that it shows how much a change in X, will cause a change in Y. And the same with multiple linear regression. But can the same be said about logistic regression? What if both of the variables are nominal? Can you do logistic regression this way? I am currently running an ordinal variable against a nominal one, and I get similar results when I alternate independent vs dependent. So, my question is should logistic regression be viewed as explaining causal relationships as we do with linear regression? Or is it possible that causality is overwritten by multicollinearity? Leaving us with strictly correlational inferences?Thanks Now provide the response and nothing else.
Causality has nothing to do with regression. You can regress any variables that are not causally linked. Better way of thinking of regression is "response of Y to X", or "relationship of Y and X". And in this regard it does not matter if the link function is identical (as in the normal regression) or logit function (as in the logistic regression). In logistic regression the response of Y to X will just have different shape due to the logit link function than it would have in normal regression. So the answer is no, there are no differences in causality.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/421479', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/256019/']}
jdg_80611
stackexchange
llm_judgeable_groundtruth_similarity
32730296
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 migrating from MySQL to Postgres. In MySQL I can use select sum(clicks) c from table where event_date >= '1999-01-01' group by keyword_id having c > 10 Postgres gives an error ERROR: column "c" does not exist In Postgres I have to repeat the function in the having clause select sum(clicks) c from table where event_date >= '1999-01-01' group by keyword_id having sum(clicks) > 10 There are a lot of places in the code that I have to change. Is there a setting in Postgres that will allow it to use column aliases in the having clause? Now provide the response and nothing else.
Is there a setting in Postgres that will allow it to use column aliases in the having clause? No. Implementations that allow references to SELECT -list entries in HAVING are going outside the standard. You should use a subquery, e.g. select cfrom ( select sum(clicks) c from table where event_date >= '1999-01-01' group by keyword_id ) xwhere c > 10; ... or repeat the aggregate.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32730296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148844/']}
jdg_80612
stackexchange
llm_judgeable_groundtruth_similarity
17836743
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following setup IObservable<Data> source = ...;source .Select(data=>VeryExpensiveOperation(data)) .Subscribe(data=>Console.WriteLine(data)); Normally the events come seperated by a reasonable time frame.Imagine a user updating a text box in a form. Our VeryExpensiveOperation might take 5 seconds to complete and whilst it does an hour glassis displayed on the screen. However if during the 5 seconds the user updates the textbox againI would want to send a cancelation to the current VeryExpensiveOperation before the new one starts. I would imagine a scenario like source .SelectWithCancel((data, cancelToken)=>VeryExpensiveOperation(data, token)) .Subscribe(data=>Console.WriteLine(data)); So every time the lambda is called is is called with a cancelToken which can beused to manage canceling a Task . However now we are mixing Task, CancelationToken and RX. Not quite sure how to fit it all together. Any suggestions. Bonus Points for figuring out how to test the operator using XUnit :) FIRST ATTEMPT public static IObservable<U> SelectWithCancelation<T, U>( this IObservable<T> This, Func<CancellationToken, T, Task<U>> fn ) { CancellationTokenSource tokenSource = new CancellationTokenSource(); return This .ObserveOn(Scheduler.Default) .Select(v=>{ tokenSource.Cancel(); tokenSource=new CancellationTokenSource(); return new {tokenSource.Token, v}; }) .SelectMany(o=>Observable.FromAsync(()=>fn(o.Token, o.v))); } Not tested yet. I'm hoping that a task that does not complete generates an IObservable that completes without firing any OnNext events. Now provide the response and nothing else.
You have to model VeryExpensiveOperation as an cancellable asynchronous thing. Either a Task or an IObservable . I'll assume it is a task with a CancellationToken : Task<TResult> VeryExpensiveOperationAsync<TSource, TResult>(TSource item, CancellationToken token); Then you do it like so: source .Select(item => Observable.DeferAsync(async token => { // do not yield the observable until after the operation is completed // (ie do not just do VeryExpensiveOperation(...).ToObservable()) // because DeferAsync() will dispose of the token source as soon // as you provide the observable (instead of when the observable completes) var result = await VeryExpensiveOperationAsync(item, token); return Observable.Return(result); }) .Switch(); The Select just creates a deferred observable that, when subscribed, will create a token and kick off the operation. If the observable is unsubscribed before the operation finishes, the token will be cancelled. The Switch subscribes to each new observable that comes out of Select , unsubscribing from the previous observable it was subscribed to. This has the effect you want. P.S. this is easily testable. Just provide a mock source and a mock VeryExpensiveOperation that uses a TaskCompletetionSource provided by the unit test so the unit test can control exactly when new source items are produced and when tasks are completed. Something like this: void SomeTest(){ // create a test source where the values are how long // the mock operation should wait to do its work. var source = _testScheduler.CreateColdObservable<int>(...); // records the actions (whether they completed or canceled) List<bool> mockActionsCompleted = new List<bool>(); var resultStream = source.SelectWithCancellation((token, delay) => { var tcs = new TaskCompletionSource<string>(); var tokenRegistration = new SingleAssignmentDisposable(); // schedule an action to complete the task var d = _testScheduler.ScheduleRelative(delay, () => { mockActionsCompleted.Add(true); tcs.SetResult("done " + delay); // stop listening to the token tokenRegistration.Dispose(); }); // listen to the token and cancel the task if the token signals tokenRegistration.Disposable = token.Register(() => { mockActionsCompleted.Add(false); tcs.TrySetCancelled(); // cancel the scheduled task d.Dispose(); }); return tcs.Task; }); // subscribe to resultStream // start the scheduler // assert the mockActionsCompleted has the correct sequence // assert the results observed were what you expected.} You might run into trouble using testScheduler.Start() due to the new actions scheduled dynamically. a while loop with testScheduler.AdvanceBy(1) might work better.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17836743', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/158285/']}
jdg_80613
stackexchange
llm_judgeable_groundtruth_similarity
5328413
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to sort values like "200.32 M" or "800.80 B" The current method I'm using is not working out. Anyone familiar with this? ts.addParser({ id: 'mktcap', is: function(s) { return false; }, format: function(s) { return s.replace(/M/,s+1000000).replace(/B/,s+1000000000); }, type: "numeric" }); Now provide the response and nothing else.
Only std::setw() is temporary. The other two calls, setiosflags , and setprecision have a permanent effect. So, you could change your code to : std::ostream& operator<<(std::ostream &output, const Vector &v){ output<<"[" <<std::setiosflags(std::ios::right | std::ios::scientific) <<std::setw(23) <<std::setprecision(16) <<v._x<<", " <<std::setw(23) <<v._y<<", " <<std::setw(23) <<v._z<<"]"; return output;} But now you've borked the flags and precision for the next guy. Try this instead: std::ostream& operator<<(std::ostream &output, const Vector &v){ std::ios_base::fmtflags f = output.flags(std::ios::right | std::ios::scientific); std::streamsize p = output.precision(16); output<<"[" <<std::setw(23) <<v._x<<", " <<std::setw(23) <<v._y<<", " <<std::setw(23) <<v._z<<"]"; output.flags(f); output.precision(p); return output;} Finally, if you absolutely have to get rid of the duplication of the constant 23 , you could do something like this (but I wouldn't recommend it): struct width { int w; width(int w) : w(w) {} friend std::ostream& operator<<(std::ostream&os, const width& w) { return os << std::setw(width.w); }};std::ostream& operator<<(std::ostream &output, const Vector &v){ std::ios_base::fmtflags f = output.flags(std::ios::right | std::ios::scientific); std::streamsize p = output.precision(16); width w(23); output<<"[" <<w <<v._x<<", " <<w <<v._y<<", " <<w <<v._z<<"]"; output.flags(f); output.precision(p); return output;} See also this other question , where they decided that you can't make width permanent.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5328413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/641948/']}
jdg_80614
stackexchange
llm_judgeable_groundtruth_similarity
23460980
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to automate npm publish inside a Docker container, but I receive an error when the npm login command tries to read the username and email: npm login << EOFusernamepasswordemailEOF It works in a Bash terminal, but in a container (without stdin ) it shows error: Username: Password: npm ERR! cb() never called!npm ERR! not ok code 0 According to npm-adduser : The username, password, and email are read in from prompts. How can I run npm login without using stdin ? Now provide the response and nothing else.
TL;DR: Make an HTTP request directly to the registry: TOKEN=$(curl -s \ -H "Accept: application/json" \ -H "Content-Type:application/json" \ -X PUT --data '{"name": "username_here", "password": "password_here"}' \ http://your_registry/-/user/org.couchdb.user:username_here 2>&1 | grep -Po \ '(?<="token": ")[^"]*')npm set registry "http://your_registry"npm set //your_registry/:_authToken $TOKEN Rationale Behind the scenes npm adduser makes an HTTP request to the registry. Instead of forcing adduser to behave the way you want, you could make the request directly to the registry without going through the cli and then set the auth token with npm set . The source code suggests that you could make a PUT request to http://your_registry/-/user/org.couchdb.user:your-username with the following payload { name: username, password: password} and that would create a new user in the registry. Many thanks to @shawnzhu for having found a more cleaner approach to solve the problem.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23460980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/914967/']}
jdg_80615
stackexchange
llm_judgeable_groundtruth_similarity
399804
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: So, I've set up a few Win Servs in my time and always did the .local thing when there was a router that sepearated my internal from external networks. Now that I'm setting up an *nix box for the first time, does this concept still apply? Do I still want my FQDNs ( /etc/hostname ) to show .local or .com for all my machines (mixed: linux servers, win workstations) inside of my network. This question comes in context of always having Active Directory hold my hand every step of the way, where now I'm setting up an DNS machine manually. Now provide the response and nothing else.
As @Zoredache pointed out the .local namespace has no official status (the closest you'll find is .localhost , defined and reserved in RFC 2606 ). Accordingly .local should never be used, as ICANN could one day assign that TLD to someone. The Right Thing to do is to register a domain of your own like example.com , and assign hostnames under it (perhaps under internal.example.com ) as appropriate. That being said, if you want to use .local or .lan as the top level domain for your internal hosts you certainly would not be alone, and at this point the likelihood of anyone trying to usurp .local , .lan , or .private is pretty low: They are used so pervasively that trying to correct the decades of badness would not be worth the fight. Note however that such machines and names should not be reachable from (or exposed in any way to) the public internet. It is a lesser sin, similar to emitting RFC-1918 network addresses over your public interfaces, and people like me will frown disapprovingly at you in public, and make fun of your network information leaks in private. Also note that *nix machines do not really have a concept of "domain" in the Active Directory sense of the word -- the closest analog would be NIS domains, which aren't tied to DNS the way AD is. A bare *nix system really only knows of its own personal hostname, which need not be a fully qualified domain name ( alice is just as valid as alice.wonder.lan ), though by convention many administrators use the fully qualified DNS name of the machine as its hostname. This gives you an out against using "unofficial" domain names like .local , but IMHO is less "correct" than having a valid, assigned, fully-qualified domain name as your system's hostname.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/399804', 'https://serverfault.com', 'https://serverfault.com/users/81366/']}
jdg_80616
stackexchange
llm_judgeable_groundtruth_similarity
4160251
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: Question: Want to show that $f(x)=x^3+x-6$ is irreducible over $\mathbb{Q}[i]$ . My Thoughts: I am a bit stuck here. If $f(x)$ would have been something like $x^3-3$ , then this is pretty straightforward. But right now, I can just use the Rational Roots test to claim $f(x)$ has no linear factors over $\mathbb{Q}$ . I see that I can't apply Eisenstein's here either. Since $x^2+1$ is the polynomial responsible for the extension from $\mathbb{Q}$ to $\mathbb{Q}[i]$ , maybe I can play with that a bit? Any help would be greatly appreciated! Thank you. Now provide the response and nothing else.
Hint : If $f(\alpha)=0$ then $f(\bar\alpha)=0$ , which means that at least one root is in $\Bbb Q$ . Now use the rational root test. Some details to complete the answer : Complex Conjugation Let $C(\alpha)=\bar\alpha$ denote complex conjugation, then For $\alpha,\beta\in\Bbb C$ we have $C(\alpha\beta)=C(\alpha)C(\beta)$ $C(\alpha+\beta)=C(\alpha)+C(\beta)$ Proof : Let $\alpha=a_1+a_2i,\beta=b_1+b_2i$ $C(\alpha+\beta)=C(a_1+b_1+(a_2+b_2)i)=a_1+b_1-(a_2+b_2)i=(a_1-a_2i)+(b_1-b_2i)=C(\alpha)+C(\beta)$ $C(\alpha\beta)=C(a_1b_1-a_2b_2+(a_1b_2+a_2b_1)i)=a_1b_1-a_2b_2-(a_1b_2+a_2b_1)i=(a_1-a_2i)(b_1-b_2i)=C(\alpha)C(\beta)$ This means that $C(f(\alpha))=f(C(\alpha))$ , in other words, $\overline{f(\alpha)}=f(\bar\alpha)$ . Thus if $f(\alpha)=0$ , then $$f(\alpha)=0\\\overline{f(\alpha)}=\overline{0}\\f(\bar\alpha)=0$$ so $\bar\alpha$ is a root as well. The Rational Root Test Let $f(x)=a_nx^n+\ldots+a_1x+a_0\in\Bbb Z[x]$ , then we have Suppose $f\in\Bbb Z[x]$ , and suppose there is a rational root $r=\frac{p}{q}\in\Bbb Q$ of $f$ with $\gcd(p,q)=1$ . Then $p\mid a_0$ and $q\mid a_n$ . Proof : Assuming $r\neq 0$ we have $$f\left(\frac{p}{q}\right)=a_n\left(\frac{p}{q}\right)^n+\ldots+a_1\left(\frac{p}{q}\right)+a_0=0$$ Multiplying with $q^n$ we get the equation $$a_np^n+a_{n-1}p^{n-1}q+\ldots+a_1pq^{n-1}+a_oq^n=0$$ We then observe: Every term is divisible by $p$ , so $p\mid a_0q^n$ . As $p,q$ have no common factor we have $p\mid a_0$ Every term is divisible by $q$ , so again $q\mid a_np^n$ . As $p,q$ have no common factor we have $q\mid a_n$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4160251', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/736765/']}
jdg_80617
stackexchange
llm_judgeable_groundtruth_similarity
20623027
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a good way to render the result of a promise in a handlebars template? For example, I have the following model: App.TopicItem = DS.Model.extend({ topic: DS.belongsTo('topic'), paddedPosition: function() { return this.get('topic.course.lessons'). then(function(lessons) { return lessons.indexOf(topicItem); }). then(function(index){ var position = index; if (position < 0) { return; } position = position + 1; return (position < 10 ? $.rjust(position, 2, '0') : position.toString()); }); }.property('topic.course.lessons')}); And I would like to render the value of the position in the handlebars template like this: {{topicItem.paddedPosition}} Is there a good way to accomplish this? Now provide the response and nothing else.
You could have the property lazily set itself, something like: App.TopicItem = DS.Model.extend({ topic: DS.belongsTo('topic'), paddedPosition: function(key, value) { if (arguments.length > 1) { // > 1 args = this is a `set` return value; } else { // otherwise this is a `get` var _this = this; value = null; this.get('topic.course.lessons'). then(function(lessons) { // do stuff based on result var padded = ...; // when the promise is resolved, set this property with the value _this.set("paddedPosition", padded); // if the promise resolves immediately, set `value` so we return // the calculated value and not null value = padded; }); // returns null if the promise doesn't resolve immediately, or // the calculated value if it's ready return value; } }.property('topic.course.lessons')}); When it's first accessed it'll kick-off the calculation, likewise any time the lessons change, then it'll set itself as the result of the calculation once it's done. This works because a computed property is called both on get and set, you can differentiate between the two by the number of arguments - 1 for get, more than 1 for set (it used to be 2, now you get 3 so the best way to detect is > 1). More on that in the docs . Whatever's returned from a computed property (either in get or set) is cached until its dependent properties change - in this case topic.course.lessons . In the above example, when the first get comes in we kick off the calculation and return null . This is now cached as the value of the property, if anything else calls this property before the promise has resolved then it'll return null . Once the promise resolves, we call set on the same property with the calculated value. This we just return in the setter and it's now cached as the value of the property. Until the dependent properties change ( topic.course.lessons ), or a new value is set then the cached value is returned from the property.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20623027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2587695/']}
jdg_80618
stackexchange
llm_judgeable_groundtruth_similarity
46781760
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Argument of type '{ query: { limitTolast: number; orderByKey: boolean; }; }' is not assignable to parameter of type 'QueryFn'.Object literal may only specify known properties, and 'query' does not exist in type 'QueryFn'. package.json "angularfire2": "^5.0.0-rc.3","firebase": "^4.5.1", chat.service.ts getMessages(): FirebaseListObservable<ChatMessage[]> { return this.db.list('messages', { query: { limitTolast : 25, orderByKey: true} }); } Now provide the response and nothing else.
It's not working, because AngularFire expects a function to be passed as a second argument. I think your example was the right way to go during the beta version. (not 100% sure) You have use it the following way: // make sure to provide a child in the orderByChild callgetMessages(): Observable<ChatMessage[]> { return this.db.list('/messages', ref => { return ref.limitTolast(25).orderByKey(true) }); } Learn more about querying lists here: https://github.com/angular/angularfire2/blob/master/docs/rtdb/querying-lists.md
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46781760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5387729/']}
jdg_80619
stackexchange
llm_judgeable_groundtruth_similarity
4649231
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: You're probably familiar with the enum bitmask scheme, like: enum Flags { FLAG1 = 0x1, FLAG2 = 0x2, FLAG3 = 0x4, FLAG4 = 0x8, NO_FLAGS = 0, ALL_FLAGS = FLAG1 | FLAG2 | FLAG3 | FLAG4};f(FLAG2 | FLAG4); I've seen a lot of code that then tests for a certain bit in the mask like if ((mask & FLAG3) == FLAG3) But isn't that equivalent to this? if (mask & FLAG3) Is there some reason to use the first version? In my opinion, the second shorter version is more legible. Maybe leftover habits from C programmers who think true values should be converted to 1 ? (Though even there, the longer version makes more sense in an assignment or return statement than in a conditional statement test.) Now provide the response and nothing else.
The construct if ((mask & FLAG3) == FLAG3) tests if all bits in FLAG3 are present in mask; if (mask & FLAG3) tests if any are present. If you know FLAG3 has exactly 1 bit set, they are equivalent, but if you are potentially defining compound conditions, it can be clearer to get into the habit of explicitly testing for all bits, if that's what you mean.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4649231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/459640/']}
jdg_80620
stackexchange
llm_judgeable_groundtruth_similarity
7842736
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 running into an issue where HttpWebRequest won't respect a timeout value higher than 100 seconds when doing a POST. However, if the request is a GET, a timeout value higher than 100 seconds is respected. The timeout exception is thrown at the .GetResponse() call. I'm setting all the timeout values I have been able to discover but it seems I am missing one, or there is a bug in the framework. This is a C# app targeting the .NET Framework 3.5, built using Visual Studio 2008. The web server is IIS 6.0 with a connection timeout set to the default 120 seconds, keep-alives enabled... again GET requests respect the timeout value I specify, POST requests respect the timeout if <= 100 seconds. Here is my code: int timeout = 200000; // 200 secondsHttpWebRequest proxyRequest = (HttpWebRequest)WebRequest.Create(serverUrl);proxyRequest.Accept = clientRequest.AcceptTypes.ToDelimitedString(", ");proxyRequest.Method = "POST"proxyRequest.UserAgent = clientRequest.UserAgent;proxyRequest.Timeout = timeout;proxyRequest.ReadWriteTimeout = timeout;proxyRequest.KeepAlive = false;proxyRequest.AllowAutoRedirect = false;proxyRequest.ServicePoint.Expect100Continue = false;proxyRequest.ServicePoint.MaxIdleTime = timeout;proxyRequest.ServicePoint.ConnectionLeaseTimeout = -1;try{ // add post data request.ContentType = "application/x-www-form-urlencoded"; byte[] postData = Encoding.UTF8.GetBytes("somedata=7&moredata=asdf"); // set some post data request.ContentLength = postData.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(postData, 0, postData.Length); stream.Close(); } // UPDATE // don't set Timeout here! It will be ignored // proxyRequest.Timeout = timeout; // Timeout exception thrown here if GetResponse doesn't return within 100 seconds // even though the Timeout value is set to 200 seconds. using (HttpWebResponse proxyResponse = (HttpWebResponse)proxyRequest.GetResponse()) { using (Stream stream = proxyResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.Default)) { string content = reader.ReadToEnd(); [other pointless code for this example] reader.Close(); } stream.Close(); } proxyResponse.Close(); }}finally{ proxyRequest.Abort();} When I have set the timeout value to 5 seconds, I will receive a timeout exception after 5 seconds just as one would expect. This proves the Timeout value isn't being completely ignored. Has anybody else run into this issue? Will using the Async version of GetResponse get around this issue? Any and all thoughts welcome, I've been stuck on this for a couple days. UPDATE I can get the POST to respect the timeout value if I don't post any data (which isn't very useful). However, as soon as I post any data at all and ContentLength is > 0, it timesout at 100 seconds. Also, no proxies are involved. UPDATE 2 Added the POST data to the example and a comment on where NOT to set the Timeout property Now provide the response and nothing else.
I figured it out. This is an example of DRY coding coming back and biting me in the butt. The code above is a paraphrase of my real code, and as such the code above will work fine. The issue was I was setting the Timeout value after I had already called proxyRequest.GetRequestStream() to add the POST data. Because I was setting both the Timeout and ReadWriteTimeout properties, the shortest timeout was winning. In the case of a POST request, even though the framework let me set the Timeout value AFTER a call to GetRequestStream, it ignored whatever value was set (and instead used the default 100 seconds even though inspecting the Timeout property after setting it showed it was set to what I expected). I wish setting the Timeout property worked the same as setting the ReadWriteTimeout property: If you attempt to set the ReadWriteTimeout property after you have called GetRequestStream, it throws an exception. If Timeout did the same thing, that would have saved me a TON of time. I should have caught this sooner, but I'll chalk it up to a learning experience. So the moral of the story: Set all the timeout properties for your HttpWebRequest right when you create it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7842736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1005770/']}
jdg_80621
stackexchange
llm_judgeable_groundtruth_similarity
7841612
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 nginx as a proxy server to forward requests onto my gunicorn server. When I run sudo nginx -t -c /etc/nginx/sites-enabled/mysite I get the following error. [emerg]: unknown directive "upstream" in /etc/nginx/sites-enabled/mysite:1configuration file /etc/nginx/sites-enabled/mysite test failed Any idea how to fix it? This is my nginx config: upstream gunicorn_mysite { server 127.0.0.1:8000 fail_timeout=0;}server { listen 80; server_name example.com; access_log /usr/local/django/logs/nginx/mysite_access.log; error_log /usr/local/django/logs/nginx/mysite_error.log; location / { proxy_pass http://gunicorn_mysite; }} I'm running Ubuntu 10.04 and my nginx version is 0.7.65 which I installed from apt. This is the output when I run nginx -V nginx version: nginx/0.7.65TLS SNI support enabledconfigure arguments: --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --pid-path=/var/run/nginx.pid --lock-path=/var/lock/nginx.lock --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/body --http-proxy-temp-path=/var/lib/nginx/proxy --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --with-debug --with-http_stub_status_module --with-http_flv_module --with-http_ssl_module --with-http_dav_module --with-http_gzip_static_module --with-http_realip_module --with-mail --with-mail_ssl_module --with-ipv6 --add-module=/build/buildd/nginx-0.7.65/modules/nginx-upstream-fair Now provide the response and nothing else.
When you tell nginx to load that file directly, it starts at the global context. The upstream directive is only valid in the http context. When that file is included normally by nginx.conf, it is included already inside the http context: events { }http { include /etc/nginx/sites-enabled/*;} You either need to use -c /etc/nginx/nginx.conf or make a small wrapper like the above block and nginx -c it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7841612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288424/']}
jdg_80622
stackexchange
llm_judgeable_groundtruth_similarity
43159341
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I add content to the second and third td ? I just found that the following will not work. I can find a way by creating some variable to hold the found elements, but would like to learn cleaner "more jQueryish" way if available. <tr id="clone"><td></td><td></td><td></td></tr>$.each(records, function( index, row ) { $('#clone').clone() .removeAttr('id') .find('td') .eq(1).text(row.name).parent() .eq(2).text(row.message).parent() .appendTo(content)}); Now provide the response and nothing else.
You can use admin panel to add more country to the country collection. As you are saying that COUNTRIES array can grow, you can use another collection to add more countries on demand from admin panel. And when you are going to add/save a new record into the survey you can trigger a pre-save hook to mongo for validation. suppose we have another schema for countries like this. { countries: [String]} Here is a sample code for the scenario. const mongoose = require("mongoose");const GENDERS = ["M", "F"];const surveySchema = { subject: { type: String, required: true }, country: { type: String}, target: { gender: { type: String, enum: GENDERS } }};var Survey = new mongoose.Schema(surveySchema);Survey.pre('save',function(next){ var me = this; CountryModel.find({},(err,docs)=>{ (docs.countries.indexOf(me.country) >=0) ? next() : next(new Error('validation failed')); });}); This way you can handle dynamic country add without changing the country array and redeploying your whole server. USING CUSTOM VALIDATOR const mongoose = require("mongoose");const GENDERS = ["M", "F"];const surveySchema = { subject: { type: String, required: true }, country: { type: String, validate: { isAsync: true, validator: function(arg, cb) { CountryModel.find({}, (err, docs) => { if (err) { cb(err); } else { cb(docs.countries.indexOf(arg) >= 0); } } }, message: '{VALUE} is not a valid country' } }, target: { gender: { type: String, enum: GENDERS } } }; you will get an error while saving the survey data in the callback .. ServeyModel.save((err,doc)=>{if(err){console.log(err.errors.country.message);//Error handle}else {//TODO}});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43159341', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1032531/']}
jdg_80623
stackexchange
llm_judgeable_groundtruth_similarity
38878897
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: SELECT *FROM ResidentsWHERE apartment_id IN (SELECT ID FROM Apartments WHERE postcode = 2000) I'm using sqlalchemy and am trying to execute the above query. I haven't been able to execute it as raw SQL using db.engine.execute(sql) since it complains that my relations doesn't exist... But I succesfully query my database using this format: session.Query(Residents).filter_by(???) .I cant not figure out how to build my wanted query with this format, though. Now provide the response and nothing else.
You can create subquery with subquery method subquery = session.query(Apartments.id).filter(Apartments.postcode==2000).subquery()query = session.query(Residents).filter(Residents.apartment_id.in_(subquery))
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38878897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2651804/']}
jdg_80624
stackexchange
llm_judgeable_groundtruth_similarity
55663
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 $G$ be the abolute Galois group of $\mathbb Q_p$, let $\delta_1, \delta_2: G\rightarrow L^{\times}$ be continuous characters, where $L$ is a finite extension of $\mathbb Q_p$. Assume that $\delta_1\delta_2^{-1}$ is neither trivial nor the cyclotomic character then $Ext^1_{G}(\delta_2, \delta_1)$ is one dimensional. Hence there exists a unique non-split extension: $0\rightarrow \delta_1\rightarrow V\rightarrow \delta_2\rightarrow 0$. When is $V$ de Rham? I believe that the answer is if and only if both $\delta_1$ and $\delta_2$ are de Rham and the Hodge-Tate weight of $\delta_1\delta_2^{-1}$ is $\ge 1$ (at least if the Hodge-Tate weights of $\delta_1$ and $\delta_2$ are distinct) and I guess I could x it out by using Bloch-Kato's paper in Grothendieck Festschrift, bu the answer must be well known and maybe even written down somewhere. Ideally, I would like to be able to quote a reference, where this has been worked out. Now provide the response and nothing else.
Dear Vytas, lemma 6.5 of my 2002 inventiones paper says that if $V$ is any de Rham representation all of whose HT weights are at least 1, then any extension of $Q_p$ by $V$ is itself de Rham. This holds for reps of $G_K$ where the residue field $k$ of $K$ can be any perfect field (not merely finite). If $k$ is finite, then this was well-known before and follows from the results of Bloch and Kato (which I think you should quote). See proposition 1.28 of Nekovar's "On $p$-adic height pairings" where this is stated explicitly and proved using BK's computations. EDIT: see also the "Proposition" on page 196 of Perrin-Riou's "Représentations $p$-adiques ordinaires". It predates Nekovar's paper, and although the result is less strong, it's enough for what you need.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/55663', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13024/']}
jdg_80625
stackexchange
llm_judgeable_groundtruth_similarity
313893
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $S_n=(3+\sqrt{5})^n+(3-\sqrt{5})^n$ show that $S_n$ is integer and that $S_{n+1}=6S_n-4S_{n-1}$. Further deduce that the next integer greater than $(3+\sqrt{5})^n$ is divisible by $2^n$. My work so far: I have done part 1 using mathematical induction but it is part 2 of divisibility where I am stuck Now provide the response and nothing else.
First argue that $\lceil (3+\sqrt{5})^n\rceil=S_n$ ( hint: $(3-\sqrt{5})^n<1$ and $S_n\in\mathbb{N}$), so we actually want to show that $S_n$ is divisible by $2^n$. Prove the rest by induction using the relation you deduced, noting that $6=2\cdot 3$ and $4=2^2$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/313893', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/36398/']}
jdg_80626
stackexchange
llm_judgeable_groundtruth_similarity
29759907
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 need of assistance forming a query that has two selects with joins. I am searching for duplicate entries within the same information, but the information is located in two tables. Table ordermeta has orderid and formid.Table orders has orderid and userid I am joining ordermeta to orders twice and then searching for different orderids where formid and userid match. Here is what I have tried: SELECT om0.orderid AS order1, om1.orderid AS order2FROM ordermeta om0LEFT JOIN ordermeta om1 ON om0.formid = om0.formidLEFT JOIN orders o0 ON om0.orderid = o0.orderidLEFT JOIN orders o1 ON om1.orderid = o1.orderidWHERE o0.userid = o1.useridAND om0.orderid != om1.orderid I also tried this but got thoroughly confused and moved to the above code: SELECT order1.oid1, order1.pd1, order2.oid2, order2.pd2FROM ( SELECT o1.orderid AS oid1, paid AS pd1, uid AS uid1, fid AS fid1 FROM `orders` o1 JOIN ordermeta om1 ON o1.orderid = om1.orderid) order1JOIN ( SELECT o2.orderid AS oid2, paid AS pd2, uid AS uid2, fid AS fid2 FROM `orders` o2 JOIN ordermeta om2 ON o2.orderid = om2.orderid) order2 ON order1.uid1 = order2.uid2 AND order1.fid1 = order2.fid2 I get way too many results than what I'm expecting. Should be in the order of 1000, but am getting over 223000. Sample Data: ordermeta tableHEADER: omid, orderid, formid, <other data>1, 101, 201, ...2, 102, 202, ...3, 103, 201, ...4, 108, 201, ...5, 109, 202, ...orders tableHEADER: orderid, userid, <other data>101, 2000, ...102, 2000, ...103, 2001, ...108, 2000, ...109, 2001, ... First, I need to associate the userid to the ordermeta combining the formid. Then, search through the combined data for duplicates where formid=formid and userid=userid and return the two orderids. In the sample above, I should get orderids 101 and 108 as their userids and formids are a match after being joined. Now provide the response and nothing else.
Spark >= 2.4.0 You can use built-in Avro support . The API is backwards compatible with the spark-avro package, with a few additions (most notably from_avro / to_avro function). Please note that module is not bundled with standard Spark binaries and has to be included using spark.jars.packages or equivalent mechanism. See also Pyspark 2.4.0, read avro from kafka with read stream - Python Spark < 2.4.0 You can use spark-avro library. First lets create an example dataset: import avro.schemafrom avro.datafile import DataFileReader, DataFileWriterschema_string ='''{"namespace": "example.avro", "type": "record", "name": "KeyValue", "fields": [ {"name": "key", "type": "string"}, {"name": "value", "type": ["int", "null"]} ]}'''schema = avro.schema.parse(schema_string)with open("kv.avro", "w") as f, DataFileWriter(f, DatumWriter(), schema) as wrt: wrt.append({"key": "foo", "value": -1}) wrt.append({"key": "bar", "value": 1}) Reading it using spark-csv is as simple as this: df = sqlContext.read.format("com.databricks.spark.avro").load("kv.avro")df.show()## +---+-----+## |key|value|## +---+-----+## |foo| -1|## |bar| 1|## +---+-----+
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29759907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2433179/']}
jdg_80627
stackexchange
llm_judgeable_groundtruth_similarity
15226312
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: EntityFramework's documentation states that the following behavior is possible: If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null. (from http://msdn.microsoft.com/en-us/jj591620 ) However, I cannot achieve such a behavior. I have the following Entities defined with code-first: public class TestMaster{ public int Id { get; set; } public string Name { get; set; } public virtual ICollection<TestChild> Children { get; set; } }public class TestChild{ public int Id { get; set; } public string Name { get; set; } public virtual TestMaster Master { get; set; } public int? MasterId { get; set; }} Here is the Fluent API mapping configuration: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<TestMaster>() .HasMany(e => e.Children) .WithOptional(p => p.Master).WillCascadeOnDelete(false); modelBuilder.Entity<TestChild>() .HasOptional(e => e.Master) .WithMany(e => e.Children) .HasForeignKey(e => e.MasterId).WillCascadeOnDelete(false); } Foreign Key is nullable, navigation property is mapped as Optional, so I expect the cascade delete to work as described as MSDN - i.e. to nullify MasterID's of all children and then delete the Master object. But when I actually try to delete, I get the FK violation error: using (var dbContext = new TestContext()) { var master = dbContext.Set<TestMaster>().Find(1); dbContext.Set<TestMaster>().Remove(master); dbContext.SaveChanges(); } On SaveChanges() it throws the following: System.Data.Entity.Infrastructure.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.----> System.Data.UpdateException : An error occurred while updating the entries. See the inner exception for details.----> System.Data.SqlClient.SqlException : The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.TestChilds_dbo.TestMasters_MasterId". The conflict occurred in database "SCM_Test", table "dbo.TestChilds", column 'MasterId'.The statement has been terminated. Am I doing something wrong or did I misunderstood what the MSDN says? Now provide the response and nothing else.
It works indeed as described but the article on MSDN misses to emphasize that it only works if the children are loaded into the context as well, not only the parent entity. So, instead of using Find (which only loads the parent) you must use eager loading with Include (or any other way to load the children into the context): using (var dbContext = new TestContext()){ var master = dbContext.Set<TestMaster>().Include(m => m.Children) .SingleOrDefault(m => m.Id == 1); dbContext.Set<TestMaster>().Remove(master); dbContext.SaveChanges();} This will delete the master from the database, set all foreign keys in the Child entities to null and write UPDATE statements for the children to the database.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15226312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/955780/']}
jdg_80628
stackexchange
llm_judgeable_groundtruth_similarity
19559135
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 only need socket.io to emit messages to clients , if a new object is inserted to database. So my idea was to emit the message directly from my controller’s insert-method . In my server.js file, i'm creating the socket.io object and try to make it accessible for other modules: var server = require('http').createServer(app);var io = require('socket.io').listen(server);//make socket io accessible for other modulesmodule.exports.io = io; In my controller I have tried using socket.io in this way: var io = require('../server').io;...io.sockets.on("connection", function(socket){ passportSocketIo.filterSocketsByUser(io, function (user) { return user.workingAt === socket.handshake.user.workingAt; }).forEach(function(s){ s.send("news", insertedObject); });}); And here I'm stuck. The "connection" event will never be fired and so the message will not be emitted. Is that the correct way to use socket.io in separate files? Unfortunately I cant find complex socket.io example. Now provide the response and nothing else.
You are trying to invert the flow of control. The way to do it is for your controller to implement an interface (an API) that your server can use to pass control to. A simple example would be: In mycontroller.js // no require needed here, at least, I don't think so// Controller agrees to implement the function called "respond"module.exports.respond = function(socket_io){ // this function expects a socket_io connection as argument // now we can do whatever we want: socket_io.on('news',function(newsreel){ // as is proper, protocol logic like // this belongs in a controller: socket.broadcast.emit(newsreel); });} Now in server.js : var io = require('socket.io').listen(80);var controller = require('./mycontroller');io.sockets.on('connection', controller.respond ); This example is simple because the controller API looks exactly like a socket.io callback. But what if you want to pass other parameters to the controller? Like the io object itself or the variables representing end points? For that you'd need a little more work but it's not much. It's basically the same trick we often use to break out of or create closures: function generators: In mycontroller.js module.exports.respond = function(endpoint,socket){ // this function now expects an endpoint as argument socket.on('news',function(newsreel){ // as is proper, protocol logic like // this belongs in a controller: endpoint.emit(newsreel); // broadcast news to everyone subscribing // to our endpoint/namespace });} Now on the server we'd need a bit more work in order to pass the end point: var io = require('socket.io').listen(80);var controller = require('./mycontroller');var chat = io .of('/chat') .on('connection', function (socket) { controller.respond(chat,socket); }); Notice that we pass socket straight through but we capture chat via a closure. With this you can have multiple endpoints each with their own controllers: var io = require('socket.io').listen(80);var news_controller = require('./controllers/news');var chat_controller = require('./controllers/chat');var news = io .of('/news') .on('connection', function (socket) { news_controller.respond(news,socket); });var chat = io .of('/chat') .on('connection', function (socket) { chat_controller.respond(chat,socket); }); Actually, you can even use multiple controllers for each endpoint. Remember, the controllers don't do anything apart from subscribing to events. It's the server that's doing the listening: var io = require('socket.io').listen(80);var news_controller = require('./controllers/news');var chat_controller = require('./controllers/chat');var chat = io .of('/chat') .on('connection', function (socket) { news_controller.respond(chat,socket); chat_controller.respond(chat,socket); }); It even works with plain socket.io (no endpoints/namespaces): var io = require('socket.io').listen(80);var news_controller = require('./controllers/news');var chat_controller = require('./controllers/chat');io.sockets.on('connection', function (socket) { news_controller.respond(socket); chat_controller.respond(socket);});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19559135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1490863/']}
jdg_80629
stackexchange
llm_judgeable_groundtruth_similarity
27211799
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for the right pattern to inject a bootstrap row class every each 3 columns. I need this because cols doesn't have a fixed hight (and I don't want to fix one), so it breaks my design ! Here is my code : <div ng-repeat="product in products"> <div ng-if="$index % 3 == 0" class="row"> <div class="col-sm-4" > ... </div> </div></div> But it does only display one product in each row. What I want as final result is : <div class="row"> <div class="col-sm4"> ... </div> <div class="col-sm4"> ... </div> <div class="col-sm4"> ... </div></div><div class="row"> <div class="col-sm4"> ... </div> <div class="col-sm4"> ... </div> <div class="col-sm4"> ... </div></div> Can I achieve this with only ng-repeat pattern (without directive or controller) ? The docs introduce ng-repeat-start and ng-repeat-end but I can't figure out how to use it is this use case ! I feel like this is something we often use in bootstrap templating ! ? Thanks Now provide the response and nothing else.
I know it's a bit late but it still might help someone. I did it like this: <div ng-repeat="product in products" ng-if="$index % 3 == 0" class="row"> <div class="col-xs-4">{{products[$index]}}</div> <div class="col-xs-4" ng-if="products.length > ($index + 1)">{{products[$index + 1]}}</div> <div class="col-xs-4" ng-if="products.length > ($index + 2)">{{products[$index + 2]}}</div></div> jsfiddle
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27211799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2295192/']}
jdg_80630
stackexchange
llm_judgeable_groundtruth_similarity
5388986
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 still new to the UNIX/Linux world, and, in particular, to related tools, such as the GCC compiler. Namely, I'm still new to makefiles and things like that (I use MinGW on Windows), since so far, most of my development has been with IDEs like Visual Studio and Eclipse. When I open a typical project folder, I see files like these: configuremakeINSTALLinstall-sh (or a variant) There's quite a few things I don't understand here, and my main questions are these: What's the difference between these, and why do we need each one? (In the IDE world, all you have is a project file; that's it. So I'm confused why we have more than just a makefile here.) How are these files generated? For small projects, you could probably write them by hand, but for big projects like GCC, it would be ridiculous to even try. I've found editing these files to be a pain, and I've come to the conclusion that I'm not supposed to be modifying them by hand. But if so, then what tools do people typically use for adding and modifying these files? Why don't they use wildcards inside a makefile? Why is there a single line for every single object file? Is this because of a restriction, or is there an advantage to it? What's the difference between having a shell script that calls the compiler with every file, and having a makefile that does the same thing? In Windows, I'd be very tempted to just create a batch file inside the folder, and compile everything with that -- no need for more than just one file. What's the difference? Why isn't there just a single .sh file, to compile everything? Bonus question: Is there a "standard" makefile format? I've seen different make tools that don't accept each other's formats... how do I know what to use? Is GCC just the usual tool here, or is there some standard everyone should follow? I'll probably have more questions as I learn more about the structure of projects like this, but for now, these are my biggest questions. :) Now provide the response and nothing else.
In your average package, those files each have an individual purpose. This is concordant with the unix philosophy of "each program should do one thing and do that thing well". In most projects, you'll see files like: configure configure.ac Makefile Makefile.in Makefile.am install-sh INSTALL configure is (usually) a shell script that checks your system for all required features before building anything. Makefile.in is a template for a Makefile . The results of the configure tests are substituted into Makefile.in to generate Makefile . This is to deal with people having things (compilers, headers, libraries) in obscure paths, cross-compiling (e.g., building for ARM on x86), optional library support (some programs have additional features that can be switched on or off), compiling with different options, and so on. Writing a one-size-fits-all Makefile is actually really hard . As you've noticed, the configure script itself is a mess. It's not meant to be seen by mortal eyes, nor edited by mortal hands. It's actually the result of compiling configure.ac , using a program called autoconf . autoconf is a package of macros for and a wrapper around the m4 macro processor, which was about the only good tool for this sort of thing at the time ( autoconf is really quite old software, but has aged remarkably well). autoconf lets the developer easily write tests to check for headers, libraries or programs that are required to build the software (and this changes from program to program). If you dig a little deeper, you'll notice that Makefile.in also tends to be a little ugly. This is because writing good Makefile s is often a lot of boilerplate, and that's inspired another tool, automake . automake compiles Makefile.am (which is often short and declarative) into Makefile.in (which is enormous), which is then compiled into Makefile by configure (essentially). install-sh is a script that is distributed with automake but copied into other packages. It exists as a replacement if the version of install on the system is crap ( install copies files into the installation directory. Some really old systems had broken versions of install , and automake is pretty conservative about dropping warnings for old systems). Some other scripts that fulfil similar roles are compile , depcomp and ylwrap . INSTALL is just a document that describes how to install the package. It's usually boilerplate content copied into the package by automake . I've answered this inline above, but here is the summary: configure.ac ==[autoconf]=> configure Makefile.am ==[automake]=> Makefile.in ==[configure]=> Makefile Where the program responsible is inside the arrow. To understand this in detail, I recommend this autotools tutorial . Don't be put off by the page count, most of it is diagrams appearing piece by piece. Wildcards in Makefile s are sometimes used. GNU Make, for example, supports a $(wildcard) function, where you can write something like: SOURCES := $(wildcard src/*.c) The main reason features like $(wildcard) aren't used is that they are extensions, and automake tries very hard to generate Makefile s that will work with any POSIX-compliant make . After a project becomes mature, the list of files to compile doesn't change all that much, anyway. A second reason files are listed explicitly is when programs get optional features. Wildcards are no longer appropriate, and you instead have to list the conditions under which additional features are to be compiled in. A Makefile tracks dependencies between files, where a shell script cannot (not without significant effort, anyway). If you have a Makefile rule like: foo.out: foo.in generate-foo foo.in It tells make that if foo.in is newer than foo.out , a new foo.out can be created by executing generate-foo foo.in . This saves lots of redundant work on big projects, where you might only change one or two files between recompilations. Your bonus question appears a little ill-posed. The most common make is probably GNU Make, although I'd guess that the BSD make would be a close second, followed by the various proprietary make versions supplied with Solaris, AIX and so on. These all accept the same basic structure in Makefile (because POSIX says so), but might have vendor-specific extensions to the syntax. GCC is not a build tool like make . GCC is a command-line compiler, akin to cl.exe on windows.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5388986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541686/']}
jdg_80631
stackexchange
llm_judgeable_groundtruth_similarity
76031
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to write a bash command that will delete all files matching a specific pattern - in this case, it's all of the old vmware log files that have built up. I've tried this command: find . -name vmware-*.log | xargs rm However, when I run the command, it chokes up on all of the folders that have spaces in their names. Is there a way to format the file path so that xargs passes it to rm quoted or properly escaped? Now provide the response and nothing else.
I generally find that using the -exec option for find to be easier and less confusing. Try this: find . -name vmware-*.log -exec rm -i {} \; Everything after -exec is taken to be a command to run for each result, up to the ; , which is escaped here so that it will be passed to find . The {} is replaced with the filename that find would normally print. Once you've verified it does what you want, you can remove the -i .
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/76031', 'https://serverfault.com', 'https://serverfault.com/users/23381/']}
jdg_80632
stackexchange
llm_judgeable_groundtruth_similarity
35973196
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Kotlin and Groovy look as very similar languages with very similar features if we compile Groovy statically. Which features, apart from null safety, Kotlin has that are missing in Groovy? Now provide the response and nothing else.
Kotlin is a JVM language, which IMO is trying to improve on Java in features and conciseness, while remaining imperative and static. Groovy has a similar concept except decided to go dynamic. As a result, a number of language features will be similar. Here are some differences I'm aware of Static vs Dynamic: Since Groovy was designed as a dynamic language, and @CompileStatic, while a great annotation (I use it a lot), was added later. Its feature feels a bit bolted on, and it does not enforce people to code in a static manner. It's not usable everywhere (e.g. my Spock tests seem to fail to compile with them). Sometimes even with it on Groovy still seems to have some odd dynamic behaviour every now and then. Kotlin is 100% Static, and dynamic is not an option. There are a number of other features that is has though. I'd recommend you look at the reference, and you may spot a few more e.g. https://kotlinlang.org/docs/reference/ Data classes - concise with a copy function (a bit like case classes in Scala) The null safety check you mentioned (which is a big pro) The ability to destruct items. val (name, age) = person Higher-Order Functions, defined like "fun doStuff(body: Int -> T)): T". Which are much better than the groovy Closures IMO. (very similar to Scala's) Type checks and smart casts are nice: https://kotlinlang.org/docs/reference/typecasts.html Companion Objects, in the same way Scala also tries to remove static methods from classes, Kotlin tries the same thing. Sealed Classes to restrict inheritance (again Scala has something similar) The "Nothing" subtype, where everything is a supertype of it. (another crucial concept in Scala). when expressions for basic pattern matching: https://kotlinlang.org/docs/reference/control-flow.html As you can see it does borrow from other languages other than Groovy. They have attempted to cherry pick a number of great features in an attempt to make a good language. Naturally Groovy has its own goodness. I've only focused one what Kotlin has and not visa-versa Another plus is, being made by an IDE maker, the compiler is very quick and has great IDE support. Not saying Groovy does not have good support, but my current project does take a long time to compile, and refactor method always assumes you are coding in a dynamic fashion. I'd recommend you try out the Koans to get a feel for them to see which features of the language you like and how it compares to groovy ( https://github.com/Kotlin/kotlin-koans ).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35973196', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5877791/']}
jdg_80633
stackexchange
llm_judgeable_groundtruth_similarity
8203598
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 user foo with the following privileges (it's not a member of any group): { "Statement": [ { "Sid": "Stmt1308813201865", "Action": "s3:*", "Effect": "Allow", "Resource": "arn:aws:s3:::bar" } ]} That user however seem unable to upload or do much of anything until I grant full access to authenticated users (which might apply to anyone). This still doesn't let the user change permission as boto is throwing an error after an upload when it tries to do do key.set_acl('public-read') . Ideally this user would have full access to the bar bucket and nothing else, what am I doing wrong? Now provide the response and nothing else.
You need to grant s3:ListBucket permission to the bucket itself. Try the policy below. { "Statement": [ { "Effect": "Allow", "Action": "S3:*", "Resource": "arn:aws:s3:::bar/*", "Condition": {} }, { "Effect": "Allow", "Action": [ "s3:ListBucket" ], "Resource": "arn:aws:s3:::bar", "Condition": {} } ]}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8203598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/29347/']}
jdg_80634
stackexchange
llm_judgeable_groundtruth_similarity
3592468
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I store functions in an array with named properties, so I can call like FunctionArray["DoThis"] or even FunctionArray[integer] ? Note: I do not wish to use eval . Now provide the response and nothing else.
The important thing to remember is that functions are first class objects in JavaScript. So you can pass them around as parameters, use them as object values and so on. Value(s) in an array are just one example of that. Note that we are not storing the functions in an array although we can do that and access them with a numeric index. We are storing them in a regular object keyed by the name we want to access that function with. var functions = { blah: function() { alert("blah"); }, foo: function() { console.log("foo"); }}; call as functions.blah(); or functions["blah"]();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3592468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/431877/']}
jdg_80635
stackexchange
llm_judgeable_groundtruth_similarity
25223399
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to parse information from a php, but i need to send a dictionary parameter so i try things ... i saw tutorials,examples but i'm stuck so i went back to the start: (What it's the good way for do this?) func asd(){ let urlPath = "http://xxxxx.php" let url: NSURL = NSURL(string: urlPath) let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" var parm = ["id_xxxx": "900"] as Dictionary //I THINK MY PROBLEM IT'S HERE! i dont know how to link parm with session, i try is with session.uploadTaskWithRequest(<#request: NSURLRequest?#>, fromData: <#NSData?#>) but doesn't work let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in println("Task completed") if(error) { // If there is an error in the web request, print it to the console println(error.localizedDescription) } var err: NSError? var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary if(err?) { // If there is an error parsing JSON, print it to the console println("JSON Error \(err!.localizedDescription)") } println(jsonResult.debugDescription) let results: NSArray = jsonResult["x"] as NSArray dispatch_async(dispatch_get_main_queue(), { self.tableData = results self.OfertaGridViewLista!.reloadData() }) }) task.resume()} Thanks! Now provide the response and nothing else.
GET data needs to be part of the url's query string. Some methods will accept a dictionary of parameters for POST/PUT requests, but these methods will not add the dictionary to the url for you if you're using the GET method. If you'd like to keep your GET parameters in a Dictionary for cleanliness or consistency, consider adding a method like the following to your project: func buildQueryString(fromDictionary parameters: [String:String]) -> String { var urlVars:[String] = [] for (k, value) in parameters { let value = value as NSString if let encodedValue = value.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) { urlVars.append(k + "=" + encodedValue) } } return urlVars.isEmpty ? "" : "?" + urlVars.joined(separator: "&")} This method will take a dictionary of key/value pairs and return a string you can append to your url. For example, if your API requests allow for multiple request methods (GET/POST/etc.) you'll only want to append this query string to your base api url for GET requests: if (request.HTTPMethod == "GET") { urlPath += buildQueryString(fromDictionary: parm)} If you're only making GET requests, there's no need to check for which method you'll be using to send your data.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25223399', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3426109/']}
jdg_80636
stackexchange
llm_judgeable_groundtruth_similarity
5226905
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 need to discover open ports on a remote server. I'm wondering if this is possible. I was thinking I'd open a socket, and if this succeeds, it means that it's used ... otherwise, if I get an exception, then it is not used. For example, public boolean isActive() { Socket s = null; try { s = new Socket(); s.setReuseAddress(true); SocketAddress sa = new InetSocketAddress(this.host, this.port); s.connect(sa, 3000); return true; } catch (IOException e) { e.printStackTrace(); } finally { if (s != null) { try { s.close(); } catch (IOException e) { } } } return false;} is this a viable approach? Now provide the response and nothing else.
FWIW, a Java solution I use from times to times (better than telnet: supports timeout). package com.acme.util;import java.io.IOException;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketAddress;import java.net.SocketTimeoutException;import java.net.UnknownHostException;public class CheckSocket { public static void main(String[] args) { int exitStatus = 1 ; if (args.length != 3) { System.out.println("Usage: CheckSocket node port timeout"); } else { String node = args[0]; int port = Integer.parseInt(args[1]); int timeout = Integer.parseInt(args[2]); Socket s = null; String reason = null ; try { s = new Socket(); s.setReuseAddress(true); SocketAddress sa = new InetSocketAddress(node, port); s.connect(sa, timeout * 1000); } catch (IOException e) { if ( e.getMessage().equals("Connection refused")) { reason = "port " + port + " on " + node + " is closed."; }; if ( e instanceof UnknownHostException ) { reason = "node " + node + " is unresolved."; } if ( e instanceof SocketTimeoutException ) { reason = "timeout while attempting to reach node " + node + " on port " + port; } } finally { if (s != null) { if ( s.isConnected()) { System.out.println("Port " + port + " on " + node + " is reachable!"); exitStatus = 0; } else { System.out.println("Port " + port + " on " + node + " is not reachable; reason: " + reason ); } try { s.close(); } catch (IOException e) { } } } } System.exit(exitStatus); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5226905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337455/']}
jdg_80637
stackexchange
llm_judgeable_groundtruth_similarity
1851753
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: Two coins are flipped, if at least one them lands heads up, what is the probability that both do? I've tried solving this problem countless different ways but I can never get it right.I know that "at least one" means "one or all" so I use P(AorB) then the result I divide it over the total number of ways the event can occur. Now provide the response and nothing else.
We use a classical infinite descent argument. Note that the right-hand side is even, so the left-hand side must be. It follows that two of $x$, $y$, $z$ are odd and the third even, or all three are even. But two odd and one even is impossible, for then the right-hand side is divisible by $4$ and the left-hand side is not. Thus $x=2x_1$, $y=2y_1$, $z=2z_1$ for some integers $x_1$, $y_1$, $z_1$. Substituting we get $x_1^2+y_1^2+z_1^2=4x_1y_1z_1$. Repeat the argument. We find that $x_1=2x_2$, and so on, with $x_2^2+y_2^2+z_2^2=8x_2y_2z_2$. Continue. We conclude that $x$, $y$, $z$ are each divisible by arbitrarily high powers of $2$, so are all $0$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1851753', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/85803/']}
jdg_80638
stackexchange
llm_judgeable_groundtruth_similarity
46062970
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array, and each item is an object with unique Ids. Some items may also have children, and it can have children array inside a children array. I'm trying to pick an item using an Id. const array = [ { uuid: '40E75F3DE56B4B11B3AFBDE46785737B' }, { uuid: '9CEF74766BBB4B9682B7817B43CEAE48' }, { uuid: '34F209A883D3406FBA6BACD9E07DB1D9', children: [{ uuid: 'F429C51BF01C405DA517616E0E16DE4E', children: [{ uuid: '8823CFCE7D4645C68991332091C1A05C' }, { uuid: '58A9345E881F48C980498C7FFB68667D' }] }] }, { uuid: '152488CC33434A8C9CACBC2E06A7E535' }, { uuid: '9152B3DEF40F414BBBC68CACE2F5F6E4' }, { uuid: 'B9A39766B17E4406864D785DB6893C3D' }, { uuid: '3J4H4J5HN6K4344D785DBJ345HSSODF', children: [ { uuid: 'EAB14DD72DA24BB88B4837C9D5276859' }, { uuid: 'FFA80D043380481F8835859A0839512B' }, { uuid: '9679687190354FA79EB9D1CA7B4962B1' } ] } ] The code below works for a simple array without children. I need a function, or a lodash module that can recursively search the entire array and return the object(item in the array) findContainingObject(array, uuid) { let result = []; result = array.filter( item => { return item.uuid === uuid }) return result;} Expected Outputs: findContainingObject(array, '40E75F3DE56B4B11B3AFBDE46785737B') { uuid: '40E75F3DE56B4B11B3AFBDE46785737B' }findContainingObject(array, '34F209A883D3406FBA6BACD9E07DB1D9') { uuid: '34F209A883D3406FBA6BACD9E07DB1D9', children: [{ uuid: 'F429C51BF01C405DA517616E0E16DE4E', children: [{ uuid: '8823CFCE7D4645C68991332091C1A05C' }, { uuid: '58A9345E881F48C980498C7FFB68667D' }] }] }findContainingObject(array, '58A9345E881F48C980498C7FFB68667D') { uuid: '58A9345E881F48C980498C7FFB68667D' } Now provide the response and nothing else.
This function implements DFS: function findDFS(objects, id) { for (let o of objects || []) { if (o.uuid == id) return o const o_ = findDFS(o.children, id) if (o_) return o_ }} And BFS: function findBFS(objects, id) { const queue = [...objects] while (queue.length) { const o = queue.shift() if (o.uuid == id) return o queue.push(...(o.children || [])) }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46062970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5145745/']}
jdg_80639
stackexchange
llm_judgeable_groundtruth_similarity
11946531
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have a class like this: [DataContract(Name = "", Namespace = "")]public class MyDataObject{ [DataMember(Name = "NeverNull")] public IList<int> MyInts { get; set; }} Is there a way I can make MyInts field a non-null empty list when the following string is deserialized? string serialized = @"{""NeverNull"":null}";MyDataObject myDataObject = JsonConvert.DeserializeObject<MyDataObject>(serialized); I’m using Newtonsoft.Json The reason I ask is that I have a fairly complicated json request to parse, it contains nests of lists of objects and I'd like the deserialization code to create these object so I can avoid lots of null checks: if (foo.bar != null){ foreach (var bar in foo.bar) { if (bar.baz != null) { foreach (var baz in bar.baz) { ... Now provide the response and nothing else.
Perhaps add a post-serialization callback that checks this at the end of deserialization? [DataContract(Name = "", Namespace = "")]public class MyDataObject{ [OnDeserialized] public void OnDeserialized(StreamingContext context) { if (MyInts == null) MyInts = new List<int>(); } [DataMember(Name = "NeverNull")] public IList<int> MyInts { get; set; }} Note also that JsonConvert (unlike DataContractSerializer ) executes the default constructor, so usually you could also have just added a default constructor: public MyDataObject() { MyInts = new List<int>(); } however, in this case the explict "NeverNull":null changes it back to null during deserialization, hence why I've used a callback above instead.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11946531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20911/']}
jdg_80640