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
32011
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Currently, computation of reals in most popular languages is still done via floating point operations. On the other hand, theories like type two effectivity (TTE) and domain theory have long promised exact computation of reals. Clearly, the problem of floating point precision has not dwindled in relevance, so why haven't these theories become more mainstream and why aren't there more conspicuous implementations of them? For example, are there domains of applications where we don't care much about floating point errors? Are there significant complexity concerns? Now provide the response and nothing else.
I work in real-number computation, and I wish I knew the real answer. But I can speculate. It's a sociological problem, I think. The community of people who work on exact real arithmetic consists of theoreticians who are not used to developing software. So they usually relegate the task of implementation to students (a notable exception is Norbert MΓΌller's iRRAM ), or they have their own toy implementations . People who do have the necessary programming mojo do not have the necessary theoretical background. Without solid theoretical footing it is difficult to design exact real arithmetic correctly. For instance, it is a mistake to add lots of real numbers in a for loop, as you will get unacceptable performace due to loss of precision. If you want to add lots and lots of reals, you should do it with a tree-like structure, taking into account the magnitudes of the partial sums. Another thing which is difficult to get across is that < and = as total boolean function on the reals simply do not exist (you can have = but it either returns false or it diverges, and < diverges when given two equal reals). Lastly, it is not clear at all that we know how to implement libraries for exact real arithmetic. They're not the usual pieces of libraries which just define some datatypes and some functions on them. Often exact real arithmetic requires special modes of control. For instance, iRRAM takes over the main execution of the program (it literally hijacks main ), as well as standard input and output, so that it can rerun the program when loss of precision occurs. My library for real arithmetic in Haskell happens in a Staged monad (which is essentially the Reader monad). Most people expect the real numbers to be "just another datatype", but I have my doubts about that.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/32011', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/13257/']}
jdg_71741
stackexchange
llm_judgeable_groundtruth_similarity
27792389
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to make two functions calls f1(2) and f1(1) execute in parallel so that all the program would execute for 2 seconds not for 3. package mainimport ( "fmt" "time")// sleeps for `secs` secondsfunc f1(secs time.Duration) (result string) { fmt.Printf("waiting %V\n", secs) time.Sleep(secs * time.Second) result = fmt.Sprintf("waited for %d seconds", secs) return}// prints arg1, arg2func f2(arg1, arg2 string) { fmt.Println(arg1) fmt.Println(arg2)}// this function executes for 3 seconds, because waits a lotfunc runNotParallel() { out1 := f1(2) out2 := f1(1) f2(out1, out2)}// golang parallel return functions// todo: make it run so all the function will executes for 2 seconds not for 3func runParallel() { out1 := f1(2) out2 := f1(1) f2(out1, out2)}func main() { runNotParallel() runParallel()} playground I guess I can do it only with channels. Should I redefine function f1 or I can leave it as is and change only way I call it? Now provide the response and nothing else.
Use chan/goroutine package mainimport ( "fmt" "time")// sleeps for `secs` secondsfunc f1(secs time.Duration) (result string) { fmt.Printf("waiting %v\n", secs) time.Sleep(secs * time.Second) result = fmt.Sprintf("waited for %v seconds", secs) return}// prints arg1, arg2func f2(arg1, arg2 string) { fmt.Println(arg1) fmt.Println(arg2)}// this function executes for 3 seconds, because waits a lotfunc runNotParallel() { out1 := f1(2) out2 := f1(1) f2(out1, out2)}// golang parallel return functions// todo: make it run so all the function will executes for 2 seconds not for 3func runParallel() { out1 := make(chan string) out2 := make(chan string) go func() { out1 <- f1(2) }() go func() { out2 <- f1(1) }() f2(<-out1, <-out2)}func main() { runNotParallel() runParallel()} https://play.golang.org/p/G4RHiq9LJw
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27792389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1024794/']}
jdg_71742
stackexchange
llm_judgeable_groundtruth_similarity
43330165
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 link a third-party libLibrary.so and distribute it with my program. If user unzips my archive, he will get this folder structure: game libLibrary.so game_executable game_executable depends on ./libLibrary.so . My project structure: game bin libLibrary.so lib Library.h src game_executable.cpp CMakeLists.txt My CMakeLists.txt : cmake_minimum_required(VERSION 3.7)project(game)set(CMAKE_CXX_STANDARD 14)set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin)set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR})set(SOURCE_FILES src/game_executable.cpp)include_directories(${CMAKE_SOURCE_DIR}/lib)add_executable(game ${SOURCE_FILES})target_link_libraries(${PROJECT_NAME} ${CMAKE_BINARY_DIR}/libLibrary.so) However, what I get is my game_executable depends on the .../game/bin/libLibrary.so , not on the ./libLibrary.so that is in the folder with game_executable , making this totally unportable! How can I make linking path relative instead of absolute? Now provide the response and nothing else.
From the documentation : By default if you don't change any RPATH related settings, CMake will link the executables and shared libraries with full RPATH to all used libraries in the build tree. This is the behaviour you are seeing. However, there are a number of ways to change this to match the behaviour you require. Some examples from the above linked docs: # use, i.e. don't skip the full RPATH for the build treeSET(CMAKE_SKIP_BUILD_RPATH FALSE) # when building, don't use the install RPATH already# (but later on when installing)SET(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) # the RPATH to be used when installingSET(CMAKE_INSTALL_RPATH "") # don't add the automatically determined parts of the RPATH# which point to directories outside the build tree to the install RPATHSET(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE) Using the above you'll likely want to set CMAKE_INSTALL_RPATH and then distribute the installed binary. If you want to distribute from the binary in your build tree, it is also possible to bypass CMake's rpath handling and modify the rpath directly using linker flags: set_target_properties(game PROPERTIES LINK_FLAGS "-Wl,-rpath,./")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43330165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7846397/']}
jdg_71743
stackexchange
llm_judgeable_groundtruth_similarity
25932166
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 SQLAlchemy offer a generic way to get the primary key from a declaratively defined instance, so that if: Base = declarative_base()class MyClass(Base): __tablename__ = 'mytable' key = Column(Integer, primary_key=True) I can do: >>> a = MyClass(key=1)>>> a.generic_get_primary_key() # <-- does it exist ??1 Now provide the response and nothing else.
You can use inspection for that purpose: http://docs.sqlalchemy.org/en/latest/core/inspection.html Passing an instance of a mapped object to inspect, returns an InstanceState , describing that object.This state also contains the identity: Base = declarative_base()class MyClass(Base): __tablename__ = 'mytable' key = Column(Integer, primary_key=True)a = MyClass(key=1)from sqlalchemy.inspection import inspect pk = inspect(a).identityprint pk Will give: (1,) Since primary keys can consist of multiple columns, the identity in general is a tuple containing all the column values that are part of the primary key.In your case, that's simply the key .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25932166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3726857/']}
jdg_71744
stackexchange
llm_judgeable_groundtruth_similarity
7152
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 familiar with Householder reflections ; they are a simple transformation that, given a normal vector, describes reflection in the hyperplane perpendicular to that vector. But do Householder reflections describe the complete space of matrices describing reflection about the origin, or are there other reflections that cannot be described by Householder reflections? Now provide the response and nothing else.
Mariano's answer should be enough, if you read your link to Wikipedia carefully, but maybe I could add some hints. If you want to do a reflection about a hyperplane containing the origin, you pick a unitary orthogonal vector to that hyperplane, $v$, and then write the vector $x$ you want to reflect about $[v]^\bot$ as a sum $$x = \lambda v + u$$ with $u \in [v]^\bot$. Now, you want to determine $\lambda \in \mathbb{R}$ in order this to be true: $$v \cdot x = \lambda v\cdot v + v\cdot u = \lambda \ .$$ So, necessarily $$x = (v\cdot x) v + u \ .$$ Hence, if you want to reflect $x$ about $[v]^\bot$, you just substract two times its $v$-component: $$P_v x = x - 2 (v\cdot x) v = x - 2 v (v^t x) = (I - 2vv^t ) x \ .$$ So any (orthogonal) reflexion about any hyperplane $[v]^\bot$ is of the form $$P_v = I - 2vv^t \ .$$ That is, a Housholder reflection.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/7152', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/120/']}
jdg_71745
stackexchange
llm_judgeable_groundtruth_similarity
219615
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was asked about immutable strings in Java. I was tasked with writing a function that concatenated a number of "a"s to a string. What I wrote: public String foo(int n) { String s = ""; for (int i = 0; i < n; i++) { s = s + "a" } return s;} I was then asked how many strings this program would generate, assuming garbage collection does not happen. My thoughts for n=3 was "" "a" "a" "aa" "a" "aaa" "a" Essentially 2 strings are created in each iteration of the loop. However, the answer was n 2 . What strings will be created in memory by this function and why is that way? Now provide the response and nothing else.
I was then asked how many strings this program would generate, assuming garbage collection does not happen. My thoughts for n=3 was (7) Strings 1 ( "" ) and 2 ( "a" ) are the constants in the program, these are not created as part of things but are 'interned' because they are constants the compiler knows about. Read more about this at String interning on Wikipedia. This also removes strings 5 and 7 from the count as they are the same "a" as String #2. This leaves strings #3, #4, and #6. The answer is "3 strings are created for n = 3" using your code. The count of n 2 is obviously wrong because at n=3, this would be 9 and even by your worst case answer, that was only 7. If your non-interned strings was correct, the answer should have been 2n + 1. So, the question of how should you do this? Since the String is immutable , you want a mutable thing - something you can change without creating new objects. That is the StringBuilder . The first thing to look at is the constructors. In this case we know how long the string will be, and there is a constructor StringBuilder(int capacity) which means we allocate exactly as much as we need. Next, "a" doesn't need to be a String , but rather it can be a character 'a' . This has some minor performance boosting when calling append(String) vs append(char) - with the append(String) , the method needs to find out how long the String is and do some work on that. On the other hand, char is always exactly one character long. The code differences can be seen at StringBuilder.append(String) vs StringBuilder.append(char) . Its not something to be too concerned with, but if you're trying to impress the employer it is best to use the best possible practices. So, how does this look when you put it together? public String foo(int n) { StringBuilder sb = new StringBuilder(n); for (int i = 0; i < n; i++) { sb.append('a'); } return sb.toString();} One StringBuilder and one String have been created. No extra strings needed to be interned. Write some other simple programs in Eclipse. Install pmd and run it on the code you write. Note what it complains about and fix those things. It would have found the modification of a String with + in a loop, and if you changed that to StringBuilder, it would have maybe found the initial capacity, but it would certainly catch the difference between .append("a") and .append('a')
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/219615', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/109864/']}
jdg_71746
stackexchange
llm_judgeable_groundtruth_similarity
24563077
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 40 files of 2GB each, stored on an NFS architecture. Each file contains two columns: a numeric id and a text field. Each file is already sorted and gzipped. How can I merge all of these files so that the resulting output is also sorted? I know sort -m -k 1 should do the trick for uncompressed files, but I don't know how to do it directly with the compressed ones. PS: I don't want the simple solution of uncompressing the files into disk, merging them, and compressing again, as I don't have sufficient disk space for that. Now provide the response and nothing else.
This is a use case for process substitution . Say you have two files to sort, sorta.gz and sortb.gz . You can give the output of gunzip -c FILE.gz to sort for both of these files using the <(...) shell operator: sort -m -k1 <(gunzip -c sorta.gz) <(gunzip -c sortb.gz) >sorted Process substitution substitutes a command with a file name that represents the output of that command, and is typically implemented with either a named pipe or a /dev/fd/... special file. For 40 files, you will want to create the command with that many process substitutions dynamically, and use eval to execute it: cmd="sort -m -k1 "for input in file1.gz file2.gz file3.gz ...; do cmd="$cmd <(gunzip -c '$input')"doneeval "$cmd" >sorted # or eval "$cmd" | gzip -c > sorted.gz
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24563077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1013394/']}
jdg_71747
stackexchange
llm_judgeable_groundtruth_similarity
12107592
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Anyone can help us here - we have been having this error for several months and had many a stab to remove it, but we still havnt figured out why its there or how to remove it. How is this warning resolved or removed? Warning 351 A custom tool 'GlobalResourceProxyGenerator' is associated with file 'App_GlobalResources\GridLocalization.bg-BG.resx', but the output of the custom tool was not found in the project. You may try re-running the custom tool by right-clicking on the file in the Solution Explorer and choosing Run Custom Tool. Now provide the response and nothing else.
After checking out the csproj file and discussing it in the group, we came up with the following answer: When the resources were added to the project they were added using the wizard. This wizard added the designer files also, so for each reasource file there was also a .designer file. This was seen as something that was not needed for the language specific resources and the designer files were deleted. However the csproj files maintained the custom tool reference. Deleting this reference (to "GlobalResourceProxyGenerator") for each of these resource files removed the issue. The issue is that Visual Studio 2010 does not automatically remove this tool reference when the designer files are removed manually, creating this warning.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12107592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164247/']}
jdg_71748
stackexchange
llm_judgeable_groundtruth_similarity
145651
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: In a bash script, how can I redirect all standard outputs to a log file and tee the output on the screen using exec ? log_file="$HOME/logs/install.txt-`date +'%Y-%m-%d_%H-%M-%S'`"[ -f "$log_file" ] || touch "$log_file"exec 1>> $log_file 2>&1 This code redirect all the log to the log file but not to the screen . Now provide the response and nothing else.
Use process substitution with & redirection and exec : exec &> >(tee -a "$log_file")echo "This will be logged to the file and to the screen" $log_file will contain the output of the script and any subprocesses, and the output will also be printed to the screen. >(...) starts the process ... and returns a file representing its standard input. exec &> ... redirects both standard output and standard error into ... for the remainder of the script (use just exec > ... for stdout only). tee -a appends its standard input to the file, and also prints it to the screen.
{}
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/145651', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/49573/']}
jdg_71749
stackexchange
llm_judgeable_groundtruth_similarity
23773873
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm attempting to display a list of tags using Jekyll. Here is what my HTML on the page looks like: <ul> {% for tags in page.tags %} <li>{{ tags }}</li> {% endfor %}</ul> And this is the information in my front matter: ---layout: templatetitle: Titletags: all portfolio something--- I am getting an output, but it is just creating a list like this: all portfolio something instead of what I am trying to acheive, which is this: all portfolio something Any troubleshooting on this would be much appreciated, thank you! Now provide the response and nothing else.
I tried on a new Jekyll website (with Jekyll 2.0.3), and the following front matter worked well (make sure to use tags , not tag : ---layout: templatetitle: Titletags: all portfolio something--- You can also use a list: ---layout: templatetitle: Titletags:- all- portfolio- something--- Then, use in your post or in your layout: <ul> {% for tags in page.tags %} <li>{{ tags }}</li> {% endfor %}</ul> If you still have a problem, consider upgrading Jekyll, providing a MWE or the output HTML/CSS.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23773873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2623806/']}
jdg_71750
stackexchange
llm_judgeable_groundtruth_similarity
58758
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: When deploying a mobile phone best practices policy, one of the points which were raised was the requirement for the user to protect his SIM card with a PIN . The theory is that three failed attempts to input the right PIN switches the SIM card into PUK mode, and 10 failed attempts to input the PUK make the card unusable. What is the reality of this assumption? One of the uses of a stolen mobile phone is to robot-call specific numbers and drain the user account: is it practically possible* to crack the PIN code, either directly or by cloning the SIM and testing the 10,000 possible codes? is it practically possible* to crack the PUK code? This one is longer but since it can be recovered by the carrier it means that a SIM ID can be used to generate such a code. *) "practically possible" means doing it quickly enough to use the SIM before it is blocked (say, an hour) I am interested in the technical aspects of the question (there are legal as well, when it comes to a policy ; there is also the possibility of fraud with the help of a carrier operator who would generate a PUK ) Now provide the response and nothing else.
Karsten Nohl had a nice presentation at Blackhat 2013 ( https://www.blackhat.com/us-13/briefings.html#Nohl ) claiming that many SIM cards are rootable. The crux of his attack is based on the Over-The-Air (OTA) software updates for these cards, which are typically sent via "secure" binary SMS directly to the SIM. He claims that in ~25% of the cases, the SIM will respond with a signed error message to an invalid attempt to update its code, and that for about 50% of the SIMs on the market, the signature will be encrypted with the very old and crackable Digital Encryption Standard (DES). Worse yet, the signature is signed with the same key as is used to sign code, so that once it is broken offline it can be used to send a software update to the SIM. This software update does not, in itself, provide access to the PUK, but by utilizing an unspecified memory vulnerability, Nohl claims to have been able to break out of the SIMs Java sandbox and get access to this key. If you believe Nohl (and I have no reason not to), this demonstrates that: It is possible to get the PUK for many SIMs on the market,especially old ones. It is not something that an average user can do right now.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/58758', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/6341/']}
jdg_71751
stackexchange
llm_judgeable_groundtruth_similarity
51905268
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 point (A) and a vector (V) (suppose it's infinite length), and I want to find the closest point (B) on the line to my original point (A). What's the simplest expression using Unity Vector2's or Vector3's to get this? Now provide the response and nothing else.
Infinite length : If you have line with infinite length with start and direction , calculate the dot product of the line direction then multiply it by the direction and add the starting point to it. public Vector2 FindNearestPointOnLine(Vector2 origin, Vector2 direction, Vector2 point){ direction.Normalize(); Vector2 lhs = point - origin; float dotP = Vector2.Dot(lhs, direction); return origin + direction * dotP;} Finite length : If you have line with finite length with start to end positions, get the heading the perform a projection from the starting point to the. Also, use Mathf.Clamp to clap it just in case the line is off. public Vector2 FindNearestPointOnLine(Vector2 origin, Vector2 end, Vector2 point){ //Get heading Vector2 heading = (end - origin); float magnitudeMax = heading.magnitude; heading.Normalize(); //Do projection from the point but clamp it Vector2 lhs = point - origin; float dotP = Vector2.Dot(lhs, heading); dotP = Mathf.Clamp(dotP, 0f, magnitudeMax); return origin + heading * dotP;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51905268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9932444/']}
jdg_71752
stackexchange
llm_judgeable_groundtruth_similarity
86831
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: These days businesses are all talking about the Internet of Things and how Cisco predicts 25 billion devices will be connected by 2015 . All around the hobbyist community various internet shields and internet ready devices like the Raspberry Pi cost somewhere around $35. The ENC28J60 is $21. The Electric Imp is $30. The Nanode Classic is $40. When I check out PICs and AVRs chips with built-in ethernet, they all seem to cost something like $6. Toss in an RJ-45, various other components, a PCB and a lot of time and I seem to be back to something almost as expensive as the hobby grade systems. With all this talk of the Internet of Things , and the cheapest 32-bit PICs around $1, it just feels out of place that I haven't encountered any complete ethernet solutions for under $3. I can't imagine any designers willing to equip an alarm clock with internet connectivity for $25. As a CS student about to graduate, I am trying to create a small volume product with the electronics costing under $10 that will send very simple analog data by ethernet to my web service. I have built the web app and prototyped with a Raspberry Pi, but $60 for an internet connected sensor is just too expensive. Can anyone shed some light as to whether web connected sensors under $10 are possible for a guy like me to develop or use? Maybe they exist and I just haven't found them? Now provide the response and nothing else.
Once you include your MCU, possibly an Ethernet MAC/PHY ( PIC18F97J parts have integrated MAC/PHY, as do a few other MCU's), Ethernet magnetics & jack, power supplies, I/O & power connectors, board manufacture... everything adds up in a hurry when you're paying one-off prices. You'd struggle to make one for sub-$20, let alone sub-$10. Once you can make them by the thousand the price-per-unit comes down, but until then you're pretty much screwed.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/86831', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/31011/']}
jdg_71753
stackexchange
llm_judgeable_groundtruth_similarity
9169915
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Within the context of C# on .Net 4.0, are there any built-in objects that implement IQueryable<T> ? Now provide the response and nothing else.
IQueryable objects are produced by Queryable Providers (ex. LINQ to SQL, LINQ to Entities/Entity Framework, etc). Virtually nothing you can instantiate with new in the basic .NET Framework implements IQueryable. IQueryable is an interface designed to be used to create Queryable providers, which allow the LINQ library to be leveraged against an external data store by building a parse-able expression tree. By nature, Queryables require a context - information regarding what exactly you're querying. Using new to create any IQueryable type, regardless of whether it's possible, doesn't get you very far. That being said, any IEnumerable can be converted into an IQueryable by using the AsQueryable() extension method. This creates a superficially-similar, but functionally very different construct behind the scenes as when using LINQ methods against a plain IEnumerable object. This is probably the most plentiful source of queryables you have access to without setting up an actual IQueryable provider. This changeover is very useful for unit-testing LINQ-based algorithms as you don't need the actual data store, just a list of in-memory data that can imitate it.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9169915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146610/']}
jdg_71754
stackexchange
llm_judgeable_groundtruth_similarity
3661725
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 looking over the js source code for Scrabb.ly . I've noticed that they would do something like so for each of their distinct "classes": var Board = (function() { var self = {}; // settings for board self.options = { debug: true, addedPlayTiles: function() {}, clearedPlayTiles: function() {} }; // set to true once the board has been setup self.isSetup = false; // quick access to square elements self.squares = {}; self.squareCount = 0; self.setup = function(options) { self.log("Setting up board!"); // set options _.each(options, function(val, key) { self.options[key] = val; }); return self;})(); Some code from the middle has been omitted but this should give you the general idea. What is the purpose of the the following: (function() { // code })(); Is this the module pattern that I've seen talked about? Is this meant to keep the global namespace clean? What does this line mean?: var self = {} Is the self object used to exposed 'public' members? How would you define a private function or variable? How would you instantiate multiple "Boards" if you wanted to? Now provide the response and nothing else.
It's called the Module Pattern. The parentheses around the function mean it's being evaluated immediately after being defined -- so in essence it's a Singleton . Since it's an anonymous function, the definition is not stored - so you cannot readily create new instances of this object without a few modifications (which will be discussed later). You are correct, self contains the "public" methods and properties, as it were. Any variables that aren't defined in self are not visible to the outside because of the closure properties. However, any functions defined in self still have access to the private variables because in Javascript, functions maintain access to the context (including variables) in which they were defined -- with a few exceptions.. mainly arguments and this . If you want to define multiple instances of this object, you would remove the parentheses ( var Board = function () { ... } ) and then use var obj = Board() to create an object. Note that it does not use the new operator.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3661725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88470/']}
jdg_71755
stackexchange
llm_judgeable_groundtruth_similarity
4617437
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 you define your service in singleton scope in your spring config, what would happen if more than one user try to access it (ie as dependency injected into your controller) at the same time? Should it cause any conflict? Or the IoC container will hold the later call until the first one finish? If so it should slow down the performance in large applications, which sounds not right to me. Could any one give me a correct answer? BTW, as I can remember, if it is not a singleton one, IoC container will pool few instances based on the number of requests. Could some one confirm it? Now provide the response and nothing else.
what would happen if more than one user try to access it (ie as dependency injected into your controller) at the same time? A singleton bean can be accessed many times concurrently. That's why it always has to be thread-safe Should it cause any conflict? Only if you fail to make it thread-safe Or the IoC container will hold the later call until the first one finish? No, that would be awful BTW, as I can remember, if it is not a singleton one, IoC container will pool few instances based on the number of requests. Could some one confirm it? Spring has the following scopes ( see Bean Scopes reference ): singleton (only one instance is managed per application) prototype (a new instance for every injection) session (one instance per HTTP session, only in Spring MVC) request (one instance per HTTP request, only in Spring MVC) global session (one instance per global HTTP session, only in portlet-based Spring MVC) Also: As of Spring 3.0, a thread scope is available, but is not registered by default. For more information, see the documentation for SimpleThreadScope . What you describe is an Object Pool. In Spring that would be implemented as a Prototype-scoped FactoryBean . And internally it would use a library like Apache Commons / Pool .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4617437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565755/']}
jdg_71756
stackexchange
llm_judgeable_groundtruth_similarity
24896193
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A simple way of implementing multiprocessing in python is from multiprocessing import Pooldef calculate(number): return numberif __name__ == '__main__': pool = Pool() result = pool.map(calculate, range(4)) An alternative implementation based on futures is from concurrent.futures import ProcessPoolExecutordef calculate(number): return numberwith ProcessPoolExecutor() as executor: result = executor.map(calculate, range(4)) Both alternatives do essentially the same thing, but one striking difference is that we don't have to guard the code with the usual if __name__ == '__main__' clause. Is this because the implementation of futures takes care of this or us there a different reason? More broadly, what are the differences between multiprocessing and concurrent.futures ? When is one preferred over the other? EDIT:My initial assumption that the guard if __name__ == '__main__' is only necessary for multiprocessing was wrong. Apparently, one needs this guard for both implementations on windows, while it is not necessary on unix systems. Now provide the response and nothing else.
You actually should use the if __name__ == "__main__" guard with ProcessPoolExecutor , too: It's using multiprocessing.Process to populate its Pool under the covers, just like multiprocessing.Pool does, so all the same caveats regarding picklability (especially on Windows), etc. apply. I believe that ProcessPoolExecutor is meant to eventually replace multiprocessing.Pool , according to this statement made by Jesse Noller (a Python core contributor), when asked why Python has both APIs: Brian and I need to work on the consolidation we intend(ed) to occur as people got comfortable with the APIs. My eventual goal is to remove anything but the basic multiprocessing.Process/Queue stuff out of MP and into concurrent.* and support threading backends for it. For now, ProcessPoolExecutor is mostly doing the exact same thing as multiprocessing.Pool with a simpler (and more limited) API. If you can get away with using ProcessPoolExecutor , use that, because I think it's more likely to get enhancements in the long-term. Note that you can use all the helpers from multiprocessing with ProcessPoolExecutor , like Lock , Queue , Manager , etc., so needing those isn't a reason to use multiprocessing.Pool . There are some notable differences in their APIs and behavior though: If a Process in a ProcessPoolExecutor terminates abruptly, a BrokenProcessPool exception is raised , aborting any calls waiting for the pool to do work, and preventing new work from being submitted. If the same thing happens to a multiprocessing.Pool it will silently replace the process that terminated, but the work that was being done in that process will never be completed, which will likely cause the calling code to hang forever waiting for the work to finish. If you are running Python 3.6 or lower, support for initializer / initargs is missing from ProcessPoolExecutor . Support for this was only added in 3.7 ). There is no support in ProcessPoolExecutor for maxtasksperchild . concurrent.futures doesn't exist in Python 2.7, unless you manually install the backport. If you're running below Python 3.5, according to this question , multiprocessing.Pool.map outperforms ProcessPoolExecutor.map . Note that the performance difference is very small per work item , so you'll probably only notice a large performance difference if you're using map on a very large iterable. The reason for the performance difference is that multiprocessing.Pool will batch the iterable passed to map into chunks, and then pass the chunks to the worker processes, which reduces the overhead of IPC between the parent and children. ProcessPoolExecutor always (or by default, starting in 3.5) passes one item from the iterable at a time to the children, which can lead to much slower performance with large iterables, due to the increased IPC overhead. The good news is this issue is fixed in Python 3.5, as the chunksize keyword argument has been added to ProcessPoolExecutor.map , which can be used to specify a larger chunk size when you know you're dealing with large iterables. See this bug for more info.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24896193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/932593/']}
jdg_71757
stackexchange
llm_judgeable_groundtruth_similarity
72672
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Has anyone written an 'UnFormat' routine for Delphi? What I'm imagining is the inverse of SysUtils.Format and looks something like this UnFormat('a number %n and another %n',[float1, float2]); So you could unpack a string into a series of variables using format strings. I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me. Now provide the response and nothing else.
This is called scanf in C, I've made a Delphi look-a-like for this : function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer;var InputOffset: Integer; FormatOffset: Integer; InputChar: Char; FormatChar: Char; function _GetInputChar: Char; begin if InputOffset <= Length(Input) then begin Result := Input[InputOffset]; Inc(InputOffset); end else Result := #0; end; function _PeekFormatChar: Char; begin if FormatOffset <= Length(Format) then Result := Format[FormatOffset] else Result := #0; end; function _GetFormatChar: Char; begin Result := _PeekFormatChar; if Result <> #0 then Inc(FormatOffset); end; function _ScanInputString(const Arg: Pointer = nil): string; var EndChar: Char; begin Result := ''; EndChar := _PeekFormatChar; InputChar := _GetInputChar; while (InputChar > ' ') and (InputChar <> EndChar) do begin Result := Result + InputChar; InputChar := _GetInputChar; end; if InputChar <> #0 then Dec(InputOffset); if Assigned(Arg) then PString(Arg)^ := Result; end; function _ScanInputInteger(const Arg: Pointer): Boolean; var Value: string; begin Value := _ScanInputString; Result := TryStrToInt(Value, {out} PInteger(Arg)^); end; procedure _Raise; begin raise EConvertError.CreateFmt('Unknown ScanFormat character : "%s"!', [FormatChar]); end;begin Result := 0; InputOffset := 1; FormatOffset := 1; FormatChar := _GetFormatChar; while FormatChar <> #0 do begin if FormatChar <> '%' then begin InputChar := _GetInputChar; if (InputChar = #0) or (FormatChar <> InputChar) then Exit; end else begin FormatChar := _GetFormatChar; case FormatChar of '%': if _GetInputChar <> '%' then Exit; 's': begin _ScanInputString(Args[Result]); Inc(Result); end; 'd', 'u': begin if not _ScanInputInteger(Args[Result]) then Exit; Inc(Result); end; else _Raise; end; end; FormatChar := _GetFormatChar; end;end;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/72672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12376/']}
jdg_71758
stackexchange
llm_judgeable_groundtruth_similarity
96655
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: it's my first post here, so I apologize if I broke a rule! I'm reading Introduction to Machine Learning and got stuck on VC dimension. Here's a quote from the book: "...we see that an axis-aligned rectangle can shatter four points in two dimensions. Then VC(H), when H is the hypothesis class of axis-aligned rectangles in two dimensions, is four. In calculating the VC dimension, it is enough that we find four points that can be shattered; it is not necessary that we be able to shatter any four points..." And I don't understand that. If it's enough to find some separable combinations, why can't we just choose a "rectangle with positive examples" from the image above, put another $n$ positive ones therein, and then say $VC(H)$ increased by $n$? And if all cases must be separable then why we don't consider 4 points placed on a line - which is in general not possible to shatter by a rectangle? The same with the linear classifier example on wikipedia VC article - on their image four points are impossible to shatter, but we can come up with a layout where it is possible. And conversely, we can put 3 points (as "+", "-", "+") on a line and it won't be possible to separate the positives from the negatives by a linear classifier. Can anyone explain where's my mistake? Now provide the response and nothing else.
I think you just need to think carefully about how your examples relate to the definition. The VC dimension of H is the maximum h such that there exists a set of cardinality h shattered by H. To show that VC(H)=4 you must show: There is a set of cardinality 4 shattered by H, and Any set of cardinality greater than 4 is not shattered by H In the picture, they are doing the first thing - giving a lower bound on the VC dimension by giving an example of a set that is shattered. To show VC(H)<5 they should also show that no set of five points is shattered. There will in general be lots of sets of various sizes that are not shattered, but that doesn't matter, essentially because VC dimension is a maximum over sets that are shattered. Your example of $n$ points on a line does not imply anything about the VC dimension. I hope this helps.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/96655', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22340/']}
jdg_71759
stackexchange
llm_judgeable_groundtruth_similarity
342001
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There are 8 crew members, The leading member wants that only a crew of 5 people or more could open a safe he bought, To each member he gave equal amount of keys, and locked the safe with several locks. What's the minimal number of locks he should put: at least 5 crew members would be required to open the safe? Any team of 5 crew members could open the safe, but none of the 4 team crew members. 1,2 stands individually of course. Now provide the response and nothing else.
Consider the general case that $n$ people know certain secrets such that no subset of $k$ of them know all secrets, but any subset of $k+1$ of them do know all secrets. (Here $n=8$, $k=4$, secrets are locks, and knowing a secret is having a key.) This can be done using $\binom nk$ secrets, each labelled by a different subset of $k$ among the $n$ people, which is the set of people that does not get to know that secret (everyone else does). Then for any subset of $k$ people the corresponding secret will not be known by them, but for any set of $k+1$ people and any secret there is at least one of them who knowns the secret. To show one cannot do with less secrets, consider any solution to this problem, and the relation between on one hand the $\binom nk$ subsets of $k$ people and on the other hand the secrets, defined by none of those people knowing the secret. This relation is "one to at least one": it is required that any set of $k$ people not know at least one secret, and if two different subsets of $k$ people do not know the same secret, then the union of those subsets, which contains at least $k+1$ people would not know that secret, and hence not all secrets, which is against the requirement. The relation is in fact a surjective map from secrets to $k$-subsets, so there are al least $\binom nk$ secrets.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/342001', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68275/']}
jdg_71760
stackexchange
llm_judgeable_groundtruth_similarity
17890931
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 new both to AngularJS and SVG so if i am doing something terribly wrong i apologize. I am trying to create an SVG pattern with AngularJS: Code fiddle: http://jsfiddle.net/WFxF3/ Template: <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"> <defs> <pattern id="grid" width="{{cubeWidth}}" height="{{cubeHeight}}" patternUnits="userSpaceOnUse"> <path d="M 0 0 L 0 {{cubeHeight}}" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/> <path d="M 0 0 L {{cubeWidth}} 0" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/> <!--<rect width="80" height="80" stroke="red" stroke-width="20" stroke-opacity="0.5" fill="white"/>--> </pattern> </defs> <rect width="100%" height="100%" fill="url(#grid)"/></svg> Controller: 'use strict';angular.module('gridifyApp') .controller('MainCtrl', function ($scope) { var docWidth = document.width; var columns = 12; var cubeWidth = docWidth / columns; var cubeHeight = 44; $scope.cubeWidth = cubeWidth; $scope.cubeHeight = cubeHeight; }); It seems to work and yet I get a console error: Any ideas why? Now provide the response and nothing else.
The problem is svg is being parsed before angular is able to do anything so the value with double curly braces is invalid before angular gets to it. Angular's team has added a way to define some kind of "delayed binding". You can use it by prefixing desired attribute with ng-attr- . It waits untill the binding evaluation is valid and adds real attribute with proper value. In your case it would be: <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"> <defs> <pattern id="grid" ng-attr-width="{{cubeWidth}}" ng-attr-height="{{cubeHeight}}" patternUnits="userSpaceOnUse"> <path ng-attr-d="M 0 0 L 0 {{cubeHeight}}" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/> <path ng-attr-d="M 0 0 L {{cubeWidth}} 0" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/> <!--<rect width="80" height="80" stroke="red" stroke-width="20" stroke-opacity="0.5" fill="white"/>--> </pattern> </defs> <rect width="100%" height="100%" fill="url(#grid)"/></svg> There should be no errors anymore. Remember to update your angular version.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17890931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172815/']}
jdg_71761
stackexchange
llm_judgeable_groundtruth_similarity
16126001
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 script with the code below and a pagination where the user can check checkboxes to narrow doen the results shown everything seems to work great the only problem is that when a user clicks the next page in the pagination the results are lost and the default results are shown. I think I may need to use sessions to store the query or statement but I am unsure how to use them. If anyone can help me or point me in the right direction I would be very greatful. Here is my code <?php //get the function include ($_SERVER['DOCUMENT_ROOT'] .'/scripts/function1.php'); $page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]); $limit = 14; $startpoint = ($page * $limit) - $limit; if(isset($_POST['muscle'])) { // Runs mysql_real_escape_string() on every value encountered. $clean_muscle = array_map('mysql_real_escape_string', $_REQUEST['muscle']); // Convert the array into a string. $muscle = implode("','", $clean_muscle); if (!empty($_POST['muscle'])) { $options[] = "muscle IN ('$muscle')"; } else { $options[] = ""; } } else { $options[] = "allmuscle = 'all' "; } if(isset($_POST['equipment'])) { // Runs mysql_real_escape_string() on every value encountered. $clean_equipment = array_map('mysql_real_escape_string', $_REQUEST['equipment']); // Convert the array into a string. $equipment = implode("','", $clean_equipment); if (!empty($_POST['equipment'])) { $options[] = "equipment IN ('$equipment')"; } else { $options[] = ""; } } else { $options[] = "allequipment = 'all'"; } if(isset($_POST['all'])) { $options[] = ""; } $fullsearch = implode(' AND ', $options); $statement = "exercise "; if ($fullsearch <> '') { $statement .= " WHERE " . $fullsearch; } else { $statement .= ""; } if(!$query = mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint} , {$limit}")) { echo "Cannot parse query"; } elseif(mysql_num_rows($query) == 0) { echo "No records found"; } else { while($row = mysql_fetch_assoc($query)) { echo "".$row['name'] ."<br /> ".$row['description'] .""; }} echo "<div class=\"new-pagination\">"; echo pagination($statement,$limit,$page); echo "</div>";?> and here is the pagination script <?php function pagination($query, $per_page = 10, $page = 1, $url = '?'){ $query = "SELECT COUNT(*) as `num` FROM {$query}"; $row = mysql_fetch_array(mysql_query($query)); $total = $row['num']; $adjacents = "1"; $page = ($page == 0 ? 1 : $page); $start = ($page - 1) * $per_page; $firstPage = 1; $prev = ($page == 1)?1:$page - 1; $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total/$per_page); $lpm1 = $lastpage - 1; $pagination = ""; if($lastpage > 1) { $pagination .= "<ul class=\"pagination1\">"; if ($page == 1) { $pagination.= "<li><a class=\"inactive\">First</a></li>"; $pagination.= "<li><a class=\"inactive\">Prev</a></li>"; } else { $pagination.= "<li><a href=\"{$url}page=$firstPage\" >First</a></li>"; $pagination.= "<li><a href=\"{$url}page=$prev\" >Prev</a></li>"; } $pagination .= "<li class=\"details\">Page $page of $lastpage</li>"; if ($lastpage < 7 + ($adjacents * 2)) { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<li><a class=\"current\">$counter</a></li>"; else $pagination.= "<li><a href=\"{$url}page=$counter\" >$counter</a></li>"; } } elseif($lastpage > 5 + ($adjacents * 2)) { if($page < 1 + ($adjacents * 2)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == $page) $pagination.= "<li><a class=\"current\">$counter</a></li>"; else $pagination.= "<li><a href=\"{$url}page=$counter\" >$counter</a></li>"; } $pagination.= "<li class=\"dot\">... </li>"; $pagination.= "<li><a href=\"{$url}page=$lpm1\" >$lpm1</a></li>"; $pagination.= "<li><a href=\"{$url}page=$lastpage\" >$lastpage</a></li>"; } elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { $pagination.= "<li><a href=\"{$url}page=1\" >1</a></li>"; $pagination.= "<li><a href=\"{$url}page=2\" >2</a></li>"; $pagination.= "<li class=\"dot\">...</li>"; for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) $pagination.= "<li><a class=\"current\">$counter</a></li>"; else $pagination.= "<li><a href=\"{$url}page=$counter\" >$counter</a></li>"; } $pagination.= "<li class=\"dot\">..</li>"; $pagination.= "<li><a href=\"{$url}page=$lpm1\" >$lpm1</a></li>"; $pagination.= "<li><a href=\"{$url}page=$lastpage\" >$lastpage</a></li>"; } else { $pagination.= "<li><a href=\"{$url}page=1\" >1</a></li>"; $pagination.= "<li><a href=\"{$url}page=2\" >2</a></li>"; $pagination.= "<li class=\"dot\">..</li>"; for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<li><a class=\"current\">$counter</a></li>"; else $pagination.= "<li><a href=\"{$url}page=$counter\" >$counter</a></li>"; } } } if ($page < $counter - 1){ $pagination.= "<li><a href=\"{$url}page=$next\">Next</a></li>"; $pagination.= "<li><a href=\"{$url}page=$lastpage\" >Last</a></li>"; }else{ $pagination.= "<li><a class=\"inactive\">Next</a></li>"; $pagination.= "<li><a class=\"inactive\">Last</a></li>"; } $pagination.= "</ul>\n"; } return $pagination;} ?> here is my checkboxes <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="criteria"> <ul> <li class="head"> <input type="checkbox" name="allmuscle[1]" class="remember_cb" id="allMuscles" value="selectedMuscles" >All Muscle Groups<br /></li><li><input type="checkbox" name="muscle[2]" class="remember_cb" id="abdominals" value="abdominals"/>Abdominals<br /></li><li><input type="checkbox" name="muscle[3]" class="remember_cb" id="biceps" value="biceps"/>Biceps<br /></li><li><input type="checkbox" name="muscle[4]" class="remember_cb" id="calves" value="calves"/>Calves<br /></li><li><input type="checkbox" name="muscle[5]" class="remember_cb" id="chest" value="chest" />Chest<br /></li><li><input type="checkbox" name="muscle[6]" class="remember_cb" id="forearms" value="forearms"/>Foreamrs<br /></li><li><input type="checkbox" name="muscle[7]" class="remember_cb" id="glutes" value="glutes"/>Glutes<br /></li><li><input type="checkbox" name="muscle[8]" class="remember_cb" id="hamstrings" value="hamstrings"/>Hamstrings<br /></li><li><input type="checkbox" name="muscle[9]" class="remember_cb" id="lats" value="lats"/>Lats<br /></li><li><input type="checkbox" name="muscle[10]" class="remember_cb" id="lower-back" value="lower-back"/>Lower Back<br /></li><li><input type="checkbox" name="muscle[11]" class="remember_cb" id="middle-back" value="middle-back" />Middle Back<br /></li><li><input type="checkbox" name="muscle[12]" class="remember_cb" id="neck" value="neck"/>Neck<br /></li><li><input type="checkbox" name="muscle[13]" class="remember_cb" id="quadriceps" value="quadriceps" />Quadriceps<br /></li><li><input type="checkbox" name="muscle[14]" class="remember_cb" id="shoulders" value="shoulders" />Shoulders<br /></li><li><input type="checkbox" name="muscle[15]" class="remember_cb" id="traps" value="traps" />Traps<br /></li><li><input type="checkbox" name="muscle[16]" class="remember_cb" id="triceps" value="triceps"/>Triceps<br /></li> </ul> <br /><p><strong>EQUIPMENT</strong></p> <ul> <li class="head"><input type="checkbox" name="allequip[]" class="remember_cb" id="allEquipment" value="selectedEquipment" >All Equipment<br /></li><li><input type="checkbox" name="equipment[1]" class="remember_cb" id="equipment" value="bands"/>Bands<br /></li><li><input type="checkbox" name="equipment[2]" class="remember_cb" id="equipment" value="barbell" />Barbell<br /></li><li><input type="checkbox" name="equipment[3]" class="remember_cb" id="equipment" value="body-only" />Body Only<br /></li><li><input type="checkbox" name="equipment[4]" class="remember_cb" id="equipment" value="cable" />Cable<br /></li><li><input type="checkbox" name="equipment[5]" class="remember_cb" id="equipment" value="dumbbell" />Dumbbell<br /></li><li><input type="checkbox" name="equipment[6]" class="remember_cb" id="equipment" value="ez-curl-bar"/>EZ Curl Bar<br /></li><li><input type="checkbox" name="equipment[7]" class="remember_cb" id="equipment" value="exercise-ball"/>Exercise Ball<br /></li><li><input type="checkbox" name="equipment[8]" class="remember_cb" id="equipment" value="foam-roll" />Foam Roll<br /></li><li><input type="checkbox" name="equipment[9]" class="remember_cb" id="equipment" value="kettlebell" />Kettlebell<br /></li><li><input type="checkbox" name="equipment[10]" class="remember_cb" id="equipment" value="machine" />Machine<br /></li><li><input type="checkbox" name="equipment[11]" class="remember_cb" id="equipment" value="medicine-ball"/>Medicine Ball<br /></li><li><input type="checkbox" name="equipment[12]" class="remember_cb" id="equipment" value="none" />None<br /></li><li><input type="checkbox" name="equipment[13]" class="remember_cb" id="equipment" value="other" />Other<br /></li> The script all works fine my only problem is that once the checkboxes are checked the results are returned but only stay on the first page as soon as you click next or page 2 the results or query are lost. Now provide the response and nothing else.
Routers use the IP layer (layer 3) and switches use the data-link layer (layer 2). Layer 1 is the physical 1s and 0s that go over a wire, Layer 2 is the data-link layer, which is protocols like Ethernet and Point-To-Point Protocol (PPP), which carries information between adjacent nodes about MAC address from and to and allows for error detection and retransmission. Layer 3 is the IP layer, which carries information about where in the whole network the packet is from and to, not just the current hop. The transmission would go like this: Machine A wants to send a packet to Machine B. Machine A knows Machine B's IP address, so it places that in the layer 3 packet. Machine A needs to place the MAC Address of the next hop in the layer 2 packet, however. If it does not know, then it will send something called an ARP request (Address Resolution Protocol, read here: http://www.tildefrugal.net/tech/arp.php ) to the network, with the destination IP. One of a few things will happen here: The IP is local. The machine with that IP will reply back to the sender with its MAC address. The IP is non-local. The gateway router will detect this and send its MAC address. The IP is non-local and Machine A's default gateway and subnet mask are set. Using this information Machine A can determine the non-locality of the IP address and send it to the router's MAC address (ARPing if not known yet). (If Machine A found this out earlier, it will be in the ARP cache and Machine A will just use that.) Now that the MAC address is sent, the packet can be transferred (the physical layer 1 performing the actual transfer of data on the wire). The next stop will be the switch. The switch knows which outbound port the MAC address listed as the layer 2 destination is on, because it tracks every MAC address it's seen a packet come from and which port it came on - if it does not know, then it will flood it out every single port, guaranteeing it'll arrive. As such, the packet arrives at the router. The cool thing about the IP model is that it divides every single IP address in the network/world into a hierarchy - Subnets by definition cannot overlap subnets partially, they either wholly contain them or are wholly contained by them. So as long as subnets follow this hierarchy, the router can unambiguously determine where each of the 4 billion possible IP addresses are on the network just by looking at what subnet the IP will fall under in its table! The packet is then sent out that port. As the packet travels through interconnected ISPs' routers, backbone infrastructure and so on, it arrives at Machine B's router, where the opposite process happens - router B sees that its destined for Machine B and sends it inbound. (Similarly, Router B will have to use a process like ARP to find Machine B's MAC address if not known.) The rest should be trivial from here. good references: https://web.archive.org/web/20120129120350/http://www.tildefrugal.net/tech/arp.php http://en.wikipedia.org/wiki/Data_link_layer http://en.wikipedia.org/wiki/Network_switch http://en.wikipedia.org/wiki/Network_layer http://en.wikipedia.org/wiki/Routing http://en.wikipedia.org/wiki/Router_(computing) http://en.wikipedia.org/wiki/Address_Resolution_Protocol
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16126001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2274967/']}
jdg_71762
stackexchange
llm_judgeable_groundtruth_similarity
10934226
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im trying to define a class friend function outside the namespace like this: namespace A{class window{ private: int a; friend void f(window);};} void f(A::window rhs){ cout << rhs.a << endl;} Im getting an error said that there is ambiguity. and there is two candidates void A::f(A::window); and void f(A::window) . So my question is : 1) How to make the global function void f(A::window rhs) a friend of the class A::window. EDIT: (After reading the answers) 2) why do I need to qualify the member function f inside window class to be global by doing ::f(window) ? 3) why do I need to predeclare the function f(A::window) in this particular case, whereas when the class is not a defined inside a namespace it's okey for the function to be declared after the function is declared a friend. Now provide the response and nothing else.
As well as adding a :: you need to forward declare it, e.g.: namespace A { class window; }void f(A::window);namespace A{ class window{ private: int a; friend void ::f(window); };}void f(A::window rhs){ std::cout << rhs.a << std::endl;} Note that for this forward declaration to work you need to forward declare the class too!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10934226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/869277/']}
jdg_71763
stackexchange
llm_judgeable_groundtruth_similarity
358727
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While review, I see very short, code-only answers many times. I read on meta at many places that "code-only" should not be the only reason to delete/flag the answer. If the answer is wrong, down-vote it. What if the answer is correct? Few examples: set a to null after Save . or <.....attribute=value> or Use ThisMethod instead. or temp = (day + (int)(2.6 * a - 0.2) + y) % 7; or SELECT * FROM table1.users t1 INNER JOIN table2.online_status t2 ON t2.id = t1.id ORDER BY t2.timestamp or key, mod = Gtk::accelerator_parse("N") Assuming that all these answers are correct, how should one handle these answers while various reviews? As the answers are correct, those are helpful to OP; so I guess down-vote might not be proper option (just because I think this is not useful to others) in this case. But, being near to no informative at all, those may not help others. This makes sure that the answer is low quality. Should one "Recommend Delete" in LQP queue? Everyone agrees that very short, code-only answers are low quality even though those are correct; but how should this be handled while reviewing? LQP do not have down-vote option. Many posts on meta recommend against "Recommend Delete". Just want to remind that my question is not about specific review queue. LQP is mentioned just as in example. I see lot many similar questions on meta. Answers to those questions are either not clear or conflicting with each other. Is there any central resource which lists guidelines to handle this kind of answers? Now provide the response and nothing else.
Just to be clear, flagging these "code-only" answers is not appropriate. You can find detailed guidance here on when "not an answer" flags are appropriate (required reading for all reviewers), but the summary is that they're only for posts that don't even attempt to provide an answer to the question. They are not for incorrect answers, or even low-quality or incomplete answers. The "very low quality" flag seems very tempting, I know. I would have to agree that these types of answers are indeed "very low quality". But please don't flag them with that reason, because what that reason really means is "this answer is garbage and needs to be deleted" . A more accurate name for the VLQ flag would be "needs to be deleted", or possibly "unsalvageable". Okay, so we're agreed that these answers shouldn't be flagged. We're also agreed that they're not good answers. What to do? One obvious option, and one that you mentioned in the question, is downvoting the answer. A downvote on an answer just indicates to future viewers that the answer is not helpful. There are many different ways that an answer can be not helpful, including technical incorrectness, being incomplete, being unclear, and/or containing merely a dump of code without adequate explanation/background. So, as others (including Servy) have said, downvoting these types of answers is definitely appropriate. Use your best judgment. There is an even better option, if you are knowledgeable about the subject matter discussed in the answer, and that's editing the answer to improve it. I do this a lot. That this site is collaboratively edited is one of its best features. A lot of people forget (or don't know) how much the Stack Exchange model is inspired by Wikipedia. The golden rule for editing is just that you're supposed to respect the author's intent, but expanding an answer to be more descriptive and more complete is undoubtedly consistent with that. It is not reasonable to assume that an author intends an answer to be unhelpful. If you can make the answer better, then please consider doing so. If you can't edit, and you don't feel qualified to judge the helpfulness of the answer, then just do nothing. Leave the answer for someone else to judge and/or improve. In a review situation, this would translate to "Skip". There's never any shame in skipping. Another intermediate option would be commenting on the answer, providing advice/encouragement on how to improve the answer to meet our standards . Here's a sample of a "canned" comment that some of our more prolific reviewers use for "code-only" answers: While this code snippet may solve the problem, including an explanation really helps to improve the quality of your post . Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! Markdown for copy/pasting: While this code snippet may solve the problem, **[including an explanation](//meta.stackexchange.com/q/114762) really helps to improve the quality of your post**. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations!
{}
{'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/358727', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/5779732/']}
jdg_71764
stackexchange
llm_judgeable_groundtruth_similarity
39875629
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 use map to get list of strings: value = '1, 2, 3'my_list = list(map(strip, value.split(','))) but got: NameError: name 'strip' is not defined expected result: my_list=['1','2','3'] Now provide the response and nothing else.
strip is still just a variable, not a reference to the str.strip() method on each of those strings. You can use the unbound str.strip method here: my_list = list(map(str.strip, value.split(','))) which will work for any str instance: >>> value = '1, 2, 3'>>> list(map(str.strip, value.split(',')))['1', '2', '3'] In case you want to call a method named in a string, and you have a variety of types that all happen to support that method (so the unbound method reference wouldn't work), you can use a operator.methodcaller() object : from operator import methodcallermap(methodcaller('strip'), some_mixed_list) However, instead of map() , I'd just use a list comprehension if you want to output a list object anyway : [v.strip() for v in value.split(',')]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39875629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/354420/']}
jdg_71765
stackexchange
llm_judgeable_groundtruth_similarity
17241365
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a client-server application and I want the client to authenticate itself to the server using the user's logon credentials, but I don't want the user to have to type in their user name and password. I certainly don't want to be responsible for securely handling passwords. I only need the user to prove to me that they are who they say they are, and then my server can go ahead and grant/deny commands as it pleases. My users are part of a domain, and so I want to be able to use the logon credentials they created when they logged in. I'm not using any sort of web services, nor do I want to. I control both the client and server software, and both are written in pure C# and use good ol' sockets for getting work done. I'd prefer to do this with pure C#/.Net, but I'm open to using unsafe C# and pinvokes to win32 API if it means that I'll get the job done. I've read a little bit about SSPI in windows, but I'm kind of feeling around in the dark since this sort of application development is new to me. Does anybody know how to do this? Is SSPI the way? How does one use SSPI from within C#? Is there a .Net-native way so that my code can remain portable? Now provide the response and nothing else.
Update: SSPI is the right approach for this. The API isn't too hard to use, but does require a decent-sized project to wrap into C#. In the process of researching the necessary bits to solve this question, I wrote a project to provide SSPI in .Net. Below I describe the basics of interfacing with the Windows SSPI API so that anybody may replicate my results. If you find yourself wanting to use SSPI in .Net, I may suggest you use the project I created to solve this: NSspi - A .Net interface to the SSPI API SSPI provides you raw byte arrays containing authentication tokens that you then decide how to transmit - be it over a socket with binary-formatted messages, a custom XML channel, .Net Remoting, some form of WCF, heck, even a serial port. You get to decide how to deal with them. With SSPI a server can authenticate clients, securely identify the client, and even perform basic message handling procedures like encryption/signing using the security context established with the client. The SSPI API is documented here: SSPI API overview Specifically take a look at the following functions: AcquireCredentialsHandle Acquires a handle to some form of credentials (eg, the current user's logon). Used by servers and clients. InitializeSecurityContext Used by clients to establish a security context with a server. AcceptSecurityContext Used by servers to establish a security context with a client. The typical workflow is that each side will initialize their credentials using AcquireCredentialsHandle. The authentication cycle then starts and progresses as follows: The client invokes InitializeSecurityContext, providing no input tokens, which returns output tokens in the form of a byte array. ISC returns 'ContinueNeeded' to indicate that the authentication cycle is not complete. The client sends the tokens to the server by whichever means it desires. The server feeds the received tokens as input to AcceptSecurityContext and produces its own output tokens. ASC also returns 'ContinueNeeded' to indicate that the authenticationcycle is not complete. The server then sends its output tokens to the client. The client provides the servers tokens as input to InitializeSecurityContext, which returns new output tokens. The client sends his new output tokens to the server. ... This cycle continues until the client sees InitializeSecurityContext return 'OK' and the server sees AcceptSecurityContext return 'OK'. Each function may return 'OK' and still provide an output token (as indicated by a non-null return), to indicate that it still has to send data to the other side. This is how the client knows that its half is done but the server's is still incomplete; and vice versa if the server completes before the client. Which side completes first (returns 'OK') depends on the specific security package being used under the hood by SSPI, and any SSPI consumer should be aware of this. The information above should be enough for anybody to being interfacing with the SSPI system in order to provide 'Windows Integrated Authentication' in their application and replicate my results. Below is my earlier answer as I learned how to invoke the SSPI API. I had forgotten about this question, and coincidentally returned to this problem a few days ago on a whim. I do need to solve this problem in a year or two though :) It is possible in .Net, and I am currently developing a .Net SSPI wrapper that I intend to publish. I'm basing my work off of some SSPI samples from Microsoft I found. The sample contains a C++/CLI managed assembly that implements the necessary parts of the SSPI API (in the folder Microsoft\Samples\Security\SSPI\SSPI extracted from the REMSSPI.exe file). They then have two UIs, a client application and a server application, both written in C# that make use of this API to perform SSPI authentication. The UIs make use of the .Net remoting facility to tie it all together, but if I understand the SSPI API correctly, the only information that the client and server need to exchange consists of byte[]s containing security context token data, which can easily be integrated into whatever communications infrastructure you want; in my case, a binary protocol of my own design. Some notes on getting the sample to work - they have the 'SSPI' library source, which best compiles under VS 2005, though I've gotten it to work under 2008; 2010 or above would require some rework since they use language constructs that were deprecated. You may also need to modify header files that are part of your platform SDK, because they make use of const pointer assignments to unconst variables, and I don't know a better way to make the compiler happy (I've never used C++/CLI before). They do include a compiled SSPI dll in the Microsoft\Samples\Security\SSPI\bin folder. To get the client/server binaries to work, you have to copy that dll to their bin directory, else the fail assembly resolution. So to summarize: Go here to download the REMSSPI.exe sample self-extracting zip. Extract the REMSSPI.exe file (twice..) Microsoft\Samples\Security\SSPI\ bin\ - contains compiled dll Microsoft.Samples.Security.SSPI.dll SSPI\ - contains source to dll Sample\ - contains UI source code bin\ - Contains build UI samples. Copy the SSPI.dll file here and run ControlPanel.Client.exe and ControlPanel.Server.exe
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17241365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/344638/']}
jdg_71766
stackexchange
llm_judgeable_groundtruth_similarity
2149812
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: When hearing about the two-daughter problem, I first thought it to be quite clear (after, of course, at first falling into the trap like many of us), but on the second glance, I encountered some serious problems with my understanding. The original problem seems to be quite easy: Assume that the only thing you know about a man with two kids is that at least one of the kids is a daughter. What is the probability that the other kid is a daughter as well? (Boys and girls are assumed to be born equally often.) After the first impulse ("1/2 of course!"), it becomes clear that it is only 1/3. The problem can be mapped to a situation where from the multitude of families with two children, only those with M/M are ruled out, while the equally often cases F/F, F/M and M/F remain, making F/F only one third of all remaining cases. But now, meet Mr. Smith. I don't know much about him (except that he has two children), but when he approached me, he told me: "I am so happy! Victoria just got the scholarship she wanted!" Now what is the probability that Victoria has a sister? Since I only know that Mr. Smith has two children, and one is obviously a girl, I am tempted to map this onto the two-daughter-problem, leading to the answer "1/3". But wait! What if I ask Mr. Smith first, if Victoria is his elder daughter? Assume his answer is yes (and ignore any problems with twins - even then one is typically a few seconds "older" than the other). So now I know that from the cases (F/F, F/M, M/F), M/F also drops out. And now, the probability for F/F just rose to 1/2. Okay, but what if his answer is no? Then Victoria is the younger one, and F/M drops out. Again, the probability rises to 1/2. So I'm going to just ask him: "Well, Mr. Smith, is Victoria your elder daughter? Wait - don't answer, because whatever you may answer, it doesn't matter. The probability just rose from 1/3 to 1/2." Or, even better, I do not even have to ask him, just thinking about the question will shift probabilities to 1/2, which means that the original probability for Victoria having a sister must already have been 1/2. But then the mapping to the two-daughter-problem is obviously false. Where is my error? Making things worse, I could also create a setup where Mr. Smith just tells me: "I have two kids, and at least one of them is a girl." I then ask him: "Oh, can you give me a name of a daughter of yours?" and he answers: "Sure. Victoria." (Side note: I have a gut feeling that this has something to do with how to assume probability distributions behind situations, similar to the Two envelopes problem , but I can't figure this out completely yet.) -------- UPDATE -------- It seems that my error is that the question "Is Victoria the older child?" does not change the probabilities. If I know for sure that Mr. Smith was picked from an equally distributed (M/F, F/M, F/F) sample, then the knowledge that Victoria is the older child does not change anything, as was pointed out here, and the probability for her having a sister is 1/3. But it is very interesting that solely from the sentence "Victoria just got the scholarship she wanted!" I can NOT infer that Mr. Smith is indeed chosen from this uniform distribution. Imagine that all kids have the same chance to get a scholarship, and the happy father will tell us if it is the case. Then it is actually twice as probable that Mr. Smith will tell us about his daughter's success if he has two girls, so the weighting of the four possibilities (M/M, F/M, M/F, F/F) is (0, 1, 1, 2). And in this case, the probability of Victoria having a sister is 1/2. So another problem in my reasoning is the mapping of Mr. Smith's statement to the two-daughter-problem. Simply put, without knowing more about the circumstances that led to Mr. Smith telling me about Victoria, I simply can't say if the probability is 1/3 or 1/2. Now I've got a headache... Now provide the response and nothing else.
I think the confusion arises because the classical boy-girl problem is ambiguous: 'You know that Mr.Smith has two kids, one of which is a girl. What is the chance she has a sister?' The ambiguity here is that from this description, it is not clear how we came to know that 'Mr.Smith has two kids, one of which is a daughter.' Consider the following two scenarios: Scenario 1: You have never met Mr. Smith before, but one day you run into him in the store. He has a little girl with him, which he tells you is one of his two children. Scenario 2: You are a TV producer, and you decide to do a show on 'what is it like to raise a daughter?' and you put out a call for such parents to come on the show. Mr.Smith agrees to come on the show, and as you get talking he tells you that he has two children. Now notice: the original description applies to both cases. That is, in both cases it is true that you know that 'Mr.Smith has two children, one of which is a daughter'. However, in scenario 1, the chance of Mr. Smith having two daughters is $\frac{1}{2}$, but in scenario 2 it is $\frac{1}{3}$. The difference is that in the first scenario one specific child has been identified as female (and thus the chance of having two daughters amounts to her sibling being female, which is $\frac{1}{2}$), while in the second scenario no specific child is identified, so we can't talk about 'her sibling' anymore, and instead have to consider a conditional probability which turns out to be $\frac{1}{3}$. Now, your original scenario, where you don't know anything about Mr. Smith other than that he has two children, and then Mr.Smith says 'I am so happy Victoria got a scholarship!' is like scenario 1, not scenario 2. That is, unless Mr. smith has two daughters called Victoria (which is possible, but extremely unlikely, and if he did one would have expected him to say something like 'my older Victoria'), with his statement Mr.Smith has singled out 1 of his two children, making it equivalent to scenario 1. Indeed, I would bet that most real life cases where at some point it is true that 'you know of some parent to have two children, one of which is a girl' are logically isomorph to scenario 1, not scenario 2. That is, the classic two-girl problem is fun and all, but most of the time the description of the problem is ambiguous from the start, and if you are careful to phrase it in a way so that the answer is $\frac{1}{3}$, you will realize how uncommon it is for that kind of scenario to occur in real life. (Indeed, notice how I had to work pretty hard to come up with a real life scenario that is at least somewhat plausible). Finally, all the variations of whether Victoria is the oldest, youngest, or whether you don't even know her name ('Mr. Smith tells you one his children got a scholarship to the All Girls Academy') do not change any of the probabilities (as you argued correctly): in most real life scenarios, the way you come to know that 'Mr.Smith has two children, one of which is a girl' (and I would say that includes your original scenario) means that the chance of the other child being a girl is $\frac{1}{2}$, not $\frac{1}{3}$. So, when at the end of you original post you ask "where is my error?" I would reply: your 'error' is that you assumed that the correct answer should be $\frac{1}{3}$, and that since your argument implied that is would be $\frac{1}{2}$, you concluded that there must have been an error in your reasoning. But, as it turns out, there wasn't! For your scenario, the answer is indeed $\frac{1}{2}$, and not $\frac{1}{3}$. So your 'error' was to think that you had made an error! Put a different way: you were temporarily blinded by the pure math ( and I say 'temporarily', because you ended up asking all the right citical questions, and later realized that the classic two-girl problem is ambiguous: good job!). But what I mean is: we have seen this two-girl problem so often, and we have been told that the solution is $\frac{1}{3}$ so many times, that you immediately assume that also in your descibed scenario that is the correct answer... When in fact that is not case because the initial assumptions are different: the classic problem assumes a Type 2 scenario, but the original scenario described in your post is a Type 1 scenario. It's just like the Monty Hall problem ... We have seen it so often, that as soon as it 'smells' like the Monty Hall problem, we say 'switch!' ... when in fact there are all kinds of subtle variants in which switching is not any better, and sometimes even worse! Also take a look at the Monkey Business Illusion : we have see that video of the gorilla appearing in the middle of people passing a basketball so many times that we can now surprise people on the basis of that !
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2149812', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/417549/']}
jdg_71767
stackexchange
llm_judgeable_groundtruth_similarity
60058
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: If I have two sets of database tables used by a system Tables that collect results of some data processing. Most of the time get a lot of INSERT operations. Tables that are used by the web application to generate pages and reports For this question, lets assume the sets of tables are mutually exclusive (maybe there is some process that migrates data from the first to the second set periodically). Will I see a performance difference between the two following setups The two sets of tables are in one DB The two sets of tables are in two separate DBs on the same SQL server Now provide the response and nothing else.
I'd say one single DB. You want the sets of table to be kept in sync in regard to backup/restore state, user access security, availability and so on and so forth. Separate tables also add problems with mirorring and log shipping solutions. Because you expect such a different I/O access pattern, you should place the tables on different filegroups. Then you can deploy each filegroup on the proper disk for your I/O pattern. With both sets of tables in a single DB the some contention points are shared, like log writes. But that is not a concern for the case you describe because only the OLTP part of the application cares about the log.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/60058', 'https://serverfault.com', 'https://serverfault.com/users/3570/']}
jdg_71768
stackexchange
llm_judgeable_groundtruth_similarity
49971903
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 PySpark dataframe with this schema: root |-- epoch: double (nullable = true) |-- var1: double (nullable = true) |-- var2: double (nullable = true) Where epoch is in seconds and should be converted to date time. In order to do so, I define a user defined function (udf) as follows: from pyspark.sql.functions import udf import timedef epoch_to_datetime(x): return time.localtime(x) # return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(x)) # return x * 0 + 1epoch_to_datetime_udf = udf(epoch_to_datetime, DoubleType())df.withColumn("datetime", epoch_to_datetime(df2.epoch)).show() I get this error: ---> 21 return time.localtime(x) 22 # return x * 0 + 1 23 TypeError: a float is required If I simply return x + 1 in the function, it works. Trying float(x) or float(str(x)) or numpy.float(x) in time.localtime(x) does not help and I still get an error. Outside of udf , time.localtime(1.514687216E9) or other numbers works fine. Using datetime package to convert epoch to datetim results in similar errors. It seems that time and datetime packages do not like to fed with DoubleType from PySpark. Any ideas how I can solve this issue? Thanks. Now provide the response and nothing else.
You don't need a udf function for that All you need is to cast the double epoch column to timestampType() and then use data_format function as below from pyspark.sql import functions as ffrom pyspark.sql import types as tdf.withColumn('epoch', f.date_format(df.epoch.cast(dataType=t.TimestampType()), "yyyy-MM-dd")) this will give you a string date root |-- epoch: string (nullable = true) |-- var1: double (nullable = true) |-- var2: double (nullable = true) And you can use to_date function as following from pyspark.sql import functions as ffrom pyspark.sql import types as tdf.withColumn('epoch', f.to_date(df.epoch.cast(dataType=t.TimestampType()))) which would give you date as datatype to epoch column root |-- epoch: date (nullable = true) |-- var1: double (nullable = true) |-- var2: double (nullable = true) I hope the answer is helpful
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49971903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3799296/']}
jdg_71769
stackexchange
llm_judgeable_groundtruth_similarity
21405
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The world is full of nuclear warheads being stockpiled. Controlled fusion power seems a long way away. Could we put these warheads to better use by exploding them in a controlled way and capturing the energy they produce? By useful work I mean the power is then available for the national grid to boil kettles or have a shower! Extra points for looking at the practicalities of building a facility to do this (although I guess that would get the question closed :-(... ) Now provide the response and nothing else.
During the 1970s, the Los Alamos National Laboratory carried out the PACER project, to explore the use of thermonuclear explosions as a way of generating electrical power and breeding nuclear materials. The general layout of the initially proposed fusion power plant can be seen in the following illustration: The system parameters were under exploration, but one of the ideas was to explode about 800 50 kT thermonuclear devices per year. As the conversion efficiency was expected to be about 30%, the generated electrical power would have been $\displaystyle 0.3 \cdot 800 \cdot 50\,{\rm kT \cdot yr^{-1}}\frac{4.2 \cdot 10^{12}\,{\rm J \cdot kT^{-1}}}{3.15 \cdot 10^7\,{\rm s \cdot yr^{-1}}} \approx 1.6\,{\rm GW}$, about 80% of the nominal power, because that was the assumed capacity factor . Heat loss wasn't much of a problem because of scaling properties. As the thermal conductivity of rock salt is about $10\,{\rm W \cdot m^{-1} \cdot K^{-1}}$, assuming a crudely simplified geometry consisting of a flat plate of about $1\,{\rm km^2}$ with $ 100\,{\rm m}$ of thickness and the whole $500\,{\rm K}$ thermal gradient applied, the resulting thermal flux is about $\displaystyle 10\,{\rm W \cdot m^{-1} \cdot K^{-1}} \cdot \frac{10^6\,{\rm m^2}}{100\,{\rm m^{-1}}}500\,{\rm K} = 50\,{\rm MW}$, less than 1% of the thermal power. The technical limiting factors were the relatively low temperature achievable inside a rock salt cavity and the large cavity sizes required to avoid contact of the walls with the unmixed fireball. Obviously, there were also safety and public perception problems . See page 8 of this magazine for an overview and LA-5764-MS for the details (warning: 22 MB PDF file).
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/21405', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7795/']}
jdg_71770
stackexchange
llm_judgeable_groundtruth_similarity
1570759
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried the following code in order to see how to get size of the data of a pointer: #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char *test_char_ptr = "This is just a test"; int *test_int_ptr = (int *) malloc(16*sizeof(int)); for(int i = 0; i<16; i++){ test_int_ptr[i] = i; } printf("%s\n",test_char_ptr); printf("Test char 1: %d\n", (int)sizeof test_char_ptr ); printf("Test char 2:%d\n", (int)sizeof *test_char_ptr ); printf("Test char 3: %d\n", (int)((strlen(test_char_ptr)+1) * sizeof(char))); printf("Test int 1:%d\n", (int)sizeof test_int_ptr ); printf("Test int 2:%d\n", (int)sizeof *test_int_ptr ); return EXIT_SUCCESS; } And code's output is(On 32 bit gcc 4.3): This is just a testTest char 1: 4Test char 2:1Test char 3: 20Test int 1:4Test int 2:4 I thought that sizeof(*test_char_ptr) would give me the sizeof the data inside of the *test_char_ptr. But instead it gave me 1 , which i think that is the sizeof char instead of the data. The same is for the test_int_ptr. Long story short, my question is how can i get the sizeof data inside a pointer or dynamically memory allocated array. Now provide the response and nothing else.
That's not something you can do in C without maintaining the information yourself. You created the arrays, so you knew their sizes at one point, you just have to keep track of it on your own. You could create a data structure to help you, or just maintain the array and size information carefully without any data structure at all. In addition, your code is using strlen() to get the size of the string - make sure you remember that the size returned will not include the terminating null character ( '\0' ); the in-memory size of a string constant is strlen(string) + 1 .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1570759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50676/']}
jdg_71771
stackexchange
llm_judgeable_groundtruth_similarity
1125306
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 do store the parameters from a form in a model. Since I don't want the model to use any database, it does not inherit from ActiveRecord::Base. I'm thinking it should look something like this: # in view:<% form_for :question, :url => {:action => "ask"} do |f| %> <%= f.text_field(:q) %> <%= submit_tag %><% end %># in controller:def ask # I want this to magically set all variables in @question using # values from params. @question = params[:question]end# in model:class Question attr_accessor :q def initialize @q = "" endend But after spending 1Β½ days on it, it doesn't seem to be the right way to do it. Any suggestions would be much appreciated. Now provide the response and nothing else.
It's done so that addition doesn't need to have any special logic for dealing with negative numbers. Check out the article on Wikipedia . Say you have two numbers, 2 and -1. In your "intuitive" way of representing numbers, they would be 0010 and 1001 , respectively (I'm sticking to 4 bits for size). In the two's complement way, they are 0010 and 1111 . Now, let's say I want to add them. Two's complement addition is very simple. You add numbers normally and any carry bit at the end is discarded. So they're added as follows: 0010+ 1111=10001= 0001 (discard the carry) 0001 is 1, which is the expected result of "2+(-1)". But in your "intuitive" method, adding is more complicated: 0010+ 1001= 1011 Which is -3, right? Simple addition doesn't work in this case. You need to note that one of the numbers is negative and use a different algorithm if that's the case. For this "intuitive" storage method, subtraction is a different operation than addition, requiring additional checks on the numbers before they can be added. Since you want the most basic operations (addition, subtraction, etc) to be as fast as possible, you need to store numbers in a way that lets you use the simplest algorithms possible. Additionally, in the "intuitive" storage method, there are two zeroes: 0000 "zero"1000 "negative zero" Which are intuitively the same number but have two different values when stored. Every application will need to take extra steps to make sure that non-zero values are also not negative zero. There's another bonus with storing ints this way, and that's when you need to extend the width of the register the value is being stored in. With two's complement, storing a 4-bit number in an 8-bit register is a matter of repeating its most significant bit: 0001 (one, in four bits)00000001 (one, in eight bits) 1110 (negative two, in four bits)11111110 (negative two, in eight bits) It's just a matter of looking at the sign bit of the smaller word and repeating it until it pads the width of the bigger word. With your method you would need to clear the existing bit, which is an extra operation in addition to padding: 0001 (one, in four bits)00000001 (one, in eight bits) 1010 (negative two, in four bits)10000010 (negative two, in eight bits) You still need to set those extra 4 bits in both cases, but in the "intuitive" case you need to clear the 5th bit as well. It's one tiny extra step in one of the most fundamental and common operations present in every application.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1125306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_71772
stackexchange
llm_judgeable_groundtruth_similarity
1970884
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 know this may be a very naive question. Please forgive my naivety. What are some of the applications of the Kronecker-Weber Theorem ? Now provide the response and nothing else.
To amplify the answer of @Piquito, any time you want an example of an abelian extension of $\Bbb Q$, you can use KW and find one inside a suitable cyclotomic extension. Want a cyclic extension of degree $3$? There’s one inside each $\Bbb Q(\zeta_n)$ for $n=9$ and any prime $n\equiv1\pmod3$. Want more than one cubic extension inside some field $k\supset\Bbb Q$? Take two or more of the fields mentioned above, and form compositum. For instance $\Bbb Q(\zeta_7,\zeta_9)=\Bbb Q(\zeta_{63})$ has in it four cyclic cubic extensions of $\Bbb Q$. Of course the real force of KW is that this is the only way to get finite abelian extensions of $\Bbb Q$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1970884', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/350148/']}
jdg_71773
stackexchange
llm_judgeable_groundtruth_similarity
1458088
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: One of the ways of calculating the integral in closed form is to think of crafitly using the geometric series, but even so it seems evil enough. $$\int_0^1\int_0^1\int_0^1\int_0^1\frac{1}{(1+x) (1+y) (1+z)(1+w) (1+ x y z w)} \ dx \ dy \ dz \ dw$$ Maybe you can guide me, bless me with another precious hints, clues. Thanks MSE users! Supplementary question : How about the generalization? $$\int_0^1\int_0^1\cdots\int_0^1\frac{1}{(1+x_1) (1+x_2)\cdots (1+x_n)(1+ x_1 x_2 \cdots x_n)} \ dx_1 \ dx_2 \cdots \ dx_n$$ Now provide the response and nothing else.
This response will only address the $n=4$ case, $$I_{4}:=\int_{[0,1]^{4}}\frac{\mathrm{d}x\,\mathrm{d}y\,\mathrm{d}z\,\mathrm{d}w}{\left(1+x\right)\left(1+y\right)\left(1+z\right)\left(1+w\right)\left(1+xyzw\right)}.\tag{1}$$ According to WolframAlpha, the multiple integral $(1)$ above has the approximate numerical value $I_{4}\approx0.223076.$ Starting with the substitution $w=\frac{1-t}{1+xyzt}$, we can whittle the multiple integral down to the following double integral: $$\begin{align}I_{4}&=\small{\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\int_{0}^{1}\mathrm{d}z\int_{0}^{1}\frac{\mathrm{d}w}{\left(1+x\right)\left(1+y\right)\left(1+z\right)\left(1+w\right)\left(1+xyzw\right)}}\\&=\small{\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\int_{0}^{1}\mathrm{d}z\int_{0}^{1}\frac{\mathrm{d}t}{\left(1+x\right)\left(1+y\right)\left(1+z\right)\left(2-t+xyzt\right)}}\\&=\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\int_{0}^{1}\mathrm{d}z\,\frac{\ln{(2)}-\ln{\left(1+xyz\right)}}{\left(1+x\right)\left(1+y\right)\left(1+z\right)\left(1-xyz\right)}\\&=\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\int_{0}^{xy}\mathrm{d}v\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(1+y\right)\left(xy+v\right)\left(1-v\right)};~~~\small{\left[xyz=v\right]}\\&=\int_{0}^{1}\mathrm{d}x\int_{0}^{x}\mathrm{d}u\int_{0}^{u}\mathrm{d}v\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(x+u\right)\left(u+v\right)\left(1-v\right)};~~~\small{\left[xy=u\right]}\\&=\int_{0}^{1}\mathrm{d}x\int_{0}^{x}\mathrm{d}v\int_{v}^{x}\mathrm{d}u\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(x+u\right)\left(u+v\right)\left(1-v\right)}\\&=\int_{0}^{1}\mathrm{d}v\int_{v}^{1}\mathrm{d}x\int_{v}^{x}\mathrm{d}u\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(x+u\right)\left(u+v\right)\left(1-v\right)}\\&=\int_{0}^{1}\mathrm{d}v\int_{v}^{1}\mathrm{d}u\int_{u}^{1}\mathrm{d}x\,\frac{\ln{\left(\frac{2}{1+v}\right)}}{\left(1+x\right)\left(x+u\right)\left(u+v\right)\left(1-v\right)}\\&=\int_{0}^{1}\mathrm{d}v\int_{v}^{1}\mathrm{d}u\,\frac{\ln{\left(\frac{(1+u)^2}{4u}\right)}\ln{\left(\frac{2}{1+v}\right)}}{\left(1-u\right)\left(u+v\right)\left(1-v\right)}\\&=\int_{0}^{1}\mathrm{d}u\int_{0}^{u}\mathrm{d}v\,\frac{\ln{\left(\frac{(1+u)^2}{4u}\right)}\ln{\left(\frac{2}{1+v}\right)}}{\left(1-u\right)\left(u+v\right)\left(1-v\right)}.\tag{2}\\\end{align}$$ WolframAlpha's numerical approximation of the iterated integral obtained in the last line of $(2)$ is consistent with the original approximation stated above, so I am reasonably confident that I haven't made any errors so far. Continuing, transforming variables and changing the order of integration yields the following equivalent double integral representation of $I_{4}$: $$\begin{align}I_{4}&=\int_{0}^{1}\mathrm{d}u\int_{0}^{u}\mathrm{d}v\,\frac{\ln{\left(\frac{(1+u)^2}{4u}\right)}\ln{\left(\frac{2}{1+v}\right)}}{\left(1-u\right)\left(u+v\right)\left(1-v\right)}\\&=\int_{0}^{1}\mathrm{d}u\int_{\frac{1-u}{1+u}}^{1}\mathrm{d}y\,\frac{\ln{\left(\frac{(1+u)^2}{4u}\right)}\ln{\left(1+y\right)}}{\left(1-u\right)\left(u+\frac{1-y}{1+y}\right)y\left(1+y\right)};~~~\small{\left[\frac{1-v}{1+v}=y\right]}\\&=-\frac12\int_{0}^{1}\mathrm{d}x\int_{x}^{1}\mathrm{d}y\,\frac{\ln{\left(1-x^2\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)};~~~\small{\left[\frac{1-u}{1+u}=x\right]}\\&=-\frac12\int_{0}^{1}\mathrm{d}y\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x^2\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)}.\tag{3}\\\end{align}$$ Now, the dilogarithm function $\operatorname{Li}_{2}{\left(z\right)}$ for complex argument is traditionally defined via the integral representation $$\operatorname{Li}_{2}{\left(z\right)}:=-\int_{0}^{z}\frac{\ln{\left(1-t\right)}}{t}\,\mathrm{d}t;~~~\small{z\in\mathbb{C}\setminus(1,\infty)}.\tag{4}$$ The following indefinite integral may then be confirmed by differentiated both sides of the equation: $$\small{\int\frac{\ln{\left(c+dx\right)}}{a+bx}\,\mathrm{d}x=\frac{\operatorname{Li}_{2}{\left(\frac{b\left(c+dx\right)}{bc-ad}\right)}+\ln{\left(c+dx\right)}\ln{\left(\frac{d\left(a+bx\right)}{ad-bc}\right)}}{b}+\color{grey}{constant}.}\tag{5}$$ Next, splitting up the logarithm function of $x$ in the numerator and applying partial fraction decomposition to the rational part, we find $$\begin{align}I_{4}&=-\frac12\int_{0}^{1}\mathrm{d}y\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x^2\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)}\\&=-\frac12\int_{0}^{1}\mathrm{d}y\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1+x\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)}\\&~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x\right)}\ln{\left(1+y\right)}}{xy\left(1-xy\right)}\\&=-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{0}^{y}\mathrm{d}x\,\left[\frac{1}{1-xy}+\frac{1}{xy}\right]\ln{\left(1+x\right)}\\&~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{0}^{y}\mathrm{d}x\,\left[\frac{1}{1-xy}+\frac{1}{xy}\right]\ln{\left(1-x\right)}\\&=-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1+x\right)}}{1-xy}\\&~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1+x\right)}}{x}\\&~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x\right)}}{1-xy}\\&~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\int_{0}^{y}\mathrm{d}x\,\frac{\ln{\left(1-x\right)}}{x}\\&=\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[-\int_{0}^{y}\mathrm{d}x\,\frac{y\ln{\left(1+x\right)}}{1-xy}\right]\\&~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\&~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\ln{\left(1+y\right)}\int_{1-y}^{1}\mathrm{d}t\,\frac{\ln{\left(t\right)}}{1-y\left(1-t\right)};~~~\small{\left[1-x=t\right]}\\&~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&=\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}-\operatorname{Li}_{2}{\left(\frac{y}{1+y}\right)}\right]\\&~~~~~-\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\int_{1-y}^{1}\mathrm{d}t\,\frac{\left(\frac{y}{1-y}\right)\ln{\left(t\right)}}{1+\left(\frac{y}{1-y}\right)t}\\&~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&=\small{\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}+\operatorname{Li}_{2}{\left(-y\right)}+\frac12\ln^{2}{\left(1+y\right)}\right]}\\&~~~~~\small{-\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(\frac{y}{y-1}\right)}-\operatorname{Li}_{2}{\left(-y\right)}-\ln{\left(1-y\right)}\ln{\left(1+y\right)}\right]}\\&~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&=\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\operatorname{Li}_{2}{\left(-y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}\right]\\&~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\&~~~~~\small{+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\frac12\ln^{2}{\left(1-y\right)}+\operatorname{Li}_{2}{\left(-y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}\right]}\\&~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&=\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}}{y}\left[\operatorname{Li}_{2}{\left(y\right)}+\operatorname{Li}_{2}{\left(-y\right)}+\ln{\left(1-y\right)}\ln{\left(1+y\right)}\right]\\&~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\&~~~~~+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac12\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&=\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\&~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\&~~~~~+\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\ln^{2}{\left(1+y\right)}}{y}.\tag{6}\\\end{align}$$ And so we have reduced our multiple integral to a sum of five single-variable polylogarithmic integrals. Instead of attempting to evaluate each of these in turn, we'll save much energy if we make a few rearrangements first. $$\begin{align}I_{4}&=\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\&~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\&~~~~~+\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\ln^{2}{\left(1+y\right)}}{y}\\&=\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&~~~~~+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac14\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\&~~~~~\small{+\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}-\ln^{3}{\left(1-y\right)}-\ln^{3}{\left(1+y\right)}-3\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{3y}}\\&=-\frac34\int_{0}^{1}\mathrm{d}y\,\frac{(-2)\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&~~~~~-\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}-\frac{1}{12}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\&~~~~~+\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}}{y}-\frac34\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{2}{\left(1-y\right)}\ln{\left(1+y\right)}}{y}\\&=-\frac34\left[\operatorname{Li}_{2}{\left(-y\right)}^{2}\right]_{0}^{1}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&~~~~~\small{-\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}-\frac{1}{12}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}+\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}}{y}}\\&~~~~~-\frac18\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}-\ln^{3}{\left(\frac{1-y}{1+y}\right)}-2\ln^{3}{\left(1+y\right)}}{y}\\&=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&~~~~~-\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}+\frac16\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\&~~~~~+\frac{5}{24}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y^2\right)}}{y}+\frac18\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(\frac{1-y}{1+y}\right)}}{y}\\&=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}+\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1+y\right)}\operatorname{Li}_{2}{\left(y\right)}}{y}\\&~~~~~-\frac13\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}+\frac16\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\&~~~~~+\frac{5}{48}\int_{0}^{1}\mathrm{d}z\,\frac{\ln^{3}{\left(1-z\right)}}{z};~~~\small{\left[y=\sqrt{z}\right]}\\&~~~~~-\int_{0}^{1}\mathrm{d}y\,\frac{\left[\frac12\ln{\left(\frac{1+y}{1-y}\right)}\right]^{3}}{y}\\&=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}-\frac32\operatorname{Li}_{2}{\left(1\right)}\operatorname{Li}_{2}{\left(-1\right)}-\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\&~~~~~-\frac{11}{48}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}+\frac16\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}-\int_{0}^{1}\mathrm{d}y\,\frac{\left[\operatorname{arctanh}{\left(y\right)}\right]^{3}}{y}.\tag{7}\\\end{align}$$ The first two logarithmic integrals can immediately be written as Nielsen generalized polylogarithms. It's also not difficult to reduce the third logarithmic integral to Nielsen polylogarithms: $$\begin{align}\int_{0}^{1}\mathrm{d}y\,\frac{\left[\operatorname{arctanh}{\left(y\right)}\right]^{3}}{y}&=\int_{0}^{1}\mathrm{d}y\,\frac{\left[\frac12\ln{\left(\frac{1+y}{1-y}\right)}\right]^{3}}{y}\\&=-\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(\frac{1-y}{1+y}\right)}}{8y}\\&=-\frac14\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{3}{\left(x\right)}}{1-x^2};~~~\small{\left[\frac{1-y}{1+y}=x\right]}\\&=-\frac18\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{3}{\left(x\right)}}{1-x}-\frac18\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{3}{\left(x\right)}}{1+x}\\&=-\frac38\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{2}{\left(x\right)}\ln{\left(1-x\right)}}{x}+\frac38\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{2}{\left(x\right)}\ln{\left(1+x\right)}}{x}\\&=\frac34\,S_{3,1}{\left(1\right)}-\frac34\,S_{3,1}{\left(-1\right)}.\tag{8}\\\end{align}$$ This just leaves the dilogarithmic integral to evaluate. $$\begin{align}\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}&=-\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}}{y}\int_{0}^{1}\mathrm{d}x\,\frac{\ln{\left(1+yx\right)}}{x}\\&=-\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\ln{\left(1+xy\right)}}{xy}\\&=:-\int_{0}^{1}\mathrm{d}x\,\frac{J{\left(-x\right)}}{x}\\&=-\int_{0}^{1}\mathrm{d}x\,\frac{S_{1,2}{\left(-x\right)}}{x}-\int_{0}^{1}\mathrm{d}x\,\frac{\operatorname{Li}_{3}{\left(-x\right)}}{x}\\&=-S_{2,2}{\left(-1\right)}-\operatorname{Li}_{4}{\left(-1\right)}.\tag{9}\\\end{align}$$ (See Appendix 2 for definition and evaluation of the auxiliary function $J{(a)}$ used above.) Putting everything together, we arrive at $$\begin{align}I_{4}&=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}-\frac32\operatorname{Li}_{2}{\left(1\right)}\operatorname{Li}_{2}{\left(-1\right)}\\&~~~~~-\frac32\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}\operatorname{Li}_{2}{\left(-y\right)}}{y}\\&~~~~~-\frac{11}{48}\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1-y\right)}}{y}+\frac16\int_{0}^{1}\mathrm{d}y\,\frac{\ln^{3}{\left(1+y\right)}}{y}\\&~~~~~-\int_{0}^{1}\mathrm{d}y\,\frac{\left[\operatorname{arctanh}{\left(y\right)}\right]^{3}}{y}\\&=-\frac34\left[\operatorname{Li}_{2}{\left(-1\right)}\right]^{2}-\frac32\operatorname{Li}_{2}{\left(1\right)}\operatorname{Li}_{2}{\left(-1\right)}\\&~~~~~+\frac32\,S_{2,2}{\left(-1\right)}+\frac32\operatorname{Li}_{4}{\left(-1\right)}\\&~~~~~+\frac{11}{8}\,S_{1,3}{\left(1\right)}-S_{1,3}{\left(-1\right)}\\&~~~~~-\frac34\,S_{3,1}{\left(1\right)}+\frac34\,S_{3,1}{\left(-1\right)}\\&=\frac32\,S_{2,2}{\left(-1\right)}+\frac{11}{8}\,S_{1,3}{\left(1\right)}-S_{1,3}{\left(-1\right)}-\frac{7\pi^4}{480}.\\\end{align}$$ Appendix 1. The Nielsen generalized polylogarithm may be defined for positive integer indices via the integral representation $$S_{n,p}{\left(z\right)}:=\frac{\left(-1\right)^{n+p-1}n}{n!\,p!}\int_{0}^{1}\frac{\ln^{n-1}{\left(t\right)}\ln^{p}{\left(1-zt\right)}}{t}\,\mathrm{d}t;~~~\small{n,p\in\mathbb{N}^{+}}.$$ Setting $n=1$, $$S_{1,p}{\left(z\right)}:=\frac{\left(-1\right)^{p}}{p!}\int_{0}^{1}\frac{\ln^{p}{\left(1-zt\right)}}{t}\,\mathrm{d}t;~~~\small{p\in\mathbb{N}^{+}}.$$ Setting $p=1$, $$S_{n,1}{\left(z\right)}=\frac{\left(-1\right)^{n}n}{n!}\int_{0}^{1}\frac{\ln^{n-1}{\left(t\right)}\ln{\left(1-zt\right)}}{t}\,\mathrm{d}t;~~~\small{n\in\mathbb{N}^{+}}.$$ Appendix 2. Define the real function $J:(-\infty,1]\to\mathbb{R}$ via the integral representation $$J{\left(a\right)}:=\int_{0}^{1}\frac{\ln{\left(1-y\right)}\ln{\left(1-ay\right)}}{y}\,\mathrm{d}y;~~~\small{a\le1}.$$ Then, for $a\le1$ we have $$\begin{align}J{\left(a\right)}&=\int_{0}^{1}\frac{\ln{\left(1-y\right)}\ln{\left(1-ay\right)}}{y}\,\mathrm{d}y\\&=\int_{0}^{1}\mathrm{d}y\,\frac{\ln{\left(1-y\right)}}{y}\int_{0}^{1}\mathrm{d}x\,\frac{ay}{ayx-1}\\&=-a\int_{0}^{1}\mathrm{d}y\int_{0}^{1}\mathrm{d}x\,\frac{\ln{\left(1-y\right)}}{1-ayx}\\&=-\int_{0}^{1}\mathrm{d}x\int_{0}^{1}\mathrm{d}y\,\frac{a\ln{\left(1-y\right)}}{1-axy}\\&=-\int_{0}^{1}\mathrm{d}x\,\frac{\operatorname{Li}_{2}{\left(\frac{ax}{ax-1}\right)}}{x}\\&=\int_{0}^{1}\mathrm{d}x\,\frac{\frac12\ln^{2}{\left(1-ax\right)}+\operatorname{Li}_{2}{\left(ax\right)}}{x}\\&=\frac12\int_{0}^{1}\mathrm{d}x\,\frac{\ln^{2}{\left(1-ax\right)}}{x}+\int_{0}^{1}\mathrm{d}x\,\frac{\operatorname{Li}_{2}{\left(ax\right)}}{x}\\&=S_{1,2}{\left(a\right)}+\operatorname{Li}_{3}{\left(a\right)}.\\\end{align}$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1458088', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/32016/']}
jdg_71774
stackexchange
llm_judgeable_groundtruth_similarity
4347327
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been reading up on Reference and value types. I get the idea. But how does this help me while coding? I don't have any good examples to understand those times where knowing this stuff helps. Now provide the response and nothing else.
It means you can understand what your code is going to do. It's kinda hard to write code when you can't predict what the effects of any given statement will be, due to not knowing the type system semantics. For example, suppose you don't know how reference types work, and someone presented you with this code: StringBuilder builder = new StringBuilder();StringBuilder other = builder;builder.Append("Foo");other.Append("Bar");Console.WriteLine(builder); We know that that will print "FooBar" because StringBuilder is a reference type - the second line is only copying a reference , not creating another object. But if you didn't understand how reference types behave, you might have expected it just to print "Foo".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4347327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/93468/']}
jdg_71775
stackexchange
llm_judgeable_groundtruth_similarity
21409439
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 new to game development and very new to c++, but I've started developing a little Arkanoid game. I've had it running previously, but after refactoring (introducing the ArkanoidGame class) it doesnt compile and I cannot figure out why. The error I'm getting is: d:\dropbox\development\gamedev\c++\arkanoid\arkanoid\main.cpp(14): error C2280: 'ArkanoidGame::ArkanoidGame(void)' : attempting to reference a deleted functiond:\dropbox\development\gamedev\c++\arkanoid\arkanoid\arkanoidgame.h(25) : compiler has generated 'ArkanoidGame::ArkanoidGame' here I simply dont understand what this means and have no idea what to do to fix it. I've included the classes in question: Main.cpp: #include "ArkanoidGame.h"int main() { ArkanoidGame game; game.init(800, 600); while (game.isRunning()) { game.checkInput(); game.checkCollisions(); game.draw(); } return 0;} Arkanoid.h: #include "Ball.h"#include "Pad.h"#include <SFML/Graphics.hpp>#include <stdarg.h>#include <memory>class ArkanoidGame{private: bool running;public: void ArkanoidGame::init(int, int); bool ArkanoidGame::isRunning(); void ArkanoidGame::checkCollisions(); void ArkanoidGame::checkInput(); void ArkanoidGame::update(); void ArkanoidGame::draw(); sf::RenderWindow* window; Pad pad; Ball ball;}; ArkanoidGame.cpp: #include "ArkanoidGame.h"void ArkanoidGame::init(int windowWidth, int windowHeight) { window = new sf::RenderWindow(sf::VideoMode(windowWidth, windowHeight), "Arkanoid!"); window->setFramerateLimit(60); ArkanoidGame::running = true; //Init pad pad = Pad((float)(windowWidth / 2), (float)(windowHeight - 50)); //Init ball ball = Ball(0.f, 0.f);}template<class T1, class T2> bool intersect(T1& mA, T2& mB) { return mA.right() >= mB.left() && mA.left() <= mB.right() && mA.bottom() >= mB.top() && mA.top() <= mB.bottom();}void ArkanoidGame::checkCollisions() { if (!intersect(pad, ball)) return; ball.velocity.y = -ball.ballVelocity; if (ball.x() < pad.x()) { ball.velocity.x = -ball.ballVelocity; } else { ball.velocity.x = ball.ballVelocity; }}void ArkanoidGame::update() { //Update positions pad.update(window->getSize().x); ball.update(window->getSize().x, window->getSize().y);}void ArkanoidGame::draw() { window->clear(Color::Black); window->draw(pad.getShape()); window->draw(ball.getShape()); window->display();}void ArkanoidGame::checkInput() { if (Keyboard::isKeyPressed(Keyboard::Key::Escape)) { running = false; }}bool ArkanoidGame::isRunning() { return running;} Now provide the response and nothing else.
Presumably, either Pad or Ball (or both) has no default constructor; therefore one can't be generated for a class that contains them. They must be initialised using one of their declared constructors. The best solution is to remove your weird init function, and replace it with a constructor: ArkanoidGame(int windowWidth, int windowHeight) : running(true), window(new ...), Pad(windowWidth / 2, windowHeight - 50), Ball(0,0){ window->setFramerateLimit(60);}int main() { ArkanoidGame game(800, 600); // ...} If you really want a two-stage initialisation dance for some reason, then you'll need to provide default constructors for both Pad and Ball . I wouldn't recommend that though; there's less scope for errors if an object can't be created in an invalid state.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21409439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253898/']}
jdg_71776
stackexchange
llm_judgeable_groundtruth_similarity
10492037
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 client/server app which I have been developing on a single PC. Now it needs two serial ports, so I borrowed a PC from a friend. When I build my app and try to run or debug it (whether in the Delphi IDE or from Windows File manager), it errors "The application was unable to start correctly (0xc000007b)". Googling doesn't bring up much, but seems to indicate that this is nothing Delphi specific and happens with other apps. It seems to be caused by calling into a 32 bit DLL from a 64 bit app or vice versa. both PCs are Windows 7, 64 bit both have Delphi Xe2 starter edition which can only handle 32 bits The app runs fine on my PC, but not on my friend's Other Delphi apps run just fine on both PCs Can anyone give me a hint as to how to track this down? Now provide the response and nothing else.
Normally we get the 0xC000007B error-code (which means STATUS_INVALID_IMAGE_FORMAT ), if: If a 32-bit app tried to load a 64-bit DLL. Or if a 64-bit app tried to load a 32-bit DLL. Or if a 64-bit app tried to run on a 32-bit Windows. To really know, I would suggest to test whether there is a problem between your application and its dependencies using dependency walker Note that all you need to do is open your App using said tool, and issues appear as red log-entries at buttom of screen. (At least, at time of writting, namely 2022) Also, make sure you run the correct version of Dependency Walker, for example, the x86 version will display incorrect results when openning x64 binaries.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10492037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192910/']}
jdg_71777
stackexchange
llm_judgeable_groundtruth_similarity
5529685
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 one is really weird. I have multiple $.post() in the code, but there is one don't know why sends the json parameters as x-www-form-urlencoded instead and therefore doesn't work. Here's the code: $.post("/Route/SaveTransportProperties", { properties: JSON.stringify(propArray), currTravelBox: JSON.stringify(travelBoxObj), accessToken: getAccessToken()}, function(data) { //DO STUFF }); The XHR looks like this in Firefox: Any ideas why is this happening? I also enforced the type as 'json' but doesn't work either. Now provide the response and nothing else.
If you want to send the data as json then use the $.ajax function You can specify type post and dataType json. $.ajax({ url: "mydomain.com/url", type: "POST", dataType: "xml/html/script/json", // expected format for response contentType: "application/json", // send as JSON data: $.param( $("Element or Expression") ), complete: function() { //called when complete }, success: function() { //called when successful }, error: function() { //called when there is an error },}); Taken from ajax documentation http://api.jquery.com/jQuery.ajax/ contentTypeStringDefault: 'application/x-www-form-urlencoded; charset=UTF-8'
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5529685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188476/']}
jdg_71778
stackexchange
llm_judgeable_groundtruth_similarity
21791071
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 sure this topic had been addressed before, but I can't seem to find an adequate solution to my problem, which I'm sure is not unique. So I get that you can't set a cookie and expect to use without refreshing the page. So I'm wondering what my options are. I have a simple set of links that change the language on the page by setting a cookie to that user's language preference. I need to detect that cookie to assign a variable so that I can then change the page output to the designated language. So, when the button is pressed, it sends a get variable to the URL bar, which then sets the cookie. After I refresh the page, I get what I want. Basically, I need to pass the GET variable and then refresh the page. How can I do this? my php code: // if someone is trying to change the languageif(isset($_GET['lang'])){ // change the cookie value to that language $value = $_GET['lang'];}// elseif they are not trying to change the language, and a cookie is already setelseif(isset($_COOKIE['language_pref'])){ // maintain the value of the language set in the cookie $value = $_COOKIE['language_pref'];}// if get nor cookie is setelse{ // set default language to english $value = 'en_US';}$name = 'language_pref';// cookie expires in 2 years$expireDate = time() + (2 * 365 * 24 * 60 * 60);$path = '/';$domain = 'example.com';$secure = false; //only transmit the cookie if a HTTPS connection is established$httponly = true; //make cookie available only for the HTTP protocol (and not for JavaScript)setcookie( $name, $value, $expireDate, $path, $domain, $secure, $httponly); My HTML: <a href="?lang=zh_CN">ZH</a><a href="?lang=en_US">EN</a> Now provide the response and nothing else.
The hidden file type is just a text field which is hidden. This means that, in order to render the widget, it just uses the simple widget template (see include statement in hidden_widget.html ): <input type="<?php echo isset($type) ? $view->escape($type) : 'text' ?>" <?php echo $view['form']->block($form, 'widget_attributes') ?><?php if (!empty($value) || is_numeric($value)): ?> value="<?php echo $view->escape($value) ?>"<?php endif ?> /> As you can see it just echo's the value you passed to the field (the escape function does not to any important things). There is the problem: You passed a DateTime class as value, not a string. Even though you specified you passed a DateTime class, it's still not changing the value and it just tries to convert the DateTime object into a string.That isn't possible. That's what currently happends. Now, let's move onto how to get it fixed. The data it tries to render ( $value ) is actually called the view data (as you see where the variable is defined ). In the current situation, the view data is equal to the Form::$viewData property (see the ->getViewData() definition ). This property is defined previously by the ->normToView() method (see the $viewData definition ). As you can see in the ->normToView() method , it runs the view transformers if available : foreach ($this->config->getViewTransformers() as $transformer) { $value = $transformer->transform($value);} So in order to convert the DateTime object to a string, we have to use a View transformer. Now, let's take a look at the available data transformers . We are very lucky as there is a DateTimeToStringTransformer : /** * Transforms between a date string and a DateTime object * * @author Bernhard Schussek <[email protected]> * @author Florian Eckerstorfer <[email protected]> */class DateTimeToStringTransformer extends BaseDateTimeTransformer{ That's just what we needed! Now, let's register this data transformer as a view transformer to the hidden field: use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;// ...$builder = $this->createFormBuilder($myClass);$builder->add( $builder->create('myDate', 'hidden') ->addViewTransformer(new DateTimeToStringTransformer())); And after you've done this, the form should be correctly generated. And because, almost everything in the form is symmetric, the transformer also works from string to datetime, meaning that your code only uses the DateTime object!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21791071', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2503750/']}
jdg_71779
stackexchange
llm_judgeable_groundtruth_similarity
41595018
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 having a data insertion problem in tables linked by foreign key. I have read in some places that there is a "with" command that helps in these situations, but I do not quite understand how it is used. I would like to put together four tables that will be used to make a record, however, that all the data were inserted at once, in a single query, and that they were associated with the last table, to facilitate future consultations. Here is the code for creating the tables: CREATE TABLE participante ( id serial NOT NULL, nome character varying(56) NOT NULL, CONSTRAINT participante_pkey PRIMARY KEY (id), ); CREATE TABLE venda ( id serial NOT NULL, inicio date NOT NULL, CONSTRAINT venda_pkey PRIMARY KEY (id) ); CREATE TABLE item ( id serial NOT NULL, nome character varying(256) NOT NULL, CONSTRAINT item_pkey PRIMARY KEY (id) ); CREATE TABLE lances_vendas ( id serial NOT NULL, venda_id integer NOT NULL, item_id integer NOT NULL, participante_id integer NOT NULL, valor numeric NOT NULL, CONSTRAINT lance_vendas_pkey PRIMARY KEY (id), CONSTRAINT lances_vendas_venda_id_fkey FOREIGN KEY (venda_id) REFERENCES venda (id), CONSTRAINT lances_vendas_item_id_fkey FOREIGN KEY (item_id) REFERENCES item (id), CONSTRAINT lances_vendas_participante_id_fkey FOREIGN KEY (participante_id) REFERENCES participante (id) ); Now provide the response and nothing else.
The idea is to write WITH clauses that contain INSERT ... RETRUNING to return the generated keys. Then these β€œviews for a single query” can be used to insert those keys into the referencing tables. WITH par_key AS (INSERT INTO participante (nome) VALUES ('Laurenz') RETURNING id), ven_key AS (INSERT INTO venda (inicio) VALUES (current_date) RETURNING id), item_key AS (INSERT INTO item (nome) VALUES ('thing') RETURNING id)INSERT INTO lances_vendas (venda_id, item_id, participante_id, valor) SELECT ven_key.id, item_key.id, par_key.id, numeric '3.1415' FROM par_key, ven_key, item_key;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41595018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6768042/']}
jdg_71780
stackexchange
llm_judgeable_groundtruth_similarity
141367
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: Bash 4.2 on CentOS 6.5: In my ~/.bash_profile I have a bunch of aliases, including: alias grep='grep -n --color=always' so that I can get color highlighting and print line numbers automatically when running grep . If I run the following, highlighting works as expected: $ grep -Re 'regex_here' *.py However, when I ran this recently: $ find . -name '*.py' | xargs grep -E 'regex_here' the results were not highlighted and line numbers weren't printed, forcing me to go back and explicitly add -n --color=always to the grep command. Does xargs not read aliases in the environment? If not, is there a way to make it do that? Now provide the response and nothing else.
An alias is internal to the shell where it is defined. It is not visible to other processes. The same goes for shell functions. xargs is a separate application, which is not a shell, so doesn't have a concept of aliases or functions. You can make xargs invoke a shell instead of invoking grep directly. However just invoking a shell isn't enough, you have to define the alias in that shell as well. If the alias is defined in your .bashrc , you can source that file; however this may not work your .bashrc performs other tasks that don't make sense in a non-interactive shell. find . -name '*.py' | xargs bash -c '. ~/.bashrc; grep -E regex_here "$@"' _ Beware of the intricacies of nested quoting when typing the regexp. You can simplify your life by passing the regexp as a parameter to the shell. find . -name '*.py' | xargs bash -c '. ~/.bashrc; grep -E "$0" "$@"' regex_here You can perform the alias lookup explicitly. Then xargs will see grep -n --color=always . find . -name '*.py' | xargs "${BASH_ALIASES[grep]}" regex_here In zsh: find . -name '*.py' | xargs $aliases[grep] regex_here By the way, note that find … | xargs … breaks on filenames containing spaces (among others) . You can fix this by changing to null-delimited records: find . -name '*.py' -print0 | xargs -0 "${BASH_ALIASES[grep]}" regex_here or by using -exec : find . -name '*.py' -exec "${BASH_ALIASES[grep]}" regex_here {} + Instead of calling find , you can do everything entirely inside the shell. The glob pattern **/ traverses directories recursively. In bash, you need to run shopt -s globstar to enable this glob pattern first. grep regex_here **/*.py This has a few limitations: If a lot of files match (or if they have long paths), the command may fail because it exceeds the maximum command line length. In bash ≀4.2 (but not in more recent versions, nor in ksh or zsh), **/ recurses into symbolic links to directories. Another approach is to use process substitution, as suggested by MariusMatutiae . grep regex_here <(find . -name '*.py') This is useful when **/ isn't applicable: for complex find expressions, or in bash ≀4.2 when you don't want to recurse under symbolic links. Note that this breaks on file names containing spaces; a workaround is to set IFS and disable globbing , but it's starting to get a bit complex: (IFS=$'\n'; set -f; grep regex_here <(find . -name '*.py') )
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/141367', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/19512/']}
jdg_71781
stackexchange
llm_judgeable_groundtruth_similarity
4392610
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 tomcat based application that needs to submit a form capable of handling utf-8 characters. When submitted via ajax, the data is returned correctly from getParameter() in utf-8. When submitting via form post, the data is returned from getParameter() in iso-8859-1. I used fiddler, and have determined the only difference in the requests, is that charset=utf-8 is appended to the end of the Content-Type header in the ajax call (as expected, since I send the content type explicitly). ContentType from ajax:"application/x-www-form-urlencoded; charset=utf-8" ContentType from form:"application/x-www-form-urlencoded" I have the following settings: ajax post (outputs chars correctly): $.ajax( { type : "POST", url : "blah", async : false, contentType: "application/x-www-form-urlencoded; charset=utf-8", data : data, success : function(data) { } }); form post (outputs chars in iso) <form id="leadform" enctype="application/x-www-form-urlencoded; charset=utf-8" method="post" accept-charset="utf-8" action="{//app/path}"> xml declaration: <?xml version="1.0" encoding="utf-8"?> Doctype: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> meta tag: <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> jvm parameters: -Dfile.encoding=UTF-8 I have also tried using request.setCharacterEncoding("UTF-8"); but it seems as if tomcat simply ignores it. I am not using the RequestDumper valve. From what I've read, POST data encoding is mostly dependent on the page encoding where the form is. As far as I can tell, my page is correctly encoded in utf-8. The sample JSP from this page works correctly. It simply uses setCharacterEncoding("UTF-8"); and echos the data you post. http://wiki.apache.org/tomcat/FAQ/CharacterEncoding So to summarize, the post request does not send the charset as being utf-8, despite the page being in utf-8, the form parameters specifying utf-8, the xml declaration or anything else. I have spent the better part of three days on this and am running out of ideas. Can anyone help me? Now provide the response and nothing else.
form post (outputs chars in iso) <form id="leadform" enctype="application/x-www-form-urlencoded; charset=utf-8" method="post" accept-charset="utf-8" action="{//app/path}"> You don't need to specify the charset there. The browser will use the charset which is specified in HTTP response header. Just <form id="leadform" method="post" action="{//app/path}"> is enough. xml declaration: <?xml version="1.0" encoding="utf-8"?> Irrelevant. It's only relevant for XML parsers. Webbrowsers doesn't parse text/html as XML. This is only relevant for the server side (if you're using a XML based view technology like Facelets or JSPX, on plain JSP this is superfluous). Doctype: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Irrelevant. It's only relevant for HTML parsers. Besides, it doesn't specify any charset. Instead, the one in the HTTP response header will be used. If you aren't using a XML based view technology like Facelets or JSPX, this can be as good <!DOCTYPE html> . meta tag: <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> Irrelevant. It's only relevant when the HTML page is been viewed from local disk or is to be parsed locally. Instead, the one in the HTTP response header will be used. jvm parameters: -Dfile.encoding=UTF-8 Irrelevant. It's only relevant to Sun/Oracle(!) JVM to parse the source files. I have also tried using request.setCharacterEncoding("UTF-8"); but it seems as if tomcat simply ignores it. I am not using the RequestDumper valve. This will only work when the request body is not been parsed yet (i.e. you haven't called getParameter() and so on beforehand). You need to call this as early as possible. A Filter is a perfect place for this. Otherwise it will be ignored. From what I've read, POST data encoding is mostly dependent on the page encoding where the form is. As far as I can tell, my page is correctly encoded in utf-8. It's dependent on the HTTP response header. All you need to do are the following three things: Add the following to top of your JSP: <%@page pageEncoding="UTF-8" %> This will set the response encoding to UTF-8 and set the response header to UTF-8. Create a Filter which does the following in doFilter() method: if (request.getCharacterEncoding() == null) { request.setCharacterEncoding("UTF-8");}chain.doFilter(request, response); This will make that the POST request body will be processed as UTF-8. Change the <Connector> entry in Tomcat/conf/server.xml as follows: <Connector (...) URIEncoding="UTF-8" /> This will make that the GET query strings will be processed as UTF-8. See also: Unicode - How to get characters right? - contains practical background information and detailed solutions for Java EE web developers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4392610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/452773/']}
jdg_71782
stackexchange
llm_judgeable_groundtruth_similarity
21494489
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 does np.random.seed do? np.random.seed(0) Now provide the response and nothing else.
np.random.seed(0) makes the random numbers predictable >>> numpy.random.seed(0) ; numpy.random.rand(4)array([ 0.55, 0.72, 0.6 , 0.54])>>> numpy.random.seed(0) ; numpy.random.rand(4)array([ 0.55, 0.72, 0.6 , 0.54]) With the seed reset (every time), the same set of numbers will appear every time. If the random seed is not reset, different numbers appear with every invocation: >>> numpy.random.rand(4)array([ 0.42, 0.65, 0.44, 0.89])>>> numpy.random.rand(4)array([ 0.96, 0.38, 0.79, 0.53]) (pseudo-)random numbers work by starting with a number (the seed), multiplying it by a large number, adding an offset, then taking modulo of that sum. The resulting number is then used as the seed to generate the next "random" number. When you set the seed (every time), it does the same thing every time, giving you the same numbers. If you want seemingly random numbers, do not set the seed. If you have code that uses random numbers that you want to debug, however, it can be very helpful to set the seed before each run so that the code does the same thing every time you run it. To get the most random numbers for each run, call numpy.random.seed() . This will cause numpy to set the seed to a random number obtained from /dev/urandom or its Windows analog or, if neither of those is available, it will use the clock. For more information on using seeds to generate pseudo-random numbers, see wikipedia .
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/21494489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2564905/']}
jdg_71783
stackexchange
llm_judgeable_groundtruth_similarity
659276
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 know that, assuming Axiom of Choice, every set is well-orderable. I know also that the assertion that $\mathbb{R}$ is NOT well-orderable is consistent with ZF. How can I find other sets such that, in ZF, I can't prove their well-orderability? For example, which elements of Von Neumann Hierarchy $V_0 = \emptyset \\ V_{\alpha+1}=P(V_{\alpha}) \\ V_\lambda = \cup_{\alpha<\lambda} V_\alpha $ (except $V_n$ for $n$ finite ordinal, and $V_\omega$ ) can be well-ordered? Now provide the response and nothing else.
It is consistent that $V_{\omega + 1}$ that is not well-orderable. $\omega \subset V_\omega$. So $\mathscr{P}(\omega) \subseteq P(V_\omega) = V_{\omega + 1}$. So if $V_{\omega + 1}$ could be well ordered, then $\mathscr{P}(\omega) = 2^\omega$ could be well-ordered. As you mentioned $\mathbb{R}$ which is isomorphic can be not well orderable.. As $V_\alpha \subseteq V_\beta$ for $\alpha < \beta$. Thus it is consistent that all $V_\alpha$ for $\alpha \geq \omega + 1$ are not well-orderable.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/659276', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/125366/']}
jdg_71784
stackexchange
llm_judgeable_groundtruth_similarity
339438
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Android developers probably are familiar with Ceja's Clean Architecture , where use cases are classes that implement the Command Pattern . Shvets defines the pattern intents as follows: Encapsulate a request as an object, thereby letting you parametrize clients with different requests, queue or log requests, and support undoable operations. Promote "invocation of a method on an object" to full object status An object-oriented callback I use that approach in order to improve code readability and testability. But, after reading Shvets's Anti-Patterns course , I got confused with his Functional Decomposition Anti-Pattern definition: Classes with "function" names such as Calculate_Interest or Display_Table may indicate the existence of this AntiPattern. All class attributes are private and used only inside the class. Classes with a single action such as a function. An incredibly degenerate architecture that completely misses the point of object-oriented architecture. Absolutely no leveraging of object-oriented principles such as inheritance and polymorphism. This can be extremely expensive to maintain (if it ever worked in the first place; but never underestimate the ingenuity of an old programmer who's slowly losing the race to technology). No way to clearly document (or even explain) how the system works. Class models make absolutely no sense. No hope of ever obtaining software reuse. Frustration and hopelessness on the part of testers. How may I am figure out if I am using Functional Decomposition Anti-Pattern instead of Command Pattern ? Now provide the response and nothing else.
I think the major problem here is Shvets's anti-pattern description is flawed , that is why you have problems to distinguish it from the Command pattern: The name is flawed because it uses an older, existing term "Functional Decomposition" together with the attribute "anti-pattern". This term was AFAIK not associated with the notion of a "pattern" or "anti-pattern" before, but by picking it for his topic Shvets gave it a new, confusing meaning. The original meaning in programming is " taking a complex process and breaking it down into simpler parts ", and that is how I would use the term still today. (Note the Wikipedia definition is about the term more generally in mathematics, but I think this is probably not really helpful in our programming context.) See also this former SE post , where other people already had problems with the anti-pattern name, the top answer suggests the name "procedural decomposition" instead, but that name might lead to similar problems. The first three symptoms you cited from the pattern description are indeed a good fit for command objects, and sometimes also for other, well desgined classes. That is exactly the reason why they are IMHO not a good indicator for this kind of "degenerated architecture" Shvets describes. See, for example, this former SE post about " classes with a single action as function " What Shvets probably had in mind was a situation where people try to shoehorn procedural code into classes. This happens most often on a completely different scale (he mentioned "Application Scale") than the scale of a typical command object, which will often be just a small class. It results in code which is not SOLID, containing too large classes, missing proper abstractions, and classes where in most cases everything could be static, since the instantiated "object" is not an abstraction for anything else but a "module" or "sub-program", existing once and with the same lifetime as the whole application process. Command objects, however, are more an object-oriented workaround for situations where the programming language does not provide an inbuilt mechanism for higher order functions or closures. Rember the term "Command Pattern" has its roots in the GOF's "Design Patterns" book from 1995, a time when C++ and Java were dominant, and both of these languages did not provide such mechanisms at that time. So whenever you need to pass a function around in your program as an abstraction of its own, best choice was probably to use the Command Pattern. Today, both of these languages (as well as other modern languages) provide additional mechanisms for encapsulating functions in a data type, so often you do not even need to use the Command Pattern (in its original OO form) any more. It still can be useful if your "commands" need a more complex interface than just for the "action" or "function" which they encapsulate.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/339438', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/212528/']}
jdg_71785
stackexchange
llm_judgeable_groundtruth_similarity
27384748
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 this PS1 PS1='\n${_:+$? }$ ' Here is the result of a few commands $ [ 2 = 2 ]0 $ [ 2 = 3 ]1 $1 $ The first line shows no status as expected, and the next two lines show thecorrect exit code. However on line 3 only Enter was pressed, so I would like thestatus to go away, like line 1. How can I do this? Now provide the response and nothing else.
Here's a funny, very simple possibility: it uses the \# escape sequence of PS1 together with parameter expansions (and the way Bash expands its prompt). The escape sequence \# expands to the command number of the command to be executed. This is incremented each time a command has actually been executed. Try it: $ PS1='\# $ '2 $ echo hellohello3 $ # this is a comment3 $3 $ echo hellohello4 $ Now, each time a prompt is to be displayed, Bash first expands the escape sequences found in PS1 , then (provided the shell option promptvars is set, which is the default), this string is expanded via parameter expansion, command substitution, arithmetic expansion, and quote removal. The trick is then to have an array that will have the k -th field set (to the empty string) whenever the ( k -1)-th command is executed. Then, using appropriate parameter expansions, we'll be able to detect when these fields are set and to display the return code of the previous command if the field isn't set. If you want to call this array __cmdnbary , just do: PS1='\n${__cmdnbary[\#]-$? }${__cmdnbary[\#]=}\$ ' Look: $ PS1='\n${__cmdnbary[\#]-$? }${__cmdnbary[\#]=}\$ '0 $ [ 2 = 3 ]1 $ $ # it seems that it works$ echo "it works"it works0 $ To qualify for the shortest answer challenge: PS1='\n${a[\#]-$? }${a[\#]=}$ ' that's 31 characters. Don't use this, of course, as a is a too trivial name; also, \$ might be better than $ . Seems you don't like that the initial prompt is 0 $ ; you can very easily modify this by initializing the array __cmdnbary appropriately: you'll put this somewhere in your configuration file: __cmdnbary=( '' '' ) # Initialize the field 1!PS1='\n${__cmdnbary[\#]-$? }${__cmdnbary[\#]=}\$ '
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27384748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1002260/']}
jdg_71786
stackexchange
llm_judgeable_groundtruth_similarity
14268796
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a HTML page with a registration button that should just silently send an email without opening the local mail client. Here is my HTML: <form method="post" action=""> <input type="text" id="email_address" name="name" placeholder="Enter your email address..." required> <button onclick="sendMail(); return false">Send Email</button></form> ... and here is my JavaScript code: <script type="text/javascript"> function sendMail() { var link = 'mailto:[email protected]?subject=Message from ' +document.getElementById('email_address').value +'&body='+document.getElementById('email_address').value; window.location.href = link;}</script> The code above works... but it opens the local email client. If I remove the return statement in the onclick attribute like this: <form method="post" action=""> <input type="text" id="email_address" name="name" placeholder="Enter your email address..." required> <button onclick="sendMail()">Send Email</button></form> ... then the email is not sent at all. Am I missing something? Any help would be reeeally appreciated :-) Now provide the response and nothing else.
You need a server-side support to achieve this. Basically your form should be posted (AJAX is fine as well) to the server and that server should connect via SMTP to some mail provider and send that e-mail. Even if it was possible to send e-mails directly using JavaScript (that is from users computer), the user would still have to connect to some SMTP server (like gmail.com), provide SMTP credentials, etc. This is normally handled on the server-side (in your application), which knows these credentials.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14268796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278659/']}
jdg_71787
stackexchange
llm_judgeable_groundtruth_similarity
3587663
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: SQL Server Reporting Services (SSRS) 2008 R2 I've set up a shared dataset that takes a few minutes to execute. It is shared between three reports, and is the core data for these reports. (Some other datasets exist in the reports for parameter population.) I've enabled caching on the dataset, and would like to add the dataset execution time to the reports' footers. I suppose I could add a column to the dataset with current time in SQL, but is there any SSRS function that will give this to me? Now provide the response and nothing else.
Late to the game... here's an implementation of the MergeSort algorithm in VBA for both Arrays and Collections. I tested the performance of this implementation against the BubbleSort implementation in the accepted answer using randomly generated strings. The chart below summarizes the results, i.e. that you should not use BubbleSort to sort a VBA collection . You can download the source code from my GitHub Repository or just copy/paste the source code below into the appropriate modules. For a collection col , just call Collections.sort col . Collections module 'Sorts the given collection using the Arrays.MergeSort algorithm.' O(n log(n)) time' O(n) spacePublic Sub sort(col As collection, Optional ByRef c As IVariantComparator) Dim a() As Variant Dim b() As Variant a = Collections.ToArray(col) Arrays.sort a(), c Set col = Collections.FromArray(a())End Sub'Returns an array which exactly matches this collection.' Note: This function is not safe for concurrent modification.Public Function ToArray(col As collection) As Variant Dim a() As Variant ReDim a(0 To col.count) Dim i As Long For i = 0 To col.count - 1 a(i) = col(i + 1) Next i ToArray = a()End Function'Returns a Collection which exactly matches the given Array' Note: This function is not safe for concurrent modification.Public Function FromArray(a() As Variant) As collection Dim col As collection Set col = New collection Dim element As Variant For Each element In a col.Add element Next element Set FromArray = colEnd Function Arrays module Option Compare TextOption ExplicitOption Base 0Private Const INSERTIONSORT_THRESHOLD As Long = 7'Sorts the array using the MergeSort algorithm (follows the Java legacyMergesort algorithm'O(n*log(n)) time; O(n) spacePublic Sub sort(ByRef a() As Variant, Optional ByRef c As IVariantComparator) If c Is Nothing Then MergeSort copyOf(a), a, 0, length(a), 0, Factory.newNumericComparator Else MergeSort copyOf(a), a, 0, length(a), 0, c End IfEnd SubPrivate Sub MergeSort(ByRef src() As Variant, ByRef dest() As Variant, low As Long, high As Long, off As Long, ByRef c As IVariantComparator) Dim length As Long Dim destLow As Long Dim destHigh As Long Dim mid As Long Dim i As Long Dim p As Long Dim q As Long length = high - low ' insertion sort on small arrays If length < INSERTIONSORT_THRESHOLD Then i = low Dim j As Long Do While i < high j = i Do While True If (j <= low) Then Exit Do End If If (c.compare(dest(j - 1), dest(j)) <= 0) Then Exit Do End If swap dest, j, j - 1 j = j - 1 'decrement j Loop i = i + 1 'increment i Loop Exit Sub End If 'recursively sort halves of dest into src destLow = low destHigh = high low = low + off high = high + off mid = (low + high) / 2 MergeSort dest, src, low, mid, -off, c MergeSort dest, src, mid, high, -off, c 'if list is already sorted, we're done If c.compare(src(mid - 1), src(mid)) <= 0 Then copy src, low, dest, destLow, length - 1 Exit Sub End If 'merge sorted halves into dest i = destLow p = low q = mid Do While i < destHigh If (q >= high) Then dest(i) = src(p) p = p + 1 Else 'Otherwise, check if p<mid AND src(p) preceeds scr(q) 'See description of following idom at: https://stackoverflow.com/a/3245183/3795219 Select Case True Case p >= mid, c.compare(src(p), src(q)) > 0 dest(i) = src(q) q = q + 1 Case Else dest(i) = src(p) p = p + 1 End Select End If i = i + 1 LoopEnd Sub IVariantComparator class Option Explicit'The IVariantComparator provides a method, compare, that imposes a total ordering over a collection _of variants. A class that implements IVariantComparator, called a Comparator, can be passed to the _Arrays.sort and Collections.sort methods to precisely control the sort order of the elements.'Compares two variants for their sort order. Returns -1 if v1 should be sorted ahead of v2; +1 if _v2 should be sorted ahead of v1; and 0 if the two objects are of equal precedence. This function _should exhibit several necessary behaviors: _ 1.) compare(x,y)=-(compare(y,x) for all x,y _ 2.) compare(x,y)>= 0 for all x,y _ 3.) compare(x,y)>=0 and compare(y,z)>=0 implies compare(x,z)>0 for all x,y,zPublic Function compare(ByRef v1 As Variant, ByRef v2 As Variant) As LongEnd Function If no IVariantComparator is provided to the sort methods, then the natural ordering is assumed. However, if you need to define a different sort order (e.g. reverse) or if you want to sort custom objects, you can implement the IVariantComparator interface. For example, to sort in reverse order, just create a class called CReverseComparator with the following code: CReverseComparator class Option ExplicitImplements IVariantComparatorPublic Function IVariantComparator_compare(v1 As Variant, v2 As Variant) As Long IVariantComparator_compare = v2-v1End Function Then call the sort function as follows: Collections.sort col, New CReverseComparator Bonus Material: For a visual comparison of the performance of different sorting algorithms check out https://www.toptal.com/developers/sorting-algorithms/
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3587663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/400375/']}
jdg_71788
stackexchange
llm_judgeable_groundtruth_similarity
16809
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: Given an option , which one should I choose , a HMAC for storing a password securely or a bcrypt or scrypt library? Now provide the response and nothing else.
In order to give you a proper idea of the problems and subtleties of computing password hashes, as well as why HMAC isn't suitable for this problem, I'll provide a much broader answer than is really necessary to directly answer the question. A HMAC hash algorithm is, essentially, just a keyed version of a normal hash algorithm. It is usually used to verify integrity and authenticity. The usual notation of this is H(m,k) = h , where H is the HMAC hash algorithm, m is the message, k is the key, and h is the resulting hash. The idea is that two parties that share a secret k can verify that the other person is the author of m . Furthermore, an attacker cannot forge a message hash without knowing k . This is done as follows: Alice and Bob both know a shared secret key k . Alice writes a message m , and computes the HMAC hash of it using k , i.e. H(m,k) = h . Alice sends the message m and hash h to Bob. Bob computes H(m,k) and compares it to the hash h that Alice sent. If the hashes match, he knows that Alice sent the message, and that it was not altered after she hashed it. Now that you understand what HMAC is, let's move onto what you really want to do - store passwords in a database. Many years ago, it was standard practice to store passwords in plaintext in databases. This was a bad idea because, when the database was compromised, the attacker got all the passwords. To combat this, we started hashing passwords in the database using one-way cryptographic hash algorithms. MD5 became popular, but weaknesses (collisions, partial preimage, etc) discovered in it mean it's no longer recommended. A lot of people moved onto SHA1, which is more secure. The problem with this approach is that it's possible to construct a huge table of hashes and their corresponding plaintexts. These are called rainbow tables . They work on the concept that it is more efficient to compute a huge list of hashes for all possible passwords (within a certain set) and then store it, so it can be quickly queried later on. So, instead of brute-forcing individual hashes, it became possible to just query the database for a hash and have its plaintext returned immediately. In order to fix this, security nerds invented salts. Salts are large unique random values appended to passwords before they are hashed. This salt is stored with the hash, so that it can be computed again later. So, we compute H(m+s) = h , then store h and s in the database. This provides significant protection against rainbow tables because it essentially requires a separate rainbow table to be generated for each salt. So, the bad guys switched back to dictionary attacks and brute-force cracking. With the advent of GPU computing, it became possible to compute billions of hashes per second on a moderately powerful graphics card. In fact, people have built computers that can compute nearly 50 billion MD5 hashes per second - pretty impressive / scary. The reason GPUs are capable of this is that they're designed to do huge numbers of parallel scalar operations. Scalar operations are math and logic operations that do not involve branches - i.e. they don't need to do much/any "if x then do y". Cryptographic hash algorithms tend to fit into this model. In order to make this difficult, we have to make the hash operation slow enough to make brute forcing infeasible. Normal hash algorithms (e.g. SHA1) are designed to be fast, which makes them unsuitable for this purpose. HMAC adds very little overhead and no extra security margin, so it too isn't much use here. Creating a slow cryptographic hash algorithm is easier said than done - it's very hard to come up with one that is slow, irreducible (i.e. cannot be optimised beyond its current state) and secure. There are three popular hash functions that can do this: PBKDF2 , bcrypt , and scrypt . These are known as adaptive key derivation functions, because they accept a work factor value along with the plaintext and salt. The work factor alters the amount of time it takes to compute the hash, and is designed to safeguard against future hardware improvements. So, for an adaptive key derivation algorithm H , we compute H(m,s,w) = h , where m is the message (password), s is the salt, and w is the work factor. The resulting h usually contains s and w , so that a verification function can later compute the same hash using the same parameters. The work factor generally controls the number of iterations performed of an internal cryptographic primitive. The goal is to make the computation take long enough to make cracking infeasible, but not to exceed the resources that we have. In order to provide more security against dedicated hardware-based cracking, scrypt ensures that the hash computation is both CPU-hard and memory-hard, i.e. it requires significant CPU and memory resources in order to produce the hash value. This is important, because FPGAs usually have access to very little immediate memory. Now, the obvious question arises: if I set up my site to use bcrypt, won't that mean my server has to compute CPU-intensive hashes all the time? Well, if you run them on your server, then yes, that's something to take into consideration. A better solution is to have the client compute the hash, then send it to the server over SSL. The server can then compare it to the value in the database. This ensures that the password hash cannot be easily cracked if it is stolen (e.g. through a database compromise), and that your server isn't overwhelmed by the overhead of password hash computation. For websites, you can use jsBcrypt . Update: This method has been pointed out as flawed by a commenter below. Don't use it. Hopefully this gives you a good overview of the situation, and why HMAC isn't suitable for this kind of use.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/16809', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/10894/']}
jdg_71789
stackexchange
llm_judgeable_groundtruth_similarity
16971757
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 picturelink that fades opacity on hover. What I need is for text to be displayed over it. Here is an example of what I want: http://kspla.tumblr.com/ My code below fades the opacity to 40% but I have no idea how to get text to be displayed over it. <script type="text/javascript">$(document).ready(function() { $('#wb_Image2, #wb_Image3 a img').animate({ opacity:1 }); $('#wb_Image2, #wb_Image3 a img').hover(function() { $(this).stop().animate({opacity:.4},200); }, function() { $(this).stop().animate({opacity:1},500) });}); Thanks in advance. Now provide the response and nothing else.
It's good to remember that if you're handling how things look, chances are it should be done in CSS (which will make your life easier in the long run). I've mocked up an example here: http://jsfiddle.net/HAcE2/ You basically need to create a box that appears when you hover. By using position:absolute you can get the box to appear over the top and using CSS we can get it to appear when we hover over.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16971757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1905243/']}
jdg_71790
stackexchange
llm_judgeable_groundtruth_similarity
17892702
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 hide the URL of my audio streams for my HTML5 player and was really struggling to think of a way to do so and then I realised, soundcloud must hide the URL's of their streams. So i went onto soundcloud, opened up the console and played a track but I couldn't see any obvious way that the URL is hidden. After this I took a look at the DOM tree to see if there was any kind of audio information in there but I found nothing! There's not even an ID for the player/audio so i'm very confused as to how soundcloud have done it. Now I have done as best as I can so far with hiding the audio URL. I have put an ID in the DOM for the track, got that ID when the play button is clicked and retrieved the URL for that ID from the database. The obvious problem with that is that anyone willing enough can just go to the console and get the URL from the network events. I am not trying to break past soundcloud's security to download tracks I shouldn't be. I'm just curious as to how they've hidden the URL. Now i'm also curious as to how each track is distinguished as there's nothing in the DOM distinguishing them (not that I found on my brief look anyway). So, in short, does anyone have any ideas on how soundcloud has achieved this or how this could be achieved? Now provide the response and nothing else.
Soundcloud is pretty much a pure JS site. As you said, there is no ID of the song loaded with the HTML. The way songs are recognized is by the page URL. The is done via. this url (example): https://api.sndcdn.com/resolve?url=https%3A//soundcloud.com/hoodinternet/joywave-tongues-hood-internet-remix&_status_code_map%5B302%5D=200&_status_format=json&client_id=YOUR_CLIENT_ID This returns something like this: {"status":"302 - Found","location":"https://api.soundcloud.com/tracks/100270342?client_id=YOUR_CLIENT_ID"} Next up it loads the location URL, from the JSON above. This returns a bunch of information about the track, including: stream_url: "https://api.soundcloud.com/tracks/100270342/stream" Then it loads this URL: https://api.sndcdn.com/i1/tracks/100270342/streams?client_id=YOUR_CLIENT_IT Which returns a response like this: {"http_mp3_128_url":"https://ec-media.soundcloud.com/2gNVBYiZ06bU.128.mp3?ff61182e3c2ecefa438cd021sdf02d0e385713f0c1faf3b0339595664fe070de810d30a8e3a1186eda958909e9ed97799adfeceabc135efac83aee4271217a108450591db3b88\u0026AWSAccessKeyId=AKIAsdfJ4IAZE5EOIdsf7PA7VQ\u0026Expires=1374883403\u0026Signature=%2B1%2B7dfdfLN4NWP3C3bNF3gizSEVIU%3D"} So that's how they hide their stream URL's. The only non obvious part is that they find the song ID, by hitting an API with the URL as a parameter. Same can be done with download URL's on tracks that support it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17892702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1420724/']}
jdg_71791
stackexchange
llm_judgeable_groundtruth_similarity
2112454
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 in a little bit of a bind. I'm working with a legacy system that contains a bunch of delimited strings which I need to parse. Unfortunately, the strings need to be ordered based on the first part of the string. The array looks something like array[0] = "10|JohnSmith|82";array[1] = "1|MaryJane|62";array[2] = "3|TomJones|77"; So I'd like the array to order to look like array[0] = "1|MaryJane|62";array[1] = "3|TomJones|77";array[2] = "10|JohnSmith|82"; I thought about doing a 2 dimensional array to grab the first part and leave the string in the second part, but can I mix types in a two dimensional array like that? I'm not sure how to handle this situation, can anyone help? Thanks! Now provide the response and nothing else.
Call Array.Sort , but passing in a custom implementation of IComparer<string> : // Give it a proper name really :)public class IndexComparer : IComparer<string>{ public int Compare(string first, string second) { // I'll leave you to decide what to do if the format is wrong int firstIndex = GetIndex(first); int secondIndex = GetIndex(second); return firstIndex.CompareTo(secondIndex); } private static int GetIndex(string text) { int pipeIndex = text.IndexOf('|'); return int.Parse(text.Substring(0, pipeIndex)); }} Alternatively, convert from a string array into an array of custom types by splitting the string up appropriately. This will make life easier if you're going to do further work on the array, but if you only need to sort the values, then you might as well use the code above. You did say that you need to parse the strings - so is there any particular reason why you'd want to parse them before sorting them?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2112454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/250912/']}
jdg_71792
stackexchange
llm_judgeable_groundtruth_similarity
66711660
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Deployed servlet based web application at context path [/VirtualStore], but context failed to start with below log. 19-Mar-2021 11:46:35.075 INFO [main] org.apache.catalina.startup.HostConfig.deployDescriptor Deployment of deployment descriptor [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\conf\Catalina\localhost\VS.xml] has finished in [448] ms19-Mar-2021 11:46:35.079 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\docs]19-Mar-2021 11:46:35.291 WARNING [main] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [143] milliseconds.19-Mar-2021 11:46:35.306 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\docs] has finished in [228] ms19-Mar-2021 11:46:35.307 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\examples]19-Mar-2021 11:46:35.613 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\examples] has finished in [307] ms19-Mar-2021 11:46:35.613 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\host-manager]19-Mar-2021 11:46:35.646 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\host-manager] has finished in [32] ms19-Mar-2021 11:46:35.646 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\manager]19-Mar-2021 11:46:35.676 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\manager] has finished in [29] ms19-Mar-2021 11:46:35.676 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\ROOT]19-Mar-2021 11:46:35.703 INFO [main] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\webapps\ROOT] has finished in [27] ms19-Mar-2021 11:46:35.708 INFO [main] org.apache.coyote.AbstractProtocol.start Starting ProtocolHandler ["http-nio-8085"]19-Mar-2021 11:46:35.726 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [1894] milliseconds19-Mar-2021 11:46:36.546 INFO [http-nio-8085-exec-9] org.apache.catalina.startup.HostConfig.undeploy Undeploying context [/VirtualStore]19-Mar-2021 11:46:36.562 INFO [http-nio-8085-exec-4] org.apache.catalina.startup.HostConfig.deployDescriptor Deploying deployment descriptor [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\conf\Catalina\localhost\VirtualStore.xml]19-Mar-2021 11:46:36.563 WARNING [http-nio-8085-exec-4] org.apache.catalina.startup.HostConfig.deployDescriptor The path attribute with value [/VirtualStore] in deployment descriptor [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\conf\Catalina\localhost\VirtualStore.xml] has been ignored19-Mar-2021 11:46:36.934 SEVERE [http-nio-8085-exec-4] org.apache.catalina.startup.HostConfig.deployDescriptor Error deploying deployment descriptor [C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\apache-tomcat-10.0.4\conf\Catalina\localhost\VirtualStore.xml] java.lang.IllegalStateException: Error starting child at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:720) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:690) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:743) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:692) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:540) at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1777) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:288) at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819) at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801) at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1570) at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:1022) at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:357) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:663) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:770) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:126) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:668) at org.apache.catalina.valves.RequestFilterValve.process(RequestFilterValve.java:378) at org.apache.catalina.valves.RemoteAddrValve.invoke(RemoteAddrValve.java:56) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:353) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:870) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1696) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/VirtualStore]] at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:717) ... 44 more Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletRequestListener at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:756) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2470) at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:866) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1370) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1224) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:540) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:521) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:151) at org.apache.catalina.core.ApplicationContext.addListener(ApplicationContext.java:1086) at org.apache.catalina.core.ApplicationContextFacade.addListener(ApplicationContextFacade.java:664) at org.apache.jasper.servlet.JasperInitializer.onStartup(JasperInitializer.java:92) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5115) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ... 45 more Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletRequestListener at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1401) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1224) ... 60 more How is this caused and how can I solve it? Now provide the response and nothing else.
C:\Users\Ing.Girbson BIJOU\Documents\NetBeansProjects\apache-tomcat-10.0.4-windows-x64\ apache-tomcat-10.0.4 \conf\Catalina\localhost\VirtualStore.xml You're thus using Tomcat 10.x which is based off Servlet API version 5.0 which in turn is part of Jakarta EE version 9. java.lang.NoClassDefFoundError: javax/servlet/ServletRequestListener This is unexpected. The javax.* package has been renamed to jakarta.* package since Jakarta EE version 9. This thus means that the deployed web application is actually not compatible with Jakarta EE version 9. The deployed web application is most likely developed for an older JEE version where the javax.* package is still used. So, summarized, the targeted JEE versions don't match up and it's causing trouble for you. You have 2 options: Downgrade Tomcat to version 9.x. This is the latest available version which still uses the javax.* package. Or, upgrade the deployed web application to target Jakarta EE 9 instead. I.e. adjust the project's dependencies (e.g. pom.xml ) to reference JEE 9+ based versions instead, and perform a project-wide Find & Replace of javax.* to jakarta.* (of course except for javax.naming.* and javax.xml.* and probably a few others, but the Java compiler will quickly point out them for you). See also: Apache Tomcat - Versions Tomcat 9 casting servlets to javax.servlet.Servlet instead of jakarta.servlet.http.HttpServlet (this answer contains complete examples of proper pom.xml declarations for Tomcat 10+, Tomcat 9-, JEE 9+ and JEE 8-).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/66711660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11079729/']}
jdg_71793
stackexchange
llm_judgeable_groundtruth_similarity
15631890
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As part our rebase-heavy workflow, I am hoping to use a merge on the master branch. In particular I want to merge only when the topic branch has been rebased onto the most recent master commit thereby making any merge a fast-forward one. I can achieve that by using: git merge --ff-only Furthermore, I would like to record the integration of the topic branch with an empty commit which is why I would like to use --no-ff which forces that behaviour: git merge --no-ff What I really want, though, is a combination of both: merge only when it's trivial but let me record it anyway. Git thinks that fatal: You cannot combine --no-ff with --ff-only. which appears self-evident to some. git merge --edit --no-ff topicbranch doesn't achieve the behaviour I want either. So how can I merge with the --no-ff option iff the topic branch in question is rebased to the latest master commit? UPDATE: Seems like Charles Bailey's answer will do the trick. If you desire to have this rolled into a git alias you could issue this here: git config --global alias.integrate '!test "$(git merge-base HEAD "$1")" = "$(git rev-parse HEAD)" && git merge --no-ff --edit $1 || echo >&2 "Not up-to-date; refusing to merge, rebase first!"' A bit of a mouthful but works. Note the force of a commit message edit with option --edit . Now provide the response and nothing else.
You don't want --ff-only because you do want to make a merge commit which --ff-only would inhibit. The check that you want can be made as a separate check before running the merge command. You could package this into a simple shell function. E.g. merge_if_ahead () { if test "$(git merge-base HEAD "$1")" = "$(git rev-parse HEAD)"; then git merge --no-ff "$1" else echo >&2 "Not up to date; refusing to merge" return 1 fi}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15631890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/607562/']}
jdg_71794
stackexchange
llm_judgeable_groundtruth_similarity
1259693
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm a bit confused about the way Java treats == and equals() when it comes to int , Integer and other types of numbers. For example: Integer X = 9000;int x = 9000;Short Y = 9000;short y = 9000;List<Boolean> results = new ArrayList<Boolean>();// results.add(X == Y); DOES NOT COMPILE 1)results.add(Y == 9000); // 2)results.add(X == y); // 3)results.add(X.equals(x)); // 4)results.add(X.equals(Y)); // 5)results.add(X.equals(y)); // 6)System.out.println(results); outputs (maybe you should make your guess first): [true, true, true, false, false] That X == Y does not compile is to be expected, being different objects. I'm a little surprised that Y == 9 is true , given that 9 is by default an int , and given that 1) didn't even compile. Note that you can't put an int into a method expecting a Short , yet here they are equal. This is surprising for the same reason as two, but it seems worse. Not surprising, as x is autoboxed to and Integer . Not surprising, as objects in different classes should not be equal() . What?? X == y is true but X.equals(y) is false ? Shouldn't == always be stricter than equals() ? I'd appreciate it if anyone can help me make sense of this. For what reason do == and equals() behave this way? Edit: I have changed 9 to 9000 to show that this behavior is not related to the any unusual ways that the integers from -128 to 127 behave. 2 nd Edit: OK, if you think you understand this stuff, you should consider the following, just to make sure: Integer X = 9000;Integer Z = 9000;short y = 9000;List<Boolean> results = new ArrayList<Boolean>();results.add(X == Z); // 1)results.add(X == y); // 2)results.add(X.equals(Z)); // 3)results.add(X.equals(y)); // 4)System.out.println(results); outputs: [false, true, true, false] The reason, as best as I understand it: Different instance, so different. X unboxed, then same value, so equal. Same value, so equal. y cannot be boxed to an Integer so cannot be equal. Now provide the response and nothing else.
(small) Integer instances are cached, so the invariant x == y is holded for small instances (actually -127 +128, depends on JVM): Integer a = 10;Integer b = 10;assert(a == b); // ok, same instance reuseda = 1024;b = 1024;assert(a == b); // fail, not the same instance....assert(a.equals(b)); // but same _value_ EDIT 4) and 5) yield false because equals check types: X is an Integer whereas Y is a Short. This is the java.lang.Integer#equals method: public boolean equals(Object obj) { if (obj instanceof Integer) { return value == ((Integer)obj).intValue(); } return false;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1259693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82474/']}
jdg_71795
stackexchange
llm_judgeable_groundtruth_similarity
23517699
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 Java in Play framework and I have some tests (functional tests) that are passed when I run them through my IDE (IntelliJ) but failed when I run the tests through console. My problems is that the stack traces that are shown in the test logs are only 2 lines and I need the complete stack trace to see what is going on in there, I have tried any combination of settings mentioned here: spec2 settings both through putting them in build.sbt or providing them in the command line. It seems that there is no effect! Here is my build.sbt : version := "1.0-SNAPSHOT"libraryDependencies ++= Seq( javaJdbc, javaEbean, cache, filters) logBuffered in Test := falsetestOptions += Tests.Argument(TestFrameworks.JUnit, "-v")testOptions += Tests.Argument("fullStackTrace","true")traceLevel := 50 Can someone help me please? I am using Typesafe activator (play 2.2.2). Thanks Now provide the response and nothing else.
In Play 2.3.2 this can be acheieved using the -a option in build.sbt : testOptions += Tests.Argument(TestFrameworks.JUnit, "-a") I use: testOptions += Tests.Argument(TestFrameworks.JUnit, "-v", "-q", "-a") as this provides test started/finished messages ( -v ) and suppresses logging for passed tests ( -q ). All of the available options can be found in the SBT JUnit Interface : -v Log "test run started" / "test started" / "test run finished" events on log level "info" instead of "debug". -q Suppress stdout for successful tests. Stderr is printed to the console normally. Stdout is written to a buffer and discarded when a test succeeds. If it fails, the buffer is dumped to the console. Since stdio redirection in Java is a bad kludge (System.setOut() changes the static final field System.out through native code) this may not work for all scenarios. Scala has its own console with a sane redirection feature. If Scala is detected on the class path, junit-interface tries to reroute scala.Console's stdout, too. -n Do not use ANSI colors in the output even if sbt reports that they are supported. -s Try to decode Scala names in stack traces and test names. Fall back silently to non-decoded names if no matching Scala library is on the class path. -a Show stack traces and exception class name for AssertionErrors (thrown by all assert* methods in JUnit). Without this option, failed assertions do not print a stack trace or the "java.lang.AssertionError: " prefix. -c Do not print the exception class name prefix for any messages. With this option, only the result of getMessage() plus a stack trace is shown. +v Turn off -v. Takes precedence over -v. +q Turn off -q. Takes precedence over -q. +n Turn off -n. Takes precedence over -n. +s Turn off -s. Takes precedence over -s. +a Turn off -a. Takes precedence over -a. +c Turn off -c. Takes precedence over -c. --ignore-runners=<COMMA-SEPARATED-STRINGS> Ignore tests with a @RunWith annotation if the Runner class name is contained in this list. The default value is org.junit.runners.Suite. --tests=<REGEXPS> Run only the tests whose names match one of the specified regular expressions (in a comma-separated list). Non-matched tests are ignored. Only individual test case names are matched, not test classes. Example: For test MyClassTest.testBasic() only "testBasic" is matched. Use sbt's test-only command instead to match test classes. -Dkey=value Temporarily set a system property for the duration of the test run. The property is restored to its previous value after the test has ended. Note that system properties are global to the entire JVM and they can be modified in a non-transactional way, so you should run tests serially and not perform any other tasks in parallel which depend on the modified property. --run-listener=<CLASS_NAME> A (user defined) class which extends org.junit.runner.notification.RunListener. An instance of this class is created and added to the JUnit Runner, so that it will receive the run events. For more information, see RunListener. Note: this uses the test-classloader, so the class needs to be defined in src/test or src/main or included as a test or compile dependency --include-categories=<CLASSES> A comma separated list of category class names that should be included. Only tests with one or more of these categories will be run. --exclude-categories=<CLASSES> A comma separated list of category class names that should be excluded. No tests that match one or more of these categories will be run.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23517699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313245/']}
jdg_71796
stackexchange
llm_judgeable_groundtruth_similarity
327231
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 find the best way to display results on my page via an Ajax call using jQuery, do you think the best way is to pass it as JSON or plain text? I have worked with ajax calls before, but not sure which is preferred over the other and for the JSON version what is the best way to read from a JSON file generated by a PHP page to display my results. i know I would include a .each to run through it to display them all. Now provide the response and nothing else.
Something like this: $.getJSON("http://mywebsite.com/json/get.php?cid=15", function(data){ $.each(data.products, function(i,product){ content = '<p>' + product.product_title + '</p>'; content += '<p>' + product.product_short_description + '</p>'; content += '<img src="' + product.product_thumbnail_src + '"/>'; content += '<br/>'; $(content).appendTo("#product_list"); }); }); Would take a json object made from a PHP array returned with the key of products. e.g: Array('products' => Array(0 => Array('product_title' => 'Product 1', 'product_short_description' => 'Product 1 is a useful product', 'product_thumbnail_src' => '/images/15/1.jpg' ) 1 => Array('product_title' => 'Product 2', 'product_short_description' => 'Product 2 is a not so useful product', 'product_thumbnail_src' => '/images/15/2.jpg' ) ) ) To reload the list you would simply do: $("#product_list").empty(); And then call getJSON again with new parameters.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/327231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_71797
stackexchange
llm_judgeable_groundtruth_similarity
63054997
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 Django documentation, it uses User.objects.create_user() to create a user. I am confused, what is the difference between that and User.objects.create() and User().save() which are the normal ways to create objects of other models Now provide the response and nothing else.
The most significant difference is that if you supply a password to the .create() method, it will be set verbatim on the user, and will not be usable to authenticate the user. >>> user = User.objects.create(username="foo", password="bar")>>> user.password'bar'>>> user.check_password("bar")False Instead, the create_user() method hashes the password argument, which is then. >>> user = User.objects.create_user(username="foo", password="bar")>>> user.password'pbkdf2_sha256$120000$2pHBVu3tYYbK$ESG1nbUY2ZhEmstJ7Fzu1DioXmGYXiLw31YDkOGn9E0='>>> user.check_password("bar")True See https://github.com/django/django/blob/master/django/contrib/auth/models.py#L145 . Some other 'tidying' is also done. See the rest of the function linked above.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/63054997', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13585419/']}
jdg_71798
stackexchange
llm_judgeable_groundtruth_similarity
2214651
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 an efficient way to initialize and access elements of a large array in Python? I want to create an array in Python with 100 million entries, unsigned 4-byte integers, initialized to zero. I want fast array access, preferably with contiguous memory. Strangely, NumPy arrays seem to be performing very slow. Are there alternatives I can try? There is the array.array module, but I don't see a method to efficiently allocate a block of 100 million entries. Responses to comments: I cannot use a sparse array. It will be too slow for this algorithm because the array becomes dense very quickly. I know Python is interpreted, but surely there is a way to do fast array operations? I did some profiling, and I get about 160K array accesses (looking up or updating an element by index) per second with NumPy. This seems very slow. Now provide the response and nothing else.
I have done some profiling, and the results are completely counterintuitive.For simple array access operations, numpy and array.array are 10x slower than native Python arrays . Note that for array access, I am doing operations of the form: a[i] += 1 Profiles: [0] * 20000000 Access: 2.3M / sec Initialization: 0.8s numpy.zeros(shape=(20000000,), dtype=numpy.int32) Access: 160K/sec Initialization: 0.2s array.array('L', [0] * 20000000) Access: 175K/sec Initialization: 2.0s array.array('L', (0 for i in range(20000000))) Access: 175K/sec, presumably, based upon the profile for the other array.array Initialization: 6.7s
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2214651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82733/']}
jdg_71799
stackexchange
llm_judgeable_groundtruth_similarity
270517
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $ \sum_{n=1}^\infty a_n $ be a conditionally convergent series. Then the series $\sum_{n=1}^\infty b_n$ of positive terms of $\{a_n\}_{n=1}^\infty$ and $\sum_{n=1}^\infty c_n$ of negative terms are divergent. My proof : if $\sum_{n=1}^\infty a_n$ is conditionally convergent, then $\sum_{n=1}^\infty |a_n| = \infty$. Let's suppose that $\sum_{n=1}^\infty b_n$ and $\sum_{n=1}^\infty c_n$ are convergent, so since they are composed of positive and negative terms respectively, then $\sum_{n=1}^\infty |b_n| < \infty$ and $\sum_{n=1}^\infty |c_n| <\infty$ and we have that $$ \sum_{n=1}^\infty |a_n| = \sum_{n=1}^\infty |b_n| + \sum_{n=1}^\infty |c_n| < \infty $$ which is absurd since we supposed that the series was conditionally convergent. Edit Can I define $b_n := \left\{\begin{array}{ll} a_n &\text{if } a_n > 0 \\ 0 &\text{otherwise} \end{array} \right.$ and $c_n$ analogously for negative terms and say that $\sum a_n = \sum b_n + \sum c_n $ and, since $\sum a_n$ converges then both $\sum b_n, \sum c_n$ converge? Are the new series equal to the series of positive (and negative) terms? Is this correct? Thanks in advance Now provide the response and nothing else.
Note that$$b_n=\dfrac{a_n+|a_n|}{2} \;\;(\geqslant 0), \\c_n=\dfrac{a_n-|a_n|}{2} \;\;(\leqslant 0)$$and$$c_n=a_n-b_n.$$ If $\sum a_n$ converges (conditionally) and $\sum b_n$ is convergent (absolutely) then $\sum {c_n}$ is convergent (absolutely). Because $a_n=b_n+c_n$ then $\sum a_n$ must be absolutely convergent, which contradicts to its conditional convergence.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/270517', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54087/']}
jdg_71800
stackexchange
llm_judgeable_groundtruth_similarity
26414424
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Now that SSL 3 has been found to be vulnerable to the POODLE attack: Which versions of SSL/TLS does System.Net.WebRequest use when connecting to any https Uri? I use WebRequest to connect to several 3rd party API's. One of these has now said they will block any request that uses SSL 3. But WebRequest is part of the .Net core framework (using 4.5) so it is not obvious what version it uses. Now provide the response and nothing else.
When using System.Net.WebRequest your application will negotiate with the server to determine the highest TLS version that both your application and the server support, and use this. You can see more details on how this works here: http://en.wikipedia.org/wiki/Transport_Layer_Security#TLS_handshake If the server doesn't support TLS it will fallback to SSL, therefore it could potentially fallback to SSL3. You can see all of the versions that .NET 4.5 supports here: http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx In order to prevent your application being vulnerable to POODLE, you can disable SSL3 on the machine that your application is running on by following this explanation: https://serverfault.com/questions/637207/on-iis-how-do-i-patch-the-ssl-3-0-poodle-vulnerability-cve-2014-3566
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26414424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325727/']}
jdg_71801
stackexchange
llm_judgeable_groundtruth_similarity
41926890
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am making a 2D Game with Unity 5 and I have a problem with child GameObject collider. I want to detect a collision between a Child GameObject with another object, doing this from the parent script and using tags. Follow my parent script below: void OnCollisionEnter2D(Collision2D hit) { if(hit.transform.tag == "Enemy"){ this.playerRigidbody.AddForce(new Vector2(0, this.forceJump)); } } The "Enemy" tag is another object that is colliding with the collider of my player child. I want to detect the collision between the child object and that another object, I searched in many similar forums about Unity but I couldn't solve my problem. Someone can help me with this problem? Now provide the response and nothing else.
When a collision occurs, Unity will search up the hierarchy for the nearest Rigidbody and run any scripts on that same GameObject. So, the simple approach is to make sure the rigidbody is on the parent object with the script. Here's an example hierarchy: Parent Child A Child B Parent has: A Rigidbody 2D The script Child B has: A Box Collider 2D When the box collider collides with something, the event will bubble up straight through Child A and be received by the Rigidbody on the parent, which will then cause the script to run. If you can't put the rigidbody on the parent.. Unity won't bubble the event up the hierarchy any further than that for performance reasons. So, your other options are.. Add a script to the child which catches the collision and deals with it there. If you need to, you could forward the event to the parent script like so: void OnCollisionEnter2D(Collision2D hit) { // Forward to the parent (or just deal with it here). // Let's say it has a script called "PlayerCollisionHelper" on it: PlayerCollisionHelper parentScript = transform.parent.GetComponent<PlayerCollisionHelper>(); // Let it know a collision happened: parentScript.CollisionFromChild(hit);} Or a script on the "another" object in order to catch that collision event from its point of view instead.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41926890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6706597/']}
jdg_71802
stackexchange
llm_judgeable_groundtruth_similarity
59757355
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 workflow for CI in a monorepo, for this workflow two projects end up being built. The jobs run fine, however, I'm wondering if there is a way to remove the duplication in this workflow.yml file with the setting up of the runner for the job. I have them split so they run in parallel as they do not rely on one another and to be faster to complete. It's a big time difference in 5 minutes vs. 10+ when waiting for the CI to finish. jobs: job1: name: PT.W Build runs-on: macos-latest steps: - name: Checkout Repo uses: actions/checkout@v1 - name: Setup SSH-Agent uses: webfactory/[email protected] with: ssh-private-key: | ${{ secrets.SSH_PRIVATE_KEY }} - name: Setup JDK 1.8 uses: actions/setup-java@v1 with: java-version: 1.8 - name: Setup Permobil-Client run: | echo no | npm i -g nativescript tns usage-reporting disable tns error-reporting disable npm run setup.all - name: Build PT.W Android run: | cd apps/wear/pushtracker tns build android --env.uglify job2: name: SD.W Build runs-on: macos-latest steps: - name: Checkout Repo uses: actions/checkout@v1 - name: Setup SSH-Agent uses: webfactory/[email protected] with: ssh-private-key: | ${{ secrets.SSH_PRIVATE_KEY }} - name: Setup JDK 1.8 uses: actions/setup-java@v1 with: java-version: 1.8 - name: Setup Permobil-Client run: | echo no | npm i -g nativescript tns usage-reporting disable tns error-reporting disable npm run setup.all - name: Build SD.W Android run: | cd apps/wear/smartdrive tns build android --env.uglify You can see here the jobs have almost an identical process, it's just the building of the different apps themselves. I'm wondering if there is a way to take the duplicate blocks in the jobs and create a way to only write that once and reuse it in both jobs. Now provide the response and nothing else.
As I know currently there is no way to reuse steps but in this case, you can use strategy for parallel build and different variation: jobs: build: name: Build runs-on: macos-latest strategy: matrix: build-dir: ['apps/wear/pushtracker', 'apps/wear/smartdrive'] steps: - name: Checkout Repo uses: actions/checkout@v1 - name: Setup SSH-Agent uses: webfactory/[email protected] with: ssh-private-key: | ${{ secrets.SSH_PRIVATE_KEY }} - name: Setup JDK 1.8 uses: actions/setup-java@v1 with: java-version: 1.8 - name: Setup Permobil-Client run: | echo no | npm i -g nativescript tns usage-reporting disable tns error-reporting disable npm run setup.all - name: Build Android run: | cd ${{ matrix.build-dir }} tns build android --env.uglify For more information please visit https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idstrategy
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/59757355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1893557/']}
jdg_71803
stackexchange
llm_judgeable_groundtruth_similarity
78100
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: How fast is booting over PXE?. Is it conceivable to boot a linux installation? Does it take a long time? I have never really looked into it at all, but I was considering setting up a compiler farm and thought this might be interesting to try. Does one have a main computer that the PXE answers to to get its image? Can you have multiple PXE images to pick from? Thanks! Now provide the response and nothing else.
PXE booting is awesome. I manage a cluster of about 20 physical machines that are located on the opposite side of the globe, and they're all installed automatically without any physical intervention from anyone at the DC. I couldn't do my job nearly so well without PXE booting -- all the other remote installation options (virtual media, getting a DC tech to shuffle CDs, whatever) are very poor substitutes. To answer your specific questions: "Does it take a long time?" If you mean install time, it takes less than 10 minutes to go from "burnt-in" to "booted into the installed OS". In terms of setting things up, it'll take a while the first time, but I've got it all automated so a new PXE server can be installed all by itself if I need it. "Does one have a main computer?" Yes, the PXE system relies on you having a server (which I call the "Gold" server, based on the nomenclature and concepts at http://infrastructures.org/ ) that instructs PXE clients what to do. In theory you can have several servers which contain different images, but I've yet to exercise that functionality, and I expect it would be a lot more complexity than it's worth in a greenfields installation. "Can you have multiple PXE images to choose from?" Yes, I use this functionality heavily to do my burn-ins -- all machines start with a memtest boot option, then when they've passed that I toggle a flag in the build system and reboot, and they get the burnin boot image. When they pass that, another flag gets toggled and they install. One more flag toggle and they'll boot off the local disks (and hence locally installed OS) from then on. All this decision making is based on the MAC address of the machine. For our general-purpose infrastructure at work (a couple of hundred physical machines) we also use this to perform the installs of client machines -- we've got PXE images of most Fedora/RHEL/CentOS/Ubuntu/Debian versions for customers to choose from.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/78100', 'https://serverfault.com', 'https://serverfault.com/users/-1/']}
jdg_71804
stackexchange
llm_judgeable_groundtruth_similarity
56075455
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just updated the Android Studio to 3.5 Beta 1 and I'm getting Expiring Daemon because JVM heap space is exhausted message while the build is running. Also, the build is taking more time to complete. Does anyone have any idea regarding this? Now provide the response and nothing else.
This can be fixed by increasing the configured max heap size for the project. Through IDE: Add the below lines into the gradle.properties file. Below memory size (1) can be configured based on the RAM availability org.gradle.daemon=trueorg.gradle.jvmargs=-Xmx2560m Through GUI: In the Settings, search for 'Memory Settings' and increase the IDE max heap size and Daemon max heap size as per the system RAM availability. (1) $ man java...-Xmxsize Specifies the maximum size (in bytes) of the memory allocation pool in bytes. This value must be a multiple of 1024 and greater than 2 MB. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes. The default value is chosen at runtime based on system configuration. For server deployments, -Xms and -Xmx are often set to the same value. See the section "Ergonomics" in Java SE HotSpot Virtual Machine Garbage Collection Tuning Guide at http://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/index.html. The following examples show how to set the maximum allowed size of allocated memory to 80 MB using various units: -Xmx83886080 -Xmx81920k -Xmx80m The -Xmx option is equivalent to -XX:MaxHeapSize....
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/56075455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3948854/']}
jdg_71805
stackexchange
llm_judgeable_groundtruth_similarity
35668631
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 read a string line for line down a .txt file in order to initiate an array of objects using a constructor that takes a string. The text file is written like TransAm Mustang Corvette I feel like my loop is not iterating the information I want to be set correctly. Is there an easy way of accomplishing this?main.cc #include <string> #include <iostream> #include "Car.cc" #include <fstream> using namespace std; int main() { Car cars[3]; string STRING; ifstream infile; infile.open("cars.txt");// THIS IS HOW IT'S ACHIEVED USING FOR-LOOP - Samfor(int i = 0; i<3 && infile;++i){ getline(infile,STRING); cars[i].setName(STRING); }/* THIS IS WHAT I HAD while(!infile) { getline(infile,STRING); for(int i = 0; i<sizeof(cars);i++){ cars[i].setName(STRING); } } */ infile.close(); for(int j = 0;j<sizeof(cars);j++){ cars[j].print(); } } Car.h #include <string>using namespace std;class Car{public: Car(); Car(string); string getName(); void setName(string); void print();private: string name;}; Car.cc #include <string>#include "Car.h"using namespace std; Car::Car() { } Car::Car(string s){ setName(s);}void Car::setName(string s){ name = s;}string Car::getName(){ return name;}void Car::print(){ cout << name;} Now provide the response and nothing else.
Task.WhenAny is going to return a Task<Task<TResult>> : Awaiting the result of Task.WhenAny() will return the first task that completed Awaiting that task will return the results of the task, i.e. a TResult[] . You might find it easy to understand with explanatory variables: var firstCompletedTask = await Task.WhenAny(killJoy.Task, Task.WhenAll(tasks));var firstResult = await firstCompletedTask;return firstResult; It's not clear why you're concerned around the performance of this - it's just two await expressions, not particularly different to any other method with two await expressions. It's pretty natural to do this when using Task.WhenAny<TResult>(Task<TResult>[]) , given that the return type is a Task<Task<TResult>> .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35668631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3685916/']}
jdg_71806
stackexchange
llm_judgeable_groundtruth_similarity
26
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Can a (possibly infinite-dimensional) vector space ever be a finite union of proper subspaces? If the ground field is finite, then any finite-dimensional vector space is finite as a set, so there are a finite number of 1-dimensional subspaces, and it is the union of those. So let's assume the ground field is infinite. Now provide the response and nothing else.
You can prove by induction on n that: An affine space over an infinite field $F$ is not the union of $n$ proper affine subspaces. The inductive step goes like this: Pick one of the affine subspaces $V$. Pick an affine subspace of codimension one which contains it, $W$. Look at all the translates of $W$. Since $F$ is infinite, some translate $W'$ of $W$ is not on your list. Now restrict all other subspaces down to $W'$ and apply the inductive hypothesis. This gives the tight bound that an $F$ affine space is not the union of $n$ proper subspaces if $|F|>n$. For vector spaces, one can get the tight bound $|F|\geq n$ by doing the first step and then applying the affine bound.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/26', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1/']}
jdg_71807
stackexchange
llm_judgeable_groundtruth_similarity
21696
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Iron(II) sulphate solution is added to a test-tube. Following this, potassium manganate solution is added gradually to the test-tube as well. The observation seen is that the green solution turns pink at first, then potassium manganate turns colourless as manganese(VII) is oxidised to manganese(II). But Fe(II) is oxidised to Fe(III) ions as well, which are brown in colour, so shouldn’t the solution turn brown instead of colourless? I have seen these observations experimentally in the lab but still did not understand. I know I’m probably thinking about it the wrong way so any help would be much appreciated. Now provide the response and nothing else.
In solution, the iron(III) will be hexaaqua iron(III), 6 water molecules coordinating the iron ion, with the oxygen atoms being at the vertices of an octahedron. Hexaaqua iron(III) has a high spin d5 electron configuration. All the d-d transitions are spin forbidden. Hexaaqua iron(III) is nearly colorless.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/21696', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/7481/']}
jdg_71808
stackexchange
llm_judgeable_groundtruth_similarity
233057
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The question speaks for itself, but here is more details: Vector bundles are easy to motivate for students; they come up because one is trying to do "linear algebra on spaces". How does one motivate parabolic bundles (i.e., vector bundles with flags at finitely many points)? Said differently, how do parabolic bundles arise in nature? Now provide the response and nothing else.
Parabolic bundles were introduced in the 70's by Mehta and Seshadri in the setup of a Riemann surface with cusps. They were trying to generalize theNarasimhan-Seshadri correspondence on a compact Riemann surface (betweenpolystable bundles of degree $0$ and unitary representations of thefundamental group). In the non-compact case, they were able to determine themissing piece of data - partial flags and weights at each cusp. Theyestablished what is now called the Mehta-Seshadri correspondence. Then theyproceeded to study the moduli space. Mehta, V. B.; Seshadri, C. S.Moduli of vector bundles on curves with parabolic structures.Math. Ann. 248 (1980), no. 3, 205–239. https://link.springer.com/article/10.1007/BF01420526 Since then, the definition of a parabolic bundle has been clarified (tensorproduct with the initial definition is not really computable for instance) andgeneralized. This is a long story starting with C.Simpson, I.Biswas, and manyauthors. The upshot is that given a scheme $X$ , a Cartier divisor $D$ , and aninteger $r$ , there is a one to one tensor (and Fourier-like) equivalencebetween parabolic vector bundles on $(X,D)$ with weights in $\frac{1}{r}\mathbb Z$ and standard vector bundles on a certain orbifold $\sqrt[r]{D/X}$ , the stack of $r$ -th roots of $D$ on $X$ . So one can turn yourquestion in: why are these orbifolds natural ? They were first introduced byA.Vistoli in relation with Gromov-Witten theory. They also turned out to berelated to the section conjecture (rational points of stack of roots areGrothendieck's packets in his anabelian letter to Faltings). So parabolicsheaves - and stack of roots - are ubiquitous. They are also very stronglyrelated to logarithmic geometry.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/233057', 'https://mathoverflow.net', 'https://mathoverflow.net/users/41301/']}
jdg_71809
stackexchange
llm_judgeable_groundtruth_similarity
306583
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 layout similar to this: <div id="..."><img src="..."></div> and would like to use a jQuery selector to select the child img inside the div on click. To get the div , I've got this selector: $(this) How can I get the child img using a selector? Now provide the response and nothing else.
The jQuery constructor accepts a 2nd parameter called context which can be used to override the context of the selection. jQuery("img", this); Which is the same as using .find() like this: jQuery(this).find("img"); If the imgs you desire are only direct descendants of the clicked element, you can also use .children() : jQuery(this).children("img");
{}
{'log_upvote_score': 13, 'links': ['https://Stackoverflow.com/questions/306583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16974/']}
jdg_71810
stackexchange
llm_judgeable_groundtruth_similarity
1030793
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why does display:block;width:auto; on my text input not behave like a div and fill the container width? I was under the impression that a div is simply a block element with auto width. In the following code shouldn't the div and the input have identical dimensions? How do I get the input to fill the width? 100% width won't work, because the input has padding and a border (causing a final width of 1Β pixel + 5Β pixels + 100% + 5Β pixels + 1Β pixels). Fixed widths aren't an option, and I'm looking for something more flexible. I'd prefer a direct answer to a workaround. This seems like a CSS quirk and understanding it may be useful later. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html> <head> <title>width:auto</title> <style> div, input { border: 1px solid red; height: 5px; padding: 5px; } input, form { display: block; width: auto; } </style> </head> <body> <div></div> <form> <input type="text" name="foo" /> </form> </body></html> I should point out I can already do this with wrapper workarounds. Apart from this screwing with the page semantics and CSS selector relationships I'm trying to understand the nature of the problem and whether it can be overcome by changing the nature of the INPUT itself. Ok, this is TRULY strange! I've found that the solution is to simply add max-width:100% to an input with width:100%;padding:5px; . However this raises even more questions (which I'll ask in a separate question), but it seems that width uses the normal CSS box model and max-width uses the InternetΒ Explorer border-box model. How very odd. Ok, that last one appears to be a bug in Firefox 3. InternetΒ ExplorerΒ 8 and SafariΒ 4 limit the max-width to 100% + padding + border which is what the spec says to do. Finally, InternetΒ Explorer got something right. Oh my god, this is awesome! In the process of playing with this, and with much help from the venerable gurus Dean Edwards and Erik Arvidsson , I managed to piece together three separate solutions to make a true cross-browser 100% width on elements with arbitrary padding and borders. See answer below. This solution does not require any extra HTML markup, just a class (or selector) and an optional behaviour for legacy InternetΒ Explorer. Now provide the response and nothing else.
Check out what I came up with, a solution using the relatively unknown box-sizing:border-box style from CSSΒ 3. This allows a 'true' 100% width on any element regardless of that elements' padding and/or borders. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"><html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>Cross-browser CSS box-sizing:border-box</title> <style type="text/css"> form {display:block; margin:0; padding:0; width:50%; border:1px solid green; overflow:visible} div, input {display:block; border:1px solid red; padding:5px; width:100%; font:normal 12px Arial} /* The voodoo starts here */ .bb { box-sizing: border-box; /* CSS 3 rec */ -moz-box-sizing: border-box; /* Firefox 2 */ -ms-box-sizing: border-box; /* Internet Explorer 8 */ -webkit-box-sizing: border-box; /* Safari 3 */ -khtml-box-sizing: border-box; /* Konqueror */ } </style> <!-- The voodoo gets scary. Force Internet Explorer 6 and Internet Explorer 7 to support Internet Explorer 5's box model --> <!--[if lt IE 8]><style>.bb {behavior:url("boxsizing.htc");}</style><![endif]--> </head> <body> <form name="foo" action="#"> <div class="bb">div</div> <input class="bb" size="20" name="bar" value="field"> </form> </body></html> This solution supports InternetΒ ExplorerΒ 6 and InternetΒ ExplorerΒ 7 via a behaviour written by Erik Arvidsson with some tweaks from Dean Edwards to support percentage and other non-pixel widths. Working example Behaviour (boxsizing.htc)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1030793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108741/']}
jdg_71811
stackexchange
llm_judgeable_groundtruth_similarity
87734
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 the major axis of the ellipse is vertical or horizontal, it's easy to calculate the bounding box, but what about when the ellipse is rotated? The only way I can think of so far is to calculate all the points around the perimeter and find the max/min x and y values. It seems like there should be a simpler way. If there's a function (in the mathematical sense) that describes an ellipse at an arbitrary angle, then I could use its derivative to find points where the slope is zero or undefined, but I can't seem to find one. Edit: to clarify, I need the axis-aligned bounding box, i.e. it should not be rotated with the ellipse, but stay aligned with the x axis so transforming the bounding box won't work. Now provide the response and nothing else.
You could try using the parametrized equations for an ellipse rotated at an arbitrary angle: x = h + a*cos(t)*cos(phi) - b*sin(t)*sin(phi) [1]y = k + b*sin(t)*cos(phi) + a*cos(t)*sin(phi) [2] ...where ellipse has centre (h,k) semimajor axis a and semiminor axis b, and is rotated through angle phi. You can then differentiate and solve for gradient = 0: 0 = dx/dt = -a*sin(t)*cos(phi) - b*cos(t)*sin(phi) => tan(t) = -b*tan(phi)/a [3] Which should give you many solutions for t (two of which you are interested in), plug that back into [1] to get your max and min x. Repeat for [2]: 0 = dy/dt = b*cos(t)*cos(phi) - a*sin(t)*sin(phi) => tan(t) = b*cot(phi)/a [4] Lets try an example: Consider an ellipse at (0,0) with a=2, b=1, rotated by PI/4: [1] => x = 2*cos(t)*cos(PI/4) - sin(t)*sin(PI/4) [3] => tan(t) = -tan(PI/4)/2 = -1/2 => t = -0.4636 + n*PI We are interested in t = -0.4636 and t = -3.6052 So we get: x = 2*cos(-0.4636)*cos(PI/4) - sin(-0.4636)*sin(PI/4) = 1.5811 and x = 2*cos(-3.6052)*cos(PI/4) - sin(-3.6052)*sin(PI/4) = -1.5811
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/87734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2214/']}
jdg_71812
stackexchange
llm_judgeable_groundtruth_similarity
37489245
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 dictionary that looks like: {'x': [1, 2, 3], 'y': [4, 5, 6]} I want to transform it to the following format: [{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, {'x': 3, 'y': 6}] I can do it by explicit loops but is there a good pythonic way to do it? Edit: Turns out there is a similar question here and one of the answers is same as the accepted answer here but the author of that answer writes "I do not condone the use of such code in any kind of real system". Can someone explain why such code is bad? It appears very elegant to me. Now provide the response and nothing else.
Use zip() a few times, counting on the fact that both dict.items() and iteration directly over a dict return elements in the same order as long as the dictionary is not mutated in between: [dict(zip(d, col)) for col in zip(*d.values())] The zip(*d.values()) call transposes the list values , and the zip(d, col) call pairs up each column with the keys in the dictionary again. The above is the equivalent of spelling out the keys manually: [dict(zip(('x', 'y'), col)) for col in zip(d['x'], d['y'])] without having to spell out the keys manually. Demo: >>> d = {'x': [1, 2, 3], 'y': [4, 5, 6]}>>> [dict(zip(d, col)) for col in zip(*d.values())][{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, {'x': 3, 'y': 6}]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37489245', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1893075/']}
jdg_71813
stackexchange
llm_judgeable_groundtruth_similarity
66176453
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 the following code in Svelte (3) to fetch options from an API. There's subsequent s that depend on the first one. My expectation is that selectedOption would change to options[0] when the select has its options populated but it's not changing until I manually select another option and then select the first one. Am I binding it wrong? AFAIK I don't need a reactive variable for this and should theoretically work like this. onmount(async () => { options = await getOptions()})let selectedOption;<select bind:value={selectedOption}>{#each options as option} <option value={option} selected={selectedOption === option}> {option.name} </option>{/each} Now provide the response and nothing else.
The problem is <div {...props}> in MyWrapper ; that adds the handleMoveAll prop onto the div. What you could do is something like: export const MyWrapper: FC<Props> = (props): JSX.Element => ( const {handleMoveAll, ...rest} = props; <div {...rest}> <IconBox label="Move All" onClick={handleMoveAll}> <MyIcon /> </IconBox> </div>) to pull out handleMoveAll from the passed-in props, while still passing any other props into the div.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/66176453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9435367/']}
jdg_71814
stackexchange
llm_judgeable_groundtruth_similarity
2100973
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 reliably redirect an applications look up of a specific DLL. Using the app.exe.local approach does not work because local files are ignored if the application has a manifest (embedded or separate file). So I am trying to do DLL redirection by defining the DLL as a private assembly in the manifests. I have a test application, LoadDll.exe which simply calls LoadLibrary("C:\\EmptyDll.dll"); The LoadDll.exe has the manifest (as a separate file, LoadDll.exe.manifest) <?xml version="1.0" encoding="UTF-8" standalone="yes"?><assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"><assemblyIdentity version="1.0.0.1" processorArchitecture="x86" name="LoadDll" type="win32"/><dependency> <dependentAssembly> <assemblyIdentity type="win32" name="EmptyDll" version="1.0.0.1" processorArchitecture="x86" /> </dependentAssembly></dependency></assembly> The Application folder containing LoadDll.exe (NOT c:\) contains the EmptyDll.dll with the embedded manifest. <?xml version='1.0' encoding='UTF-8' standalone='yes'?><assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'><assemblyIdentity type="win32" name="EmptyDll" version="1.0.0.1" processorArchitecture="x86" /> </assembly> However, LoadDll.exe goes ahead and loads C:\EmptyDll.dll, and not the EmptyDll.dll in the application folder. If you break either manifest (e.g. change the version number in the EmptyDll.dll manifest identity), LoadDll.exe does not load, so the manifest files are being read and processed by windows, but just ignored. Anyone got any ideas? Thanks! Toby Now provide the response and nothing else.
So it seems its impossible to redirect calls to LoadLibrary with absolute paths using manifests. After a lot of playing around with manifests, it seems that once you get past all the bad documentation manifests are actually stupidly simple. Basically when the executable is loaded Windows collects all the related manifests that are linked using the identity and dependency elements. Then for each file element contained in the manifest files, it adds an entry into the activation context: 'name attribute of file element' -> 'absolute path of manifest file' + 'name attribute of file element' Now when a load library call is made, it searches the activation context map for a key that matches the path argument of load library, and then calls Loadlibrary with the value for that key. So if my application c:\foo\foo.exe has a dependency on the manifest in c:\foo\baa\baa.manifest , and baa.manifest contains a file element <file name="empty.dll"/> , then the activation context will have the mapping: "empty.dll" -> "c:\foo\baa\empty.dll" So any calls to LoadLibrary("empty.dll") will be redirected to LoadLibrary("C:\foo\baa\empty.dll") . However, LoadLibrary("c:\anotherpath\empty.dll") Will not be redirected! Now to prove my point of how stupidly simple manifest files and activation contexts are. If the file element of baa.manifest was <file name="c:\anotherpath\empty.dll"/> and you made a LoadLibrary("C:\anotherpath\empty.dll") call, the LoadLibrary call will be redirected to LoadLibrary("C:\foo\baa\C:\anotherpath\empty.dll") , yes, a malformed path... The file element does have an undocumented attribute called "loadFrom", which does what it sounds like, and seems like its perfect to solve this problem. Using loadFrom, I was able to redirect an absolute path loadlibrary call, but it seemed to screw up other dependencies in the executable in weird ways. If someone knows more about how "loadFrom" works I would be very interested. So how did I solve my problem in the end? By using an incredibly heavy handed approach of DLL Trojaning described at Ethical Hacker . Basically you create a dummy kernel32.dll that redirects all calls to the original kenerl32.dll, except for the LoadLibrary calls, in which you place your own redirection logic. Then in the applications manifest, you place a file element that redirects the kernel32.dll to your dummy. Fun. All this describes my experiments on Windows Xp Sp2. For extra fun I'm led to believe manifests behave differently on almost every version of Windows.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2100973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/254832/']}
jdg_71815
stackexchange
llm_judgeable_groundtruth_similarity
37859582
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 Firebase, how do I catch a specific exception and tell the user gracefully about it? E.g : FirebaseAuthInvalidCredentialsException: The email address is badly formatted. I'm using the code below to signup the user using email and password, but I'm not that advanced in java. mAuth.createUserWithEmailAndPassword(email, pwd) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (!task.isSuccessful()) { //H.toast(c, task.getException().getMessage()); Log.e("Signup Error", "onCancelled", task.getException()); } else { FirebaseUser user = mAuth.getCurrentUser(); String uid = user.getUid(); } } }); Now provide the response and nothing else.
You can throw the Exception returned by task.getException inside a try block and catch each type of Exception that may be thrown by the method you are using. Here is an example from the OnCompleteListener for the createUserWithEmailAndPassword method. if(!task.isSuccessful()) { try { throw task.getException(); } catch(FirebaseAuthWeakPasswordException e) { mTxtPassword.setError(getString(R.string.error_weak_password)); mTxtPassword.requestFocus(); } catch(FirebaseAuthInvalidCredentialsException e) { mTxtEmail.setError(getString(R.string.error_invalid_email)); mTxtEmail.requestFocus(); } catch(FirebaseAuthUserCollisionException e) { mTxtEmail.setError(getString(R.string.error_user_exists)); mTxtEmail.requestFocus(); } catch(Exception e) { Log.e(TAG, e.getMessage()); }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/37859582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2873357/']}
jdg_71816
stackexchange
llm_judgeable_groundtruth_similarity
4629642
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 detect the latest updates made to a database and silently refresh a page when a change occurs? Let's say the database access looks like: $host = "localhost";$username = "root";$password = "root";$db = mysql_connect($host,$username,$password) or die(mysql_error());mysql_select_db('ccr') or die(mysql_error()); Any ideas and samples would be appreciated. Thank you. Now provide the response and nothing else.
This is how I recently implemented a solution using jQuery. PHP increments a field in the database every time a significant update occurs. <?php// Call this function when data changesfunction update_clients(){ mysql_query( "UPDATE pageGen SET id = id + 1 LIMIT 1" );}// Call this function to get the ID to pass to JavaScriptfunction get_update(){ $result = mysql_query( "SELECT id FROM pageGen LIMIT 1" ); $update = mysql_result( $result, 0, 'id' ); return $update;}?> When the page is initially loaded, populate a JavaScript variable with a number from the database: <script type="text/javascript">var pageGenID = 25218603 // generated by PHPvar processUpdate = function( response ) { if ( pageGenID < response ) { replace_current_data_with_new_via_ajax(); pageGenID = response; }}// Compare our Page Generate ID against that of the servervar checkUpdates = function(){ serverPoll = setInterval( function() { $.get('script_to_return_latest_pageGenID.php', { lastupdate: 1 }, processUpdate, 'html'); }, 10000 )};// Check for updates every 10 seconds$( document ).ready( checkUpdates );</script>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4629642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/566646/']}
jdg_71817
stackexchange
llm_judgeable_groundtruth_similarity
338295
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've seen this stated in a few places. If $$\vartheta(x) = \sum_{p\le{x}} \log (p) \qquad \psi(x) = \sum_{m=1}^{\infty}\vartheta\left(\sqrt[m]{x}\right)$$ Then $$\log(x!) = \sum_{m=1}^{\infty} \psi\left(\frac{x}{m}\right).$$ It is used by Ramanujan here . It is used by Jitsuro Nagura here . Can anyone provide a proof for why it is true or provide a link to a proof? Thanks very much. Now provide the response and nothing else.
We find $$\sum_{m\ge1}\psi\left(\frac{x}{m}\right)=\sum_{m\ge1}\sum_{k\ge1}\vartheta\left(\sqrt[k]{\frac{x}{m}}\right)=\sum_{m\ge1}\sum_{k\ge1}\sum_{p\le \sqrt[k]{x/m}}\log p$$ $$=\sum_{m\ge1}\sum_{k\ge1}\sum_{mp^k\le x}\log p=\log \prod_{p\le x}p^{\#\{(m,k):mp^k\le x\}}=\log x!$$ since when counting $\#\{(m,k):mp^k\le x\}$, one sees for every $1\le n\le x$ there are $t=v_p(n)$ different tuples $(m,t),(mp,t-1),\cdots,(mp^{t-1},1)$ counted in the set (note $k\ge1$).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/338295', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/48606/']}
jdg_71818
stackexchange
llm_judgeable_groundtruth_similarity
3893
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: lista = {{0., 1., 0.1, 0.}, {0., 1., 0.2, 0.}, {0., 1., 0.3, 0.}};listb = { {0., 1., 1., 0.}, {0., 0.85, 1., 0.}, {0., 1., 0.1, 0.}, {0.,1., 0.2, 0.}, {0., 1., 0.3, 0.}, {0., 1., 0.4, 0.}, {0., 1., 0.55, 0.}, {0., 1., 0.7, 0.}, {0., 1., 0.85, 0.}, {0.4, 0.4, 0.2, 0.1}, {0.4, 0.4, 0.4, 0.1}, {0.4, 0.4, 0.7, 0.1}, {0.4, 0.7, 0., 0.1}, {0.4, 0.7, 0.1, 0.1}, {0.4, 0.7, 0.2, 0.1}, {0.4, 0.7, 0.4, 0.1}, {0.4, 0.7, 0.7, 0.1}, {0.5, 0.4, 0.4, 0.}, {1., 0., 0., 0.1}, {0., 1., 0., 0.1}, {0., 0., 1., 0.1}, {0.,1., 1., 0.1}, {1., 0., 1., 0.1}, {1., 1., 0., 0.1}}; How would one go about finding the first positions of lista sublists in listb ? Now provide the response and nothing else.
How about mapping Position like so Position[listb, #] & /@ lista(*{{{3}}, {{4}}, {{5}}, {{6}}, {{7}}, {{8}}, {{9}}, {{1}}, {{2}}}*) which gives the position of each sublist of lista in listb ? To get only the first instance, use Position[listb, #, 1, 1] & /@ lista ( the last argument of Position specifies how many positions found to return; the penultimate argument specifies the level at which to search).
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/3893', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/686/']}
jdg_71819
stackexchange
llm_judgeable_groundtruth_similarity
108330
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 $f: \mathbb R \to \mathbb R$ be any function. When is the graph of $f$ dense in $\mathbb R^2$? The only examples I know for this are for non-measurable functions, but is that a necessary condition? Now provide the response and nothing else.
The Conway base 13 function is probably a standard example: the graph is dense because any restriction of the function to an open interval is surjective. But meanwhile, since the graph of the base 13 function is easily defined by an arithmetic property of the digits, the function is Borel and hence measurable. More information is available at Is Conway's base-13 function measurable?
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/108330', 'https://mathoverflow.net', 'https://mathoverflow.net/users/26844/']}
jdg_71820
stackexchange
llm_judgeable_groundtruth_similarity
45874
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: Many moons ago, I asked how to differentiate between two very similar non-linear fits and which was better . Finally got that all straightened out after many headaches and three different software packages -- calculating AIC, AICc, and BIC and all give a consistent result. Now I'm trying to apply a slight modification to the data and re-fit. The question is, since $\chi^2$ is fairly useless on very non-linear models, can I use AIC to tell me if the original data or new data are better fits to that model? As in, I use an $f(x)$ model, fit it with dataset1, and then I fit the SAME model to dataset2, and I calculate AIC/AICc/BIC of both fits. Is that a meaningful comparison, or can they only be used to rate between two different fits to the same data? Now provide the response and nothing else.
The comparison is utterly meaningless. Consider, for instance, fitting iid data $\mathbb{x} = (x_1, \ldots, x_n)$ to a location-scale family having a continuous pdf $$f(x; \mu, \sigma) = f\left(\frac{x-\mu}{\sigma}\right) / \sigma.$$ The log likelihood for these data equals $$\Lambda(\mathbb{x}; \mu, \sigma) = \sum_{i=1}^n \log \left(f\left(\frac{x_i-\mu}{\sigma}\right)/\sigma\right) = -n \log(\sigma) + \sum_{i=1}^n \log f\left(\frac{x_i-\mu}{\sigma}\right).$$ Because $\frac{x-\mu}{\sigma} = \frac{\alpha x-\alpha\mu}{\alpha\sigma}$ for any positive real number $\alpha$, $(\hat{\mu}, \hat{\sigma})$ maximize the log likelihood for $\mathbb{x}$ if and only if $(\alpha \hat{\mu}, \alpha \hat{\sigma})$ maximize the log likelihood for a corresponding dataset $(\alpha x_1, \ldots, \alpha x_n)$ obtained by rescaling the original data. This is tantamount to a change in their units of measurement, so the "fit" to the model cannot be any better or worse. However, $$\Lambda(\mathbb{x}; \hat{\mu}, \hat{\sigma}) = n\log(\alpha) + \Lambda(\alpha\mathbb{x}; \alpha\hat{\mu}, \alpha\hat{\sigma}).$$ It follows that we may change the optimal value of the log likelihood by any arbitrary amount $n\log(\alpha)$ by means of an appropriate choice of $\alpha$ without changing the fit (at least not in any statistically reasonable sense). For instance, if your data are lengths measured in meters and you were to re-express those lengths in kilometers, you would thereby increase the maximum log likelihood by $n\log(1000)$ without changing the "fit." Because both AIC and BIC differ from the optimal value of $\Lambda$ by functions depending only on $n$, which does not change, the same conclusion holds for them, too.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/45874', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/13668/']}
jdg_71821
stackexchange
llm_judgeable_groundtruth_similarity
704152
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I were to have a system of 2 masses that rotate around their barycenter such that $m_1$ has a radius of $r_1$ and $m_2$ has a radius of $r_2$ , what would the ratio of the periods of the planets be? My thinking: Following Kepler's 3rd law that says $T^2/R^3=4Ο€^2/GM$ , and since both would have a common $4Ο€^2/GM$ ratio, this would result in the periods having a ratio of $T_1/T_2 = (r_1/r_2)$ 3/2 Answer: The period for both will be the same as they have the same angular velocity. My question: So does this idea of the periods being the same for 2 planets orbiting their barycenter always hold? If so why? I can't seem to see the connection as to how if they are orbiting the barycenter, their angular velocities are equal. Now provide the response and nothing else.
You’re asking about a two-body system. Suppose the periods were slightly different: perhaps for every 1000 orbits of the more massive body, the less-massive one does 1001. If that were the case, the faster object would have to eventually β€œlap” the slower one, like a runner in a race. But at some point during that overtaking, the two masses would have to be on the same side of the barycenter. That’s unphysical. The barycenter is the system’s center of mass.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/704152', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/320422/']}
jdg_71822
stackexchange
llm_judgeable_groundtruth_similarity
5215469
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: How can I split an IEnumerable<String> into groups of IEnumerable<string> I have a list that I would like to break into groups of 10. If I have an object List<Person> allPendingPersons that is of length m. Is there an elegant way in LINQ to break up allPendingPersons into one or more List objects that all have a up to 10 Persons? Now provide the response and nothing else.
You can write your own extension method: public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> sequence, int size) { List<T> partition = new List<T>(size); foreach(var item in sequence) { partition.Add(item); if (partition.Count == size) { yield return partition; partition = new List<T>(size); } } if (partition.Count > 0) yield return partition;} I explored this in more depth in my blog.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5215469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/279911/']}
jdg_71823
stackexchange
llm_judgeable_groundtruth_similarity
2814041
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $(a_n)_{n\in\mathbb{N}}$ be a positive sequence. Assume, that $\lim_{n \to \infty} a_n = \infty$. $\forall\ \zeta > 0, \exists\ n=n(\zeta) \geq 1: a_n < \zeta.$ From 1. we know, that $\forall\ C > 0, \exists\ N = N(C) \geq 1: a_n \geq C, \forall\ n \geq N.$ The difference $N(C) - n(\zeta)$ can be interpreted as the 'recovery time', i.e. the time the sequence needs from being arbitrarily small to become larger than an arbitrary positive constant $C$ for the rest of its existence. Question: Can somebody think of an example where $\forall\ C > 0: N(C) - n(\zeta)$ is arbitrarily large? (Is this even possible?) Now provide the response and nothing else.
There is no sequence satisfying both of your conditions 1 and 2. Proof: given that $a_n \to \infty$, there is a constant $N = N(1)$ such that $a_n \geq 1$ for all $n \geq N$. Then there are only finitely many terms smaller than 1, and you can choose $\zeta$ to be smaller than any of these.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2814041', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59723/']}
jdg_71824
stackexchange
llm_judgeable_groundtruth_similarity
26737826
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 partial that I refresh via Ajax. View Javascript: $("#SelectedId").change(function () { var id = $("#SelectedId").val(); if (id > 0) { $.ajax({ url: "/Home/Refresh", data: { id: id }, type: "POST", success: function (result) { $('#partialHolder').html(result); } }); }}); Refresh action: [HttpPost]public ActionResult Refresh(int id){ HomeViewModel model = new HomeViewModel(); model.id = id; ViewBag.id = model.id; PrepareModel(ref model); return PartialView("~/Views/PartialView.cshtml", model);} This works well, except that when an error (such as an HTTP exception) occurs, the error view is sent to the partial when I want it to be shown as the main view. Error action: public ActionResult Error(string message){ ViewBag.Message = message; return View();} I have tried using Javascript (both in the view and returned by the controller) to redirect the browser, however both are buggy and I assume bad practice. Now provide the response and nothing else.
TL;DR: peerDependencies are for dependencies that are exposed to (and expected to be used by) the consuming code, as opposed to "private" dependencies that are not exposed, and are only an implementation detail. The problem peer dependencies solve NPM's module system is hierarchical. One big advantage for simpler scenarios is that when you install an npm package, that package brings its own dependencies with it so it will work out of the box. But problems arise when: Both your project and some module you are using depend on another module. The three modules have to talk to each other. In Example Let's say you are building YourCoolProject and you're using both JacksModule 1.0 and JillsModule 2.0 . And let's suppose that JacksModule also depends on JillsModule , but on a different version, say 1.0 . As long as those 2 versions don't meet, there is no problem. The fact that JacksModule is using JillsModule below the surface is just an implementation detail. We are bundling JillsModule twice, but that's a small price to pay when we get stable software out of the box. But now what if JacksModule exposes its dependency on JillsModule in some way. It accepts an instance of JillsClass for example... What happens when we create a new JillsClass using version 2.0 of the library and pass it along to jacksFunction ? All hell will break loose! Simple things like jillsObject instanceof JillsClass will suddenly return false because jillsObject is actually an instance of another JillsClass , the 2.0 version. How peer dependencies solve this They tell npm I need this package, but I need the version that is part of theproject, not some version private to my module. When npm sees that your package is being installed into a project that does not have that dependency, or that has an incompatible version of it, it will warn the user during the installation process. When should you use peer dependencies? When you are building a library to be used by other projects, and This library is using some other library, and You expect/need the user to work with that other library as well Common scenarios are plugins for larger frameworks. Think of things like Gulp, Grunt, Babel, Mocha, etc. If you write a Gulp plugin, you want that plugin to work with the same Gulp that the user's project is using, not with your own private version of Gulp.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/26737826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4214577/']}
jdg_71825
stackexchange
llm_judgeable_groundtruth_similarity
66006
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know what are the reasons for choosing bipolar junction transistor (BJT) versus a field-effect transistor (FET) ( MOSFET or a JFET ) to switch a load from a microcontroller. In our hypothetical situation, assume that the load requires more current than the microcontroller can provide, and the question is what considerations would bias in favor or against the BJT and a FET switch design, assuming that "ease of use" is not a consideration. This question is a more specific version of the when to use what transistor question. Now provide the response and nothing else.
Partial answer - could get very long - may add more later: Choices in this context are usually bipolar or MOSFET. Once you get to JFET you may also wish to think about SCR/TRIAC, IGBT, ... . You may wish to throw bipolar-Darlington into the mix. Short: Goes something like - Small bipolars up to say 500 mA and 30 Volt load voltage are low cost, can be driven by 1V up of drive voltage, need drive currents that are available from most processors and are widely available. Heat sinking when run in switching on/off mode is not usually required or is modest (modest PCB copper usually enough) and SOT23 or TO92 size packages are usually adequate. When linear loads are driven and dissipation rises lower VI products and/or better heatsinking and/or larger packages are required. Frequencies of 10's of kHz are available with a single resistor drive, 100's of kHz with a slightly more complex RC drive and low MHz with more care. Higher again gets specialist Ease of use in this range is usually as good or better than MOSFETS and cost is lower. For currents from about 500 mA to 10's of amps at 10's to 100+ Volts a MOSFET is often easier to use overall. For DC or low frequency switching (say < 1 kHz) direct DC gate drive at typical microcontroller levels is possible with selected parts. As frequencies increase somewhat more complex drivers are required to charge and discharge gate capacitance (typically around NF) in times which are short enough to keep switching losses during transition low enough to be acceptable. In the 10 kHz - 100 kHz range simple drivers of typically 2 or 3 jellybean BJTs suffice. (SO you need 2 or 3 BJTS added if you uses a MOSFET). Specialist driver ICs are available but not usually necessary or cost justified For higher voltages and/or higher frequencies bipolars start to win again. Specialist bipolars exist such as TV line output devices (what's that ? :-) ) which run at around 1 kV with a Beta of about 3 (!!!). As base power ~= Vdrive x Idrive and Vload >>> Vbase it does not overly matter that Ibas ~= Iload. An IGBT is an attempt (usually successful) to run with the hares and hunt with the hounds - it uses a MOSFET input stage to get low drive power and bipolar output stage to get high voltage at high frequency performance. Darlington transistors (two bipolars "in series") (properly, probably, 'Darlington pair') have very high Betas (1000+ common) with the penalty of Vdrive = 2 x Vbe (as opposed to 1 x Vbe for a single BJT) and Vsat > Vbe of the output transistor and a pronounced reluctance to turn off if driven hard into saturation. Limiting base drive to stop saturation slow down further increases Vast_minimum. My favourite Olde time but useful switching regulator the MC34063 includes an amazingly capable output driver which is a Darlington pair. It can be useful but saturation must be avoided at it's massive [tm] ~ 100 kHz full speed, so efficiency suffers at low Vsupply when the Volt + of output saturation significantly detracts from the load drive voltage. A small darlington transistor can be driven from say 1.5V (more better) at usually <= 1 mA per Amp of load. If output saturation is acceptable they can be very useful. The useful and popular ULN200x and ULN280x hex and octal driver ICs use open collector darlingtons, with 500 mA per channel rating (not all at once, ideally). There are a range of input voltage versions and some are suitable for direct processor drive without even a resistor. The ULM2003 and ULN2803 are the best known but not necessarily the most useful in processor drive applications. Considerations include but are certainly not limited to power level, drive voltage, load voltage, available drive level, switching speed, required simplicity, heatsinking, efficiency, manufacturing volume & commercial/hobbyist, cost, ... . At low power levels and modest voltages - say 10's of volts and under 500 mA (and possibly up to a few amps) small bipolars may be a good choice. Drive current is about Iload/Beta (Beta = current gain) and a Beta 0f 100 to 250 at 500 mA is available with better performance parts and 500+ with specialist ones. An eg BC337-400 (my favourite TO92 BJT tipple) has Beta of 250-600 which has sqrt(250 x 600) ~~= 400 hence the part name. The "guaranteed" Beta of 250 (do check the data sheet) allows Iload of 250 mA per mA of drive. With a 2 mA drive - available from most but not all processors - you can get 500 mA load current, although more drive will not go astray. This is achievable with drive voltages of say 1V or more so a processor running on 3V3 or even 2V will probably manage it OK. MOSFETs with low enough Vgsth (gate threshold voltage) can run at these drive voltages but they become rarer and more specialist below a few volts drive. Required minimum drive voltage is usually volt or few above Vgsth (see datasheet in EVERY case). Bipolar have on state voltage drops (Vsat) dependant on load current, drive current & specific device type. A Vsat of a few tenths of a Volt at rated current would be very good, 500 mV probably typical and higher by no means unknown. A MOSFET has an on resistance Rdson rather than Vsat. Rdson is dependant on drive voltage, load current and device (at least). Rdson increases with temperature and may double over ambient temperature values. Take due care - data sheets USUALLY cheat and give Rdson with pulsed loads and say 1% duty cycle and low enough frequency to allow die cooling between pulses. Very naughty. Double published value as a rule of thumb when used 'in anger', although some parts manage say only 20% increase over ambient to max temperature - see datasheet in each case. A bipolar with say 100 mV Vsat at 500 mA has an equivalent resistance of R = V/I = 0.1/0.5 = 200 milliOhms. Tjis figure is very easily bettered by MOSFETS, with Rdson of say 50 milliOhms being common, under 5 milliOhms being reasonably available and under 1 milliOhm being available for people with special needs and bigger wallets. Added: This is a long winded and useful when you need it expansion on 2 points from Andy Aka's answer. @Andy aka in his answer makes two very good points which are missing from my answer above. I concentrated more on switching and load driving aspects. Andy points out (not quite in these words) that: (1) The voltage between input and output on a MOSFET "source follower" is less defined and much more device dependent than with a BJT. When used as an emitter follower where the "reference" voltage is applied to the base and output voltage taken from the emitter, a BJT drops "about" 0.6V dc from base to collector in typical operation. Voltages from as low as about 0.4V and as high as say 0.8V can be expected in extreme designs (very low current or very high). A MOSFET source follower with reference on the gate and output from the source will drop at least Vgsth from gate to source + whatever extra gate voltage is needed to support the current drawn - typically 0.1 to 1 volt more but could be 2V+ in high load or low spec device examples. Vgsth is device dependant and varies from about 0.5V to say 6V+ and is typically 2 to 6V. So the source follower drop may be anything from about 0.5V (rare) to 7V+ (rare). (2) A transistor is a 1 quadrant device (eg NPN = Gate +ve, collector +ve, both wrt emitter for turn on BUT the "undefined" negative Y axis locus (base ZERO, collector negative, tends to be non conductive for a device dependant voltage but "some volts" is usual. A reverse biased MOSFET presents a forward diode substrate diode across the drain source terminals when the MOSFET is off and a good approximation to a small capacitor when the MOSFET is off but forward biased. So, an AC signal more than about 0.8V peak-peak is increasingly clipped on the reverse bias half cycles as voltage is increased. This effect can be overcome by connecting two MOSFETS of the same type in series opposition. Gates connected as Vin, sources connected as floating midpoint, drains as vin and vout either polarity. This arrangement makes for a truly awesome and useful switch and also leads to some head scratching from those who do not realose that a MOSFET is on in quadrants 1 and 3 (For an N Channel FET Quadrant 1 = DS+, SG+. Quadrant 3 = DS- SG+).
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/66006', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/19941/']}
jdg_71826
stackexchange
llm_judgeable_groundtruth_similarity
13958614
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 reliably detect if a device has full internet access, i.e. that the user is not confined to a captive portal (also called walled garden ), i.e. a limited subnet which forces users to submit their credentials on a form in order to get full access. My app is automating the authentication process, and therefore it is important to know that full internet access is not available before starting the logon activity. The question is not about how to check that the network interface is up and in a connected state. It is about making sure the device has unrestricted internet access as opposed to a sandboxed intranet segment. All the approaches I have tried so far are failing, because connecting to any well-known host would not throw an exception but return a valid HTTP 200 response code because all requests are routed to the login page. Here are all the approaches I tried but they all return true instead of false for the reasons explained above: 1: InetAddress.getByName(host).isReachable(TIMEOUT_IN_MILLISECONDS);isConnected = true; <exception not thrown> 2: Socket socket = new Socket();SocketAddress sockaddr = new InetSocketAddress(InetAddress.getByName(host), 80);socket.connect(sockaddr, pingTimeout);isConnected = socket.isConnected(); 3: URL url = new URL(hostUrl));URLConnection urlConn = url.openConnection();HttpURLConnection httpConn = (HttpURLConnection) urlConn;httpConn.setAllowUserInteraction(false);httpConn.setRequestMethod("GET");httpConn.connect();responseCode = httpConn.getResponseCode();isConnected = responseCode == HttpURLConnection.HTTP_OK; So, how do I make sure I connected to an actual host instead of the login redirection page? Obviously, I could check the actual response body from the 'ping' host I use but it does not look like a proper solution. Now provide the response and nothing else.
For reference, here is the 'official' method from the Android 4.0.1 AOSP code base: WifiWatchdogStateMachine.isWalledGardenConnection() . I am including the code below just in case the link breaks in the future. private static final String mWalledGardenUrl = "http://clients3.google.com/generate_204";private static final int WALLED_GARDEN_SOCKET_TIMEOUT_MS = 10000;private boolean isWalledGardenConnection() { HttpURLConnection urlConnection = null; try { URL url = new URL(mWalledGardenUrl); // "http://clients3.google.com/generate_204" urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setInstanceFollowRedirects(false); urlConnection.setConnectTimeout(WALLED_GARDEN_SOCKET_TIMEOUT_MS); urlConnection.setReadTimeout(WALLED_GARDEN_SOCKET_TIMEOUT_MS); urlConnection.setUseCaches(false); urlConnection.getInputStream(); // We got a valid response, but not from the real google return urlConnection.getResponseCode() != 204; } catch (IOException e) { if (DBG) { log("Walled garden check - probably not a portal: exception " + e); } return false; } finally { if (urlConnection != null) { urlConnection.disconnect(); } }} This approach relies on a specific URL, mWalledGardenUrl = "http://clients3.google.com/generate_204" always returning a 204 response code. This will work even if DNS has been interfered with since in that case a 200 code will be returned instead of the expected 204 . I have seen some captive portals spoofing requests to this specific URL in order to prevent the Internet not accessible message on Android devices. Google has a variation of this theme: fetching http://www.google.com/blank.html will return a 200 code with a zero-length response body. So if you get a non-empty body this would be another way to figure out that you are behind a walled garden. Apple has its own URLs for detecting captive portals: when network is up IOS and MacOS devices would connect to an URL like http://www.apple.com/library/test/success.html , http://attwifi.apple.com/library/test/success.html , or http://captive.apple.com/hotspot-detect.html which must return an HTTP status code of 200 and a body containing Success . NOTE :This approach will not work in areas with regionally restricted Internet access such as China where the whole country is a walled garden , and where some Google/Apple services might be blocked. Some of these might not be blocked: http://www.google.cn/generate_204 , http://g.cn/generate_204 , http://gstatic.com/generate_204 or http://connectivitycheck.gstatic.com/generate_204 β€” yet these all belong to google so not guaranteed to work.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13958614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191246/']}
jdg_71827
stackexchange
llm_judgeable_groundtruth_similarity
366025
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: The Problem We have an issue with performance on an existing platform, so I'm turning to the hive mind for a second opinion on this. The performance issue so far relates to IOPS rather than throughput. The Scenario A blade centre of 16 hosts, each with 64GB of RAM. (It's a Dell M1000e w/ M610s, but that's probably not relevant)500 VMs, all web servers (or associated web technologies such as MySQL, load balancers, etc), around 90% are Linux and the rest Windows.Hypervisor is VMWare vSphere.We need to provide host HA, so local storage is out. As such the hosts just have an SD card to boot. A bit of background thinking At the moment we are up to 6 hosts (the blade centre will be at full capacity in a years time at current growth) and we are running iSCSI to a Dell MD3220i w/ MD1220 for expansion. Possible options we have considered, and immediate thoughts along with them: Spreading the VMs across NFS datastores, and running NFS storage that meets performance requirement for up to a given number of VMs. NFS seems cheaper to scale, as well as been abstracted a bit more than block level storage so we can move it around as needed. Adding more MD3220i controllers/targets. We are concerned though that doing this could have a negative effect somehow in how VMWare handles having lots of targets. Swapping all disks from Nearline SAS to SSD. This ought to entirely solve the IOPS issue, but has the obvious side effect of slashing our storage capacity. Also it's still very expensive. vSphere 5 has a storage appliance. We haven't researched this much, but it must work well? The Question What sort of storage would you run underneath all of that? It wouldn't need to scale to another blade centre, it would just need to provide relatively good performance for all of those VMs. I'm not looking for "Buy SAN x because it's the best" answers. I'm looking for thoughts on the various SAN technologies (iSCSI, FC, FCoE, InfiniBand, NFS, etc), different types of storage (SATA, SAS, SSD), and methodologies for handling storage for 100s of VMs (Consolidation, Separation, Sharding, etc). Absolutely any thoughts, links, guides, pointers etc are welcome on this. I'd also love to hear thoughts on the above options we'd already considered. Many thanks in advance for any input! Update 5th March '12 Some fantastic responses so far, thank you very much everyone! Going by the responses to this question so far, I'm beginning to think the following route is the way: Tier the available storage to the VMWare cluster and place VM disks on suitable storage for their workloads. Potentially make use of a SAN that is able to manage the placement of data on to suitable storage automagically. Infiniband looks to be the most cost effective to get the required bandwidth with the hosts at full capacity. It definitely sounds like it would be worth making use of the pre-sales services of a major SAN vendor to get their take on the scenario. I'm going to continue to consider this problem for a while. In the mean time any more advise gratefully received! Now provide the response and nothing else.
The key to a good VMWare storage platform is understanding what kind of load VMWare generates. First, since you host a lot of servers, the workload is typically random. There are many IO streams going at the same time, and not many of them can be successfully pre-cached. Second, it's variable. During normal operations, you may see 70% random reads, however the instant you decide to move a VM to a new datastore or something, you'll see a massive 60GB sequential write. If you're not careful about architecture, this can cripple your storage's ability to handle normal IO. Third, a small portion of your environment will usually generate a large portion of the storage workload. The best way to approach building storage for a VMWare platform is to start with the fundamentals. You need the ability to service a large random read workload, which means smaller faster drives, as well as possibly SSD. Most modern storage systems allow you to move data around automatically depending on how it's accessed. If you are going to use SSD, you want to ensure this is how you use it. It should be there as a way of gradually reducing hot-spots. Whether you use SSD or not, it's beneficial to be able to put all the work across all the drives, so something with a type of storage pooling would be beneficial. You need the ability to service intermittent large writes, which doesn't care as much about the spindle speed of the underlying drives, but does care about the controller stack's efficiency and the size of the cache. If you have mirrored caching (which is not optional unless you're willing to go back to backups whenever you have a controller failure), the bandwidth between the two caches used for mirroring will be your bottleneck for large sequential writes, usually. Ensure that whatever you get has a high speed controller (or cluster) interconnect for write caching. Do your best to get a high speed front end network with as many ports as you can get while remaining realistic on price. The key to good front end performance is to put your storage load across as many front end resources as possible. You can seriously reduce costs by having a tier for low priority storage, as well as thin provisioning. If your system isn't automatically migrating individual blocks to cheap large/slow drives (like nearline SAS or SATA with 7200 RPM and 2TB+ sizes), try to do it manually. Large slow drives are excellent targets for archives, backups, some file systems, and even servers with low usage. Insist that the storage is VAAI integrated so that VMWare can de-allocate unused parts of the VMs as well as the datastores.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/366025', 'https://serverfault.com', 'https://serverfault.com/users/87855/']}
jdg_71828
stackexchange
llm_judgeable_groundtruth_similarity
1173177
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 new to C#, and just started using XmlElement and its SelectSingleNode method. In my XML file there's a tag that may have a value (i.e. <tag>value</tag> ) or be empty (i.e. <tag></tag> ). If it's empty, SelectSingleNode returns null. I'm currently using the following code to catch the value of the tag: XmlElement elem = ....string s = elem.SelectSingleNode("somepath").Value; This code obviously raises an exception for empty tags. However, for me an empty tag is a valid value, where I expect the value of my string to be "". Wrapping each call to SelectSingleNode with try...catch seems a huge waste of code (I have many fields that may be empty), and I'm sure there's a better way to achieve this. What is the recommended approach? EDIT: Following requests, a sample XML code will be: <Elements> <Element> <Name>Value</Name> <Type>Value</Type> <-- may be empty <Color>Value</Color> </Element> <Element> <Name>Value</Name> <Type>Value</Type> <Color>Value</Color> </Element></Elements> The CS code: XmlDocument doc = new XmlDocument();doc.Load("name.xml");foreach (XmlElement elem in doc.SelectNodes("Elements/Element")){ myvalue = elem.SelectSingleNode("Type/text()").Value;} Now provide the response and nothing else.
Your sample code: myvalue = elem.SelectSingleNode("Type/text()").Value; is where the problem is. The XPath expression you've used there doesn't mean "give me text of element Type ". It means "give me all child text nodes of element Type". And an empty element doesn't have any child text nodes (a text node cannot be empty in XPath document model). If you want to get text value of the node, you should use: myvalue = elem.SelectSingleNode("Type").InnerText;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1173177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103532/']}
jdg_71829
stackexchange
llm_judgeable_groundtruth_similarity
4513818
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: Recently I found the inequality : $$\arcsin\left(\frac{9}{10}\right)\cdot\left(\frac{6}{10}\right)!>1$$ I don't ask for a proof . I ask if someone can give some details on the link with the Gamma function and arcsin . I ask also because we have a formula on wiki page for the Gamma's function wich gives an equality with the function $\sin$ . But now why arcsin ? Can we find a infinite series ? I can gives some other terms of the "series" we want : $$\left(\frac{9}{10}\right)\cdot\frac{\left(\frac{6}{10}\right)!\arcsin\left(\left(\frac{99}{100}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{999}{1000}\right)^{\frac{1}{80}}\right)}\frac{\arcsin\left(\left(\frac{9999}{10000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999}{100000}\right)^{\frac{1}{70}}\right)}>1$$ Edit : I gives more terms : $$\arcsin\left(\frac{9}{10}\right)\cdot\frac{\left(\frac{6}{10}\right)!\arcsin\left(\left(\frac{99}{100}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{999}{1000}\right)^{\frac{1}{80}}\right)}\frac{\arcsin\left(\left(\frac{9999}{10000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999}{100000}\right)^{\frac{1}{70}}\right)}\frac{\arcsin\left(\left(\frac{999999}{1000000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{9999999}{10000000}\right)^{\frac{1}{62}}\right)}\frac{\arcsin\left(\left(\frac{99999999}{100000000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{999999999}{1000000000}\right)^{\frac{1}{85}}\right)}\frac{\arcsin\left(\left(\frac{9999999999}{10000000000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999999999}{100000000000}\right)^{\frac{1}{79}}\right)}>1$$ And made a conjecture : Let $a_k>0$ such that : $$\arcsin\left(\frac{9}{10}\right)\cdot\frac{\left(\frac{6}{10}\right)!\arcsin\left(\left(\frac{99}{100}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{999}{1000}\right)^{\frac{1}{a_{k}}}\right)}\frac{\arcsin\left(\left(\frac{9999}{10000}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999}{100000}\right)^{\frac{1}{a_{k+1}}}\right)}\cdot\cdot\cdot\frac{\arcsin\left(\left(\frac{9999\cdot\cdot\cdot9}{1000\cdot\cdot\cdot00}\right)^{\frac{1}{600}}\right)}{\arcsin\left(\left(\frac{99999\cdot\cdot\cdot9}{10000\cdot\cdot\cdot00}\right)^{\frac{1}{a_{m}}}\right)}\cdot\cdot\cdot=1$$ Then I conjecture that for $a_1=80,a_2=70,a_3=62,a_4=85,a_5=79,a_6=61.75$ : $$a_k<100$$ How to (dis)prove it ? Now provide the response and nothing else.
$f \in C^\infty(M)$ means that $f$ is a smooth function $f:M \to \Bbb R$ . Now if we have a vector field $X:M \to TM$ , then we can define $fX:M \to TM$ as follows: for each point $p \in M$ , the space $T_pM$ is a vector space and $X(p)$ lives in that vector space. So we may scale $X(p) \in T_pM$ by the scalar $f(p) \in \Bbb R$ and define $(fX)(p):=f(p)X(p)$ to obtain a smooth map $fX:M \to TM$ such that $(fX)(p) \in T_pM$ for all $p \in M$ , i.e. a vector field. Intuitively, imagine you have at each point of the manifold a direction, i.e. a tangent vector (your $p \mapsto X(p)$ ) and also a scalar ( $p \mapsto f(p)$ ), then you can scale at each point the tangent vector you have by the scalar to obtain a new tangent vector. The notation $X(f)$ denotes the directional derivative of $f$ with respect to $X$ , see this question for an equivalent definition of vector fields that makes this construction clear.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4513818', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/698573/']}
jdg_71830
stackexchange
llm_judgeable_groundtruth_similarity
157745
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Every now and then I read that a severe fire has happened in some datacenter, lots of equipment has been damaged and customers have gone offline. Now I wonder what is there to support and spread fire? I mean walls in a server room usually have little or no finish. Racks are made of metal. Almost all units have metal cases. Cables have (or at least should have) insulation of materials that don't spread fire. What is spreading fire in a server room or datacenter? Now provide the response and nothing else.
Here's a bit of information not generally published and at times even denied - the insulation used in most electronic components will burn and burn rather well once a suitable temperature has been reached. This includes the material circuit boards are made of, as well as the lacquer used to coat most components. Some types of insulation, once lit, will add to the problem by producing gases that themselves are somewhat flammable. Of course they also produce noxious gases that could incapacitate or kill anyone unfortunate enough to breath in too much of it. The insulation on normal (non fire resistant) cables burns extremely well. Even worse, prior to, as well as after, ignition the plastic flows very freely, which helps greatly in the spread of the fire. During a fire some components, such as capacitors, will explode, which further helps to spread the fire by throwing already burning bits around. Once the temperature is nice and high we start to factor in things like paint and other decorative coatings that can be hard to light but burn well once lit. Even powder coating will burn. Far from adding protection from an already lit fire the metal case will add to the fire by providing additional fuel (the paint or other coating) and will help to sustain the fire by retaining heat and feeding it back to the fire.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/157745', 'https://serverfault.com', 'https://serverfault.com/users/101/']}
jdg_71831
stackexchange
llm_judgeable_groundtruth_similarity
15569018
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 don't know how to solve a problem with generic interfaces. Generic interface represents factory for objects: interface IFactory<T>{ // get created object T Get(); } Interface represents factory for computers (Computer class) specyfing general factory: interface IComputerFactory<T> : IFactory<T> where T : Computer{ // get created computer new Computer Get();} Generic interface represents special factory for objects, which are cloneable (implements interface System.ICloneable): interface ISpecialFactory<T> where T : ICloneable, IFactory<T>{ // get created object T Get();} Class represents factory for computers (Computer class) and cloneable objects: class MyFactory<T> : IComputerFactory<Computer>, ISpecialFactory<T>{} I get compiler error messages In MyFactory class: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'exer.ISpecialFactory<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'exer.IFactory<T>'. The type 'T' cannot be used as type parameter 'T' in the generic type or method 'exer.ISpecialFactory<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'System.ICloneable'. Now provide the response and nothing else.
Not sure if this is a typo, but should this: interface ISpecialFactory<T> where T : ICloneable, IFactory<T> have really been interface ISpecialFactory<T> : IFactory<T> where T : ICloneable Really, I think this is probably what you're trying to do: public class Computer : ICloneable{ public object Clone(){ return new Computer(); }}public interface IFactory<T>{ T Get(); }public interface IComputerFactory : IFactory<Computer>{ Computer Get();}public interface ISpecialFactory<T>: IFactory<T> where T : ICloneable{ T Get();}public class MyFactory : IComputerFactory, ISpecialFactory<Computer>{ public Computer Get() { return new Computer(); }} Live example: http://rextester.com/ENLPO67010
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15569018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/968379/']}
jdg_71832
stackexchange
llm_judgeable_groundtruth_similarity
1446094
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Show that there is no rational number $x$ satisfying the equation $x^2-[x]=4$ . Find the roots of the equation $x^2-[x]=4$ where $[x]$ is the greatest integer less than or equal to $x$ . I tried to solve this equation but stuck. For the first part i supposed $x=\frac{p}{q}$ be the solution of the equation. $$\frac{p^2}{q^2}-4=\left[\frac{p}{q}\right]$$ Now LHS is rational and RHS is an integer. Therefore our assumption is wrong. There is contradiction. So its roots are not rational. $x^2-4=[x]\implies (x-2)(x+2)=[x]$ How should i move ahead? Please guide me. Its roots are $-\sqrt2,\sqrt6$ . Is my method of solving the first part correct? Now provide the response and nothing else.
Write $x = [x] + \varepsilon$ . Then you are trying to solve $$n^2 + 2\varepsilon n + \varepsilon^2 - n - 4= 0 $$ For an integer value of $n$ and some $\varepsilon \in [0,1)$ . By the quadratic formula we can express $\varepsilon$ in terms of $n$ , $$\varepsilon^2 + (2n)\varepsilon +[n^2 - n - 4]= 0 $$ $$\varepsilon = \frac{-2n Β± \sqrt{4n^2 - 4(n^2 - n - 4)}}{2} = -n Β± \sqrt{n+4}$$ So now we want to find values of $n$ where $$ -n + \sqrt{n+4} \in [0,1)$$ or $$-n -\sqrt{n+4} \in [0,1)$$ Lets try the first case, i.e. find $n$ such that $-n + \sqrt{n+4} \in [0,1) $ .Both conditions below must hold for a solution: $$ -n + \sqrt{n+4} \geq 0 \quad\text{ and } -n + \sqrt{n+4} < 1\quad$$ We try small values of $n\geq -4$ , $$\begin{array}{c|cccc}n & -4 & -3 & -2 & -1 & 0 & 1 & 2 & 3\\ \hline-n+\sqrt{n+4} & 4 & 4 & 2+\sqrt{2} & 1+\sqrt{3} & 2 & -1+\sqrt{5} & \color{red}{-2+\sqrt{6}} & -3+\sqrt{7}\end{array}$$ There is no need to check $n<-4$ since $\sqrt{n+4}$ won't be defined, and no need to check $n>3$ since the gap only widens. ( $-n + \sqrt{n+4}$ is decreasing for $n>3$ ). so $n=2$ is the only solution for the first case, with $\varepsilon=-2+\sqrt{6}$ and $x=\sqrt{6}$ . Similarly for the second case, we need $$ -n - \sqrt{n+4} \geq 0 \quad\text{ and } -n - \sqrt{n+4} < 1\quad$$ $$\begin{array}{c|cccccc}n & -4 & -3 & -2 & -1 & 0 \\ \hline-n-\sqrt{n+4} & 4 & 2 & \color{red}{2-\sqrt{2}} & 1-\sqrt{3}& -2 \\\end{array}$$ There is no need to check $n\le-4$ or $n>0$ , for similar reasons to the first case. Hence, the only two solutions to the whole problem are $$ x=-\sqrt{2},\sqrt{6}.$$ Regarding the rest of the question as in your edit: Your proof is incomplete. An integer is also rational! If $p/q$ is a solution, then we do indeed get $\frac{p^2}{q^2} - 4 = \left[\frac{p}{q}\right]$ , but this itself is not a contradiction. It only means that $q^2=1$ . Thus the equation reduces to $$p^2 - p - 4 = 0, \quad p\in\Bbb Z$$ But of course the only real solutions to this are $\frac{1Β± \sqrt{1+16}}{2}$ which are not integers.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1446094', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/257841/']}
jdg_71833
stackexchange
llm_judgeable_groundtruth_similarity
25009
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why do the Hs in ( E )-1-bromo-2-chloroethene split into doublets instead of staying as a singlet. Wouldn't they be isolated from each other since the double bond does not rotate? Now provide the response and nothing else.
The hydrogens are not 'isolated' - they are still vicinal protons (3-bonds away) and so the J-coupling between them is strong. The strength of a splitting interaction is primarily determined by the number of bonds in between the hydrogens involved. The angle between them also plays a role but to a lesser extent. The Karplus equation describes the three-bond J-coupling between two protons as a function of their dihedral angle.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/25009', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/402/']}
jdg_71834
stackexchange
llm_judgeable_groundtruth_similarity
42767489
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 plotting multiple dataframes as point plot using seaborn . Also I am plotting all the dataframes on the same axis . How would I add legend to the plot ? My code takes each of the dataframe and plots it one after another on the same figure. Each dataframe has same columns date count2017-01-01 352017-01-02 432017-01-03 122017-01-04 27 My code : f, ax = plt.subplots(1, 1, figsize=figsize)x_col='date'y_col = 'count'sns.pointplot(ax=ax,x=x_col,y=y_col,data=df_1,color='blue')sns.pointplot(ax=ax,x=x_col,y=y_col,data=df_2,color='green')sns.pointplot(ax=ax,x=x_col,y=y_col,data=df_3,color='red') This plots 3 lines on the same plot. However the legend is missing. The documentation does not accept label argument . One workaround that worked was creating a new dataframe and using hue argument . df_1['region'] = 'A'df_2['region'] = 'B'df_3['region'] = 'C'df = pd.concat([df_1,df_2,df_3])sns.pointplot(ax=ax,x=x_col,y=y_col,data=df,hue='region') But I would like to know if there is a way to create a legend for the code that first adds sequentially point plot to the figure and then add a legend. Sample output : Now provide the response and nothing else.
I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated. Instead use matplotlib plot_date . This allows to set labels to the plots and have them automatically put into a legend with ax.legend() . import matplotlib.pyplot as pltimport pandas as pdimport seaborn as snsimport numpy as npdate = pd.date_range("2017-03", freq="M", periods=15)count = np.random.rand(15,4)df1 = pd.DataFrame({"date":date, "count" : count[:,0]})df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})f, ax = plt.subplots(1, 1)x_col='date'y_col = 'count'ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")ax.legend()plt.gcf().autofmt_xdate()plt.show() In case one is still interested in obtaining the legend for pointplots, here a way to go: sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])plt.gcf().autofmt_xdate()plt.show()
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42767489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7491646/']}
jdg_71835
stackexchange
llm_judgeable_groundtruth_similarity
115748
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: What is the best way to simulate ANOVA data for a 2 x 2 design with interaction using a regression approach? I want to generate the data so that I know the true regression coefficients of the model when running lm() in R. lm(A * B, data=df) Thanks in advance Now provide the response and nothing else.
You can simulate this by running your regression equation backwards into R. You equation is $$y = \alpha + \beta_1 A + \beta_2 B + \beta_3 A B + \epsilon$$ where $y$ is the dependant variable, $\alpha$ the intercept, $\beta_n$ your coefficients for your $n$ predictors, in this case, $A$, $B$, and $A*B$ (the interaction), and $\epsilon$ the normally distributed noise, or error. In R: # Set coefficientsalpha = 10beta1 = .3beta2 = -.5beta3 = -1.1# Generate 200 trialsA = c(rep(c(0), 100), rep(c(1), 100)) # '0' 100 times, '1' 100 timesB = rep(c(rep(c(0), 50), rep(c(1), 50)), 2) # '0'x50, '1'x50, '0'x50, '1'x50e = rnorm(200, 0, sd=1) # Random noise, with standard deviation of 1# Generate your data using the regression equationy = alpha + beta1*A + beta2*B + beta3*A*B + e# Join the variables in a data framedata = data.frame(cbind(A, B, y))# Fit an ANOVAmodel = aov(y ~ A*B, data=data)summary(model) Output: Df Sum Sq Mean Sq F value Pr(>F) A 1 0.97 0.97 0.79 0.375336 B 1 63.76 63.76 51.97 1.2e-11 ***A:B 1 15.02 15.02 12.24 0.000577 ***Residuals 196 240.48 1.23 ---Signif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1 Because this is a $2\times2$ ANOVA, we can also fit it as a regression model, revealing thatthe coefficients estimated from the data are close to those we set when simulating it. lin.model = lm(y ~ A*B, data = data)summary(lin.model)Call:lm(formula = y ~ A * B, data = data)Residuals: Min 1Q Median 3Q Max -2.69066 -0.78089 0.00864 0.72583 2.93863 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 9.9081 0.1566 63.251 < 2e-16 ***A 0.4090 0.2215 1.846 0.066386 . B -0.5811 0.2215 -2.623 0.009404 ** A:B -1.0963 0.3133 -3.499 0.000577 ***---Signif. codes: 0 β€˜***’ 0.001 β€˜**’ 0.01 β€˜*’ 0.05 β€˜.’ 0.1 β€˜ ’ 1Residual standard error: 1.108 on 196 degrees of freedomMultiple R-squared: 0.249, Adjusted R-squared: 0.2375 F-statistic: 21.67 on 3 and 196 DF, p-value: 3.67e-12 EDIT In response to your comment, you could generate more complicated designs by specifying them at minimal length (i.e. what the data would look like with one trial per condition), and then use rep on that. # 3x2 balanced designA = c(0,0,0,0,1,1,1,1)B = c(0,0,1,1,0,0,1,1)C = c(0,1,0,1,0,1,0,1)# Repeat 50 times, for N = 200A = rep(A, 50)B = rep(B, 50)C = rep(C, 50)
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/115748', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/24423/']}
jdg_71836
stackexchange
llm_judgeable_groundtruth_similarity
477247
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $\displaystyle A_{5\times 5}$ be an invertible matrix whose sum of each rows equals 1. How can we prove that the sum of all elements of $A^{\displaystyle-1}$ is $5$?. Now provide the response and nothing else.
Let $v=(1,1,1,1,1)$. Note $Av=v$. Deduce $A^{-1}v=v$. What does this say about row sums of $A^{-1}$?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/477247', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91906/']}
jdg_71837
stackexchange
llm_judgeable_groundtruth_similarity
3326023
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 figure out the difference between $a=&$b and $a=$b .I know & make the variable to be a reference variable. But the following test gave me the same result. Can anyone explain the difference? Thanks. $a=5; $b=6; $a=&$b; echo $a; //6 $a=5; $b=6; $a=$b; echo $a; //6 Now provide the response and nothing else.
First of all: you'll hardly ever need references, avoid the confusion of using them if you can. $a=5; //assign value to a$b=&$a; //make $b a reference to $a$b=6; //assigning a value to $b assigns the same value to $a (as they point to the same locationecho $a; //6$a=5; //assign a value to a$b=$a; //set $b to the value of $a$b=6; //set $b to another value leaves $a at it's original valueecho $a; //5
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3326023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/401147/']}
jdg_71838
stackexchange
llm_judgeable_groundtruth_similarity
57570968
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 update my serializers in my drf project to be shown in a nested way. The two models in question are Image and Gallery, images are related to Galleries. I tried following https://www.django-rest-framework.org/api-guide/relations/#nested-relationships , but i am not entirely sure why it is not working. Below is models.py class Gallery(models.Model): title = models.CharField(max_length=30) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True, blank=True) modified_on = models.DateTimeField(auto_now=True, blank=True) def __str__(self): return self.titleclass Image(models.Model): gallery_id = models.ForeignKey(Gallery, on_delete=models.CASCADE) img = models.ImageField(upload_to='images/') created_on = models.DateTimeField(auto_now_add=True, blank=True) serializers.py class ImageSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Image fields = ["gallery_id", "img", "created_on", "id"]class GallerySerializer(serializers.HyperlinkedModelSerializer): image = ImageSerializer(many=True, read_only=True) def validate(self, data): # Check if user id is equal object id before creation or if SuperUser request = self.context.get("request") if request.user.id != data["author"].id and request.user.is_superuser is not True: raise ValidationError("Unauthorized User Post") return data class Meta: model = Gallery fields = ["title", "author", "created_on", "modified_on", "image", "id"] Expecting outcome would be [ { "title": "test_1", "author": "http://127.0.0.1:8000/api/users/2/", "created_on": "2019-08-19T09:13:45.107658Z", "modified_on": "2019-08-19T09:13:45.107731Z", "image": [ { "gallery_id": "http://127.0.0.1:8000/api/galleries/24/", "img": "http://127.0.0.1:8000/media/images/angga-tantama-background-art-minimalism.jpg", "created_on": "2019-08-20T09:17:31.790901Z", "id": 6 }, { "gallery_id": "http://127.0.0.1:8000/api/galleries/24/", "img": "http://127.0.0.1:8000/media/images/art-vector-background-illustration-minimalism-angga-tantam-2.jpg", "created_on": "2019-08-20T09:31:40.505035Z", "id": 7 } ] "id": 24 }, { "title": "test_2", "author": "http://127.0.0.1:8000/api/users/2/", "created_on": "2019-08-20T09:42:09.448974Z", "modified_on": "2019-08-20T09:42:09.449042Z", "id": 27 }] Now provide the response and nothing else.
image = ImageSerializer(many=True, read_only=True, source='image_set') or image_set = ImageSerializer(many=True, read_only=True) # use image_set in fields list too. Let's say you have a Gallery object similar to this: g = Gallery.objects.get(pk=1) Now the queryset for all the images related the given Galley object will be: Image.objects.filter(gallery_id=g) # g is the gallery object In Django we can simplify it as: g.image_set # same as Image.objects.filter(gallery_id=g) Now the thing is where does this magical image_set comes from. In Django ORM if you can use related_name in model's ForeignKey to query related objects, like this: gallery_id = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name='something')# if you do this in your models.py then to get all images of a gallery you will now do:g.something But since you didn't specified related_name in the ForeginKey it defaults to model name all lowercase + _set , therefore in this case: image_set . Here is a link to docs . If you specify two ForeignKey to same model from a model django will ask you to add related_name too (when making migrations), as it can default related name for one fields only. This is called reverse_relationship. forward_relationship will be when you do something like this: img = Image.objects.get(pk=1)img.gallery_id # get the gallery object related to the image This is quite straightforward as gallery_id is a field in your model. Also side note don't name your ForeignKey fields with a trailing _id , it's misleading. img.gallery_id is not the id of the Gallery it's the whole Gallery object. Django saves Related fields with a trailing id in the database, so in your case the column name in your database will be gallery_id_id (most likely, might have been changed in newer version). When querying if your field name is gallery_id : img.gallery_id # the gallery objectimg.gallery_id.id # actual id of the galleryimg.gallery_id_id # actual id of the gallery But if you name your field just gallery : img.gallery # the gallery objectimg.gallery.id # actual id of the galleryimg.gallery_id # actual id of the gallery Which is a lot more clear. So now you know why image_set is an attribute of your model class. And drf looks for model attributes in field names, so you either have your field name same the attribute( image_set ) or specify the attribute using the source argument of the serializer.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57570968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9856515/']}
jdg_71839
stackexchange
llm_judgeable_groundtruth_similarity
48998395
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 the best way to check that we have minimum require version software in bash script.E.g. git 2.16.2 Now provide the response and nothing else.
git provides its version info like this: $ git --versiongit version 2.11.0 GNU sort understands version numbers and can sort them: $ (echo min version 2.16.3; git --version) | sort -Vk3git version 2.11.0min version 2.16.3$ (echo min version 2.9.3; git --version) | sort -Vk3min version 2.9.3git version 2.11.0 We can combine this to make a test: if (echo a version 2.16.3; git --version) | sort -Vk3 | tail -1 | grep -q gitthen echo "Good enough."else echo "Not good"fi
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48998395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8600145/']}
jdg_71840