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
1665250
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 understand what static does, but not why we use it. Is it just for keeping the abstraction layer? Now provide the response and nothing else.
There are a few reasons to use static in C. When used with functions, yes the intention is for creating abstraction. The original term for the scope of a C source code file was "translation unit." The static functions may only be reached from within the same translation unit. These static functions are similar to private methods in C++, liberally interpreted (in that analogy, a translation unit defines a class). Static data at a global level is also not accessible from outside the translation unit, and this is also used for creating an abstraction. Additionally, all static data is initialized to zero, so static may be used to control initialization. Static at the local ("automatic") variable level is used to abstract the implementation of the function which maintains state across calls, but avoids using a variable at translation unit scope. Again, the variables are initialized to zero due to static qualification.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1665250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/183487/']}
jdg_75541
stackexchange
llm_judgeable_groundtruth_similarity
3832552
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 project that builds in 32/64-bit and has corresponding 32/64-bit dependencies. I want to be able to switch configurations and have the correct reference used, but I don't know how to tell Visual Studio to use the architecture-appropriate dependency. Maybe I'm going about this the wrong way, but I want to be able to switch between x86 and x64 in the configuration dropdown, and have the referenced DLL be the right bitness. Now provide the response and nothing else.
Here is what I've done in a previous project, which will require the manual edition of the .csproj file(s). You also need separate directories for the different binaries, ideally siblings of each other, and with the same name as the platform you are targeting. After adding a single platform's references to the project, open the .csproj in a text editor. Before the first <ItemGroup> element within the <Project> element, add the following code, which will help determine which platform you're running (and building) on. <!-- Properties group for Determining 64bit Architecture --><PropertyGroup> <CurrentPlatform>x86</CurrentPlatform> <CurrentPlatform Condition="'$(PROCESSOR_ARCHITECTURE)'=='AMD64' or '$(PROCESSOR_ARCHITEW6432)'=='AMD64'">AMD64</CurrentPlatform></PropertyGroup> Then, for your platform specific references, you make changes such as the following: <ItemGroup> <Reference Include="Leadtools, Version=16.5.0.0, Culture=neutral, PublicKeyToken=9cf889f53ea9b907, processorArchitecture=x86"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\Lib\Leadtools\$(CurrentPlatform)\Leadtools.dll</HintPath> </Reference> <Reference Include="Leadtools.Codecs, Version=16.5.0.0, Culture=neutral, PublicKeyToken=9cf889f53ea9b907, processorArchitecture=x86"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\Lib\Leadtools\$(CurrentPlatform)\Leadtools.Codecs.dll</HintPath> </Reference> <Reference Include="Leadtools.ImageProcessing.Core, Version=16.5.0.0, Culture=neutral, PublicKeyToken=9cf889f53ea9b907, processorArchitecture=x86"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\Lib\Leadtools\$(CurrentPlatform)\Leadtools.ImageProcessing.Core.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data.Entity" /> <!-- Other project references --></ItemGroup> Note the use of the $(CurrentPlatform) property, which we defined above. You could, instead, use conditionals for which assemblies to include for which platform. You could also need to: Replace the $(PROCESSOR_ARCHITEW6432) and $(PROCESSOR_ARCHITECTURE) with $(Platform) to consider ONLY the target platform of the projects Alter the platform determination logic in order to be appropriate to the current machine, so that you're not building/referencing a 64 bit binary to execute on a 32 bit platform. I had this written up originally for an internal Wiki at work, however, I've modified it and posted the full process to my blog , if you are interested in the detailed step-by-step instructions.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3832552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16320/']}
jdg_75542
stackexchange
llm_judgeable_groundtruth_similarity
5866129
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: is it true that RSA encryption only can handle limited payload of data ? ... im confused with the theory ... theoretically there is no note regarding this ... Now provide the response and nothing else.
RSA encrypts a single message which has a length which is somewhat smaller than the modulus. Specifically, the message is first "padded", resulting in a sequence of bytes which is then interpreted as a big integer between 0 and n-1 , where n is the modulus (a part of the public key) -- so the padded message cannot be longer than the modulus, which implies a strict maximum length on the raw message. Specifically, with the most common padding scheme ( PKCS#1 "old-style", aka "v1.5"), the padding adds at least 11 bytes to the message, and the total padded message length must be equal to the modulus length, e.g. 128 bytes for a 1024-bit RSA key. Thus, the maximum message length is 117 bytes. Note that the resulting encrypted message length has the same size than the modulus, so the encryption necessarily expands the message size by at least 11 bytes. The normal way of using RSA for encrypted a big message (say, an e-mail) is to use an hybrid scheme: A random symmetric key K is chosen (a raw sequence of, e.g., 128 to 256 random bits). The big message is symmetrically encrypted with K , using a proper and efficient symmetric encryption scheme such as AES. K is asymmetrically encrypted with RSA. "Splitting" a big message into so many 117-byte blocks, each to be encrypted with RSA, is not normally done, for a variety of reasons: it is difficult to do it right without adding extra weaknesses; each block would be expanded by 11 bytes, implying a non-negligible total message size increase (network bandwidth can be a scarce resource); symmetric encryption is much faster.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5866129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/296231/']}
jdg_75543
stackexchange
llm_judgeable_groundtruth_similarity
2478079
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 understand how the mechanism of Shadowing and Nested function work.For example: let func y = let dup y = y + y let z = dup y let dup y = let dup z = let y = y * z y let z = y y dup z + z;;val func : int -> int> func 3;;val it : int = 12 Can someone explain what happen here? Now provide the response and nothing else.
Your code is equivalent to the following, where I've simply numbered instances of your names to help you visualize how shadowing is occurring. let func y0 = let dup0 y1 = y1 + y1 let z0 = dup0 y0 let dup1 y2 = let dup2 z1 = let y3 = y2 * z1 y3 let z2 = y2 y2 dup1 z0 + z0 This can be further simplified, of course. Since dup2 and z2 are never used, dup1 is equivalent to let dup1 y2 = y2 , and the whole function is equivalent to let func y0 = let dup0 y1 = y1 + y1 let z0 = dup0 y0 dup1 z0 + z0 Which is equivalent to let func y0 = let z0 = y0 + y0 z0 + z0 by substitution. This is the same as let func y0 = 4 * y0 Does this help?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2478079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/284813/']}
jdg_75544
stackexchange
llm_judgeable_groundtruth_similarity
3728054
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We have a website that has all its PHP/HTML/JS/CSS/etc files stored in a Git repository. We currently have 3 types of computers (or use cases) for the repository. Local developer: pull latest changes, make changes, commit to local repo, push to master server Master server: central repository, all changes get pushed to the master server Web server: changes are pulled down from the master server when deploying the website So currently we: local: git push origin masterlocal: password: ********local: ssh [email protected]: password: ********webserver: cd ~/domain.example/webserver: git pull origin master So my question is: is there a way that from my local computer I can push straight to the web server? ie. local: git push origin masterlocal: password: ********local: git push webserver masterlocal: password: ******** Now provide the response and nothing else.
Yes you can push directly to your webserver, but I wouldn't recommend it since you should only push to repositories cloned with the --bare argument. I'd utilize the Git hook system to let the main repository automatically update the repo on the web server. Check out the post-update hook in: http://git-scm.com/docs/githooks This script could in turn login to the web server via SSH and do cd ~/example.com/git checkout mastergit pull origin master This way you only need to focus on pushing to the central server and don't have to care about the web server, it will always be updated once a push has been made. If you can automate something, then automate it :) I even found a nice article for you about logging in via SSH in a script (if you must use password, this is trivial if a ssh-key has been setup): http://bash.cyberciti.biz/security/expect-ssh-login-script/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3728054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/268074/']}
jdg_75545
stackexchange
llm_judgeable_groundtruth_similarity
24479310
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there are difference between random() * random() and random() ** 2 ? random() returns a value between 0 and 1 from a uniform distribution. When testing both versions of random square numbers I noticed a little difference. I created 100000 random square numbers and counted how many numbers are in each interval of 0.01 (0.00 to 0.01, 0.01 to 0.02, ...). It seems that these versions of squared random number generation are different. Squaring a random number instead of multiplying two random numbers has you reuse a random number, but I think the distribution should remain the same. Is there really a difference? If not, why is my test showing a difference? I generate two random binned distributions for random() * random() and one for random() ** 2 like so: from random import randomlst = [0 for i in range(100)]lst2, lst3 = list(lst), list(lst)#create two random distributions for random() * random()for i in range(100000): lst[int(100 * random() * random())] += 1for i in range(100000): lst2[int(100 * random() * random())] += 1for i in range(100000): lst3[int(100 * random() ** 2)] += 1 which gives >>> lst[ 5626, 4139, 3705, 3348, 3085, 2933, 2725, 2539, 2449, 2413, 2259, 2179, 2116, 2062, 1961, 1827, 1754, 1743, 1719, 1753, 1522, 1543, 1513, 1361, 1372, 1290, 1336, 1274, 1219, 1178, 1139, 1147, 1109, 1163, 1060, 1022, 1007, 952, 984, 957, 906, 900, 843, 883, 802, 801, 710, 752, 705, 729, 654, 668, 628, 633, 615, 600, 566, 551, 532, 541, 511, 493, 465, 503, 450, 394, 405, 405, 404, 332, 369, 369, 332, 316, 272, 284, 315, 257, 224, 230, 221, 175, 209, 188, 162, 156, 159, 114, 131, 124, 96, 94, 80, 73, 54, 45, 43, 23, 18, 3]>>> lst2[ 5548, 4218, 3604, 3237, 3082, 2921, 2872, 2570, 2479, 2392, 2296, 2205, 2113, 1990, 1901, 1814, 1801, 1714, 1660, 1591, 1631, 1523, 1491, 1505, 1385, 1329, 1275, 1308, 1324, 1207, 1209, 1208, 1117, 1136, 1015, 1080, 1001, 993, 958, 948, 903, 843, 843, 849, 801, 799, 748, 729, 705, 660, 701, 689, 676, 656, 632, 581, 564, 537, 517, 525, 483, 478, 473, 494, 457, 422, 412, 390, 384, 352, 350, 323, 322, 308, 304, 275, 272, 256, 246, 265, 227, 204, 171, 191, 191, 136, 145, 136, 108, 117, 93, 83, 74, 77, 55, 38, 32, 25, 21, 1]>>> lst3[ 10047, 4198, 3214, 2696, 2369, 2117, 2010, 1869, 1752, 1653, 1552, 1416, 1405, 1377, 1328, 1293, 1252, 1245, 1121, 1146, 1047, 1051, 1123, 1100, 951, 948, 967, 933, 939, 925, 940, 893, 929, 874, 824, 843, 868, 800, 844, 822, 746, 733, 808, 734, 740, 682, 713, 681, 675, 686, 689, 730, 707, 677, 645, 661, 645, 651, 649, 672, 679, 593, 585, 622, 611, 636, 543, 571, 594, 593, 629, 624, 593, 567, 584, 585, 610, 549, 553, 574, 547, 583, 582, 553, 536, 512, 498, 562, 536, 523, 553, 485, 503, 502, 518, 554, 485, 482, 470, 516] The expected random error is the difference in the first two: [ 78, 79, 101, 111, 3, 12, 147, 31, 30, 21, 37, 26, 3, 72, 60, 13, 47, 29, 59, 162, 109, 20, 22, 144, 13, 39, 61, 34, 105, 29, 70, 61, 8, 27, 45, 58, 6, 41, 26, 9, 3, 57, 0, 34, 1, 2, 38, 23, 0, 69, 47, 21, 48, 23, 17, 19, 2, 14, 15, 16, 28, 15, 8, 9, 7, 28, 7, 15, 20, 20, 19, 46, 10, 8, 32, 9, 43, 1, 22, 35, 6, 29, 38, 3, 29, 20, 14, 22, 23, 7, 3, 11, 6, 4, 1, 7, 11, 2, 3, 2] But the difference between the first and third is much larger, hinting that the distributions are different: [ 4421, 59, 491, 652, 716, 816, 715, 670, 697, 760, 707, 763, 711, 685, 633, 534, 502, 498, 598, 607, 475, 492, 390, 261, 421, 342, 369, 341, 280, 253, 199, 254, 180, 289, 236, 179, 139, 152, 140, 135, 160, 167, 35, 149, 62, 119, 3, 71, 30, 43, 35, 62, 79, 44, 30, 61, 79, 100, 117, 131, 168, 100, 120, 119, 161, 242, 138, 166, 190, 261, 260, 255, 261, 251, 312, 301, 295, 292, 329, 344, 326, 408, 373, 365, 374, 356, 339, 448, 405, 399, 457, 391, 423, 429, 464, 509, 442, 459, 452, 513] Now provide the response and nothing else.
Here are some plots: All the possibilities for random() * random() : The x-axis is one random variable increasing rightwards, and the y-axis is another increasing upwards. You can see that if either is low, the result will be low, and both have to be high to get a high result. When the only decider is a single axis, as in the random() ** 2 case, you get In this it is far more likely to get a very dark (large) value, as the whole top is dark, not just a corner. When you make both linearized, with random() * random() on top: You see that the distributions are indeed different. Code: import numpyimport matplotlibfrom matplotlib import pyplotimport matplotlib.cmdef make_fig(name, data): figure = matplotlib.pyplot.figure() print(data.shape) figure.set_size_inches(data.shape[1]//100, data.shape[0]//100) axes = matplotlib.pyplot.Axes(figure, [0, 0, 1, 1]) axes.set_axis_off() figure.add_axes(axes) axes.imshow(data, origin="lower", cmap=matplotlib.cm.Greys, aspect="auto") figure.savefig(name, dpi=200)xs, ys = numpy.mgrid[:1000, :1000]two_random = xs * ysmake_fig("two_random.png", two_random)two_random_flat = two_random.flatten()two_random_flat.sort()two_random_flat = two_random_flat[::1000]make_fig("two_random_1D.png", numpy.tile(two_random_flat, (100, 1)))one_random = xs * xsmake_fig("one_random.png", one_random)one_random_flat = one_random.flatten()one_random_flat.sort()one_random_flat = one_random_flat[::1000]make_fig("one_random_1D.png", numpy.tile(one_random_flat, (100, 1))) You can also approach this mathematically. The probability of getting a value less than x , with 0 ≤ x ≤ 1 is For random()² : √x as the probability the random value being lower than x is the probability that random()² < x . For random() · random() : Given the first random variable is r and the second is R , we can find the probability that Rr < x with a fixed R : P(Rr < x)= P(r < x/R)= 1 if x > R (and so x/R > 1)or= x/R otherwise So we want ∫ P(Rr < x) dR from R=0 to R=1= ∫ 1 dR from R=0 to R=x+ ∫ x/R dR from R=x to R=1= x(1 - ln R) As we can see, √x ≠ x(1 - ln R) . These distributions show up as: The y-axis gives the probability that the line ( random()² or random() · random() ) is less than the x axis. We see that for the random() · random() , the probability of large numbers is significantly less. Density functions I guess the most revealing thing is to differentiate ( ½x ^ -½ and - ln x ) and plot the probability density functions: This shows the probability of each x in relative terms. So the probability that x is large ( > 0.5 ) is about twice for the random()² variant.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24479310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2886364/']}
jdg_75546
stackexchange
llm_judgeable_groundtruth_similarity
2168581
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: $$\int\limits_0^1 \frac{x^{1-\alpha} (1-x)^\alpha}{(1+x)^3} \, dx $$ After the substitution $z=\frac{1}{x} - 1$, I've got this: $$\int\limits_0^\infty \left(\frac{1}{z}-1\right)^\alpha\left(\frac{1}{z}+1\right)^{-3} dz $$ But it is still far from the Beta function. Now provide the response and nothing else.
The key is the linear-fractional transformation, $$x\mapsto\frac{1-t}{1+t}.$$ Then $1-x=\frac{2t}{1+t}$ and $1+x=\frac{2}{1+t}$, and we find $$\begin{align}\int_{0}^{1}\frac{x^{1-a}\left(1-x\right)^{a}}{\left(1+x\right)^{3}}\,\mathrm{d}x&=\frac12\int_{1}^{0}\left(\frac{1-x}{x}\right)^{a}\frac{x}{1+x}\cdot\frac{\left(-2\right)}{\left(1+x\right)^{2}}\,\mathrm{d}x\\&=\frac12\int_{0}^{1}\left(\frac{2t}{1-t}\right)^{a}\frac{1-t}{2}\,\mathrm{d}t;~~~\small{\left[x=\frac{1-t}{1+t}\right]}\\&=\frac{1}{2^{2-a}}\int_{0}^{1}t^{a}\left(1-t\right)^{1-a}\,\mathrm{d}t\\&=\frac{1}{2^{2-a}}\operatorname{B}{\left(1+a,2-a\right)}.\blacksquare\\\end{align}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2168581', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/421169/']}
jdg_75547
stackexchange
llm_judgeable_groundtruth_similarity
672771
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I wish to extracted out elapsedTime attribute values from the file. Records look {"realm":"/test","transactionId":"9e26c614","elapsedTime":17,"elapsedTimeUnits":"MILLISECONDS","_id":"9e26c6asdasd"} The file I am having is in gb's and I want to get the values greater than 10000. I tried to grep but due to colon grep is not working. grep -wo --color 'elapsedTime' fileName -> this just prints attribute namesgrep -w --color "elapsedTime" fileName -> this just highlights the attribute. Now provide the response and nothing else.
The data is JSON format so it's best to use a parser that understands this format. This will pick out the elapsedTime value from the JSON in the file /tmp/data jq .elapsedTime /tmp/data17 This will pick out only those values larger than 10000 jq '.elapsedTime | select(. > 10000)' /tmp/data If you really cannot use jq then a sed|awk construct can be considered. However, this requires that there must be only one elapsedTime label and associated value per line. There may be other caveats and I really do not recommend it, but if you're desperate here it is, sed -En 's/^.*"elapsedTime":\s*"?([0-9]+).*$/\1/p' /tmp/data | awk '$1 > 10000' In response to a follow-up question ( comment ), to pick out two elements you need to filter on a single element from the object, and then display the required elements: jq -r 'select (.elapsedTime > 10000) | [ .elapsedTime, .transactionId ] | @tsv ' /tmp/data
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/672771', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/333713/']}
jdg_75548
stackexchange
llm_judgeable_groundtruth_similarity
11965515
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 the title, I'd like to know how to define a vectorized function in R. Is it just by using a loop in the function? Is this method efficient? And what's the best practice ? Now provide the response and nothing else.
A loop at the R level is not vectorized . An R loop will be calling the same R code for each element of a vector, which will be inefficient. Vectorized functions usually refer to those that take a vector and operate on the entire vector in an efficient way. Ultimately this will involve some form of loop, but as that loop is being performed in a low-level language such as C it can be highly efficient and tailored to the particular task. Consider this silly function to add pairwise the elements of two vectors sillyplus <- function(x, y) { out <- numeric(length = length(x)) for(i in seq_along(x)) { out[i] <- x[i] + y[i] } out} It gives the right result R> sillyplus(1:10, 1:10) [1] 2 4 6 8 10 12 14 16 18 20 and is vectorised in the sense that it can operate on entire vectors at once, but it is not vectorised in the sense I describe above because it is exceptionally inefficient. + is vectorised at the C level in R so we really only need 1:10 + 1:10 , not an explicit loop in R. The usual way to write a vectorised function is to use existing R functions that are already vectorised. If you want to start from scratch and the thing you want to do with the function doesn't exist as a vectorised function in R (odd, but possible) then you will need to get your hands dirty and write the guts of the function in C and prepare a little wrapper in R to call the C function you wrote with the vector of data you want it to work on. There are ways with functions like Vectorize() to fake vectorisation for R functions that are not vectorised. C is not the only option here, FORTRAN is a possibility as is C++ and, thanks to Dirk Eddelbuettel & Romain Francois, the latter is much easier to do now with the Rcpp package.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11965515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/243755/']}
jdg_75549
stackexchange
llm_judgeable_groundtruth_similarity
10352442
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been looking at the std::nth_element algorithm which apparently: Rearranges the elements in the range [first,last), in such a way that the element at the resulting nth position is the element that would be in that position in a sorted sequence, with none of the elements preceding it being greater and none of the elements following it smaller than it. Neither the elements preceding it nor the elements following it are guaranteed to be ordered. However, with my compiler, running the following: vector<int> myvector; srand(GetTickCount()); // set some values: for ( int i = 0; i < 10; i++ ) myvector.push_back(rand()); // nth_element around the 4th element nth_element (myvector.begin(), myvector.begin()+4, myvector.end()); // print results for (auto it=myvector.begin(); it!=myvector.end(); ++it) cout << " " << *it; cout << endl; Always returns a completely sorted list of integers in exactly the same way as std::sort does. Am I missing something? What is this algorithm useful for? EDIT : Ok the following example using a much larger set shows that there is quite a difference: vector<int> myvector; srand(GetTickCount()); // set some values: for ( int i = 0; i < RAND_MAX; i++ ) myvector.push_back(rand()); // nth_element around the 4th element nth_element (myvector.begin(), myvector.begin()+rand(), myvector.end()); vector<int> copy = myvector; std::sort(myvector.begin(), myvector.end()); cout << (myvector == copy ? "true" : "false") << endl; Now provide the response and nothing else.
It's perfectly valid for std::nth_element to sort the entire range for fulfilling the documented semantic - however, doing so will fail at meeting the required complexity (linear). The key point is that it may do so, but it doesn't have to . This means that std::nth_element can bail out early - as soon as it can tell what the n'th element of your range is going to be, it can stop. For instance, for a range [9,3,6,2,1,7,8,5,4,0] asking it to give you the fourth element may yield something like [2,0,1,3,8,5,6,9,7,4] The list was partially sorted, just good enough to be able to tell that the fourth element in order will be 3 . Hence, if you want to answer 'which number is the fourth-smallest' or 'which are the four smallest' numbers then std::nth_element is your friend. If you want to get the four smallest numbers in order you may want to consider using std::partial_sort .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10352442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193128/']}
jdg_75550
stackexchange
llm_judgeable_groundtruth_similarity
485
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What would you say would be the advantages/disadvantages of two approaches to coding a general (finite volume, fem, dg) library for Computational Continuum Mechanics? This is how I see things right now, so please provide your own experiences and don't flame me for mine :) : 1) C++: generic programming, virtual functions, overloading, speed... : all the genreic + OOP tools available to build whatever you want low level libraries available mostly (no wide spread science&engineering library development such as the one for Python) 2) Python + wrappers for parallel computing (pyOpenCL and others) huge amount of supporting libs of various kinds code what you think: the implementation is done really fast slower execution time If you wanted to code a framework that would support various methods, work with complex geometries and problems, what would you choose and why? Now provide the response and nothing else.
I would aim to get the best of both worlds and code the "user interface" (that is, the framework of functions that the user of your library will call to describe the geometry and other properties of the problem) in Python to get the quick turnaround time, then write the simulation run time in C++. In fact, I would probably mock even the simulation run time up in Python first, then replace it by C++ code piece by piece. Eventually you could consider having your Python code generate C++ source, to be compiled and linked to your runtime online, so that the actual simulation doesn't need to call into Python at all - only return the results at the end. The nice thing about this setup is that it's inherently agile: you start with the quickest and easiest working solution, you'll find out quickly what works and doesn't work, and once you have something you like you can start speeding it up. (This is how Maple's ODE/DAE solver works, except using Maple instead of Python. Full disclosure: I work for them.)
{}
{'log_upvote_score': 5, 'links': ['https://scicomp.stackexchange.com/questions/485', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/383/']}
jdg_75551
stackexchange
llm_judgeable_groundtruth_similarity
3634529
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 is new/override required on abstract methods but not on virtual methods? Sample 1: abstract class ShapesClass{ abstract public int Area(); // abstract!}class Square : ShapesClass{ int x, y; public int Area() // Error: missing 'override' or 'new' { return x * y; }} The compiler will show this error: To make the current member override that implementation, add the override keyword. Otherwise add the new keyword Sample 2: class ShapesClass{ virtual public int Area() { return 0; } // it is virtual now!}class Square : ShapesClass{ int x, y; public int Area() // no explicit 'override' or 'new' required { return x * y; }} This will compile fine, by hiding the method by default. I fully understand the technical differences. However I wonder why the language was designed that way. Wouldn't it be better to have the same restriction in "Sample 2" as well? I mean in most cases if you create a method with the same name as in the parent class, you usually intent to override it. So I think explicitly stating Override/New would make sense on virtual methods as well. Is there a design-wise reason for this behavior? Update: The 2nd sample actually causes a warning. The first sample shows an error because the subclass is required to implement the abstract method. I didn't see the warning in VS.. makes perfectly sense to me now. Thanks. Now provide the response and nothing else.
Using either the C# 3.0 compiler as shipped in .NET 3.5 SP1, or the C# 4.0 compiler as shipped in .NET 4.0, I get the following error for your first example: error CS0534: 'ConsoleApplication3.Square' does not implement inherited abstract member 'ConsoleApplication3.ShapesClass.Area()' And the following warning for the second one: warning CS0114: 'ConsoleApplication3.Square.Area()' hides inherited member 'ConsoleApplication3.ShapesClass.Area()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. In the first case it's an error because you aren't actually overriding the base method, which means there is no implementation for the abstract method in a concrete class. In the second case it's a warning because the code is technically correct, but the compiler suspects that it isn't what you meant. This is one of the reasons it's generally a good idea to enable the "treat warnings as errors" compilation setting. So I can't repro your behaviour, and the behaviour of the compiler looks right to me. Which version of the compiler are you using?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3634529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50430/']}
jdg_75552
stackexchange
llm_judgeable_groundtruth_similarity
518097
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: We see that all the natural systems aspire for minimum potential energy state and we also see that all the natural systems also aspire for maximum entropy state. Now from this understanding it seems that entropy is inversely proportional to potential energy. All the systems aspire for minimum potential energy and maximum entropy. It seems like the concept of potential energy itself and in isolation sufficient to explain all the phenomena which we explain with the help of concept of Entropy, so why do we need an extra concept of Entropy when the concept of potential energy can serve all the purposes? Can we completely define concept of Entropy in terms of concept of potential energy? What extra knowledge the concept of Entropy serves us in addition to the concept of potential energy? Now provide the response and nothing else.
We see that all the natural systems aspire for minimum potential energy state This is not true. For example, the earth's minimum potential energy state would be a state in which it was inside the sun. What extra knowledge the concept of Entropy serves us in addition to the concept of potential energy? The concrete sidewalk in front of my house was wet when it was first poured. Then the concrete dried and hardened. When it rains, the concrete doesn't reverse the chemical reaction and become soft again, nor will it do so even if I apply some heat, although it would be consistent with conservation of energy if it did so. We need the second law of thermodynamics to explain why this doesn't happen.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/518097', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/185612/']}
jdg_75553
stackexchange
llm_judgeable_groundtruth_similarity
28773342
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 pandas.DataFrame called df which has an automatically generated index, with a column dt : df['dt'].dtype, df['dt'][0]# (dtype('<M8[ns]'), Timestamp('2014-10-01 10:02:45')) What I'd like to do is create a new column truncated to hour precision. I'm currently using: df['dt2'] = df['dt'].apply(lambda L: datetime(L.year, L.month, L.day, L.hour)) This works, so that's fine. However, I've an inkling there's some nice way using pandas.tseries.offsets or creating a DatetimeIndex or similar. So if possible, is there some pandas wizardry to do this? Now provide the response and nothing else.
In pandas 0.18.0 and later, there are datetime floor , ceil and round methods to round timestamps to a given fixed precision/frequency. To round down to hour precision, you can use: >>> df['dt2'] = df['dt'].dt.floor('h')>>> df dt dt20 2014-10-01 10:02:45 2014-10-01 10:00:001 2014-10-01 13:08:17 2014-10-01 13:00:002 2014-10-01 17:39:24 2014-10-01 17:00:00 Here's another alternative to truncate the timestamps. Unlike floor , it supports truncating to a precision such as year or month. You can temporarily adjust the precision unit of the underlying NumPy datetime64 datatype, changing it from [ns] to [h] : df['dt'].values.astype('<M8[h]') This truncates everything to hour precision. For example: >>> df dt0 2014-10-01 10:02:451 2014-10-01 13:08:172 2014-10-01 17:39:24>>> df['dt2'] = df['dt'].values.astype('<M8[h]')>>> df dt dt20 2014-10-01 10:02:45 2014-10-01 10:00:001 2014-10-01 13:08:17 2014-10-01 13:00:002 2014-10-01 17:39:24 2014-10-01 17:00:00>>> df.dtypesdt datetime64[ns]dt2 datetime64[ns] The same method should work for any other unit: months 'M' , minutes 'm' , and so on: Keep up to year: '<M8[Y]' Keep up to month: '<M8[M]' Keep up to day: '<M8[D]' Keep up to minute: '<M8[m]' Keep up to second: '<M8[s]'
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28773342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1252759/']}
jdg_75554
stackexchange
llm_judgeable_groundtruth_similarity
49387699
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 sentence for which i need to identify the Person names alone: For example: sentence = "Larry Page is an American business magnate and computer scientist who is the co-founder of Google, alongside Sergey Brin" I have used the below code to identify the NERs. from nltk import word_tokenize, pos_tag, ne_chunkprint(ne_chunk(pos_tag(word_tokenize(sentence)))) The output i received was: (S (PERSON Larry/NNP) (ORGANIZATION Page/NNP) is/VBZ an/DT (GPE American/JJ) business/NN magnate/NN and/CC computer/NN scientist/NN who/WP is/VBZ the/DT co-founder/NN of/IN (GPE Google/NNP) ,/, alongside/RB (PERSON Sergey/NNP Brin/NNP)) I want to extract all the person names, such as Larry PageSergey Brin In order to achieve this, I refereed this link and tried this. from nltk.tag.stanford import StanfordNERTaggerst = StanfordNERTagger('/usr/share/stanford-ner/classifiers/english.all.3class.distsim.crf.ser.gz','/usr/share/stanford-ner/stanford-ner.jar') However i continue to get this error: LookupError: Could not find stanford-ner.jar jar file at /usr/share/stanford-ner/stanford-ner.jar Where can i download this file? As informed above, the result that i am expecting in the form of list or dictionary is : Larry PageSergey Brin Now provide the response and nothing else.
In Long Please read these carefully : https://stackoverflow.com/a/49345866/610569 Extract list of Persons and Organizations using Stanford NER Tagger in NLTK Understand the solution, don't just copy and paste. TL;DR In terminal: pip install -U nltkwget http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zipunzip stanford-corenlp-full-2016-10-31.zip && cd stanford-corenlp-full-2016-10-31java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer \-preload tokenize,ssplit,pos,lemma,parse,depparse \-status_port 9000 -port 9000 -timeout 15000 In Python from nltk.tag.stanford import CoreNLPNERTaggerdef get_continuous_chunks(tagged_sent): continuous_chunk = [] current_chunk = [] for token, tag in tagged_sent: if tag != "O": current_chunk.append((token, tag)) else: if current_chunk: # if the current chunk is not empty continuous_chunk.append(current_chunk) current_chunk = [] # Flush the final current_chunk into the continuous_chunk, if any. if current_chunk: continuous_chunk.append(current_chunk) return continuous_chunkstner = CoreNLPNERTagger()tagged_sent = stner.tag('Rami Eid is studying at Stony Brook University in NY'.split())named_entities = get_continuous_chunks(tagged_sent)named_entities_str_tag = [(" ".join([token for token, tag in ne]), ne[0][1]) for ne in named_entities]print(named_entities_str_tag) [out]: [('Rami Eid', 'PERSON'), ('Stony Brook University', 'ORGANIZATION'), ('NY', 'LOCATION')] You might find this help too: Unpacking a list / tuple of pairs into two lists / tuples
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49387699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8241998/']}
jdg_75555
stackexchange
llm_judgeable_groundtruth_similarity
425399
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following data ( prop is like empirical CDF): td <- data.frame(a = 3:14, prop=c(0, 0, 0.026, 0.143, 0.21, 0.361, 0.535, 0.719, 0.814, 0.874, 0.950, 0.964)) I want to fit a normal CDF using an appropriate mean and standard deviation. How can I find such a mean and a standard deviation value that fits the data above? mean <- 8.8 # <-- How can I find a best fitting number?sd <- 2.3 # <-- How can I find a best fitting number?x <- seq(from = 2, to = 15, by = .1)cdf <- data.frame(x = x, y = pnorm(q = x, mean = mean, sd = sd))library(ggplot2)ggplot(data = td, aes(x = a, y = prop)) + geom_point() + geom_line(data = cdf, aes(x = x, y = y)) EDIT: The motivation behind this question is to replicate a graph I saw on a book. The book used the same proportions and fitted the normal ogive to the data. It looks like normal ogive fitted so well and I couldn't replicate it. There is no way the author used the raw data because the data is from a 100 years old book and the author's book published about 17 years ago. Here is the graph with its caption: Caption : "Proportions correct on item 46, plotted against age, with a fitted normal ogive." Now provide the response and nothing else.
Edit @JarleTufto is right to suggest a binomial glm with a probit link. library(ggplot2)dat <- data.frame(a = 3:14, prop=c(0, 0, 0.026, 0.143, 0.21, 0.361, 0.535, 0.719, 0.814, 0.874, 0.950, 0.964))mod <- glm(prop~a, family = binomial(link = "probit"), data = dat)xx <- seq(min(dat $a), max(dat$ a), length.out = 1000)pred_frame <- data.frame(a = xx)pred_frame$fitted <- predict(mod, newdata = pred_frame, type = "response") theme_set(theme_bw())ggplot(data = dat, aes(x = a, y = prop)) + geom_point(size = 3) + geom_line(data = pred_frame, aes(x = a, y = fitted), size = 1, colour = "steelblue") Original answer I mean you could just minimze the sum of squared residuals (least square fit). The best fitting normal distribution has a mean of $8.826$ and a standard deviation of $2.396$ . The R code: library(ggplot2)dat <- data.frame(a = 3:14, prop=c(0, 0, 0.026, 0.143, 0.21, 0.361, 0.535, 0.719, 0.814, 0.874, 0.950, 0.964))foo <- function(parms, x, y) { sum((pnorm(x, mean = parms[1], sd = parms[2]) - y)^2)}fit <- optim(c(8, 2), fn = foo, x = dat $a, y = dat$ prop)$par[1] 8.826028 2.396412xx <- seq(min(dat $a), max(dat$ a), length.out = 1000)fitted <- pnorm(xx, fit $par[1], fit$ par[2])dat2 <- data.frame(a = xx, prop = fitted)theme_set(theme_bw())ggplot(data = dat, aes(x = a, y = prop)) + geom_point(size = 3) + geom_line(data = dat2, size = 1, colour = "steelblue") I'm unsure if that makes much sense, though.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/425399', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/41166/']}
jdg_75556
stackexchange
llm_judgeable_groundtruth_similarity
7251714
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know that the C# Random class does not make "true random" numbers, but I'm coming up with an issue with this code: public void autoAttack(enemy theEnemy) { //Gets the random number float damage = randomNumber((int)(strength * 1.5), (int)(strength * 2.5)); //Reduces the damage by the enemy's armor damage *= (100 / (100 + theEnemy.armor)); //Tells the user how much damage they did Console.WriteLine("You attack the enemy for {0} damage", (int)damage); //Deals the actual damage theEnemy.health -= (int)damage; //Tells the user how much health the enemy has left Console.WriteLine("The enemy has {0} health left", theEnemy.health); } I then call the function here (I called it 5 times for the sake of checking if the numbers were random): if (thePlayer.input == "fight") { Console.WriteLine("you want to fight"); thePlayer.autoAttack(enemy1); thePlayer.autoAttack(enemy1); thePlayer.autoAttack(enemy1); } However, when I check the output, I get the exact same number for each 3 function calls. However, each time I run the program, I get a different number (which repeats 3 times) like this: You attack the enemy for 30 damage. The enemy has 70 health left. You attack the enemy for 30 damage. The enemy has 40 health left. You attack the enemy for 30 damage. The enemy has 10 health left. I will then rebuild/debug/run the program again, and get a different number instead of 30, but it will repeat all 3 times. My question is: how can I make sure to get a different random number each time I call this function? I am just getting the same "random" number over and over again. Here is the random class call that I used: private int randomNumber(int min, int max) { Random random = new Random(); return random.Next(min, max); } Now provide the response and nothing else.
My guess is that randomNumber creates a new instance of Random each time... which in turn creates a new pseudo-random number generator based on the current time... which doesn't change as often as you might think. Don't do that. Use the same instance of Random repeatedly... but don't "fix" it by creating a static Random variable. That won't work well either in the long term, as Random isn't thread-safe. It will all look fine in testing, then you'll mysteriously get all zeroes back after you happen to get unlucky with concurrency :( Fortunately it's not too hard to get something working using thread-locals, particularly if you're on .NET 4. You end up with a new instance of Random per thread. I've written an article on this very topic which you may find useful, including this code: using System;using System.Threading;public static class RandomProvider{ private static int seed = Environment.TickCount; private static ThreadLocal<Random> randomWrapper = new ThreadLocal<Random> (() => new Random(Interlocked.Increment(ref seed))); public static Random GetThreadRandom() { return randomWrapper.Value; }} If you change your new Random() call to RandomProvider.GetThreadRandom() that will probably do everything you need (again, assuming .NET 4). That doesn't address testability, but one step at a time...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7251714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/920787/']}
jdg_75557
stackexchange
llm_judgeable_groundtruth_similarity
10007786
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 building a Backbone app and I need to have automated tests. I prefer not to use selenium for automated testing. I am looking into Jasmine and Cucumber.js. I think Jasmine might be better but in the company I work they use cucumber for the server side testing and I am investigating if cucumber.js can be used for production. Any suggestions? Now provide the response and nothing else.
Cucumber.js is quite stable and ready to be used in production. It lacks a few advanced features compared to Cucumber ruby, like scenario outlines and (now available) transforms, though. See the README for the development status table. It can be used with Zombie.js, Phantom.js, Selenium and even within browsers. Virtually, you can use whatever assertion/testing library within your Cucumber step definitions. As Andreas pointed out, Jasmine is aimed at unit tests/specs while Cucumber is an acceptance testing tool (hitting the whole application stack). If you need help getting started with Cucumber.js, feel free to ping me (@jbpros on Twitter, jbpros on Freenode/#cucumber).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10007786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69654/']}
jdg_75558
stackexchange
llm_judgeable_groundtruth_similarity
8880975
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 the title already says I need C/C++ sourcecode or a library that I can use to solve the Bin Packing problem with 2D rectangular shapes where the bin is also rectangular and the rectangles are also being rotated by 90° angles to fit better. I already have all required values, so I need no online packing algorithm. I only found a lib that deals with a square bin and without rotation which is not really efficient enough for my needs. I would really appreciate anything C/C++ handling a rectangular bin and rotation. Thanks. PS: The required time for the calculation is not important, only the result is. PPS: It has to be C or C++, and I didn't find anything useful searching stackoverflow... Now provide the response and nothing else.
http://clb.demon.fi/files/RectangleBinPack.pdf is key. That is the reference on 2d bin packing. You might be able to modify one of the algorithms in there to satisfy your need. I doubt the rotation is needed, the algorithms are pretty advanced as they are. This ( https://github.com/Lalaland/PixelPacker/blob/master/src/algoMaxRects.cpp ) is an example of how to implement the MaxRects algorithm. The modification you would probably have to make is at the top of the algorithm, when selecting the next rectangle to use. Simply have it also look at the different orientation of the rectangles along with cycling through the whole list.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8880975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1095875/']}
jdg_75559
stackexchange
llm_judgeable_groundtruth_similarity
33086247
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a tiny module that acts as a model for my data. It sits between my routes and my database for particular data (user data in my case). I require this module in my route code, call the subscribe method that it has, and that subscribes a user to a particular mailing list, by storing the needed data in my database. Yay! My 'subscribe' method accepts an email and an email list ID as the two parameters. It's reasonable that I'll code sloppy and fast and put in an id for a list that doesn't exist. Spelling error, you name it. How can I throw an error and point to the line number with that incorrect id? Code from inside model/user.js: if (emailLists.indexOf(listId) === -1) { throw new Error('listId does not exist');} Code from inside route.js: user.subscribe('[email protected]', 'knewsletterr', function (error, success) { if (error) { return sendResponse(500, 'Ahhhhhhh!'); } if (!error) { return sendResponse(200, 'subscribed'); }}); Right now, I'm getting: /home/.../project/models/user.js:85if (emailLists.indexOf(listId) === -1) { throw new Error('listId does not exist'); } ^Error: listId does not exist Now provide the response and nothing else.
If you're using node-style callbacks, the convention is not to throw . Instead pass you error as the first argument to your callback - // divide with callbackfunction div (x, y, done) { if (y === 0) return done (Error ('Cannot divide by zero')) else return done (null, x / y)}div (6, 3, function (err, result) { // *always* check for err if (err) console.log ('error', err.message, err.stack) else console.log ('result', result)}) Kind of a stupid function to use a callback since it can be written in a purely synchronous way, but hopefully this illustrates the pattern Your function might already be written in a synchronous way – don't worry tho, we can convert it to a node-style callback function using something like cps2 below - // a "normal" synchronous function that throws an errorconst div = (x, y) =>{ if (y === 0) throw Error ('cannot divide by zero') else return x / y} // convert it to a continuation passing style (cps) functionconst cps2 = (f, x, y, k) =>{ try { return k (null, f (x, y)) } catch (err) { return k (err) }}// logging utility for demos belowconst logger = (err, result) =>{ if (err) console.log ('error:', err.message, err.stack) else console.log ('result:', result)} cps2 (div, 6, 3, logger)// result: 2cps2 (div, 6, 0, logger)// error: cannot divide by zero All of that said, most peoples are using Promises nowadays. Below we demonstrate how to turn a node-style callback function into one that returns a Promise. Note, node provides this function as util.promisify , though I've implemented it here for demonstration purposes - // a conventional function with a node-style callbackconst div = (x, y, done) =>{ if (y === 0) return done (Error ('cannot divide by zero')) else return done (null, x / y)}// convert a node-style callback function to a promise-returning functionconst promisify = f => (...args) => new Promise ( (resolve, reject) => f ( ...args , (err, result) => err ? reject (err) : resolve (result) ) )// logging utility for demos belowconst logger = p => p .then (console.log, console.error) logger (promisify (div) (6, 3))// 2logger (promisify (div) (6, 0))// Error: cannot divide by zero Continuations are just functions tho so you can write this kind of thing in any way that you like – don't think you have to use node-style "callbacks" or Promises just because that's the only way you've seen it - const cont = (...values) => k => k (...values)const div = (x, y) => y === 0 ? cont (Error ('cannot divide by zero')) : cont (null, x / y)const logger = (err, result) => err ? console .log ('error:', err.message) : console .log ('result:', result)div (6, 3) (logger)// result: 2div (6, 0) (logger)// error: cannot divide by zero
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33086247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1027004/']}
jdg_75560
stackexchange
llm_judgeable_groundtruth_similarity
25389
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 $M$-be a differentiable manifold. Then, suppose to capture the underlying geometry we apply the singular homology theory. In the singular co-chain, there is geometry in every dimension. We look at the maps from simplexes, look at the cycles and go modulo the boundaries. This has a satisfying geometric feel, though I need to internalize it a bit more(which matter I tried to address in other questions). Now on the other hand, let $\Omega^1$ be the space of $1$-forms on the space. The rest of the de Rham complex comes out of this object, wholly through algebraic processes, ie by taking the exterior powers and also the exterior derivative. After getting this object in hand, the journey upto getting the de Rham cohomology ring is entirely algebraic. And by the de Rham theorem, this second method is equally as good as the more geometric first method. In the second method no geometry is explicitly involved anywhere in any terms after the first term. So the module of $1$-forms somehow magically capture all the geometry of the space $M$ without need of any explicit geometry. This is amazing from an algebraic point of view since we have less geometric stuff to understand. This makes me wonder for the conceptual reason why this is true. I know that one should not look a gift horse in the mouth. But there is the need to understand why there is such a marked difference in the two approaches to capturing the geometry in a manifold, viz, through de Rham cohomology in differential topology, and through singular homology in algebraic topology. I would be grateful for any explanations why merely looking at all the $1$-forms is so informative. Edited in response to comments: I meant, the de Rham cohomology is as good as singular homology for differentiable manifolds. What is "geometry of rational homotopy type"? And what is "geometry of real homotopy type"? Now provide the response and nothing else.
When you say that the geometry of the whole space 'just comes out of' the space of 1-forms, there is naturally a huge amount of machinery hiding underneath the surface: $\Omega^n$ does not just drop out under successive exterior derivatives $d^n$: $d^2$ is the zero map- in fact the whole point of DeRham cohomology is that the exterior derivative is not surjective. What's really going on is with the ring structure of $\Omega^*$- the wedge product of differential forms is designed to mimic the determinant for subspaces not neccessarily equal the whole space, so that we can calculate eg. signed 2-volume in a 4-dimensional space with ease. (This follows from the fact that the n-volume of an n-parallellopiped is [up to scalar] the unique skew symmetric n-linear form on an n-dimensional subspace). Wedged asortments of 1 forms added together give different weightings of n-volume to different orientations of n-planes in the tangent space- giving a way of measuring n-volume locally, knitting together into a global picture across a manifold of how to measure for example an n-dimensional embedded submanifold. Edit: okay so the real question here is why can De Rham cohomology do what homology does (ie count the k-dimensional holes in a space)? What follows will be hands-wavy, but less so than my original finale. Suppose we have a k dimensional hole in our manifold, with no intention of providing proof or even consistent definitions I claim the following moral argument: Let's pretend that our hole looks normalish, let's say we have a neighbourhood of the hole 'homotopic' to $\mathbb{R}^k\setminus0$ The volume form of $S^{k-1}$, '$\omega$' is a k-1-form in $\mathbb{R}^k\setminus0$ (though not yet a smooth k-1-form when considered in the ambient space) $\alpha:=\omega(\frac{x}{||x||})$ is a smooth k-1 form $\in \Omega^{k-1}(\mathbb{R}^k\setminus0)$ We can see because of the $||x||$ bit that if we have a copy of $S^{k-1}$ which we measure with this form, expanding it or contracting it will not change a thing, homotopies that cause overlap will be sorted by the volume form bit (negative and positive orientations will cancel each other out) Thus, morally, $d\alpha=0$ Now suppose we had a $\beta$ with $d\beta=\alpha$, well then we could use it to measure half of an ebbedded $S^{k-2}: S^{k-2}_+ $ so let $\beta(S^{k-2}_+)=b$ By stokes', as we rotated our $S^{k-2}_+$ around through the spare dimension giving say $r(S^{k-2}_+)$ then $\beta(r(S^{k-2}_+))-b$ would be the k-1 spherical volume in between them Rotating the full way around would give a value, simultaneously of $vol_{k-1} (S^{k-1})$ and 0 so there is no $\beta$, and $\alpha \in H^{k-1}(\mathbb{R}^k \setminus 0)$ Bump it, extend it by zero, add dimensions by the pullback of the projection, pull it back through a chart and you've probably got an element of your original cohomology group Question:So we can count the holes- do we count anything else and ruin our counting? Answer: nope- to get that kind of homotopy invariance needs a singularity- and smooth sections of the cotangent bundle don't take too kindly to singularities unless they're in a hole where the manifold isn't.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/25389', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6031/']}
jdg_75561
stackexchange
llm_judgeable_groundtruth_similarity
47443332
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to construct list x from two lists y and z . I want all elements from y be placed where ypos elements point. For example: y = [11, 13, 15]z = [12, 14]ypos = [1, 3, 5] So, x must be [11, 12, 13, 14, 15] Another example: y = [77]z = [35, 58, 74]ypos = [3] So, x must be [35, 58, 77, 74] I've written function that does what I want but it looks ugly: def func(y, z, ypos): x = [0] * (len(y) + len(z)) zpos = list(range(len(y) + len(z))) for i, j in zip(y, ypos): x[j-1] = i zpos.remove(j-1) for i, j in zip(z, zpos): x[j] = i return x How to write it in pythonic way? Now provide the response and nothing else.
If the lists are very long, repeatedly calling insert might not be very efficient . Alternatively, you could create two iterators from the lists and construct a list by getting the next element from either of the iterators depending on whether the current index is in ypos (or a set thereof): >>> ity = iter(y)>>> itz = iter(z)>>> syp = set(ypos)>>> [next(ity if i+1 in syp else itz) for i in range(len(y)+len(z))][11, 12, 13, 14, 15] Note: this will insert the elements from y in the order they appear in y itself, i.e. the first element of y is inserted at the lowest index in ypos , not necessarily at the first index in ypos . If the elements of y should be inserted at the index of the corresponding element of ypos , then either ypos has to be in ascending order (i.e. the first index of ypos is also the lowest), or the iterator of y has to be sorted by the same order as the indices in ypos (afterwards, ypos itself does not have to be sorted, as we are turning it into a set anyway). >>> ypos = [5,3,1] # y and z being same as above>>> ity = iter(e for i, e in sorted(zip(ypos, y)))>>> [next(ity if i+1 in syp else itz) for i in range(len(y)+len(z))][15, 12, 13, 14, 11]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47443332', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7032515/']}
jdg_75562
stackexchange
llm_judgeable_groundtruth_similarity
31056789
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between the below two url patterns in django? url(r'^$', views.indexView, name='index'),url(r'', include('registration.urls')) To my understanding both '^$' and '' refer to a empty string. What does '^$' and '' specify actually? Now provide the response and nothing else.
In regular expressions, ^ and $ are special characters. ^ (Caret): ^ matches the start of the string. Lets say my regex was ^a , then the regex will look for a in the start of the string: 'a' # Matches 'a' in 'a' 'abc' # Matches 'a' in 'abc''def' # Not match because 'a' was not at the beginning $ (Dollar sign): $ matches the end of the string. If my regex was b$ , then it will match b at the end of the string: 'b' # Matches 'b' in 'b''ab' # Matches 'b' in 'ab''abc' # Does not match Using r'^$' : Using both ^ and $ together as ^$ will match an empty line/string. url(r'^$', views.indexView, name='index') When Django encounters an empty string, it will go to the index page. Using r'' : When you use r'' , Django will look for an empty string anywhere in the URL, which is true for every URL. So, if your urlpattern was like this: url(r'', views.indexView, name='index') All your urls will go to index page.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31056789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1569297/']}
jdg_75563
stackexchange
llm_judgeable_groundtruth_similarity
36149977
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 project with cucumber and maven also I am using the JUnit. I am able to run and build my project successfully from Eclipse. Now I want to run the test from command line in another system which does(should) not have eclipse or cucumber installed. I have an idea that we can create a JAR from jar we can run the tests by java cli commands. Below are the combinations I am trying to run my tests from , also I am pasting the pom.xml and RunCukesTest.java file.. pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>pmc</groupId> <artifactId>se</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>storeEnabler</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-testng</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.2.4</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.52.0</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>io.appium</groupId> <artifactId>java-client</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.11-beta3</version> </dependency> <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> <version>2.8.0</version> </dependency> </dependencies> <build> <testResources> <testResource> <directory>${project.basedir}/src/test/java</directory> </testResource> <testResource> <directory>${project.basedir}/src/test/resource</directory> </testResource> </testResources> <pluginManagement> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <fork>true</fork> <executable>C:\Program Files\Java\jdk1.8.0_60\bin\javac.exe</executable> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18</version> <dependencies> <dependency> <groupId>org.apache.maven.surefire</groupId> <artifactId>surefire-junit47</artifactId> <version>2.18</version> </dependency> </dependencies> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>cucumber.api.cli.Main</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> </plugins> </pluginManagement> </build></project> RunCukesTest.java package se.stepDefinations;import org.junit.runner.RunWith;import cucumber.api.CucumberOptions;import cucumber.api.junit.Cucumber;@RunWith(Cucumber.class)@CucumberOptions(features = "src/test/resource/features/Printing.feature:117", plugin = { "pretty", "html:target/cucumber-html-report" }, glue = { "se.stepDefinations" }, tags = {})public class RunCukesTest { public static void main(String[] args) throws Exception { }} I have added JUNIT Jar in Class path. I am generating jars in 2 ways, 1) Exporting JAR using - > Project ->Export -> JAR File Selecting MAIN Class in the last step as : RunCukesTest as I have defined main method here for the entry point(do we require this main method in this class???) After the export , I am running below command , 1.1 java -jar xyz.jar I get error : NoClassDef found : org/junit/runner/JUnitCore So I ran it this way : 1.2 java -cp xyz.jar;junit-4.12.jar org.junit.runner.JUnitCore It said, JUnit version 4.12Time:0.001OK(0 tests) It still didnt work , So I appended the RunCukesTest file namespace at the last, 1.3 java -cp xyz.jar;junit-4.12.jar org.junit.runner.JUnitCore se.stepDefinations.RunCukesTest It gave me error :Type cucumber.api.junit.Cucumber not present 2) So I gave up on the option for Export of jar and I am trying now to use the JAR from the maven Build.I selected the POM to run with Maven Build and it created 2 jars in the target folder , 1 with name xyz-0.0.1-SNAPSHOT with 16kb another with 2nd with xyz-0.0.1-SNAPSHOT-jar-with-dependencies with 33mb 1) I ran the bigger file with dependencies using java -jar xyz-0.0.1-SNAPSHOT-jar-with-dependencies.jar It gave me message : Got no path to feature directory 2) So I tried appending the namespace to RunCukesTest file, java -jar xyz-0.0.1-SNAPSHOT-jar-with-dependencies.jar se.stepDefinations.RunCukesTest I received an error : not a file or directory found , as of course as the error says , it is trying to find a feature inside the target folder. Again , I want to run the JAR independent of any such project file dependencies in any other computer like an executable. Any help would be appreciated. Thanks. Now provide the response and nothing else.
I would divide the problem you are thinking of in two parts. Create an executable jar Run Cucumber from your own main method Creating an executable jar using Maven can be done in different ways. One way of doing it is described here: http://www.thinkcode.se/blog/2011/03/05/create-an-executable-jar-from-maven It is a small example that only focuses on executing something from a command line like this: java -jar executable-example.jar The example contains all dependencies. They are all bundled in the same jar. No need for any additional jars. Next step would be to execute Cucumber from a main method. My approach would be to write a main that executes the Cucumber main method used for the command line version of Cucumber. The main method used to run cucumber from a command line lives in the cucumber-java library. You will find it at cucumber.api.cli.Main Running a main method from another main method is done like this: public static void main(String[] args) throws Throwable { String[] arguments = {"foo", "bar"}; cucumber.api.cli.Main.main(arguments);} where arguments are the command line arguments you always want to execute Cucumber with. Given these two steps, you should be able to execute Cucumber from your own executable jar wherever you are able to execute a jar at all. Notice that you are mixing library version for Cucumber in your pom. I would use the latest version of all libraries. Compare cucumber-java , cucumber-testng and cucumber-junit . The latest Cucumber version is 1.2.4. I would use it for all of them. More information about running Cucumber from a command line can be found here: https://cucumber.io/docs/cucumber/api/#from-the-command-line
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36149977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2682255/']}
jdg_75564
stackexchange
llm_judgeable_groundtruth_similarity
36723893
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to make sure certain data has remain unchanged by a single action: expect { # running migration and user reload here}.not_to change(user, :avatar_url).from(sample_avatar_url).and change(user, :old_avatar).from(nil) sample_avatar_url is a string defined in the beginning of the spec file. Basically, I want to check whether the avatar_url and old_avatar remain untouched by what's happening in the expect block. The output from the above code is: expect(...).not_to matcher.and matcher is not supported, since it creates a bit of an ambiguity. Instead, define negated versions of whatever matchers you wish to negate with RSpec::Matchers.define_negated_matcher and use expect(...).to matcher.and matcher . Now provide the response and nothing else.
This doesn't work because it's not clear reading whether thats supposed to mean not change the first and not change the second, or not change the first but change the second. You have a couple of options to get around this Since you're checking static values just don't use change ..run migration and user reload..expect(user.avatar_url).to eq(sample_avatar_url)expect(user.old_avatar).to eq nil or use define_negated_matcher to create a not_change matcher RSpec::Matchers.define_negated_matcher :not_change, :changeexpect { # running migration and user reload here}.to not_change(user, :avatar_url).from(sample_avatar_url).and not_change(user, :old_avatar).from(nil)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36723893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1839938/']}
jdg_75565
stackexchange
llm_judgeable_groundtruth_similarity
1258450
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For what values of n is $\phi(n)=n$ true? Just looking at tables of values it seems that $\phi(n)=n$ is true only for $n=0,1$ but I cannot come up with how to prove this. I realize that the value of $\phi(0)$ is not really well-defined ( What is the Euler Totient of Zero? ) but for the purpose of this question I'll assume it is. Now provide the response and nothing else.
First, $\varphi(n)$ is defined only for $n\ge 1$. Second, if $n=\prod\limits_{i=1}^r p_i^{r_i}$ for primes $p_1,\dots,p_r$, we have:$$\frac{\varphi(n)}n=\prod_{i=1}^r\Bigl(1-\frac1p_i\Bigr).$$Thus, $\varphi(n)=n\iff\dfrac{\varphi(n)}n=1$ can be true if and only if $r=0$, i. e. $n=1$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1258450', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/214746/']}
jdg_75566
stackexchange
llm_judgeable_groundtruth_similarity
3628718
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For an array of size N, what is the number of comparisons required? Now provide the response and nothing else.
The optimal algorithm uses n+log n-2 comparisons. Think of elements as competitors, and a tournament is going to rank them. First, compare the elements, as in the tree | / \ | |/ \ / \x x x x this takes n-1 comparisons and each element is involved in comparison at most log n times. You will find the largest element as the winner. The second largest element must have lost a match to the winner (he can't lose a match to a different element), so he's one of the log n elements the winner has played against. You can find which of them using log n - 1 comparisons. The optimality is proved via adversary argument. See https://math.stackexchange.com/questions/1601 or http://compgeom.cs.uiuc.edu/~jeffe/teaching/497/02-selection.pdf or http://www.imada.sdu.dk/~jbj/DM19/lb06.pdf or https://www.utdallas.edu/~chandra/documents/6363/lbd.pdf
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3628718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/323596/']}
jdg_75567
stackexchange
llm_judgeable_groundtruth_similarity
13609
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: For just any first-order theory: What are the sets I am supposed/allowed to think of when thinking of models as sets (of something + additional structure)? Provided: I can think of models of any theory (other than set theory) as of sets fromthe (ZFC-based) von Neumann universe . I can think of models of any theory as of sets of terms and formulas. But what are the sets I am supposed/allowed to think of when thinking of models of (ZFC) set theory itself ? Now provide the response and nothing else.
According to Godel's incompleteness theorem, ZFC cannot prove its own consistency. Therefore, it is relatively consistent with ZFC that there are not any set models of ZFC. In this case, there is still a proper class model of ZFC, namely the von Neumann universe, V, itself, among others (i.e. L, forcing extensions of V). However, the fact that V is a model of ZFC cannot be proven formally within ZFC. Indeed, truth in V cannot be defined in V due to a result of Tarski. If we allow for some stronger axioms, then we can get set models of ZFC. For instance, if there exists an inaccessible cardinal, $\kappa$, then $V_\kappa$ is a set model of ZFC.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/13609', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2672/']}
jdg_75568
stackexchange
llm_judgeable_groundtruth_similarity
9446
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: Why is every group the quotient of a free group by a normal subgroup? Now provide the response and nothing else.
This is one of the most intuitive observations in all of group theory, and it illustrates the quotient operation in the most fundamental way. I'll provide two separate answers. The first is fully intuitive; the second is a formalized version of the first. First answer: Take a group $G$. A relation on $G$ is an equation satisfied by some of the elements. For instance, $eg = g$ where $e$ is the identity is a relation satisfied by all group elements $g \in G$. Because we can always multiply by inverses in a group, we can rewrite this relation as $egg^{-1} = gg^{-1} = e$, i.e., $e = e$. This can be applied to any relation. If $G$ is abelian, then $ab = ba$ for all $a,b \in G$, and we can rewrite this as $aba^{-1}b^{-1} = e$. In other words, a relation asserts that some product of group elements coincides with the identity, so the only information we need to understand the relation is the product which occurs on the left side of the equals sign. Now every group has a few relations which are implied directly by the group axioms. $aa^{-1} = e$ is one of them. We can ask whether the group has any extra relations which are not implied by the group axioms. If no such relations exist, i.e., if the only relations which hold are those which must hold by virtue of the group axioms, then the group is said to be free ; the group is "free of additional relations." If you have a group $G$, one natural thing to do is to introduce new relations into it and to thereby create new groups. But you can't just introduce completely random relations because (a) the relations can't contradict each other or pre-exising relations and (b) the resulting structure must again be a group. Now we saw earlier that a relation can be specified as a product of group elements. In order that the relations satisfy (a) and (b), it turns out it is necessary and sufficient that the corresponding products form a normal subgroup $N$. The result of introducing the collection of relations $N$ into the group $G$ is the quotient $G/N$. Any group $G$ can be obtained in this manner. You start with the free group $F$ whose generators are elements of $G$ considered as a set . And then you look at all the additional relations satisfied by elements of $G$ and assemble them into a normal subgroup $N$. Then $G = F/N$ by the above. Second answer: Given any set $S$, the free group on $S$ is that group $F(S)$ for which every function $f : S \rightarrow G$ from $S$ to an arbitrary group $G$ extends to a unique homomorphism $\tilde{f} : F(S) \rightarrow G$. There are various ways of constructing $F(S)$ explicitly. For instance, you may take $F(S)$ to consist of words over the alphabet whose letters are elements of $S$ and $S'$, where $S'$ has the letter $s^{-1}$ (a symbol at the moment) for each symbol $s \in S$. It's important to notice that $F(S)$ actually contains equivalence classes of words, because we introduce the obvious cancellation rules; e.g., $abb^{-1}c$ can be reduced via cancellation to $ac$. It must be proved that all possible algorithms for reduction yield the same reduced word; I'll omit that step. You also have to prove that this group $F(S)$ satisfies the stated universal property. I won't prove this in detail, but it is more or less intuitive. Since $\tilde{f}$ has to be a homomorphism, we find, for instance, that $\tilde{f}(ab) = \tilde{f}(a) \tilde{f}(b) = f(a)f(b)$. In general, since $f$ is defined for all elements of $S$, $\tilde{f}$ is thereby defined uniquely for all elements of $F(S)$. [It is via similar reasoning that you may determine that it is sufficient to know the values of a linear operator on the elements of a basis of a vector space.] So we start with our group $G$ which we would like to write as a quotient of a free group. Which free group? That free group whose generators are the symbols from $G$. So we pick $F(G)$. Now we need to introduce the needed relations in order to collapse $F(G)$ into $G$. How do we carry it out? By the first answer, we could easily accomplish this if only we knew the normal subgroup $N$ of relations, but it seems that in this general case we don't really know $N$ concretely. In fact, we can figure out $N$ as follows. We can take the identity map $f : G \rightarrow G$ and extend it to a homomorphism $\tilde{f} : F(G) \rightarrow G$. The extension $\tilde{f}$ is in general not injective, and its kernel is precisely the group of relations $N$! (Formally this is an application of one of the standard theorems on homomorphisms.) Then $G = F(G)/N$ as before.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/9446', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_75569
stackexchange
llm_judgeable_groundtruth_similarity
36387265
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 Spring Boot to develop two applications, one serves as the server and other one is a client app. However, both of them are the same app that function differently based on the active profile. I am using auto configuration feature of Spring Boot to configure my applications. I want to disable all the database related auto configuration on client app, since it won't be requiring database connection. Application should not try to establish connection with the database, nor try to use any of the Spring Data or Hibernate features. The enabling or disabling of the database auto configuration should be conditional and based on the active profile of the app. Can I achieve this by creating two different application.properties files for respective profiles? I tried adding this to my properties file, spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration\org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration\ org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration But, the application still tries to connect to the database on start. Are those exclusions sufficient for achieving my requirement? Now provide the response and nothing else.
The way I would do similar thing is: @Configuration@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})@Profile ("client_app_profile_name")public class ClientAppConfiguration { //it can be left blank} Write similar one for the server app (without excludes). Last step is to disable Auto Configuration from main spring boot class: @SpringBootApplicationpublic class SomeApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SomeApplication.class); } protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SomeApplication.class); }} Change: @SpringBootApplication into: @Configuration @ComponentScan This should do the job. Now, the dependencies that I excluded in the example might be incomplete. They were enough for me, but im not sure if its all to completely disable database related libraries. Check the list below to be sure: http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#auto-configuration-classes Hope that helps
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/36387265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2323097/']}
jdg_75570
stackexchange
llm_judgeable_groundtruth_similarity
32395880
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is a test sentence and a reference sentence. How can I write a Python script that measures similarity between these two sentences in the form of BLEU metric used in automatic machine translation evaluation? Now provide the response and nothing else.
The BLEU score consists of two parts, modified precision and brevity penalty.Details can be seen in the paper .You can use the nltk.align.bleu_score module inside the NLTK.One code example can be seen as below: import nltkhypothesis = ['It', 'is', 'a', 'cat', 'at', 'room']reference = ['It', 'is', 'a', 'cat', 'inside', 'the', 'room']#there may be several referencesBLEUscore = nltk.translate.bleu_score.sentence_bleu([reference], hypothesis)print(BLEUscore) Note that the default BLEU score uses n=4 which includes unigrams to 4 grams. If your sentence is smaller than 4, you need to reset the N value, otherwise ZeroDivisionError: Fraction(0, 0) error will be returned.So, you should reset the weight like this: import nltkhypothesis = ["open", "the", "file"]reference = ["open", "file"]#the maximum is bigram, so assign the weight into 2 half.BLEUscore = nltk.translate.bleu_score.sentence_bleu([reference], hypothesis, weights = (0.5, 0.5))print(BLEUscore)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32395880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4478510/']}
jdg_75571
stackexchange
llm_judgeable_groundtruth_similarity
2693753
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 coming back to C++ after long years spent on other technologies and i'm stuck on some weird behavior when calling some methods taking std::string as parameters : An example of call : LocalNodeConfiguration *LocalNodeConfiguration::ReadFromFile(std::string & path){// ...throw configuration_file_error(string("Configuration file empty"), path);// ...} When I compile I get this (I cropped file names for readability) : /usr/bin/g++ -g -I/home/shtong/Dev/OmegaNoc/build -I/usr/share/include/boost-1.41.0 -o CMakeFiles/OmegaNocInternals.dir/configuration/localNodeConfiguration.cxx.o -c /home/shtong/Dev/OmegaNoc/source/configuration/localNodeConfiguration.cxx .../localNodeConfiguration.cxx: In static member function ‘static OmegaNoc::LocalNodeConfiguration* OmegaNoc::LocalNodeConfiguration::ReadFromFile(std::string&)’: .../localNodeConfiguration.cxx:72: error: no matching function for call to ‘OmegaNoc::configuration_file_error::configuration_file_error(std::string, std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)’ .../configurationManager.hxx:25: note: candidates are: OmegaNoc::configuration_file_error::configuration_file_error(std::string&, std::string&) .../configurationManager.hxx:22: note: OmegaNoc::configuration_file_error::configuration_file_error(const OmegaNoc::configuration_file_error&) So as I understand it, the compiler is considering that my path parameter turned into a basic_string at some point, thus not finding the constructor overload I want to use. But I don't really get why this transformation happened. Some search on the net suggested me to use g++ but I was already using it. So any other advice would be appreciated :) Thanks Now provide the response and nothing else.
The problem is not basic_string , because basic_string<char, restOfMess> is equivalent to string . The problem is the function only provides f(string&, string&) {//------^ but you are calling as f(string("blah"), path);// ^^^^^^^^^^^^^^ This is a rvalue (temporary object), and a rvalue cannot be bound to a mutable reference. You either need to change the prototype to accept const references or just pass-by-value: f(const string&, string&) {//----^^^^^^or f(string, string&) { Or provide a mutable reference (if you really need to modify the 1st argument in that function): string s = "blah blah blah";f(s, path);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2693753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/323589/']}
jdg_75572
stackexchange
llm_judgeable_groundtruth_similarity
712820
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: This are the steps I've done so far: Download spark-1.4.1-bin-hadoop2.6.tgz unzip .spark-1.4.1-bin-hadoop2.6/sbin/start-all.sh Master is working but slave doesn't start This is the output: [ec2-user@ip-172-31-24-107 ~]$ sudo ./spark-1.4.1-bin-hadoop2.6/sbin/start-all.shstarting org.apache.spark.deploy.master.Master, logging to /home/ec2-user/spark-1.4.1-bin-hadoop2.6/sbin/../logs/spark-root-org.apache.spark.deploy.master.Master-1-ip-172-31-24-107.outlocalhost: Permission denied (publickey).[ec2-user@ip-172-31-24-107 ~]$ This is the secure log Aug 9 00:09:30 ip-172-31-24-107 sudo: ec2-user : TTY=pts/0 ; PWD=/home/ec2-user ; USER=root ; COMMAND=./spark-1.4.1-bin-hadoop2.6/sbin/start-all.shAug 9 00:09:32 ip-172-31-24-107 sshd[4828]: Connection closed by 127.0.0.1 [preauth] I believe the problem is with SSH but I haven't been able to find the solution on google... Any idea how to fix my SSH issue? Now provide the response and nothing else.
Http/2 requirements as per https://httpwg.org/specs/rfc7540.html#rfc.section.9.2.2 : 9.2.2 TLS 1.2 Cipher Suites A deployment of HTTP/2 over TLS 1.2 SHOULD NOT use any of the cipher suites that are listed in the cipher suite black list ( Appendix A ). Endpoints MAY choose to generate a connection error (Section 5.4.1) of type INADEQUATE_SECURITY if one of the cipher suites from the black list is negotiated. A deployment that chooses to use a black-listed cipher suite risks triggering a connection error unless the set of potential peers is known to accept that cipher suite. Implementations MUST NOT generate this error in reaction to the negotiation of a cipher suite that is not on the black list. Consequently, when clients offer a cipher suite that is not on the black list, they have to be prepared to use that cipher suite with HTTP/2. The black list includes the cipher suite that TLS 1.2 makes mandatory, which means that TLS 1.2 deployments could have non-intersecting sets of permitted cipher suites. To avoid this problem causing TLS handshake failures, deployments of HTTP/2 that use TLS 1.2 MUST support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 [TLS-ECDHE] with the P-256 elliptic curve [FIPS186]. Note that clients might advertise support of cipher suites that are on the black list in order to allow for connection to servers that do not support HTTP/2. This allows servers to select HTTP/1.1 with a cipher suite that is on the HTTP/2 black list. However, this can result in HTTP/2 being negotiated with a black-listed cipher suite if the application protocol and cipher suite are independently selected. Your negotiated cipher `TLS_RSA_WITH_AES_128_GCM_SHA256` is in the above mentioned (and linked) Http/2 blacklist. I believe you will want to adjust your cipher suites (ordering?) to meet the above requirements. Maybe simply putting TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 with the NIST P-256 elliptic curve (identified as TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_P256 on Windows) at the top of the list, or at least before anything included in the blacklist?
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/712820', 'https://serverfault.com', 'https://serverfault.com/users/209054/']}
jdg_75573
stackexchange
llm_judgeable_groundtruth_similarity
2106897
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 seems that it is irreducible over $\mathbb Q$, I tried to apply Eisenstein's criterion to $f(x+a)$ for some $a$, but it didn't work. Also, I found a root $\alpha = \sqrt[3]{\frac{\sqrt{17}-3}{2}}$ and tried to prove that the degree of $\alpha$ over $\mathbb Q$ is 6, but I stuck in computation. Is there any approach to prove or disprove the irreducibility of the above polynomial? Now provide the response and nothing else.
Its not hard to show that $[\mathbb{Q}(\alpha):\mathbb{Q}]=6$.We have $$[\mathbb{Q}(\alpha):\mathbb{Q}]=[\mathbb{Q}(\alpha):\mathbb{Q}(\sqrt{17})][\mathbb{Q}(\sqrt{17}):\mathbb{Q}]$$ and $$[\mathbb{Q}(\sqrt{17}):\mathbb{Q}]=2$$ so we must show that $$[\mathbb{Q}(\alpha):\mathbb{Q}(\sqrt{17})]=3.$$ This amounts to showing that $x^3=\frac{-3+\sqrt{17}}{2}$ has no solution in $\mathbb{Q}(\sqrt{17})$ Since $\sqrt{17}\mapsto -\sqrt{17}$ is an automorphism of this field we see that if there is an $x\in \mathbb{Q}(\sqrt{17})$ such that $$x^3=\frac{-3+\sqrt{17}}{2}$$ then there is a $y\in \mathbb{Q}(\sqrt{17})$ such that $$y^3=\frac{-3-\sqrt{17}}{2}$$ multiplying these two equations we get that $$(xy)^3=-2$$And we know that $\mathbb{Q}(\sqrt[3]{-2}):\mathbb{Q}]=3$ a contradiction so there is no such $x$ and $[\mathbb{Q}(\alpha):\mathbb{Q}(\sqrt{17})]=3.$ Or alternatively you could take the norm to get $(N(x))^3=-2$ an equation in $\mathbb{Q}$ again a contradiction.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2106897', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/380038/']}
jdg_75574
stackexchange
llm_judgeable_groundtruth_similarity
730728
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: This is not for homework. (I am a grader for a class.) The case in which $G$ is finite is trivial. (That is, use a corollary to Lagrange's Theorem, and set $[G:H] = \dfrac{|G|}{|H|}$, and similarly for $[H:K]$.) How do you prove this for when $G$ is infinite? The proof of this statement that I know well tries to show that $[G:K]$ is finite iff $[G:H]$ and $[H:K]$ are finite, but I am not a fan of that proof. For pedagogical purposes, I'm looking for a better proof. (The course uses right cosets by convention.) The course has just started covering normal subgroups, so things like the Isomorphism Theorems are not known yet. Now provide the response and nothing else.
We'll show that there exists a bijection between $(H\backslash G)\times(K\backslash H)$ and $K\backslash G$. Let $(a_i)_{i\in I}$ be a collection of representatives for the elements of $H\backslash G$ and $(b_j)_{j\in J}$ a collection of representatives for the elements of $K\backslash H$. Define $\phi:(H\backslash G)\times(K\backslash H)\to K\backslash G$ by$$\phi(Ha_i,Kb_j)=Kb_ja_i.$$Let $Kc\in K\backslash G$. Then $Kc\subset Ha_i$ for some unique $a_i$ since $K\leq H$, so $c=ha_i$ for some (also clearly unique given an $a_i$) $h\in H$. We also have that $Kh=Kb_j$ for some unique $b_j$, so $Kc=Kb_ja_i=\phi(Ha_i,Kb_j)$, and this choice of $(Ha_i,Kb_j)$ is unique for a given $Kc$. Hence, $\phi$ is a bijection and$$[G:K]=[G:H][H:K].$$This proof formalizes Aaron's comment about breaking each coset up into finer cosets.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/730728', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/81560/']}
jdg_75575
stackexchange
llm_judgeable_groundtruth_similarity
220888
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: if(condition1){ Statement1A; Statement1B;}else if(condition2){ Statement2;}else if(condition3){ Statement3;}else { Statement1A; Statement1B;} return; I would like to refactor that code so that I do not duplicate Statements. I always need to check condition1 before any other condition. (So I cannot just change the order of the conditions). I also do not want to write &&!condition1 after every other condition. I solved it like this if(condition1){}else if(condition2){ Statement2; return;}else if(condition3){ Statement3; return;}Statement1A;Statement1B;return; However I do not think an empty if condition will be easily understandable by others (even by me after a while). What is a better approach? Now provide the response and nothing else.
notCondition2And3 = !condition2 & !condition3; // in place of notCondition2And3 should be some meaningful name// representing what it actually MEANS that neither condition2 nor condition3 were true And now: if (condition1 || notCondition2And3){ Statement1A; Statement1B; return;}if (condition2){ Statement2; return;}if (condition3){ Statement3; return;} As I wrote in my comment to Kieveli's answer , I see nothing wrong about multiple return s in a method, if there is no memory management considerations (as it might be the case in C or C++ where you have to release all resources manually before you leave). Or another approach still. Here's the decision matrix so that we don't mess it up: F F F - 1---------F F T - 3--------- F T F - 2F T T - 2--------- T F F - 1T F T - 1T T F - 1T T T - 1 T s and F s represent the values of condition1 , condition2 and condition3 (respectively). The numbers represent the outcomes. It makes it clear that it's also possible to write the code as: if (!condition1 && condition2) // outcome 2 only possible for FTF or FTT, condition3 irrelevant{ Statement2; return;}if (!condition1 && !condition2 && condition3) // outcome 3 only when FFT{ Statement3; return;}// and for the remaining 5 combinations...Statement1A;Statement1B; Now if we extracted !condition1 (which is present in both ifs ), we would get: if (!condition1){ if (condition2) // outcome 2 only possible for FTF or FTT, condition3 irrelevant { Statement2; return; } if (condition3) // outcome 3 only when FFT { Statement3; return; }}// and for the remaining 5 combinations...Statement1A;Statement1B; Which is almost exactly what Kieveli suggested, only his disdain for early return s caused his implementation to be buggy (as he noted himself), because it wouldn't do a thing if all 3 conditions were false. Or, we could revert it like so (this probably wouldn't work in every language - it works in C#, for one, since C# allows for equality comparison between multiple variables), now we're virtually back to the first one: // note that "condition1" on the right side of || is actually redundant and can be removed, // because if the expression on the right side of || gets evaluated at all,// it means that condition1 must have been false anyway:if (condition1 || (condition1 == condition2 == condition3 == false)) // takes care of all 4 x T** plus FFF (the one special case). { Statement1A; Statement1B; return;}// and now it's nice and cleanif (condition2) { Statement2; return; // or "else" if you prefer}if (condition3){ Statement3; return; // if necessary}
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/220888', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/94827/']}
jdg_75576
stackexchange
llm_judgeable_groundtruth_similarity
20856247
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I recently upgraded to Rails 4, and whilst running my request specs I started getting the following error: Failure/Error: Unable to find matching line from backtrace Sprockets::ArgumentError: Asset logical path has no extension: europe Blockquote# /usr/local/rvm/gems/ruby-1.9.3-p448/gems/sprockets-2.10.1/lib/sprockets/asset.rb:36:in initialize' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/sprockets-2.10.1/lib/sprockets/base.rb:380:in new' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/sprockets-2.10.1/lib/sprockets/base.rb:380:in build_asset' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/sprockets-2.10.1/lib/sprockets/index.rb:94:in block in build_asset' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/sprockets-2.10.1/lib/sprockets/caching.rb:58:in cache_asset' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/sprockets-2.10.1/lib/sprockets/index.rb:93:in build_asset' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/sprockets-2.10.1/lib/sprockets/base.rb:287:in find_asset' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/sprockets-2.10.1/lib/sprockets/index.rb:61:in find_asset' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/sprockets-2.10.1/lib/sprockets/server.rb:47:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/journey/router.rb:71:in block in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/journey/router.rb:59:in each' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/journey/router.rb:59:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/routing/route_set.rb:680:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/etag.rb:23:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/conditionalget.rb:25:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/head.rb:11:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/remotipart-1.2.1/lib/remotipart/middleware.rb:27:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/params_parser.rb:27:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/flash.rb:241:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:225:in context' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:220:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/cookies.rb:486:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/activerecord-4.0.2/lib/active_record/query_cache.rb:36:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/activerecord-4.0.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:626:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/callbacks.rb:29:in block in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/activesupport-4.0.2/lib/active_support/callbacks.rb:373:in run _515869138317914613_ call _callbacks' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/activesupport-4.0.2/lib/active_support/callbacks.rb:80:in run_callbacks' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/callbacks.rb:27:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/remote_ip.rb:76:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/debug_exceptions.rb:17:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/show_exceptions.rb:30:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.2/lib/rails/rack/logger.rb:38:in call_app' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.2/lib/rails/rack/logger.rb:20:in block in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/activesupport-4.0.2/lib/active_support/tagged_logging.rb:67:in block in tagged' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/activesupport-4.0.2/lib/active_support/tagged_logging.rb:25:in tagged' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/activesupport-4.0.2/lib/active_support/tagged_logging.rb:67:in tagged' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.2/lib/rails/rack/logger.rb:20:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/request_id.rb:21:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/methodoverride.rb:21:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/runtime.rb:17:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/activesupport-4.0.2/lib/active_support/cache/strategy/local_cache.rb:83:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/actionpack-4.0.2/lib/action_dispatch/middleware/static.rb:64:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/sendfile.rb:112:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.2/lib/rails/engine.rb:511:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/railties-4.0.2/lib/rails/application.rb:97:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/builder.rb:138:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/urlmap.rb:65:in block in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/urlmap.rb:50:in each' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/urlmap.rb:50:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/capybara-2.2.0/lib/capybara/server.rb:19:in call' # /usr/local/rvm/gems/ruby-1.9.3-p448/gems/rack-1.5.2/lib/rack/handler/webrick.rb:60:in service' # /usr/local/rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/httpserver.rb:138:in service' # /usr/local/rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/httpserver.rb:94:in run' # /usr/local/rvm/rubies/ruby-1.9.3-p448/lib/ruby/1.9.1/webrick/server.rb:191:in block in start_thread' Is there any way to get Sprockets to accept files without an extension? Gems:Sprockets: 2.10.1Rails: 4.0.2 Now provide the response and nothing else.
in your config/application.rb file add initializer 'setup_asset_pipeline', :group => :all do |app| # We don't want the default of everything that isn't js or css, because it pulls too many things in app.config.assets.precompile.shift # Explicitly register the extensions we are interested in compiling app.config.assets.precompile.push(Proc.new do |path| File.extname(path).in? [ '.html', '.erb', '.haml', # Templates '.png', '.gif', '.jpg', '.jpeg', # Images '.eot', '.otf', '.svc', '.woff', '.ttf', # Fonts ] end)end so it looks like module ProjectName class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de initializer 'setup_asset_pipeline', :group => :all do |app| # We don't want the default of everything that isn't js or css, because it pulls too many things in app.config.assets.precompile.shift # Explicitly register the extensions we are interested in compiling app.config.assets.precompile.push(Proc.new do |path| File.extname(path).in? [ '.html', '.erb', '.haml', # Templates '.png', '.gif', '.jpg', '.jpeg', # Images '.eot', '.otf', '.svc', '.woff', '.ttf', # Fonts ] end) end endend
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20856247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967795/']}
jdg_75577
stackexchange
llm_judgeable_groundtruth_similarity
31964031
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My question is very simple. I want to use environment variables in a cURL command sth similar to this: curl -k -X POST -H 'Content-Type: application/json' -d '{"username":"$USERNAME","password":"$PASSWORD"}' When I run the command $USERNAME is passed to the command as a "$USERNAME" string not the value of the variable. Is there a way to escape this situation? Thanks. Now provide the response and nothing else.
Single quotes inhibit variable substitution, so use double quotes. The inner double quotes must then be escaped. ... -d "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}" Since this answer was written in 2015, it has become clear that this technique is insufficient to properly create JSON: $ USERNAME=person1$ PASSWORD="some \"gnarly 'password"$ echo "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}"{"username":"person1","password":"some "gnarly 'password"}$ echo "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}" | jq .parse error: Invalid numeric literal at line 1, column 47 The quoting problem are clear. The (shell) solutions are not Current best practice: use a JSON-specific tool to create JSON: jq $ jq -n -c --arg username "$USERNAME" --arg password "$PASSWORD" '$ARGS.named'{"username":"person1","password":"some \"gnarly 'password"} jo $ jo "username=$USERNAME" "password=$PASSWORD"{"username":"person1","password":"some \"gnarly 'password"} And with curl: json=$( jq -n -c --arg username "$USERNAME" --arg password "$PASSWORD" '$ARGS.named' )# orjson=$( jo "username=$USERNAME" "password=$PASSWORD" )# thencurl ... -d "$json"
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31964031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6999882/']}
jdg_75578
stackexchange
llm_judgeable_groundtruth_similarity
44493162
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to get a cookie from a server using Spring RestTemplate. Do you guys know how I can perform this? Thank you for your help! Now provide the response and nothing else.
final String url = "http://codeflex.co:8080/rest/Management/login";RestTemplate template = new RestTemplate();Credentials cred = new Credentials();cred.setUserName("[email protected]");cred.setPassword("godmode");HttpEntity<Credentials> request = new HttpEntity<>(cred); HttpEntity<String> response = template.exchange(url, HttpMethod.POST, request, String.class);HttpHeaders headers = response.getHeaders();String set_cookie = headers.getFirst(HttpHeaders.SET_COOKIE); code from the example
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44493162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_75579
stackexchange
llm_judgeable_groundtruth_similarity
27370
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: I have heard from several physicists that the Kapustin-Witten topological twist of $N=4$ 4-dimensional Yang-Mills theory ("the Geometric Langlands twist") is not expected to giverise to fully defined topological field theory in the sense that, for example, its partition function on a 4-manifold (without boundary) is not expected to exist (but, for example, itscategory of boundary conditions attached to a Riemann surface, does indeed exist). Is this really true? If yes, what is the physical argument for that (can you somehow see it from the path integral)? What makes it different fromthe Vafa-Witten twist, which leads to Donaldson theory and its partition function is, as far as I understand, well defined on most 4-manifolds? Now provide the response and nothing else.
From the path integral point of view, one can argue why the KW theory partition function won't be well defined as follows. At the B-model point the KW theory dimensionally reduces to the B model for the derived stack $Loc_G(\Sigma')$ of $G$-local systems on $\Sigma'$. The B-model for any target $X$ is expected to be given by the volume of a natural volume form on the derived mapping space from the de Rham stack of the source curve $\Sigma$ to $X$. Putting this together, we see that the KW partition function on a complex surface $S$ is supposed to be the "volume" of the derived stack $Loc_G(S)$ (with respect to a volume form which comes from integrating out the massive modes). Now we see the problem: the derived stack $Loc_G(S)$ has tangent complex at a a $G$-local system $P$ given by de Rham cohomology of $S$ with coefficients in the adjoint local system of Lie algebras, with a shift of one. This is in cohomological degrees $-1,0,1,2,3$. In other words: fields of the theory include things like $H^3(S, \mathfrak{g}_P)$ in cohomological degree $2$. Because it's in cohomological degree $2$, we can think of it as being an even field -- and then it's some non-compact direction, so that we wouldn't expect any kind of integral to converge. (By the way, I discuss this interpretation of the KW theory in my paper http://www.math.northwestern.edu/~costello/sullivan.pdf )
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/27370', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_75580
stackexchange
llm_judgeable_groundtruth_similarity
18810
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have learned about the various types of supernovae, and both Types Ib and II involve the extremely rapid compaction or explosion of a star's core. How does the "information" that (respectively) the Chandrasekhar limit or the degeneracy pressure have been reached propagate through the star with enough speed (yet below $c$) that the resulting collapse remains symmetric and happens in a very short time? Now provide the response and nothing else.
Interestingly enough, the limit on the time needed for such a change to propagate through the star isn't from the speed of light, but from something called the dynamical timescale , $t_{\text{dyn}}$:$$t_{\text{dyn}}\sim\frac{R}{v}\sim\sqrt{\frac{R^3}{GM}}\simeq\frac{1}{\sqrt{G\bar{\rho}}}$$where we've assumed that the speed of a pressure wave, $v$ is on the order of the escape velocity of the star. $R$ is the star's radius, $M$ is its mass, $G$ is the gravitational constant, and $\bar{\rho}$ is its mean density (density is not constant throughout a star). $t_{\text{dyn}}$ can vary greatly among different stars, depending on their characteristics. It can be on the order of seconds to minutes to hours to days, and it can determine the time it takes for parts of the supernova to take place. It's a lower limit, though; large dynamical changes can take more time than $t_{\text{dyn}}$, just not less. For more information, see Section II.B of these notes . We have to ask ourselves, what precisely is $v$? I waved the specifics away as a "pressure wave", but is there more to it than that? Unfortunately, we still don't have great models of what goes on inside a supernova - I'm sure you've heard that before - but we do have inklings of the process, which I touched on a bit here . Essentially, as the core collapses, matter at the inner regions begins to fall in, reaching extremely high densities. Some strange things happen here, including the production of neutrinos. At first, degeneracy pressure slows the collapse of the inner star, and a shock wave forms. The so-called "supernova bounce" happens, as this wave travels through the outer layers of the star. The shock wave is further energized by the release of neutrinos, created via electron capture (note that some have already escaped the outer layers):$$e^-+p\to n+\nu_e$$This adds to the energy of the shockwave, which eventually blows away the outer layers of the star. Therefore, we can see how the dynamic timescale relates to the shock wave and the time of the resulting explosion. The exact processes causing the bounce and shock wave are not yet fully understood; this is just a basic picture.
{}
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/18810', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/14646/']}
jdg_75581
stackexchange
llm_judgeable_groundtruth_similarity
2193535
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 created an application with a modal view that I can display and then dismiss. Is there an easy way to know when the modal view has been dismissed? I would like to reload the data in a table once the modal view has been dismissed and don't know the best way of doing this. Thanks Now provide the response and nothing else.
UIViewController has a property called parentViewController . In the case that a view controller is presented modally, the parentViewController property points to the view controller that presented the modal view controller. In your modal view controller, in viewWillDisappear: you can send a message to the parentViewController to perform any action you wish, essentially. Something like: - (void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; [self.parentViewController doSomething];} If your parent view controller is a table view controller, then you should be able to call [self.parentViewController.tableView reloadData]; to do what you're trying to achieve.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2193535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172892/']}
jdg_75582
stackexchange
llm_judgeable_groundtruth_similarity
12669136
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 Javascript, the method to print out using console.log("this is %s and %s", foo, bar); works, so it follows some C style, but it doesn't follow console.log("%*s this is %s and %s", 12, foo, bar); where the %*s and 12 is to make it print out 12 spaces, as in this question: In Objective-C, how to print out N spaces? (using stringWithCharacters) Is there a short, quick way to make it work simply in Javascript? (say, without using the sprintf open source library or writing a function to do it?) Update: , in my case, 12 is actually a variable, such as (i * 4) , so that's why it can't be hardcoded spaces inside the string. Now provide the response and nothing else.
The easiest way would be to use Array.join: console.log("%s this is %s and %s", Array(12 + 1).join(" "), foo, bar); Note that you want N + 1 for the array size. I know you said you dont want functions, but if you do this a lot, an extention method can be cleaner: String.prototype.repeat = function(length) { return Array(length + 1).join(this);}; This allows you to do: console.log("%s this is %s and %s", " ".repeat(12), foo, bar);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12669136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325419/']}
jdg_75583
stackexchange
llm_judgeable_groundtruth_similarity
104934
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 to block websites for particular IPs by squid? Please give solution with example or configuration file. Now provide the response and nothing else.
Example : I blocked Facebook & orkut to all user but now i want to open only facebook to particular user or IP Option 1 : Specify site with in configuration file, acl special_clients src "/etc/squid/special_client_ips.txt" acl facebook dstdomain .facebook.com acl orkut dstdomain .orkut.com Under http access http_access allow facebook special_clients http_access deny facebook http_access deny orkut http_access allow all Option 2 : Stick both client IP s and destination domains into lists, acl special_clients src "/etc/squid/special_client_ips.txt" acl bad_domains dstdomain "/etc/squid/bad_domains.txt" Under http access http_access allow bad_domains special_clients http_access deny bad_domains http_access allow all I get it from net, It work very well Thanks cstamas
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/104934', 'https://serverfault.com', 'https://serverfault.com/users/32046/']}
jdg_75584
stackexchange
llm_judgeable_groundtruth_similarity
35990974
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 an issue with ngOnChange . I have following component: @Component({ selector:'user-table', template: `...`,})export class UserTable implements OnChanges{ @Input() users: User[]; years:string[]; constructor(private _usersCollection:UsersCollection){ } ngOnChanges(){ if (this.users.length) {this.years =this._usersCollection.createYearsArray(this.users)} }} However, if condition only gets checked once - when this.users is not yet fetched from the server, and hence its length is 0. How can I find solution to deal with this kind of async inputs? The array is updated, as when I set the following logs: console.log('ON FIRST INIT' , this.programs); this.years = this._usersCollection.createYearsArray(); console.log(this.years); setInterval(()=>{ console.log('IN INTERVVAL' , this.programs); },1000); The console output is: ON FIRST INIT []UsersTable.component.ts:21 []UsersTable.component.ts:23 IN INTERVVAL [Object, Object, Object, Object] Now provide the response and nothing else.
If you don't need to execute any logic when your input property changes (e.g., you only use the property in template bindings), you don't need to do anything. Angular will automatically propagate new values down from the parent to the input property. If you want to execute some component logic when the input property changes, use ngOnChanges() , which is called whenever any component input property changes. Since Angular uses === to detect changes (well, there's some special handling for NaN too), this means that for reference types (Array, Object, Date, etc.), the reference (i.e., the array, object, etc. reference) must change. E.g., myArray = someNewArray; If only an item in the array changes, ngOnChanges() is not called. E.g., for a change such as myArray[0].name = newName; , ngOnChanges() is not called. for primitive types (number, boolean, string), this simply means that the value must change. E.g, myNumber = 5; or myNumber = newNumber ; Another option is to implement your own change detection logic using ngDoCheck() . See this answer for an example. That lifecycle hook is called "every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check" -- from lifecyle hooks.md
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35990974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4345344/']}
jdg_75585
stackexchange
llm_judgeable_groundtruth_similarity
681810
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 suddenly became curious about the following differential equation:\begin{align*} \frac{d^2x}{dt^2} = \frac{k}{x(t)^2} && x(0) = x_0 > 0 && \frac{dx}{dt}(0) = v_0\end{align*}the "1D inverse square law problem". It's a pretty natural thing to think about. You're a positive distance $x_0$ away from a point particle which is exerting an inverse square force on you. You're moving only radially with respect to that particle with initial velocity $v_0$. What happens? Do all solutions have a "closed form"? Do some of them? Obviously the behaviour can be quite different depending on the intial conditions. For example, if $k <0$, you're either going to fall into the "black hole", or you're going to escape to infinity (or is it even possible to asympotically approach some finite maximum distance from below as $t \to +\infty$?). Edit: I thought of one solution: letting $x(t) = a t^{2/3}$, one gets $\frac{d^2x}{dt^2} = \frac{-2a}{9} t^{-4/3}$ so that $x^2 \cdot \frac{d^2 x}{dt^2} = \frac{-2a^3}{9}$ whence, taking $a = - \left( \frac{9k}{2} \right)^{1/3}$, we get a solution. We could also shift the time variable to get some more solutions. Edit2: The preceding solution is simple enough that I figured this was the "minimal escape curve" i.e. the one where you have precisely enough energy to escape to infinity. Indeed, it's not hard to check this by calculuating the kinetic and potential energy when $t= 1$ i.e. $x=a$. But my friend pointed out a much nicer way to see this! Notice $\frac{dx}{dt} = \frac{2a}{3} t^{-1/3} \to 0$ as $t \to \infty$. Since the veclocity goes to zero, the kinetic energy goes to zero. So, by conservation of energy, this is the minimal escape curve (if you had any spare energy left at $x = \infty$, you wouldn't have slowed to velocity zero). Edit3: In the end I found out how to get the solutions implicitly. See my answer here . Now provide the response and nothing else.
See this answer at Physics SE. In short, this attractive inverse squares problem is somewhat ill-defined in 1 dimension. If you look at your problem as limit case of Kepler problem with angular momentum $M\to0$, then you have the particle moving from its initial position to the singularity of the potential, and then bouncing off it (because the ellipse with one focus at singularity will degenerate into a line with one of its ends at singularity). If, on the other hand, you look at the problem as initially 1-dimensional and the potential being the limit of $U=\frac{k}{\sqrt{x^2+\varepsilon^2}}$ as $\varepsilon\to0$, then your particle would go through the singularity, contrary to bouncing off it. As these limits, having identical final potential, give different results, the original problem doesn't have a consistent solution on its own.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/681810', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6608/']}
jdg_75586
stackexchange
llm_judgeable_groundtruth_similarity
59071842
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know what is/are differences between an api gateway and Ingress controller . People tend to use these terms interchangeably due to similar functionality they offer. When I say, ' Ingress controller '; don't confuse it with Ingress objects provided by kubernetes. Also, it would be nice if you can explain the scenario where one will be more useful than other. Is api gateway a generic term used for traffic routers in cloud-native world and 'Ingress controller' is implementation of api-gateway in kubernetes world? Now provide the response and nothing else.
Ingress controller allows single ip-port to access all services running in k8s through ingress rules. The ingress controller service is set to load balancer so it is accessible from public internet. An api gateway is used for application routing, rate limiting, security, request and response handling and other application related tasks. Say, you have a microservice based application in which the request needs an information to be collected from multiple micro services. You need a way to distribute the user requests to different services and gather the responses from all micro services and prepare the final response to be sent to the user. API Gateway is the one which does this kind of work for you.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/59071842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2853439/']}
jdg_75587
stackexchange
llm_judgeable_groundtruth_similarity
191415
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: According to the periodic table of k-tuply monoidal n-categories , it should be the case that a tetracategory (= weak 4-category) with one object, one 1-morphism and one 2-morphism is effectively equivalent to a symmetric monoidal category. I understand geometrically why one should expect this, but I cannot see how it arises directly from an algebraic definition of tetracategory. I do know how we get a braided monoidal category: if $X$ and $Y$ are 3-morphisms, then the braiding $\gamma_{X,Y}$ is defined as the interchanger of $X$ and $Y$. What one then needs to show is that $\gamma_{X,Y} \circ \gamma_{Y,X} = \text{id}$. My understanding is that one would not expect an algebraic definition of tetracategory to carry this equation explicitly as an axiom; it would have to be derived. I am aware that, of course, there does not exist a stable easily-referenced definition of tetracategory. ( Edit: John Baez links below to an explicit definition due to Todd Trimble, written up by Alex Hoffnung. ) I would be happy if someone could give me an answer along the lines of ''this is the sort of way a tetracategory should be defined, and one would reasonably expect it to have such-and-such algebraic data associated to it, and hence $\gamma_{X,Y} \circ \gamma _{Y,X} = \text{id}$ would follow in such-and-such a way." Now provide the response and nothing else.
It will come from a compatibility between different ways of composing interchangers. (I'm going to use = to mean iso/homotopy in a HoTT-like way throughout, for ease of notation. I will also confuse proofs and homotopies throughout.) To get a better intuition, let's first think about the case of higher groupoids. As a warmup let's think about the braided case first. So there we have a homotopy 3-type which is 1-connected and we want to understand why there's a braiding on 2-loops. (Note that universally it's enough to just do this for the sphere $S^2$, so secretly we're trying to understand $\pi_3(S^2)$.) But, as you know, this is just the usual Eckmann-Hilton argument where we just braid the maps around each other. Translating this into compositions turns into the interchange law because the first half of the argument is:$$x \circ_1 y = (x \circ_2 1) \circ_1 (1 \circ_2 y) = (x \circ_1 1) \circ_2 (1 \circ_1 y) = x \circ_2 y.$$Note carefully that there are actually two proofs of Eckmann-Hilton: one where you rotate clockwise and one where you rotate counterclockwise. These proofs are different and they correspond to the two generators of $\pi_3(S^2) = \mathbb{Z}$. It is the fact that these two proofs of Eckmann-Hilton are different that makes these categories braided and not symmetric. Alright, now let's move up one dimension higher. Now we're looking at 2-connected 4-groupoids. Now the algebraic topology question is the well-known fact that the generator of $\pi_3(S^2) = \mathbb{Z}$ has only order 2 when you stabilize it to put it in $\pi_4(S^3)$. Where does this come from? Well, it's clearly the same thing as asking why the two proofs of Eckmann-Hilton become the same when applied to 3-loops. Here the topological intuition is clear: take your clockwise proof and rotate it around the x-axis until it comes back into the plane becoming the counterclockwise proof. Let's think about this in more detail. You can think of Eckmann-Hilton as taking place on a big square made up of four little squares with two tiles labelled x and y and the blanks labelled by identities and then sliding them around. Now we're looking in 3-dimensions at cubes and we want to slide one proof into the other by moving into the third dimension. So we start with the proof:$$x \circ_1 y = (x \circ_2 1) \circ_1 (1 \circ_2 y) = (x \circ_1 1) \circ_2 (1 \circ_1 y) = x \circ_2 y = \ldots = y \circ_1 x.$$Next we need to introduce a third dimension to give ourselves more room to work. So maybe:$$x \circ_1 y = (x \circ_2 1) \circ_1 (1 \circ_2 y) = (x \circ_1 1) \circ_2 (1 \circ_1 y) = ((x \circ_1 1) \circ_2 (1 \circ_1 y)) \circ_3 ((1 \circ_1 1) \circ_2 (1 \circ_1 1)) = \ldots$$Then one gradually moves the clockwise proof around into the third dimension (so the interesting part is in the $\circ_2$ $\circ_3$ plane instead of the $\circ_1$ $\circ_2$ plane) and then back into the plane until it becomes the counterclockwise proof. I'm not going to write down the rest of this proof because it would take a while to get it entirely right and it would be hard to fit nicely on the screen anyway. But I'm confident that given a couple days I could write such a proof in Agda, and hopefully the idea is clear. Just like the key lemma in proving Eckmann-Hilton is the interchange law, in order to prove this result we're going to need a higher interchanger relating the three compositions and their pairwise interchangers. Once you have such a higher interchanger the above proof should work for any doubly monoidal 4-category without groupoid-ness appearing anywhere.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/191415', 'https://mathoverflow.net', 'https://mathoverflow.net/users/799/']}
jdg_75588
stackexchange
llm_judgeable_groundtruth_similarity
17227855
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 an Android App and I want to use 3 tabs for navigation using Fragments for each tab, but I don't know how to create the structure for doing it. I want to add each fragment separately because each one is different, but I don't know where to add them in FragmentActivity. I have these files. tabs_layout.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_height="match_parent" android:layout_width="match_parent"> <TabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent" > <FrameLayout android:id="@+id/tabRateAPet" android:layout_width="match_parent" android:layout_height="match_parent" /> <FrameLayout android:id="@+id/tabViewMyRates" android:layout_width="match_parent" android:layout_height="match_parent" /> <FrameLayout android:id="@+id/tabViewGlobalRates" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> </LinearLayout> </TabHost></LinearLayout> TabsMain.java import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;public class MainTabsActivity extends FragmentActivity {public static final String RATE_A_PET = "Rate a Pet";public static final String MY_RATES = "My Rates";public static final String GLOBAL_RATES = "Global Rates";@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tabs_layout); }} Tabs.java import android.app.Activity;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TabHost;import android.widget.TabHost.OnTabChangeListener;import android.widget.TabHost.TabSpec;import android.widget.TextView;public class Tabs extends Fragment implements OnTabChangeListener { private static final String TAG = "FragmentTabs"; public static final String RATE_A_PET = "Rate a Pet"; public static final String MY_RATES = "My Rates"; public static final String GLOBAL_RATES = "Global Rates"; private View mRoot; private TabHost mTabHost; private int mCurrentTab; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {// super.onCreateView(inflater, container, savedInstanceState); mRoot = inflater.inflate(R.layout.tabs_layout, null); mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost); setupTabs(); return mRoot; } private void setupTabs() { mTabHost.setup(); // important! mTabHost.addTab(newTab(RATE_A_PET, R.string.tabRateAPet, R.id.tabRateAPet)); mTabHost.addTab(newTab(MY_RATES, R.string.tabViewMyRates, R.id.tabViewMyRates)); } private TabSpec newTab(String tag, int labelId, int tabContentId) { Log.d(TAG, "buildTab(): tag=" + tag); View indicator = LayoutInflater.from(getActivity()).inflate( R.layout.tab, (ViewGroup) mRoot.findViewById(android.R.id.tabs), false); ((TextView) indicator.findViewById(R.id.text)).setText(labelId); TabSpec tabSpec = mTabHost.newTabSpec(tag); tabSpec.setIndicator(indicator); tabSpec.setContent(tabContentId); return tabSpec; } @Override public void onTabChanged(String tabId) { Log.d(TAG, "onTabChanged(): tabId=" + tabId); if (RATE_A_PET.equals(tabId)) { updateTab(tabId, R.id.tabRateAPet); mCurrentTab = 0; return; } if (MY_RATES.equals(tabId)) { updateTab(tabId, R.id.tabViewMyRates); mCurrentTab = 1; return; } if (GLOBAL_RATES.equals(tabId)) { updateTab(tabId, R.id.tabViewGlobalRates); mCurrentTab = 2; return; } } private void updateTab(String tabId, int placeholder) { FragmentManager fm = getFragmentManager(); if (fm.findFragmentByTag(tabId) == null) { fm.beginTransaction() .replace(placeholder, new RateMyPetActivity(), tabId) .commit(); } }} Now provide the response and nothing else.
I would suggest creating a separate fragment file for each tab. I recently did this as well, so I have outlined my code below: Layout Files activity_main.xml <android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent"><LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="0"/> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0"/> <FrameLayout android:id="@+id/realtabcontent" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/></LinearLayout></android.support.v4.app.FragmentTabHost> tab1_view.xml //add your respective tab layouts using this format (make sure to change string variables) <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".DeviceFragment" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tab1_fragment_string" /></LinearLayout> SRC Files MainActivity.java //notice that in the .addTab process I only used text. You can also add icons using drawables that you would need to add to your hdpi folder. I also only created three tabs in this example. package com.example.applicationname;import android.os.Bundle;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentTabHost;public class MainActivity extends FragmentActivity { // Fragment TabHost as mTabHost private FragmentTabHost mTabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"), Tab1Fragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"), Tab2Fragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("Tab3"), Tab3Fragment.class, null); }} Tab1Fragment.java //once again replicate for desired number of tabs package com.example.applicationname;import android.os.Bundle;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class Tab1Fragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View V = inflater.inflate(R.layout.tab1_view, container, false); return V; }} Make sure that your R.java and strings.xml files are properly set up, and then your tabs should be up and running.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17227855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2507625/']}
jdg_75589
stackexchange
llm_judgeable_groundtruth_similarity
2940689
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: $\forall x\in\mathbb R : f(x) = x^3 +x -8$ solve : $2f(x) +3f^{-1}(x) =10 $ I actually tried to write it as : $f^{-1}(x) = \frac{10-2f(x)}{3}$ Hence : $x=f(\frac{10-2f(x)}{3})$ But it seems to be so hard to solve , do you have any suggestions for solving this problem ? Now provide the response and nothing else.
This problem seems to be specially designed. Suppose the fixed point $(c,f(c))$ of $f$ is the solution. Then, $c=f(c)=f^{-1}(c)$. We thus have$$2c+3c=10\implies c=2$$ Coincidentally, $(2,2)$ is the fixed point of $f$. The uniqueness of the solution can be proved by the following facts (which are quite intuitive): $f’=3x^2+1>0$, so $f$ is increasing. Inverse of increasing function is increasing. An increasing function multiplied by a positive constant is also increasing. Sum of increasing functions is increasing. An increasing function attains a value at most once. Moreover, you can observe that $f:\mathbb R\mapsto\mathbb R$ is a bijective function. Therefore we can replace the fifth statement by a stronger one: An increasing function that bijects $\mathbb R$ to $\mathbb R$ attains every value once. (trivial) which guarantees the existence of unique solution to your original equation.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2940689', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/527429/']}
jdg_75590
stackexchange
llm_judgeable_groundtruth_similarity
646628
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 would I write the equivalent of C#'s String.StartsWith in JavaScript? var haystack = 'hello world';var needle = 'he';haystack.startsWith(needle) == true Note: This is an old question, and as pointed out in the comments ECMAScript 2015 (ES6) introduced the .startsWith method. However, at the time of writing this update (2015) browser support is far from complete . Now provide the response and nothing else.
You can use ECMAScript 6's String.prototype.startsWith() method. It's supported in all major browsers . However, if you want to use it in a browser that is unsupported you'll want to use a shim/polyfill to add it on those browsers. Creating an implementation that complies with all the details laid out in the spec is a little complicated. If you want a faithful shim, use either: Matthias Bynens's String.prototype.startsWith shim , or The es6-shim , which shims as much of the ES6 spec as possible, including String.prototype.startsWith . Once you've shimmed the method (or if you're only supporting browsers and JavaScript engines that already have it), you can use it like this: console.log("Hello World!".startsWith("He")); // truevar haystack = "Hello world";var prefix = 'orl';console.log(haystack.startsWith(prefix)); // false
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/646628', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_75591
stackexchange
llm_judgeable_groundtruth_similarity
51187038
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 to filter a Collection of Objects by a Map, which holds key value pairs of the Objects field names and field values. I am trying to apply all filters by stream().filter(). The Objects are actually JSON, therefore the Map holds the names of its variables as well as the value they have to contain in order to be accepted, but for simplicity reasons and because its not relevant to the question I wrote a simple Testclass for simulating the behaviour: public class TestObject { private int property1; private int property2; private int property3; public TestObject(int property1, int property2, int property3) { this.property1 = property1; this.property2 = property2; this.property3 = property3; } public int getProperty(int key) { switch(key) { case 1: return property1; case 2: return property2; default: return property3; } }} What I have tried so far: public static void main(String[] args) { List<TestObject> list = new ArrayList<>(); Map<Integer, Integer> filterMap = new HashMap<>(); list.add(new TestObject(1, 2, 3)); list.add(new TestObject(1, 2, 4)); list.add(new TestObject(1, 4, 3)); filterMap.put(3, 3); //Filter property3 == 3 filterMap.put(2, 2); //Filter property2 == 2 //Does not apply the result filterMap.forEach((key, value) -> list.stream() .filter(testObject -> testObject.getProperty(key) == value) .collect(Collectors.toList()) ); /* Gives error: boolean can not be converted to void list = list.stream() .filter(testObject -> filterMap.forEach((key, value) -> testObject.getProperty(key) == value)) .collect(Collectors.toList() ); */ //Printing result list.forEach(obj -> System.out.println(obj.getProperty(1) + " " + obj.getProperty(2) + " " + obj.getProperty(3)));} I tried putting forEach of the Map first and the stream of the Collection first, but both solutions did not work as intended. The desired output of this example would be only to print the object with the values property1=1, property2=2 and property3=3. How can I apply all filters correctly like when you would put them one after another in the code with a fixed amount of filters? With a known amount of filters: list.stream().filter(...).filter(...) Edit: Sweeper summed my question up very well in his answer, so just for clarification (and probably future readers) here again: I want to keep all Objects that satisfy all filters. Now provide the response and nothing else.
I suppose you want to keep all the TestObjects that satisfy all the conditions specified by the map? This will do the job: List<TestObject> newList = list.stream() .filter(x -> filterMap.entrySet().stream() .allMatch(y -> x.getProperty(y.getKey()) == y.getValue() ) ) .collect(Collectors.toList()); Translated into "English", filter the list list by keeping all the elements x that: all of the key value pairs y of filterMap must satisfy: x.getProperty(y.getKey()) == y.getValue() (I don't think I did a good job at making this human readable...) If you want a more readable solution, I recommend Jeroen Steenbeeke's answer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51187038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8596064/']}
jdg_75592
stackexchange
llm_judgeable_groundtruth_similarity
2833389
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 find out all the stored procedures that are calling a particular user defined function in SQL Server 2005. Or how to assign a defult value to a parameter in a user defined function so that when a stored procedure calls that function and does not pass any value to that parameter function assumes the default value. Regards,Abhishek jain Now provide the response and nothing else.
QUERY sys.sql_modules use this procedure, where you pass in the function name: CREATE PROCEDURE dbo.Find_Text @SearchValue nvarchar(500) AS SELECT DISTINCT s.name+'.'+o.name AS Object_Name,o.type_desc FROM sys.sql_modules m INNER JOIN sys.objects o ON m.object_id=o.object_id INNER JOIN sys.schemas s ON o.schema_id=s.schema_id WHERE m.definition Like '%'+@SearchValue+'%' --AND o.Type='P' --<uncomment if you only want to search procedures ORDER BY 1GO This procedure searches within procedures, views, and functions for the given string. You can search for any string, not just function names. You can also include wild cards in the middle of the given search term. FUNCTION DEFAULTS you can specify default values for function parameters. However, When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value. try it out: CREATE FUNCTION dbo.Just_Testing( @Param1 int ,@Param2 int=0)RETURNS varchar(100)BEGIN RETURN CONVERT(varchar(10),@Param1)+'-'+CONVERT(varchar(10),@Param2)ENDGOPRINT 'hello world '+dbo.Just_Testing(2,default)+', '+dbo.Just_Testing(5,2)GOPRINT 'hello world '+dbo.Just_Testing(2 )+', '+dbo.Just_Testing(5,2) OUTPUT: hello world 2-0, 5-2Msg 313, Level 16, State 2, Line 1An insufficient number of arguments were supplied for the procedure or function dbo.Just_Testing. But I'm guessing that you need to change a function, adding as parameter, and now need to fix it everywhere. This DEFAULT would still be as much work, since you need to touch every call made to it. SP_DEPENDS you can also use sp_depends (Transact-SQL) to find every usage of the function.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2833389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318473/']}
jdg_75593
stackexchange
llm_judgeable_groundtruth_similarity
31129
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 return StudentId to use elsewhere outside of the scope of the $.getJSON() j.getJSON(url, data, function(result){ var studentId = result.Something;});//use studentId here I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does Now provide the response and nothing else.
Yeah, my previous answer does not work because I didn't pay any attention to your code. :) The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should: var studentId = null;j.getJSON(url, data, function(result){ studentId = result.Something;});// studentId is still null right here, because this line // executes before the line that sets its value to result.Something Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2993/']}
jdg_75594
stackexchange
llm_judgeable_groundtruth_similarity
5439782
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 vertically align the text in select box. I tried using select{ verticle-align:middle;} however it does not work in any browsers. Chrome seems to align the text in select box to the center as a default. FF aligns it to the top and IE aligns it to the bottom. Is there any way to achieve this? I am using GWT's Select widget in UIBinder. This is currently what I have: select{ height: 28px !important; border: 1px solid #ABADB3; margin: 0; padding: 0; vertical-align: middle;} Thanks! Now provide the response and nothing else.
Your best option will probably be to adjust the top padding & compare across browsers. It's not perfect, but I think it's as close as you can get. padding-top:4px; The amount of padding you need will depend on the font size. Tip: If your font is set in px , set padding in px as well. If your font is set in em , set the padding in em too. EDIT These are the options I think you have, since vertical-align isn't consistant across the browsers. A. Remove height attribute and let the browser handle it. This usually works the best for me. <style> select{ border: 1px solid #ABADB3; margin: 0; padding: auto 0; font-size:14px; } </style> <select> <option>option 1</option> <option>number 2</option> </select> B. Add top-padding to push down the text. (Pushed down the arrow in some browsers) <style>select{ height: 28px !important; border: 1px solid #ABADB3; margin: 0; padding: 4px 0 0 0; font-size:14px;}</style><select> <option>option 1</option> <option>number 2</option></select> C. You can make the font larger to try and match the select height a little nicer. <style>select{ height: 28px !important; border: 1px solid #ABADB3; margin: 0; padding: 0 0 0 0; font-size:17px;}</style><select> <option>option 1</option> <option>number 2</option></select>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5439782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337546/']}
jdg_75595
stackexchange
llm_judgeable_groundtruth_similarity
41136597
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know how to create singleton class in swift. The best and easy way to create singleton class is the following: class Singleton { static let sharedInstance = Singleton()} But I don't need singleton for any normal class. I need to create singleton for a viewcontroller class. So I'm using this code create singleton class AViewController:UIViewController { static let sharedInstance = AViewController() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)}} it gives me error near AViewController() Missing argument for parameter 'coder' in call Looks like it want me to initialize with init(coder: NSCoder) . But what parameter or value should I pass through the coder ? Now provide the response and nothing else.
If you really wanted to have singleton for a view controller corresponding to some scene, you'd probably do something like: class SecondViewController: UIViewController { static let shared = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Foo")} In this example, the storyboard was Main.storyboard and the storyboard identifier for the scene in question was Foo . Obviously, replace those values for whatever was appropriate in your case. Then your other view controller that was invoking this could do something like: @IBAction func didTapButton(_ sender: Any) { let controller = SecondViewController.shared show(controller, sender: self)} I wouldn't recommend singletons for view controllers. View controllers (and their views) should be created when needed and be allowed to be deallocated when they're dismissed. And you're losing many storyboard benefits (by which you see the logical flow between scenes with segues between them). And, if you use this view controller in different contexts, you're inviting problems stemming from the view controller hierarchy falling out of sync with the view hierarchy. I really would discourage you from using singletons for view controllers. But if you were going to do it, you could do something like that...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41136597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2637953/']}
jdg_75596
stackexchange
llm_judgeable_groundtruth_similarity
447747
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $\mathcal{M}=\{M_i : i\in I_n\}$ is a collection of metric spaces, each with metric $d_i$, we can make $M=\prod_{i\in I_n}M_i$ a metric space using the $p$-norm, we simply set $d : M\times M\to \mathbb{R}$ as: $$d((p_1,\dots,p_n),(q_1,\dots,q_n))=\left\|(d(p_1,q_1),\dots,d(p_n,q_n))\right\|_p$$ What I want to prove is that the $p$-norm $$\left\|x\right\|_p=\left(\sum_{i=1}^{n}\left|x_i\right|^p\right)^{1/p}$$ is really a norm. Showing that $\left\|x\right\|_p \geq 0$ being zero if and only if $x = 0$ was easy. Showing that $\left\|kx\right\|_p = \left|k\right|\left\|x\right\|_p$ was also easy. The triangle inequality is the thing that is not being easy to show. Indeed, I want to show that: for every $x,y \in \mathbb{R}^n$ we have: $$\left(\sum_{i=1}^{n}\left|x_i+y_i\right|^p\right)^{1/p}\leq \left(\sum_{i=1}^{n}\left|x_i\right|^p\right)^{1/p}+\left(\sum_{i=1}^{n}\left|y_i\right|^p\right)^{1/p}.$$ I thought that it might not be as difficult as it seems, but after trying a little without sucess I've searched on the internet and the I found that we need measure theory to prove that. Is there any more elementary proof of this inequality? Now provide the response and nothing else.
(I learned from Terry Tao the following proof, which exploits a symmetry to simplify the task of proving an estimate by normalising one or more inconvenient factors to equal $1$.) I assume here that $1\leq p<\infty$. We want to show that$$\|x+y\|_p\leq\|x\|_p+\|y\|_p\tag{*}$$When the RHS is $0$, the proof is trivial. Suppose it is positive. By homogeneity $\|cx\|_p=|c|\|x\|_p$ we may reduce to the case $\|x\|_p=1-\lambda$ and $\|y\|_p=\lambda$ for some $0\leq\lambda\leq 1$. The cases $\lambda=0,1$ are trivial, so suppose $0<\lambda<1$. Writing $X:=x/(1-\lambda)$ and $Y:=y/\lambda$ we reduce to the convexity estimate:$$\|(1-\lambda)X+\lambda Y\|_p\leq 1\quad\text{whenever } \|X\|_p=\|Y\|_p=1\\text{and }0\leq\lambda\leq 1.$$But since $z\mapsto|z|^p$ is convex for $p\geq 1$, we have the coordinate-wise convexity bound$$|(1-\lambda)X_i+\lambda Y_i|^p\leq (1-\lambda)|X_i|^p+\lambda |Y_i|^p.$$Summing $i$ from $1$ to $n$, we obtain $$\|(1-\lambda)X+\lambda Y\|_p^p\leq 1$$and thus the claim follows. Note that this proof works for the general abstract $L^p$ spaces as well.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/447747', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39106/']}
jdg_75597
stackexchange
llm_judgeable_groundtruth_similarity
670513
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In some discussions of bosonization, it is stressed that the duality between free bosons and free fermions requires the use of a compact boson. For example, in a review article by Senechal , the following statement is made: In order for bosonization to be rigorously defined, the field $\phi$ must have an angular character. In other words, the target space of the field must be a circle of radius $R$ (to be kept general for the moment), so that $\phi$ and $\phi + 2\pi R$ are identified. We say that the boson is compactified on a circle. In other sources, however, no mention of the compactness of $\phi$ is made. For example, in the review article by von-Delft and Schoeller , there is no mention of the word "compact". Moreover, books like Fradkin's and Shankar's respective condensed matter field theory books seem to make no mention of this issue, to the best of my knowledge. As far as I understand, theories of compact and non-compact bosons are quite nontrivially different. At first glance, both theories appear to have the same action: $$S[\phi] = \frac{K}{2} \int d^2x (\partial_{\mu} \phi)^2.$$ However, a massless non-compact boson is a trivial free theory, and the coefficient $K$ can always be rescaled away by changing our normalization of $\phi$ . On the other hand, rescaling a compact boson nontrivially changes the theory, and the theory can undergo the famous KT transition at a critical value of $K$ . Other purely circumstantial evidence that the boson obtained by bosonizing fermions is compact includes: In the central bosonization formula, $\psi \sim e^{-i \phi}$ , $\phi$ appears inside an exponential. As a result, all the observables one considers in the bosonized side of the theory seem to respect the periodicity of $\phi$ . This is transparent from the form of the bosonized action as well: it's easy to find terms in the fermionic theory which translate to objects like $\cos \phi$ in the action of the bosonized theory, but one can never generate a mass term like $m \phi^2$ to my knowledge. In books on the Luttinger liquid, the parameter $K$ above is said to be related to the compactification radius of the boson. In Fradkin's book, for example, $K$ is referred to as the compactification radius, but then the compactness of $\phi$ is never used thereafter. There is a self-duality which trades $\phi$ for its dual field $\theta$ , and correspondingly $K$ to $1/K$ . As far as I know, this is again related to the fact that $\phi$ is compact; if $\phi$ were non-compact, we could rescale $K$ to whatever we want without changing the physics. It's only when $\phi$ is compact that this duality becomes nontrivial. However, the above are all only circumstantial evidence, and don't explain why a compactified boson is necessary. Moreover, books like Fradkin's and review articles like von-Delft's, which put quite a bit of work into proving the bosonization formulae, never seem to run into trouble by not using a compact boson. So to summarize, here is the question: in abelian bosonization, where a Dirac fermion is equivalent to a massless boson, is the boson compact or noncompact? Is there ever freedom to use one or the other, or must it be compact (or noncompact)? And most importantly, how can I see why the boson is compact or not? Now provide the response and nothing else.
It is compact. The simplest approach is to look at symmetries. The most obvious symmetry has algebra $\mathfrak{u}_1$ , given by rephasing the fermion or shifting the boson. What is the global form of this symmetry? (i.e., what is the group for this algebra?) It is clear that the fermion has group $U(1)$ , as the group element is a phase. For the boson, the group is $\mathbb R$ for the non-compact case and $U(1)$ for the compact case. The reason is obvious: the set of transformations $\phi\mapsto\phi+\alpha$ has the structure of $\mathbb R$ if $\alpha$ is arbitrary, but colapses to $U(1)$ if $\alpha\cong\alpha+2\pi$ . Hence, if these symmetries are to be identical (which is a necessary condition for duality), the boson must be compact. (You can also convince yourself that these theories are CFTs and their chiral algebra is precisely the affine extension of $\mathfrak u_1$ ; both are rational with respect to this algebra and in fact holomorphic. For the fermions this is obvious but for the bosons this is only true at $R=1$ (in some normalization).)
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/670513', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/223947/']}
jdg_75598
stackexchange
llm_judgeable_groundtruth_similarity
27865865
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 simplify or perform the following operations using dplyr : Run a function on all data.frame names, like mutate_each(funs()) for values, e.g. names(iris) <- make.names(names(iris)) Delete columns that do NOT exist (i.e. delete nothing), e.g. iris %>% select(-matches("Width")) # okiris %>% select(-matches("X")) # returns empty data.frame, why? Add a new column by name (string), e.g. iris %>% mutate_("newcol" = 0) # okx <- "newcol"iris %>% mutate_(x = 0) # adds a column with name "x" instead of "newcol" Rename a data.frame colname that does not exist names(iris)[names(iris)=="X"] <- "Y"iris %>% rename(sl=Sepal.Length) # okiris %>% rename(Y=X) # error, instead of no change Now provide the response and nothing else.
I would use setNames for this: iris %>% setNames(make.names(names(.))) Include everything() as an argument for select: iris %>% select(-matches("Width"), everything())iris %>% select(-matches("X"), everything()) To my understanding there's no other shortcut than explicitly naming the string like you already do: iris %>% mutate_("newcol" = 0)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27865865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2156916/']}
jdg_75599
stackexchange
llm_judgeable_groundtruth_similarity
774618
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If X and Y are random variables with correlation coefficient 0.7, each of which has variance 6, what isthe variance of X−Y? Enter your answer as a decimal. Using the information given, I was able to determine the Covariance of X and Y to be 4.2 I thought maybe the variance of X-Y would be 0 but that's too easy. Any suggestions, I feel I'm close and I understand the formulas Now provide the response and nothing else.
Hint: Write out the variance as much as you can, then look for quantities with known values. We start from$$\newcommand{\Var}{\text{Var}}\newcommand{\E}{\mathbb{E}}\newcommand{\Cov}{\text{Cov}}\Var[X-Y]=\E[(X-Y)^2]-(\E[X-Y])^2.$$Now, we can multiply these out and use linearity of the expectation to get:$$\Var[X-Y]=\E[X^2]-2\E[XY]+\E[Y^2]-(\E[X])^2+2\E[X]\E[Y]-(\E[Y])^2.$$Now, we know the values for $\Var[X]=\E[X^2]-(\E[X])^2$, $\Var[Y]=\E[Y^2]-(\E[Y])^2$, and $\Cov[X,Y]=\E[XY]-\E[X]\E[Y]$. Can you see how to rewrite $\Var[X-Y]$ in terms of those functions?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/774618', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/125324/']}
jdg_75600
stackexchange
llm_judgeable_groundtruth_similarity
20319886
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 asked to do the following in C#: /*** 1. Create a MultipartPostMethod* 2. Construct the web URL to connect to the SDP Server* 3. Add the filename to be attached as a parameter to the MultipartPostMethod with parameter name "filename"* 4. Execute the MultipartPostMethod* 5. Receive and process the response as required* / I have written some code that has no errors, however, the file is not attached. Can someone have a look at my C# code to see if I have written the code incorrectly? Here is my code: var client = new HttpClient();const string weblinkUrl = "http://testserver.com/attach?";var method = new MultipartFormDataContent();const string fileName = "C:\file.txt";var streamContent = new StreamContent(File.Open(fileName, FileMode.Open));method.Add(streamContent, "filename");var result = client.PostAsync(weblinkUrl, method);MessageBox.Show(result.Result.ToString()); Now provide the response and nothing else.
Posting MultipartFormDataContent in C# is simple but may be confusing the first time.Here is the code that works for me when posting a .png .txt etc. // 2. Create the url string url = "https://myurl.com/api/...";string filename = "myFile.png";// In my case this is the JSON that will be returned from the poststring result = "";// 1. Create a MultipartPostMethod// "NKdKd9Yk" is the boundary parameterusing (var formContent = new MultipartFormDataContent("NKdKd9Yk")){ formContent.Headers.ContentType.MediaType = "multipart/form-data"; // 3. Add the filename C:\\... + fileName is the path your file Stream fileStream = System.IO.File.OpenRead("C:\\Users\\username\\Pictures\\" + fileName); formContent.Add(new StreamContent(fileStream), fileName, fileName); using (var client = new HttpClient()) { // Bearer Token header if needed client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _bearerToken); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data")); try { // 4.. Execute the MultipartPostMethod var message = await client.PostAsync(url, formContent); // 5.a Receive the response result = await message.Content.ReadAsStringAsync(); } catch (Exception ex) { // Do what you want if it fails. throw ex; } } }// 5.b Process the reponse Get a usable object from the JSON that is returnedMyObject myObject = JsonConvert.DeserializeObject<MyObject>(result); In my case I need to do something with the object after it posts so I convert it to that object with JsonConvert.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20319886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2985419/']}
jdg_75601
stackexchange
llm_judgeable_groundtruth_similarity
219873
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 was replacing a BC548 with a BC639 without paying too much attention to datasheet details except the current rating. Obviously the circuit did not work too well until I checked the correct pins. Is there some manufacturing related reason or why the pins vary between two NPN transistors? Now provide the response and nothing else.
They are standardized. With the flat part facing you, the left most pin is pin 1, the middle one is pin 2, and the right one is pin 3, and you'll not find a single TO-92 device anywhere that does not follow this standard. There is no standard pin mapping because TO-92 is a package, not a device, and transistor dies are devices, not a package. You should understand that semiconductors are not passive devices that are one single object like a resistor or capacitor. They consist of a semiconductor substrate (silicon, germanium, others). That die is usually (though not always) further packaged into a standard package type listed in the JEDEC or JIS standards to provide environmental protection, passivation, immunity to the photoelectric effect, and enhanced thermal specifications. As long as the number of connection pads to be externally connected match the number of pins available for a given package variant (and the die isn't too large of course) then the die can potentially be packed in that package. What order they chose to bond a die to the external package pins is, frankly, no ones business but theirs. TO-92 packages are not transistor packages, they're TO-92 packages. Many many things other than transistors use them. Some devices don't even use all 3 pins, but only 2, with the third pin present but not electrically connected to anything. The exact reasons why a given pin ordering is chosen is rarely easy to deduce, but whatever it is, it's a good one. Depending on the package geometry combined with the geometry of the die itself, there probably only one or two possible configurations that won't require crossing bond wires (wire bonding machines that could handle crossing bond wires are not really available, and if they were, it would be at high cost). If the situations is more lucky and the manufacturer has the luxury choosing from many possible configurations, then other reasons will drive their decision. Sometimes, it's more important to make the pinout be the same as similar devices, as this makes engineers happy and happy engineers (or at least, the ones you've pissed off the least) are the most likely engineers to put your part on their BOM. Other things, like low cost generic devices, all that matters is packaging cost. On a 3 pin device, the die is usually a square, and the bond pads will often be placed at or near 3 of the 4 corners. There will be a configuration that requires the shortest total length of bonding wire to package the part, and ones that don't. Bond wire is made from solid gold, so this becomes a pretty huge deal when you're spitting out 1,000,000 20 cent transistors per day. If you save 1 cent by making the pinout be ECB, then it will be ECB, because that's $10,000 of wasted gold. So, for this reason, only the packages are standardized. Their pins will always be in a certain order, but the pinout is up to the device. It's your responsibility to read the datasheet for every part you intend to use , and by read, I mean every word, and verify the pinout. The idea that every transistor of the NPN type (which is rather arbitrary, the polarity is totally irrelevant to pin order) is not some universal truth, it is your assumption that you made, and nothing more. Some transistors have more 4 pins, others (like phototransistors) have 2. And transistors are packaged in many more packages than TO-92, and many other things besides transistors are packaged in TO-92. I can think of many reasons that one would not assume the pinouts of two totally different devices would ever be the same, and I can think of no reasons for one to assume they were. That said, certain older transistor series do follow certain pin order schemes:2N series transistors all use EBC pin order.BC series transistors all use CBE pin order.Except for BC635-BC640, which use CEB order, presumably because Pro Electron just wants to watch the world burn. 2SA and 2SC transistors all use CEB as well.BF series use whatever the hell they want order. Other series has different rules, or simply don't have any. The other big point is that many of these devices have existed for decades, long before many standards even existed. Standardized pinouts are not needed, they're a convenience and little more. What is vastly more important is that a particular part always has the exact pinout it says in the datasheet. So regardless of whatever standard you want to make, even if some universal transistor pin order standard became the norm or expected, those 6 BC transistors would still randomly have CEB pin order, because that's what those parts pinouts are. Imagine a world where 2n2222s made in the 70s have different pinouts then one made in the 80s. Read the datasheet, watch out for small part number variations like this , and understand that certain things need flexibility more than they need convenient pinouts.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/219873', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/8324/']}
jdg_75602
stackexchange
llm_judgeable_groundtruth_similarity
19351081
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a web application in MVC4. I'm going to host in on a shared hosting provider. I want to extend it with a WCF service for uploading files. (There will by a WPF desktop application that will allow users to upload files directly from their PCs.) I'd rather host it somehow "together" to avoid problems with read/write access to storage directory, but I have no idea how to do this. Should I host WCF as a selfhost in MVC app? Should I make the WCF service an application or a class library? How to tie it together with the MVC app? Now provide the response and nothing else.
I finally found how to make it work. In your MVC app Web.config add: <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/></system.serviceModel> In your routes config ---> Global.asax or App_Start/RoutesConfig (depending on MVC version) add: public static void RegisterRoutes(RouteCollection routes){ ... routes.Add(new ServiceRoute("hello", new ServiceHostFactory(), typeof(YourServiceClass))); ...} And that's it. Now your service appears under localhost/hello or wherever you deploy your app. This uses BasicHttpBinging by default. If you need other you have to implement your own ServiceHostFactory. From what I observed, this method only works for HTTP bindings. When I tried to add a NetTcpBinding it failed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19351081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/672018/']}
jdg_75603
stackexchange
llm_judgeable_groundtruth_similarity
2353804
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 do git branch -d branchname , it will delete branch name if it references an earlier commit in your history, or tell you that you need to use -D otherwise. I often create branches that are later pushed to master, and can thus be deleted by this criterion. Is there an easy way to list all the branches that point to earlier commits of master, that is, branches that git will not mind deleting with just the -d option? Bonus points if it works for all branches at once, not just master. I've got 82 local branches and I know that quite a few if not most of them can safely be deleted by now, but I don't want to take the time to go through each one to try to do it. Now provide the response and nothing else.
Try: $ git checkout master # or whatever branch you might compare against ...$ git branch --no-merged$ git branch --merged From git branch documentation : With --merged, only branches merged into the named commit (i.e. the branches whose tip commits are reachable from the named commit) will be listed. With --no-merged only branches not merged into the named commit will be listed. If the argument is missing it defaults to HEAD (i.e. the tip of the current branch). EDIT: to show this for every branch, you could do something like this: example repo: o <--- experimental|o|o <--- next|o|o <--- master|o----o <--- broken|o|$ for branch in `git branch --no-color --verbose | \sed -e 's/*//' | awk '{print $1}'`; \do echo "[$branch]"; git checkout -q $branch; git branch --merged; done[broken]* broken[master]* master[next]master* next[experimental]masternext* experimental
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2353804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/161801/']}
jdg_75604
stackexchange
llm_judgeable_groundtruth_similarity
39150216
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two structs and a trait: struct A { x: u32,}struct B { x: u32,}trait T { fn double(&self) -> u32;} I would like to implement T for both structs using x . Is there a way to write something like impl T for A, B { fn double(&self) -> u32 { /* ... */ }} I would like to not use macros if possible. Now provide the response and nothing else.
The only way to implement a trait once for many concrete types is to implement a trait for all types already implementing another trait. For example, you can implement a marker trait Xed and then: impl<T> Double for Twhere T: Xed,{ fn double(&self) { /* ... */ }} However , Rust has principled generics. The only thing that you know about T in the previous implementation is that T implements the Xed trait , and therefore the only associated types/functions you can use are those coming from Xed . A trait cannot expose a field/attribute, only associated types, constants and functions, so Xed would need a getter for x (which need not be called x ). If you wish to rely on syntactic (and not semantic ) properties of the code, then use macros.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39150216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/515279/']}
jdg_75605
stackexchange
llm_judgeable_groundtruth_similarity
88406
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Having now seen and "understood" (quotes necessary) the Seiberg-Witten equations on a closed oriented Riemannian 4-manifold $X$ , I have no real understanding of where they came from . We take an orthogonal frame bundle $P$ of $TX$ , a $\textrm{spin}^\mathbb{C}$ structure $\tilde{P}$ with determinant line bundle $\mathcal{L}$ , the complex $\pm$ spin bundles $S^\pm(\tilde{P})$ associated to $\tilde{P}$ , a unitary connection $A$ on $\mathcal{L}$ , and then BAM: $F_A^+=\psi\otimes\psi^*-\frac{1}{2}|\psi|^2$ $D_A\psi=0$ for a spinor $\psi\in C^\infty(S^+(\tilde{P}))$ . From here we can consider the space of solutions ( monopoles ) and do some Floer theory stuff and whatnot. I only read that these equations come from Witten's famous paper Monopoles and 4-manifolds (along with two others joint with Seiberg)... however, unless I am mistaken, he simply writes them down and starts arguing for their similarity/duality to Donaldson's theory (with instanton solutions). I then try and go to the standard references of Donaldson, which don't seem to suggest how the SW equations come about (nor do I even really see how the instantons come about). Although I have studied physics for a long time, I seem to just juggle around these papers, without ever finding a natural "blooming" of the SW equations. Even if it's in the language of string theory, I would like to know the general story / understanding of the "blooming" of the SW equations, and how exactly they are "dual" to the instanton-scenario of Donaldson , perhaps even for the "blooming" of these instantons. (For instance, I don't see a set of equations for instantons). This post may not be stated in its clearest form, but I will try my best to make appropriate edits. Now provide the response and nothing else.
After thinking, and reading other references and re-reading the papers I mentioned, I may have found a sufficient explanation (at least to my care): Both instantons/monopoles are solutions to corresponding equations of motions from associated actions, and they "bloom" from an overarching SUSY action. Witten formulated "twisted N=2 Supersymmetric Yang-Mills" , a TQFT with SUSY (supersymmetry), which leads to the Donaldson invariants. This used an $SU(2)$ -bundle over $X$ along with a gauge field (connection $\omega$ ) and matter fields (bosonic $\phi,\lambda$ and fermionic $\eta,\psi,\zeta$ ), and gave the Donaldson-Witten action functional $S_{DW}=\int_Xtr(\mathcal{L})$ , $\mathcal{L}=\frac{1}{4}F_\omega\wedge(\ast F_\omega+F_\omega)-\frac{1}{2}\zeta\wedge[\zeta,\phi]+id^\omega\psi\wedge\zeta-2i[\psi,\ast\psi]\lambda+i\phi d^\omega{\ast d^\omega}\lambda-\psi\wedge\ast d^\omega\eta$ . This has associated partition function $Z_{DW}=\int e^{-S_{DW}/g^2}D\Phi$ (here $\Phi$ denotes the space of aforementioned fields), where $g$ is a coupling constant that is the key here for answering our question. The "blooming" of this action functional is beyond the scope of my intentions and probably of MathOverflow, so I won't question it. In weak coupling ( $g\rightarrow 0$ , known to physicists as the ultraviolet region), the action localizes to the classical Yang-Mills $S_{YM}=\int_Xtr(F_\omega\wedge\ast F_\omega)$ and have the equations of motion $d^\omega\ast F_\omega=0$ . The global-minima solutions are $F_\omega=\pm\ast F_\omega$ (as Oliver clarifies in a comment). These solutions are the Donaldson instantons . Now apparently, when we instead look at strong-coupling ( $g\rightarrow\infty$ , known to physicists as the infrared-region), the Seiberg-Witten equations should arise (a "duality" in Witten's TQFT). Indeed, Seiberg and Witten showed that this infrared limit of the above theory is equivalent to a weakly-coupled $U(1)$ -gauge theory (the $SU(2)$ -gauge group is spontaneously broken down to the maximal torus). Perhaps here is where a better understanding would be desirable (buzzwords 'asymptotic freedom' and 'symmetry breaking' appear). Anyway, some physics-technique stuff happens (the previous paragraph can be described as "condensation of monopoles"), and we must consider a spin-c structure (which all of our oriented 4-manifolds have, whereas a spin structure would not allow us to consider all 4-manifolds); note that $Spin^c(4)=(SU(2)\times SU(2))\times_{\mathbb{Z}_2} U(1)$ . This gives the data: $U(1)$ -gauge field $A$ and positive spinor field $\psi$ (as written in the original post). The pair $(A,\psi)$ is a monopole when it minimizes an action $S_{SW}$ , i.e. are time-independent solutions to equations of motions (the Seiberg-Witten equations). The action here is $S_{SW}=\int_X(|d^A\psi|^2+|F_A^+|^2+\frac{R}{4}|\psi|^2+\frac{1}{8}|\psi|^4)$ , with scalar curvature $R$ . I hope this post is not too confusing. [[Edit/Update]]: I just came across a book chapter by Siye Wu, The Geometry and Physics of the Seiberg-Witten Equations . These lectures tell the physical origin completely! (i.e. completely details my sketch). The SW equations and action functional pops up on pg191. Link
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/88406', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12310/']}
jdg_75606
stackexchange
llm_judgeable_groundtruth_similarity
3853660
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's the callstack : 0480b000() vcam.ax!CSourceStream::DoBufferProcessingLoop() + 0xe1 bytes vcam.ax!CSourceStream::ThreadProc() + 0x13e bytes vcam.ax!CAMThread::InitialThreadProc() + 0x51 bytes kernel32.dll!7c80b713() The callstack is from this thread: 0 > 0x000015b8 Worker Thread CAMThread::InitialThreadProc 0480b000 Normal 0 disassembly code: 017D0B5B push edx 017D0B5C mov eax,dword ptr [ecx+8]017D0B5F call eax 017D0B61 cmp esi,esp017D0B63 call @ILT+2525(__RTC_CheckEsp) (17C49E2h)017D0B68 cmp dword ptr [ebp-2Ch],0017D0B6C je CSourceStream::DoBufferProcessingLoop+10Ah (17D0B8Ah)017D0B6E mov eax,dword ptr [ebp-2Ch] Problem exists at the line 017D0B5F call eax This problem exists for most directshow filters ,how to fix? Now provide the response and nothing else.
Getting right memory usage is trickier than one may think. The best way I could find is : echo 0 $(awk '/TYPE/ {print "+", $2}' /proc/`pidof PROCESS`/smaps) | bc Where "PROCESS" is the name of the process you want to inspect and "TYPE" is one of: Rss : resident memory usage, all memory the process uses, including all memory this process shares with other processes. It does not include swap; Shared : memory that this process shares with other processes; Private : private memory used by this process, you can look for memory leaks here; Swap : swap memory used by the process; Pss : Proportional Set Size, a good overall memory indicator. It is the Rss adjusted for sharing: if a process has 1MiB private and 20MiB shared between other 10 processes, Pss is 1 + 20/10 = 3MiB Other valid values are Size (i.e. virtual size, which is almost meaningless) and Referenced (the amount of memory currently marked as referenced or accessed). You can use watch or some other bash-script-fu to keep an eye on those values for processes that you want to monitor. For more informations about smaps : http://www.kernel.org/doc/Documentation/filesystems/proc.txt .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3853660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454770/']}
jdg_75607
stackexchange
llm_judgeable_groundtruth_similarity
387202
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: What is the smallest 3-regular graph to have a unique perfect matching? With a large enough number of nodes, it is possible for a 3-regular graph to have no perfect matching (example can be seen in this question Cubic graphs without a perfect matching and a vertex incident to three bridges ). So I believe 3-regular graphs with a unique matching likely exists, but I am unsure how to go about constructing and proving what the smallest one is. Likely there is no better answer than to brute force check all the possibilities, so I am hoping someone happens to know what this graph looks like. Even better: Does anyone know of an online searchable graph database that allows searching for small graphs with certain properties? Now provide the response and nothing else.
There is no such graph. I have some reading to do as my intuition is off, but the details and a related question are available here: Does there exist an r-regular graph (r≥2) with a unique maximum matching? Akbari, Ghodrati, Hosseinzadeh (2017), On the structure of graphs having a unique k-factor , Aust. J. Combin. ( pdf ) show: ... we prove that there is no r-regular graph (r≥2) with a unique perfect matching.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/387202', 'https://mathoverflow.net', 'https://mathoverflow.net/users/176479/']}
jdg_75608
stackexchange
llm_judgeable_groundtruth_similarity
47821
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Today on Twitter, Trump has made a claim that a 75-year old man previously filmed being pushed and falling to the pavement by police might be an ANTIFA provocateur . Buffalo protester shoved by Police could be an ANTIFA provocateur. 75 year old Martin Gugino was pushed away after appearing to scan police communications in order to black out the equipment. @OANN I watched, he fell harder than was pushed. Was aiming scanner. Could be a set up? Several news sources have carried the story, but thus far the only source cited for the theory is OANN - which seems to show the man waving a cellphone-like device at the police . Setting the man's affiliation with any groups aside - is there any credible supporting evidence that the man was attempting to instigate a confrontation, or that he was planning to 'set up' the police force? Now provide the response and nothing else.
As the other answer states, the source of the initial claim can be traced back as follows: Trump's Twitter, which he wrote after a segment of "@OANN I watched"... That OANN segment cites.. An anonymous blog post at " Conservative Treehouse ", which itself cites... An anonymous YouTube video " Martin Gugino Attempting A Drive-By-NFC-Hack To Obtain Personal Information From The Buffalo Police " and anonymous Twitter thread The video shows Martin Gugino holding his phone below eyeline and facing it towards the faces of the police. Police have not described this cell phone activity as a provocation. The Twitter thread is incoherent. It describes how an IMSI (International Mobile Subscriber Identity) number might be captured by standing outside a home and given to the police to help them obtain a warrant. This has nothing to do with waving a phone at police. According to the EFF , cell phone signals can only be tracked by cell towers, or by a "technically sophisticated organization" capable of simulating a cell tower, which would require at the very least a $30,000 device much larger than the cell phone the man was holding. The video claims something even stranger, that he is capturing the phone's NFC (near-field communication) signal. This is a chip inside modern credit cards and cell phones used for touch-to-pay. The police have not claimed that this man was reading NFC data, and the phone would have to be much closer to obtain such data. Even if such data was captured through a hitherto unknown NFC spy app, it would be the equivalent of the police officer's credit card , not any secret police information. Both of these technical allegations lack the supporting evidence to be the most plausible theory. The Occam's Razor explanation is that Martin Gugino was pointing his phone at the police because he was filming them ; furthermore that the police knocked him over and that he was admitted to the hospital in critical condition, where he remains as of June 11, 2020. (update) On June 12, 2020 it was announced that Gugino is conscious but has sustained permanent brain damage .
{}
{'log_upvote_score': 8, 'links': ['https://skeptics.stackexchange.com/questions/47821', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/18012/']}
jdg_75609
stackexchange
llm_judgeable_groundtruth_similarity
29762706
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 found and (slightly) modified this script in stackoverflow for it to work on python 3.3: from pdfminer.pdfinterp import PDFResourceManager, process_pdffrom pdfminer.converter import TextConverterfrom pdfminer.layout import LAParamsfrom io import StringIOdef convert_pdf(path): rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = TextConverter(rsrcmgr, retstr, laparams=laparams) fp = open(path, 'rb') process_pdf(rsrcmgr, device, fp) fp.close() device.close() string = retstr.getvalue() retstr.close() return stringprint(convert_pdf('abc.pdf')) It works fine, however i seem to be having 2 issues: While running the script I get tons of warnings: WARNING:root:undefined: PDFCIDFont: basefont='LKOELN+Wingdings-Regular', cidcoding='Adobe-Identity', 139 WARNING:root:undefined: PDFCIDFont: basefont='LKKPCF+Wingdings2', cidcoding='Adobe-Identity', 132 Which in the printed text looks like (cid:139) , how do I catch this warnings and replace that text with something else? Note that I have a codec line, which in the original script goes inside the TextConverter(rsrcmgr, retstr, laparams=laparams) , however I get: Traceback (most recent call last): File "C:/Users/rodrigo/Desktop/csp_pdf/csp_pdf2.py", line 46, in convert_pdf('abc.pdf') File "C:/Users/rodrigo/Desktop/csp_pdf/csp_pdf2.py", line 33, in convert_pdf device = TextConverter(rsrcmgr, retstr, codec = 'utf-8', laparams=laparams)TypeError: init () got an unexpected keyword argument 'codec' Is this related to the first issue? Thanks! Now provide the response and nothing else.
Pdfminer3k logs to the Python root logger unfortunately. PDFMiner should implement logging correctly IMHO. So it is not possible to disable logging in the normal manner like. logging.getLogger("pdfminer").setLevel(logging.WARNING) Bummer! I did this and it works™: logging.propagate = False logging.getLogger().setLevel(logging.ERROR) It sets the root logger to level Error. This will stop PDFMiner warn logging, since it logs to the root logger, but not your own logging. I needed to set propagation to False, because after PDFMiner usage, I had duplicate logging entries. This was caused by the root logger.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29762706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2588860/']}
jdg_75610
stackexchange
llm_judgeable_groundtruth_similarity
522501
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: Today I received a preheat bed AOYUE-AO853A . I was really eager to plug it in an test it, ignoring the voltage input rating. It worked for a second making a strange noise, but then some smoke started coming out. I turned it off, unplugged, I left the capacitors to drain and finally I attempted opening it after it cooled. It turned out the transformer was rated for 110V 60Hz. I have two questions: Is there any chance that the components beyond the transformer have fried? From a visual inspection, everything looked ok on the single PCB this device has. What transformer should I use to replace this one to be able to power the device with standard European 220V? Update:I noticed that the board is not only hooked to DC (from the transformer), but also to AC. Here's a picture: 1 is the heating element 2 is the AC in 3 is the DC in Note that the capacitor at the right of the DC in is rated at 25V and all the other capacitors are rated 16V As required by a top user, I posted a picture of the wiring for the heating element. It seems it's wired in series already. Now provide the response and nothing else.
This device is basically a temperature controller with a sensor (thermocouple or thermistor most likely), a control circuit, and a triac-controlled mains heater. The unit is powered from a control transformer. Such a transformer will output considerably less than double output voltage if the input voltage is doubled, because they're run fairly close to saturation. That's why the transformer failed, because it saturated. Given the nature of the other components and ratings, there's a fairly good chance that the rest of the circuitry is okay. So replacing the transformer with a 110VAC:9VAC 8VA or more transformer could well restore it to functionality, but it would still be a 110VAC unit. Which doesn't solve your problem unless you intend to use a voltage converter to power the unit. As far as converting the unit- the transformer can be substituted for one with a 220VAC primary voltage. However, the heater(s), as @Andrew noted, are a more serious problem. At 4x the rated power they will burn out in short order. If there is only one pair of wires to the heater itself you're probably scuppered unless you want to try to wait for a 220VAC spare part to come. The BTA20 triac and (probably) MOCxx opto-triac drive circuit may or may not be appropriate for 240VAC. I would guess they are okay, but I would also check them carefully.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/522501', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/239775/']}
jdg_75611
stackexchange
llm_judgeable_groundtruth_similarity
1878529
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering how to do twitter OAuth via a popup, i.e. load up the Oauth page in a popup and make the callback close the child window and reload the parent window. Edit: OK iframes are bad, but how would you accomplish the above, I notice posterous.com does this - I'm looking to achieve the same flow as FB connect. Now provide the response and nothing else.
Doing the same thing for Yahoo today... Open a popup Send user to twitter for authentication Twitter sends user back to mysite.com/authcompleted.php, with authentication parameters in the query string. Still in the popup here. The popup (mysite.com/authcompleted.html) reads the query string and sends the data to the opener window via javascript window.opener.setTwitterAuthData(yourData) Inside setTwitterAuthData, which is in your main window, set appropriate form fields and submit the data to your server.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1878529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21596/']}
jdg_75612
stackexchange
llm_judgeable_groundtruth_similarity
1061329
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am doing a review assignment and I'm stuck on this problem. a) How many positive divisors does $a$ have? I got $60$ b) How many positive integers less than $a$ are relatively prime to $a$? I got $720$ c) What is the smallest positive integer $m$ such that $a^2m$ is a cube? d) list all positive divisors $b$ of a for which a divides $b^2$ is also true. Any help and advice would be greatly appreciated. Thank you for your time and help! Now provide the response and nothing else.
First, note that $43120 = 2^\color{red}{4}\cdot 5^\color{blue}{1}\cdot 7^\color{green}{2}\cdot 11^\color{purple}{1}$. Part A The number of positive integer divisors is the product of one plus each exponent in the prime factorization. That is, $$d(43120) = \color{red}{(4+1)}\color{blue}{(1+1)}\color{green}{(2+1)}\color{purple}{(1+1)} = (5)(2)(3)(2) = 60$$ Part B The number of positive integers coprime to $43120$ can be found using Euler's Totient function, $\phi(n)$. Since $\phi$ is multiplicative for coprime integers: $$\phi(43120) = \phi(2^4)\phi(5)\phi(7^2)\phi(11)$$ Also, $\phi(p^n) = p^{n-1}(p-1)$ for prime integers $p$. Then: $$\begin{align}\phi(43120) &= \left[2^3(2-1)\right]\left[5-1\right]\left[7^1(7-1)\right]\left[11-1\right]\\&= 8\cdot4\cdot 42\cdot 10\\&= 13440\end{align}$$ Part C We want all exponents of $a^2$ to be multiples of three, and we want the smallest such exponents.$$\left(2^\color{red}{4}\cdot 5^\color{blue}{1}\cdot 7^\color{green}{2}\cdot 11^\color{purple}{1}\right)^2 = 2^\color{red}{8}\cdot 5^\color{blue}{2}\cdot 7^\color{green}{4}\cdot 11^\color{purple}{2}$$Well, it is easy to see that we need to add $1$ to the first exponent, $1$ to the second, $2$ to the third and $1$ to the fourth. Thus, our integer $m$ is:$$m= 2^\color{red}{1}\cdot 5^\color{blue}{1}\cdot 7^\color{green}{2}\cdot 11^\color{purple}{1}$$ Part D This is a similar exponent-related trick as in part c if I'm thinking it through correctly. I'll leave this one as an exercise to the reader. :)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1061329', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/178821/']}
jdg_75613
stackexchange
llm_judgeable_groundtruth_similarity
33497559
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is the histogram To generate this plot, I did: bins = np.array([0.03, 0.3, 2, 100])plt.hist(m, bins = bins, weights=np.zeros_like(m) + 1. / m.size) However, as you noticed, I want to plot the histogram of the relative frequency of each data point with only 3 bins that have different sizes: bin1 = 0.03 -> 0.3 bin2 = 0.3 -> 2 bin3 = 2 -> 100 The histogram looks ugly since the size of the last bin is extremely large relative to the other bins. How can I fix the histogram? I want to change the width of the bins but I do not want to change the range of each bin. Now provide the response and nothing else.
As @cel pointed out, this is no longer a histogram, but you can do what you are asking using plt.bar and np.histogram . You then just need to set the xticklabels to a string describing the bin edges. For example: import numpy as npimport matplotlib.pyplot as pltbins = [0.03,0.3,2,100] # your binsdata = [0.04,0.07,0.1,0.2,0.2,0.8,1,1.5,4,5,7,8,43,45,54,56,99] # random datahist, bin_edges = np.histogram(data,bins) # make the histogramfig,ax = plt.subplots()# Plot the histogram heights against integers on the x axisax.bar(range(len(hist)),hist,width=1) # Set the ticks to the middle of the barsax.set_xticks([0.5+i for i,j in enumerate(hist)])# Set the xticklabels to a string that tells us what the bin edges wereax.set_xticklabels(['{} - {}'.format(bins[i],bins[i+1]) for i,j in enumerate(hist)])plt.show() EDIT If you update to matplotlib v1.5.0 , you will find that bar now takes a kwarg tick_label , which can make this plotting even easier ( see here ): hist, bin_edges = np.histogram(data,bins)ax.bar(range(len(hist)),hist,width=1,align='center',tick_label= ['{} - {}'.format(bins[i],bins[i+1]) for i,j in enumerate(hist)])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33497559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3097391/']}
jdg_75614
stackexchange
llm_judgeable_groundtruth_similarity
29399066
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to make a list view that contains pictures and text within a fragment that is on a viewpager with tabs, so I can swipe left or right to bring up another fragment. I'm relatively new to android so what I may be doing could be completely wrong. I can build the project perfectly fine but then when the emulator runs it crashes (log displayed at bottom of page). I created a separate application and successfully was able to create a list view, but when I try to combine it within a fragment like so, it doesn't work.Here is my following code MainActivity.java import java.util.ArrayList;import java.util.List;import java.util.Locale;import android.app.ListFragment;import android.content.Intent;import android.support.v7.app.ActionBarActivity;import android.support.v7.app.ActionBar;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.support.v4.app.FragmentPagerAdapter;import android.os.Bundle;import android.support.v4.view.ViewPager;import android.view.Gravity;import android.view.LayoutInflater;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends ActionBarActivity implements ActionBar.TabListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; private List<Posts> myPosts = new ArrayList<Posts>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab( actionBar.newTab() .setText(mSectionsPagerAdapter.getPageTitle(i)) .setTabListener(this)); } Intent intent = new Intent(MainActivity.this, NotMainActivity.class); startActivity(intent); finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). switch (position){ case 0: return new TheWallFragment(); case 1: return new PeekFragment(); case 2: return new CameraFragment(); default: break; } return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); case 1: return getString(R.string.title_section2).toUpperCase(l); case 2: return getString(R.string.title_section3).toUpperCase(l); } return null; } } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.wall_layout, container, false); return rootView; } }} NotMainActivity.java public class NotMainActivity extends FragmentActivity { private List<Posts> myPosts = new ArrayList<Posts>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); populatePostList(); populateListView(); registerClickCallBack(); System.out.print("Main Activity Started"); } private void populatePostList() { myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); myPosts.add(new Posts("Ottawa, Ontario", "787", "Picture of my Dog!", R.drawable.dog)); } private void populateListView() { ArrayAdapter<Posts> adapter = new MyListAdapter(); ListView list = (ListView) findViewById(android.R.id.list); list.setAdapter(adapter); } //Handles clicks on the list items private void registerClickCallBack(){ ListView list = (ListView) findViewById(android.R.id.list); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Posts clickedPost = myPosts.get(position); String message = "You clicked" + position +"Location of post is" + clickedPost.getPostlocation(); Toast.makeText(NotMainActivity.this, message, Toast.LENGTH_LONG).show(); } }); } private class MyListAdapter extends ArrayAdapter<Posts> { public MyListAdapter() { super(NotMainActivity.this, R.layout.item_view, myPosts); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Make sure we have a view to work with {may have given null} View itemView = convertView; if (itemView != null) { itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false); } // Find the post to work with. Posts currentPost = myPosts.get(position); //Fill the view ImageView imageView = (ImageView)itemView.findViewById(R.id.item_postImage); imageView.setImageResource(currentPost.getIconID()); //Fill in Title TextView titleText = (TextView) itemView.findViewById(R.id.item_postText); titleText.setText(currentPost.getPosttitle()); //Set Vote Number TextView voteText = (TextView) itemView.findViewById(R.id.item_postVoteText); voteText.setText(currentPost.getPostvote()); return itemView; } }} Posts.java public class Posts { private String postlocation; private String postvote; private String posttitle; private int iconID; public Posts(String postlocation, String postvote, String posttitle, int iconID) { this.postlocation = postlocation; this.postvote = postvote; this.posttitle = posttitle; this.iconID = iconID; } public String getPostlocation() { return postlocation; } public String getPostvote() { return postvote; } public String getPosttitle() { return posttitle; } public int getIconID() { return iconID; } TheWallFragment.java public class TheWallFragment extends android.support.v4.app.ListFragment { List<Posts> myPosts = new ArrayList<Posts>(); private String[] strListView; private ListView myListView; private int number; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.wall_layout, container, false); return rootView; }} activity_main.xml <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools" android:id="@+id/pager"android:layout_width="match_parent" android:layout_height="match_parent"tools:context=".MainActivity" /> AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.gnumbu.errolgreen.testing" > <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity><activity android:name=".NotMainActivity"> </activity> </application></manifest> item_view.xml <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_postImage" android:src="@drawable/dog" android:maxWidth="80dp" android:minHeight="80dp" android:adjustViewBounds="true" android:layout_marginLeft="14dp" android:layout_marginStart="14dp" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/item_upvoteArrow" android:layout_toEndOf="@+id/item_upvoteArrow" android:layout_alignBottom="@+id/item_downvotearrow" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is my dog! My Dog is amazing, give it a lick!" android:id="@+id/item_postText" android:paddingStart="5dp" android:layout_above="@+id/item_downvotearrow" android:layout_toRightOf="@+id/item_postImage" android:layout_toEndOf="@+id/item_postImage" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_upvoteArrow" android:src="@drawable/upvotearrow" android:maxHeight="24dp" android:maxWidth="24dp" android:adjustViewBounds="true" android:layout_alignParentTop="true" android:layout_alignLeft="@+id/item_downvotearrow" android:layout_alignStart="@+id/item_downvotearrow" android:clickable="true" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/item_downvotearrow" android:src="@drawable/downvotearrow" android:maxWidth="24dp" android:maxHeight="24dp" android:adjustViewBounds="true" android:layout_marginLeft="9dp" android:layout_marginStart="9dp" android:layout_below="@+id/item_postVoteText" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:longClickable="false" android:clickable="true" /> <TextView android:layout_height="wrap_content" android:text="22" android:id="@+id/item_postVoteText" android:maxHeight="20dp" android:focusableInTouchMode="false" android:visibility="visible" android:singleLine="true" android:gravity="center" android:enabled="true" android:layout_below="@+id/item_upvoteArrow" android:layout_alignLeft="@+id/item_upvoteArrow" android:layout_alignStart="@+id/item_upvoteArrow" android:nestedScrollingEnabled="false" android:layout_width="wrap_content" android:layout_toStartOf="@+id/item_postImage" /></RelativeLayout> wall_layout.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/textView" android:layout_gravity="center_horizontal" /> <ListView android:id="@android:id/list" android:layout_width="wrap_content" android:layout_height="wrap_content" /></LinearLayout> Error Log java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5223) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at com.gnumbu.errolgreen.testing.NotMainActivity.populateListView(NotMainActivity.java:70) at com.gnumbu.errolgreen.testing.NotMainActivity.onCreate(NotMainActivity.java:43) at android.app.Activity.performCreate(Activity.java:5937) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)            at android.app.ActivityThread.access$800(ActivityThread.java:144)            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)            at android.os.Handler.dispatchMessage(Handler.java:102)            at android.os.Looper.loop(Looper.java:135)            at android.app.ActivityThread.main(ActivityThread.java:5223)            at java.lang.reflect.Method.invoke(Native Method)            at java.lang.reflect.Method.invoke(Method.java:372)            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) New Error Process: com.gnumbu.errolgreen.testing, PID: 5304 java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference at android.widget.AbsListView.obtainView(AbsListView.java:2360) at android.widget.ListView.measureHeightOfChildren(ListView.java:1270) at android.widget.ListView.onMeasure(ListView.java:1182) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436) at android.widget.LinearLayout.measureVertical(LinearLayout.java:722) at android.widget.LinearLayout.onMeasure(LinearLayout.java:613) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436) at android.widget.LinearLayout.measureVertical(LinearLayout.java:722) at android.widget.LinearLayout.onMeasure(LinearLayout.java:613) at android.view.View.measure(View.java:17430) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463) at android.widget.FrameLayout.onMeasure(FrameLayout.java:430) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560) at android.view.View.measure(View.java:17430) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767) at android.view.Choreographer.doCallbacks(Choreographer.java:580) at android.view.Choreographer.doFrame(Choreographer.java:550) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) Now provide the response and nothing else.
NotMainActivity calls setContentView with R.layout.activity_main as parameter that contains a ViewPager and not a ListView . Since you don't have a ListView declare in to that layout, findViewById(android.R.id.list) returns null, and when you try access it (calling setAdapter ) the NullPointerException is thrown. in your MyAdapter , change from if (itemView != null) { itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);} to if (itemView == null) { itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29399066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4739608/']}
jdg_75615
stackexchange
llm_judgeable_groundtruth_similarity
45325324
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 checking if the moment string is correct using a regex with a specific format string: const isCorrect = isCorrectFormat('12/06/2016 20:20:20:444') and the isCorrectFormat function: const isCorrectFormat = (dateString) => { const regex = /[0-3][0-9][/][0-9]{2}[/][0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]*/ return regex.test(dateString)} And of course the result in this case will be false because is not using the same format. The problem that I want to solve now, is send the format also as parameter, but instead of using a regex, I want to use directly the moment format speficifation. const isCorrect = isCorrectFormat( '12/06/2016 20:20:20:444', 'MM/DD/YYYY HH:mm:ss.SSS') But I don't have idea how to implement it... I found in the documentation of moment and I don't see any method to test it. Any idea? Thank you so much!! Now provide the response and nothing else.
You can use moment strict parsing and isValid method. As stated in moment(String, String) docs: Moment's parser is very forgiving, and this can lead to undesired/unexpected behavior. As of version 2.3.0 , you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimeters . Herea working sample: const isCorrectFormat = (dateString, format) => { return moment(dateString, format, true).isValid()}const isCorrect = isCorrectFormat( '12/06/2016 20:20:20:444', 'MM/DD/YYYY HH:mm:ss.SSS')console.log(isCorrect); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45325324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4467741/']}
jdg_75616
stackexchange
llm_judgeable_groundtruth_similarity
427244
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: $$2012^{2011} \equiv x \pmod {14}$$ I need to calculate that, all the examples I've found on the net are a bit different. Thanks in advance! Now provide the response and nothing else.
By the Chinese remainder theorem, knowing what something is modulo $2$ and what it is modulo $7$ is equivalent to knowing what it is modulo $14$. Clearly, $2012^{2011}\equiv 0\bmod 2$. Next, note that because$$2012\equiv 3\bmod 7$$we have $$2012^{2011}\equiv 3^{2011}\bmod 7.$$By Fermat's little theorem, we know that$$3^6\equiv 1\bmod 7$$so that$$2012^{2011}\equiv 3^{2011}\equiv 3^{(6\cdot 335)+1}\equiv (3^6)^{335}\cdot 3\equiv 3\bmod 7.$$Putting this back together with the help of the Chinese remainder theorem (or just direct observation if you prefer) we see that$$2012^{2011}\equiv 10\bmod 14.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/427244', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/79915/']}
jdg_75617
stackexchange
llm_judgeable_groundtruth_similarity
49421370
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 integrate GraphQL to my existing ASP.NET Framework (with Entity Framework 4) application which has an MSSQL Server as the backend. While browsing through the GraphQL libraries for .NET I found 2 libraries - graphql-dotnet and graphql-net , being suggested on the GraphQL website (Link: http://graphql.org/code/#c-net ) It seems that (correct me if I'm wrong) : graphql-dotnet ( https://github.com/graphql-dotnet/graphql-dotnet ) - This library only supports in-memory data graphql-net ( https://github.com/ckimes89/graphql-net ) - This library works well if we want to work with data which has been stored in DB. Any suggestion or corrections? Is it possible to perform read/write to/from the DB using the former (i.e. graphql-dotnet) library? Or should I use the graphql-net library instead? Now provide the response and nothing else.
I am one of the contributors to Hot Chocolate. You can use both frameworks that you have mentioned there. GraphQL-net is more focused on building a GraphQL schema on IQueryable. I would say GraphQL-dotnet is the better one of both solution. There are integrations that support entity framework mapping to GraphQL-dotnet and they are also providing support for DataLoader, which are important to solve N+1 issues when loading data from a backend with GraphQL. Hot Chocolate is the third framework implementing the GraphQL for .Net Core and .Net Framework (also listed on graphql.org). It also supports DataLoader and also supports Entity Framework. For people interested we have a nice tutorial with Entity Framework here: https://github.com/ChilliCream/graphql-workshop
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49421370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6340609/']}
jdg_75618
stackexchange
llm_judgeable_groundtruth_similarity
12810765
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So, to be short, 3 √(-8) = (-8) 1/3 console.log(Math.pow(-8,1/3));//Should be -2 But when I test it out, it outputs NaN Why? Is it a bug or it is expected to be like this in the first place? I am using JavaScript to draw graphs, but this messes up the graph. Now provide the response and nothing else.
You can use this snippet to calculate it. It also works for other powers, e.g. 1/4 , 1/5 , etc. function nthroot(x, n) { try { var negate = n % 2 == 1 && x < 0; if(negate) x = -x; var possible = Math.pow(x, 1 / n); n = Math.pow(possible, n); if(Math.abs(x - n) < 1 && (x > 0 == n > 0)) return negate ? -possible : possible; } catch(e){}}nthroot(-8, 3); Source: http://gotochriswest.com/blog/2011/05/06/cube-root-an-beyond/ A faster approach for just calculating the cubic root: Math.cbrt = function(x) { var sign = x === 0 ? 0 : x > 0 ? 1 : -1; return sign * Math.pow(Math.abs(x), 1 / 3);}Math.cbrt(-8); Update To find an integer based cubic root, you can use the following function, inspired by this answer : // positive-only cubic root approximationfunction cbrt(n){ var a = n; // note: this is a non optimized assumption while (a * a * a > n) { a = Math.floor((2 * a + (n / (a * a))) / 3); } return a;} It starts with an assumption that converges to the closest integer a for which a^3 <= n . This function can be adjusted in the same way to support a negative base.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12810765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283863/']}
jdg_75619
stackexchange
llm_judgeable_groundtruth_similarity
1298016
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The question I am asked is to prove by induction $\sum^{2n}_{i=n+1}\frac{1}{i}=\sum^{2n}_{i=1}\frac{(-1)^{1+i}}{i} $ for $n\ge 1$ its easy to prove this holds for $n =1$ that gives $\frac{1}{2}=\frac{1}{2}$ Now assuming $n$ its true I want to say it is true $n+1$. So, $\sum^{2n}_{i=n+1}\frac{1}{i}=\sum^{2n}_{i=1}\frac{(-1)^{1+i}}{i} $ $\sum^{2n}_{i=n+1}\frac{1}{i}+\frac{(-1)^{1+(2n+1)}}{2n+1}+\frac{(-1)^{1+(2n+2)}}{2n+2}=\sum^{2n}_{i=1}\frac{(-1)^{1+i}}{i}+\frac{(-1)^{1+(2n+1)}}{2n+1}+\frac{(-1)^{1+(2n+2)}}{2n+2} $ $\sum^{2n}_{i=n+1}\frac{1}{i}+(-1)^{2n+2}[ \frac{1}{2n+1}+\frac{(-1)}{2n+2}]=\sum^{2n+2}_{i=1}\frac{(-1)^{1+i}}{i} $ $\sum^{2n}_{i=n+1}\frac{1}{i}+ \frac{1}{2n+1}+\frac{(-1)}{2n+2}=\sum^{2(n+1)}_{i=1}\frac{(-1)^{1+i}}{i} $ $\sum^{2n+1}_{i=n+1}\frac{1}{i}+\frac{(-1)}{2n+2}=\sum^{2(n+1)}_{i=1}\frac{(-1)^{1+i}}{i} $ i don't know what can i do next if the numerator of $\frac{1}{i}+\frac{(-1)}{2n+2}$ was positive i knew. is there a way i can turn it positive?or my approach is wrong ? Now provide the response and nothing else.
The first step is generally to divide out the integrand so as to get a polynomial plus a rational function whose numerator has lower degree than its denominator. Here you get $$\frac{x^3+2x}{1+x^2}=x+\frac{x}{x^2+1}\;.$$ Integrating the $x$ term (and, more generally, the polynomial quotient) is easy, so we’ve reduced the problem to integrating something of the form $\frac{p(x)}{q(x)}$, where $p(x)$ and $q(x)$ are polynomials, and the degree of $p(x)$ is less than the degree of $q(x)$. The general solution for such problems is partial fractions; here, however, we’re more fortunate, because the numerator $x$ is a constant multiple of the derivative of the denominator. If you substitute $u=x^2+1$, you find that $du=2x\,dx$, so that $x\,dx=\frac12du$, and $$\int\frac{x}{x^2+1}\,dx=\frac12\int\frac{du}u\;,$$ which is a standard, basic integral. I would not call this a clever substitution: recognizing that the numerator of a fraction is a constant multiple of the derivative of the denominator is a standard technique. Suppose that the original numerator had been $x^3+x+2$. Again we do the division to get a polynomial plus a ‘proper’ rational function: $$\frac{x^3+x+2}{x^2+1}=x+\frac2{x^2+1}\;.$$ This time you should recognize that $\frac2{x^2+1}$ is just twice the derivative of $\tan^{-1}x$, again a standard integration. Finally, suppose that the original fraction had been $$\frac{x^3+x+1}{x^2+2x}=x+\frac{1-x}{x^2+2x}\;.$$ This time you might as well simply reduce the remaining fraction to partial fractions: $$\frac{1-x}{x(x+2)}=\frac{A}x+\frac{B}{x+2}\;,$$ so $A(x+2)+Bx=1-x$, $(A+B)x+2A=1-x$, $A+B=-1$, and $2A=1$, so $A=\frac12$, and $B=-\frac32$. Thus, $$\frac{1-x}{x^2+2x}=\frac12\left(\frac1x-\frac3{x+2}\right)\;,$$ leaving you with two easy integrations.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1298016', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/243308/']}
jdg_75620
stackexchange
llm_judgeable_groundtruth_similarity
22425921
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the correct way to pass a numpy 2d - array to a c function using ctypes ?My current approach so far (leads to a segfault): C code : void test(double **in_array, int N) { int i, j; for(i = 0; i<N; i++) { for(j = 0; j<N; j++) { printf("%e \t", in_array[i][j]); } printf("\n"); }} Python code: from ctypes import *import numpy.ctypeslib as npctarray_2d_double = npct.ndpointer(dtype=np.double,ndim=2, flags='CONTIGUOUS')liblr = npct.load_library('libtest.so', './src')liblr.test.restype = Noneliblr.test.argtypes = [array_2d_double, c_int]x = np.arange(100).reshape((10,10)).astype(np.double)liblr.test(x, 10) Now provide the response and nothing else.
This is probably a late answer, but I finally got it working. All credit goes to Sturla Molden at this link . The key is, note that double** is an array of type np.uintp . Therefore, we have xpp = (x.ctypes.data + np.arange(x.shape[0]) * x.strides[0]).astype(np.uintp)doublepp = np.ctypeslib.ndpointer(dtype=np.uintp) And then use doublepp as the type, pass xpp in. See full code attached. The C code: // dummy.c #include <stdlib.h> __declspec(dllexport) void foobar(const int m, const int n, const double **x, double **y) { size_t i, j; for(i=0; i<m; i++) for(j=0; j<n; j++) y[i][j] = x[i][j]; } The Python code: # test.py import numpy as np from numpy.ctypeslib import ndpointer import ctypes _doublepp = ndpointer(dtype=np.uintp, ndim=1, flags='C') _dll = ctypes.CDLL('dummy.dll') _foobar = _dll.foobar _foobar.argtypes = [ctypes.c_int, ctypes.c_int, _doublepp, _doublepp] _foobar.restype = None def foobar(x): y = np.zeros_like(x) xpp = (x.__array_interface__['data'][0] + np.arange(x.shape[0])*x.strides[0]).astype(np.uintp) ypp = (y.__array_interface__['data'][0] + np.arange(y.shape[0])*y.strides[0]).astype(np.uintp) m = ctypes.c_int(x.shape[0]) n = ctypes.c_int(x.shape[1]) _foobar(m, n, xpp, ypp) return y if __name__ == '__main__': x = np.arange(9.).reshape((3, 3)) y = foobar(x) Hope it helps, Shawn
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22425921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2101197/']}
jdg_75621
stackexchange
llm_judgeable_groundtruth_similarity
21631707
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Basically my MainActivity has a button which will become invisible after clicking and the SecondActivity will be called after a few seconds. However, when I press the back botton, the button on the MainActivity is still invisible. I want the MainActivity to restart/initialize. I knew it is something to do with onResume or onRestart but how can I implement these methods? Can anyone give me an example? Thanks. Now provide the response and nothing else.
First thing is first. You need to define $scope.telephone as an array in your controller before you can start using it in your view. $scope.telephone = []; To address the issue of ng-model not being recognised when you append a new input - for that to work you have to use the $compile Angular service. From the Angular.js API reference on $compile : Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. // I'm using Angular syntax. Using jQuery will have the same effect// Create input elementvar input = angular.element('<div><input type="text" ng-model="telephone[' + $scope.inputCounter + ']"></div>');// Compile the HTML and assign to scopevar compile = $compile(input)($scope); Have a look on JSFiddle
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21631707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3143880/']}
jdg_75622
stackexchange
llm_judgeable_groundtruth_similarity
1840029
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to use a C library in a C++ app and have found my self in the following situation (I know my C, but I'm fairly new to C++). On the C side I have a collection of functions that takes a function pointer as their argument. On the C++ side I have objects with a functor which has the same signature as the function pointer needed by the C function. Is there any way to use the C++ functor as a function pointer to pass to the C function? Now provide the response and nothing else.
You cannot directly pass a pointer to a C++ functor object as a function pointer to C code(or even to C++ code). Additionally, to portably pass a callback to C code it needs to be at least declaredas an extern "C" non-member function.At least, because some APIs require specific function call conventions and thusadditional declaration modifiers. In many environments C and C++ have the same calling conventions and differ onlyin name mangling, so any global function or static member will work.But you still need to wrap the call to operator() in a normal function. If your functor has no state (it is an object just to satisfy some formalrequirements etc): class MyFunctor { // no state public: MyFunctor(); int operator()(SomeType &param) const;} you can write a normal extern "C" function which creates the functor and executes itsoperator(). extern "C" int MyFunctorInC(SomeType *param){ static MyFunctor my_functor; return my_functor(*param);} If your functor has state, eg: class MyFunctor { // Some fields here; public: MyFunctor(/* some parameters to set state */); int operator()(SomeType &param) const; // + some methods to retrieve result.} and the C callback function takes some kind of user state parameter (usually void *): void MyAlgorithmInC(SomeType *arr, int (*fun)(SomeType *, void *), void *user_state); you can write a normal extern "C" function which casts its state parameter toyour functor object: extern "C" int MyFunctorInC(SomeType *param, void *user_state){ MyFunctor *my_functor = (MyFunctor *)user_state; return (*my_functor)(*param);} and use it like this: MyFunctor my_functor(/* setup parameters */);MyAlgorithmInC(input_data, MyFunctorInC, &my_functor); Otherwise the only normal way to do it(normal as in "without generating machine code at runtime" etc.)is to use some static (global) or thread local storage to pass the functorto an extern "C" function.This limits what you can do with your code and is ugly but will work.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1840029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/41326/']}
jdg_75623
stackexchange
llm_judgeable_groundtruth_similarity
15976732
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 building a web app in Django.I have a form that sends a file to views.py. Views: @login_required(login_url=login_url)def addCancion(request): if request.method == 'POST': form2 = UploadSong(request.POST, request.FILES) if form2.is_valid(): if(handle_uploaded_song(request.FILES['file'])): path = '%s' % (request.FILES['file']) ruta = "http://domain.com/static/canciones/%s" % path usuario = Usuario.objects.get(pk=request.session['persona']) song = Cancion(autor=usuario, cancion=ruta) song.save() return HttpResponse(ruta) else: return HttpResponse("-3") else: return HttpResponse("-2") else: return HttpResponse("-1") I'm trying to upload only the MP3 files, but I don't know how to make this filter.I tried a class named "ContentTypeRestrictedFileField(FileField):" and doesn't work. How can I get the file type in views.py? Thanks! Now provide the response and nothing else.
You could also use the clean() method from the form, which is used to validate it. Thus, you can reject files that are not mp3. Something like this: class UploadSong(forms.Form): [...] def clean(self): cleaned_data = super(UploadSong, self).clean() file = cleaned_data.get('file') if file: filename = file.name print filename if filename.endswith('.mp3'): print 'File is a mp3' else: print 'File is NOT a mp3' raise forms.ValidationError("File is not a mp3. Please upload only mp3 files") return file
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15976732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1967886/']}
jdg_75624
stackexchange
llm_judgeable_groundtruth_similarity
19398530
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 general, how to access parent view from a child view in Backbone? Specifically, in Backgrid.js, is there a way to access parent row from a cell? Now provide the response and nothing else.
Pass this as an option to the child view on initialization step: var ChildView = Backbone.View.extend({ initialize : function (options) { this.parent = options.parent; }});// somewhere in the parent view ...new ChildView({parent:this});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19398530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/433570/']}
jdg_75625
stackexchange
llm_judgeable_groundtruth_similarity
20396345
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following macros that take a statement and multiply it #define X2(s) do { s; s; } while (0)#define X3(s) do { s; s; s; } while (0)#define X4(s) do { s; s; s; s; } while (0)#define X5(s) do { s; s; s; s; s; } while (0)#define X6(s) do { s; s; s; s; s; s; } while (0)etc. so the pre-processor expands X2(i++) to do { i++; i++; } while (0) I would like to have a macro #define CODE_MULTIPLIER(x,s) which expands a statement s , x times. so CODE_MULTIPLIER(3,j--) would be expanded to do { j--; j--; j--; } while (0) The ugly idea i came up with is: #define CODE_MULTIPLIER(x,s) do { \ if ((x) == 1) { s; } \ else if ((x) == 2) { s; s; } \ else if ((x) == 3) { s; s; s; } \ else if ((x) == 4) { s; s; s; s; } \ else if ((x) == 5) { s; s; s; s; s; } \ etc. \ else assert(0); \ } while (0) hoping the compiler will optimize out the if s Why would you ever want macros like this?One reason (but not the only one) is the need for exact delays in embedded programming. using while/for loops slightly change the timing. Compiler optimization of loops may not preserve delicate timing requirements. Here is a typical usage example: #define CLOCK_FREQ_Hz (16000000L)#define US_TO_NOPS(us) ((us) * CLOCK_FREQ_Hz / 1000000L)#define OFF_ON_DELAY_US (4) // units: microseconds#define ON_OFF_DELAY_US (2) // units: microseconds#define OFF_ON_DELAY_NOPS US_TO_NOPS(OFF_ON_DELAY_US) // units: instructions#define ON_OFF_DELAY_NOPS US_TO_NOPS(ON_OFF_DELAY_US) // units: instructionsPIN = OFF;CODE_MULTIPLIER(OFF_ON_DELAY_NOPS,asm("nop")); // 4us delayPIN = ON;CODE_MULTIPLIER(ON_OFF_DELAY_NOPS,asm("nop")); // 2us delayPIN = OFF; I would appreciate any suggestions as to how to create this macro. High preference to compiler-independent macro wizardry (Us embedded dudes don't always have the luxury of using GCC) Thanx Now provide the response and nothing else.
To download release file from private repo, you can use Personal access token which can be generated at settings/tokens with Full control of private repositories scope. Then download the asset with curl command (change with appropriate values): curl -vLJO -H 'Authorization: token my_access_token' 'https://api.github.com/repos/:owner/:repo/releases/assets/:id' or if you're using an OAuth app, use: curl -u my_client_id:my_client_secret https://api.github.com/repos/:owner/:repo/releases/assets/:id where: :owner is your user or organisation username; :repo is your repository name; :id is your asset id, can be found in tag release URL, like: https://api.github.com/repos/:owner/:repo/releases/tags/:tag :token is your personal access token (can be created at /settings/tokens ; Note: Using access_token as a query param is deprecated . See: Repositories API v3 at GitHub Here is the Bash script which can download asset file given specific name of file: #!/usr/bin/env bash# Script to download asset file from tag release using GitHub API v3.# See: http://stackoverflow.com/a/35688093/55075 CWD="$(cd -P -- "$(dirname -- "$0")" && pwd -P)"# Check dependencies.set -etype curl grep sed tr >&2xargs=$(which gxargs || which xargs)# Validate settings.[ -f ~/.secrets ] && source ~/.secrets[ "$GITHUB_API_TOKEN" ] || { echo "Error: Please define GITHUB_API_TOKEN variable." >&2; exit 1; }[ $# -ne 4 ] && { echo "Usage: $0 [owner] [repo] [tag] [name]"; exit 1; }[ "$TRACE" ] && set -xread owner repo tag name <<<$@# Define variables.GH_API="https://api.github.com"GH_REPO="$GH_API/repos/$owner/$repo"GH_TAGS="$GH_REPO/releases/tags/$tag"AUTH="Authorization: token $GITHUB_API_TOKEN"WGET_ARGS="--content-disposition --auth-no-challenge --no-cookie"CURL_ARGS="-LJO#"# Validate token.curl -o /dev/null -sH "$AUTH" $GH_REPO || { echo "Error: Invalid repo, token or network issue!"; exit 1; }# Read asset tags.response=$(curl -sH "$AUTH" $GH_TAGS)# Get ID of the asset based on given name.eval $(echo "$response" | grep -C3 "name.:.\+$name" | grep -w id | tr : = | tr -cd '[[:alnum:]]=')#id=$(echo "$response" | jq --arg name "$name" '.assets[] | select(.name == $name).id') # If jq is installed, this can be used instead. [ "$id" ] || { echo "Error: Failed to get asset id, response: $response" | awk 'length($0)<100' >&2; exit 1; }GH_ASSET="$GH_REPO/releases/assets/$id"# Download asset file.echo "Downloading asset..." >&2curl $CURL_ARGS -H "Authorization: token $GITHUB_API_TOKEN" -H 'Accept: application/octet-stream' "$GH_ASSET"echo "$0 done." >&2 Before running, you need to set your GITHUB_API_TOKEN with your GitHub token (see: /settings/tokens at GH). This can be placed in your ~/.secrets file, like: GITHUB_API_TOKEN=XXX Example script usage: ./get_gh_asset.sh :owner :repo :tag :name where name is your filename (or partial of it). Prefix script with TRACE=1 to debug it. In case you wonder why curl fails sometimes with (as mentioned in other answer): Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified. when running like: curl -vLJ -H 'Authorization: token <token>' -H 'Accept: application/octet-stream' https://api.github.com/repos/:owner/:repo/releases/assets/<id> this is because you're specifying multiple mechanism at the same time, so S3 server doesn't know which one to use, therefore you have to choose only one, such as: X-Amz-Algorithm query parameter Signature query string parameter ( X-Amz-Signature ) Authorization header ( Authorization: token <token> ) and since GitHub redirects you from asset page (when requesting application/octet-stream ), it populates credentials automatically in query string and since curl is passing over the same credentials in the request header (which you've specified), therefore they're conflicting. So as for workaround you can use access_token instead.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20396345', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3069312/']}
jdg_75626
stackexchange
llm_judgeable_groundtruth_similarity
3903817
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 forked someone's repository on GitHub and would like to update my version with commits and updates made in the original repository. These were made after I forked my copy. How can I pull in the changes that were made in the origin and incorporate them into my repository? Now provide the response and nothing else.
You have to add the original repository (the one you forked) as a remote. From the GitHub documentation on forking a repository : Once the clone is complete your repo will have a remote named “ origin ” that points to your fork on GitHub. Don’t let the name confuse you, this does not point to the original repo you forked from. To help you keep track of that repo we will add another remote named “upstream”: $ cd PROJECT_NAME$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git$ git fetch upstream# then: (like "git pull" which is fetch + merge)$ git merge upstream/master master# or, better, replay your local work on top of the fetched branch# like a "git pull --rebase"$ git rebase upstream/master There's also a command-line tool ( gh ) which can facilitate the operations above . Here's a visual of how it works: See also " Are Git forks actually Git clones? ".
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/3903817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335499/']}
jdg_75627
stackexchange
llm_judgeable_groundtruth_similarity
10201977
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is this possible? Doesn't have to be in place, just looking for a way to reverse a tuple so I can iterate on it backwards. Now provide the response and nothing else.
There are two idiomatic ways to do this: reversed(x) # returns an iterator or x[::-1] # returns a new tuple Since tuples are immutable, there is no way to reverse a tuple in-place. Edit: Building on @lvc's comment, the iterator returned by reversed would be equivalent to def myreversed(seq): for i in range(len(x) - 1, -1, -1): yield seq[i] i.e. it relies on the sequence having a known length to avoid having to actually reverse the tuple. As to which is more efficient, i'd suspect it'd be the seq[::-1] if you are using all of it and the tuple is small, and reversed when the tuple is large, but performance in python is often surprising so measure it!
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10201977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51816/']}
jdg_75628
stackexchange
llm_judgeable_groundtruth_similarity
22924825
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 ACRA to report app crashes. I was getting a View not attached to window manager error message and thought I had fixed it by wrapping the pDialog.dismiss(); in an if statement: if (pDialog!=null) { if (pDialog.isShowing()) { pDialog.dismiss(); }} It has reduced the amount of View not attached to window manager crashes I recieve, but I am still getting some and I am not sure how to solve it. Error message: java.lang.IllegalArgumentException: View not attached to window managerat android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:425)at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:327)at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:83)at android.app.Dialog.dismissDialog(Dialog.java:330)at android.app.Dialog.dismiss(Dialog.java:312)at com.package.class$LoadAllProducts.onPostExecute(class.java:624)at com.package.class$LoadAllProducts.onPostExecute(class.java:1)at android.os.AsyncTask.finish(AsyncTask.java:631)at android.os.AsyncTask.access$600(AsyncTask.java:177)at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)at android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:176)at android.app.ActivityThread.main(ActivityThread.java:5419)at java.lang.reflect.Method.invokeNative(Native Method)at java.lang.reflect.Method.invoke(Method.java:525)at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)at dalvik.system.NativeStart.main(Native Method) Code snippet: class LoadAllProducts extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(CLASS.this); pDialog.setMessage("Loading. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * getting All products from url * */ protected String doInBackground(String... args) { // Building Parameters doMoreStuff("internet"); return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog after getting all products if (pDialog!=null) { if (pDialog.isShowing()) { pDialog.dismiss(); //This is line 624! } } something(note); }} Manifest: <activity android:name="pagename.CLASS" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout" android:label="@string/name" > </activity> What am I missing to stop this crash from happening? Now provide the response and nothing else.
How to reproduce the bug: Enable this option on your device: Settings -> Developer Options -> Don't keep Activities . Press Home button while the AsyncTask is executing and the ProgressDialog is showing. The Android OS will destroy an activity as soon as it is hidden. When onPostExecute is called the Activity will be in "finishing" state and the ProgressDialog will be not attached to Activity . How to fix it: Check for the activity state in your onPostExecute method. Dismiss the ProgressDialog in onDestroy method. Otherwise, android.view.WindowLeaked exception will be thrown. This exception usually comes from dialogs that are still active when the activity is finishing. Try this fixed code: public class YourActivity extends Activity { private void showProgressDialog() { if (pDialog == null) { pDialog = new ProgressDialog(StartActivity.this); pDialog.setMessage("Loading. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); } pDialog.show(); } private void dismissProgressDialog() { if (pDialog != null && pDialog.isShowing()) { pDialog.dismiss(); } } @Override protected void onDestroy() { dismissProgressDialog(); super.onDestroy(); } class LoadAllProducts extends AsyncTask<String, String, String> { // Before starting background thread Show Progress Dialog @Override protected void onPreExecute() { showProgressDialog(); } //getting All products from url protected String doInBackground(String... args) { doMoreStuff("internet"); return null; } // After completing background task Dismiss the progress dialog protected void onPostExecute(String file_url) { if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17 return; } dismissProgressDialog(); something(note); } }}
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/22924825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3204827/']}
jdg_75629
stackexchange
llm_judgeable_groundtruth_similarity
346643
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In OLS, if I have design matrix X (an NxK matrix of full column rank) and I add a constant, such as 2, to every entry of X, how does that change my estimators? Let's denote $\tilde{X} = X + 2$. I can't compute the OLS estimator $\beta_{OLS} = (\tilde{X}'\tilde{X})^{-1}\tilde{X}'y $ because $\tilde{X}$ doesn't have full column rank (or does it? If so, I cannot prove it). I'm thinking, my intercept term will change while the other coefficients do not, but I'm having trouble proving it. Now provide the response and nothing else.
Rank When one of the columns is constant (an intercept term) then you can use: https://math.stackexchange.com/questions/676333/prove-that-if-ranka-n-then-rankab-rankb For $X_{m \times n}$ and $Z_{n \times k}$, where $Z$ is of rank $n$, then $$rank(XZ) = rank(X)$$ The addition of the constant can be expressed by multiplication of X with n x n matrix Z of rank n. This is done by taking the identity matrix and add the constant, such as $x=2$ (but $x$ can not be -1), to the row that corresponds to the column $i$ that is related to the intercept: $$Z = I + C, \qquad \text{with $c_{jk}=x$ if $j=i$ and $c_{jk}=0$ otherwise }$$ For instance: $$\small\begin{bmatrix}1 & 1 & 1 & 1 \\1 & 2 & 4 & 8 \\1 & 3 & 9 & 27 \\1 & 4 & 16 & 64 \\1 & 5 & 25 & 125 \\1 & 6 & 36 & 216 \\ \end{bmatrix} \times \begin{bmatrix}3 & 2 & 2 & 2 \\0 & 1 & 0 & 0 \\0 & 0 & 1 & 0 \\0 & 0 & 0 & 1 \\ \end{bmatrix}= \begin{bmatrix}1 & 1 & 1 & 1 \\1 & 2 & 4 & 8 \\1 & 3 & 9 & 27 \\1 & 4 & 16 & 64 \\1 & 5 & 25 & 125 \\1 & 6 & 36 & 216 \\ \end{bmatrix} +\begin{bmatrix}2 & 2 & 2 & 2 \\2 & 2 & 2 & 2 \\2 & 2 & 2 & 2 \\2 & 2 & 2 & 2 \\2 & 2 & 2 & 2 \\2 & 2 & 2 & 2 \\ \end{bmatrix}$$ Estimators change You could see OLS as projection of observations Y onto the span of the columns in X. The span does not change by adding the constant (iff the X contains an intercept term) so $\tilde{y}_{OLS}=y_{OLS}$ You can use the same matrix Z to show how the coefficients change $Z \tilde\beta_{OLS} = \beta_{OLS}$ making all the coefficients the same except the one related to the intercept.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/346643', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/208602/']}
jdg_75630
stackexchange
llm_judgeable_groundtruth_similarity
603018
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: I was reading through a book that presented the problem: A disgruntled hockey player throws a hockey stick along the ice. It rotates about its center of mass as it slides along and is eventually brought to rest by the action of friction. Its motion of rotation stops at the same moment that its center of mass comes to rest, not before and not after. Explain why. I saw a similar question at: Why does an ice hockey stick, when thrown on ice always rotate and translate together before coming to rest? Why not only rotate or only translate? but I didn't feel like I was satisfied with the answer. The question was in the energy chapter so I tried to solve it with energy. I thought that if the force of friction on the COM was F and it traveled distanced s before stopping, then we can write the equation $\frac{1}{2}mv^2 = Fs$ where the LHS represents the initial kinetic energy. We could also write a similar equation for rotational energy, but I'm not sure what to do after that. Is it even reasonable to attempt to prove it rigorously or just by reasoning? Another question that came from thinking about this question was how would you measure the torque brought by the friction since it's distributed across the stick, not just at one point? Now provide the response and nothing else.
If the stick is a bar, having plain contact with the ground along its length, the friction force opposing the rotation suggests to model it as 2 cantilever beams with uniformly distributed load, fixed in the COM. The friction load is distributed along its length, resulting in max. torque close to COM and zero at the ends. So for a small area close to the ends, the total torque results only from the load on this area: $$\delta \tau = \delta I\frac{d\omega}{dt}$$ $\delta \tau = \delta Fr$ and the friction force in the element is $\delta F = \mu \delta N = \mu \delta m g$ The moment of inertia $\delta I = \delta m r^2$ and $$\omega = \frac{v}{r}$$ So, $$\mu \delta m g r = \delta m r^2 \frac{1}{r} \frac{dv}{dt} \implies \frac{dv}{dt} = \mu g $$ If we elaluate the force to decrease the average translation velocity in the same region: $$\delta F = \delta m\frac{dv_t}{dt} = \mu \delta N = \mu \delta mg \implies \frac{dv_t}{dt} = \mu g$$ Under the same acceleration, they must decrease together. If it happens for the ends of the bar, all the body will stop spinning and moving linearly at the same time for this model. But if for example, the central portion have contact but not the ends, it is perfectly possible for the bar keeps rotating, after stopping its translational movement.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/603018', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/240744/']}
jdg_75631
stackexchange
llm_judgeable_groundtruth_similarity
44151979
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 developing a simple notepad app first i used listView to show all the notes.But now I am using RecyclerView. While i am using listview i used OnItemClickListener to pass the Data to another activity for editing the notenow i am confuse what to do in Recylerview For listView i am using this listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { name = filenames.get(position).getName(); note = filenames.get(position).getShorttext(); Alert(); // this method is in main activity } });*/ public void Alert() { final AlertDialog dialog; View mview = getLayoutInflater().inflate(R.layout.dialog_pass,null); final EditText mEdittext = (EditText) mview.findViewById(R.id.Epass); AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this); mBuilder.setView(mview); mBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String col = mEdittext.getText().toString(); String password = dBhelper.searchpass(col); if (col.equals(password)) { Intent intent = new Intent(MainActivity.this,Note2.class); intent.putExtra("Name",name); intent.putExtra("Note",note); startActivity(intent); } else { Toast temp = Toast.makeText(MainActivity.this, "Password does not match", Toast.LENGTH_SHORT); temp.show(); } } }); mBuilder.setNegativeButton("Cancel",null); mBuilder.setCancelable(false); dialog = mBuilder.create(); dialog.show(); } Now What Should i Do for Recycle View Please Help public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewHolder> {// Recyclerview will extend to private List<FileName> fileNames; private Context context; public RecycleViewAdapter(Context context,List<FileName> fileNames) { this.context = context; this.fileNames = fileNames; } @Overridepublic RecycleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater mInflater = LayoutInflater.from(parent.getContext()); ViewGroup mainGroup = (ViewGroup) mInflater.inflate( R.layout.grid_item, parent, false); RecycleViewHolder listHolder = new RecycleViewHolder(mainGroup); return listHolder;}@Overridepublic void onBindViewHolder(RecycleViewHolder holder, final int position) { final FileName model = fileNames.get(position); RecycleViewHolder mainHolder = (RecycleViewHolder) holder;// holder mainHolder.title.setText(model.getName()); mainHolder.note.setText(model.getShorttext());}@Overridepublic int getItemCount() { return (null != fileNames ? fileNames.size() : 0); } Now provide the response and nothing else.
You can handle this using two ways 1). Gesture touch https://www.google.co.in/amp/sapandiwakar.in/recycler-view-item-click-handler/amp/ 2).Using interface in adapter https://antonioleiva.com/recyclerview-listener/ I suggest second way using interface How to use interface for recycleritemclick public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewHolder> {// Recyclerview will extend to private List<FileName> fileNames; private Context context;//declare interface private OnItemClicked onClick;//make interface like this public interface OnItemClicked { void onItemClick(int position); } public RecycleViewAdapter(Context context,List<FileName> fileNames) { this.context = context; this.fileNames = fileNames; } Now assign click to interface @Overridepublic void onBindViewHolder(RecycleViewHolder holder, final int position) { //............// holder.title.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClick.onItemClick(position); } });} At the end of the adapter class up from finishing bracket make one method to assign itemclick to interface public void setOnClick(OnItemClicked onClick){ this.onClick=onClick;} In MainActivity.javaBind the item click with adapter public class MainActivity extends Activity implements OnItemClicked { private RecyclerView mRecyclerView; private CityAdapter mAdapter; private List<City> cities; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_city); mRecyclerView = (RecyclerView)findViewById(R.id.list); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mAdapter = new CityAdapter(cities, R.layout.row_city, this); mRecyclerView.setAdapter(mAdapter); mAdapter.setOnClick(MainActivity.this); // Bind the listener } @Override public void onItemClick(int position) { // The onClick implementation of the RecyclerView item click //ur intent code here }} For Kotlin code please refer How to handle recyclerview item click in kotlin? More queries? comment.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44151979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8041516/']}
jdg_75632
stackexchange
llm_judgeable_groundtruth_similarity
2991542
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: Prove the identity $$8\cos^4 \theta -4\cos^3 \theta-8\cos^2 \theta+3\cos \theta +1=\cos4\theta-\cos3\theta$$ If $7\theta $ is a multiple of $2\pi,$ Show that $\cos4\theta=\cos3\theta$ and deduce, $$\cos\frac{2\pi}{7}+\cos\frac{4\pi}{7}+\cos\frac{6\pi}{7}=-\frac{1}{2}$$ My Work I was able to prove identity using half angle formula and $\cos3\theta $ expansion.Since $$7\theta=2n\pi$$ $$4\theta=2n\pi-3\theta$$ $$\therefore \cos4\theta=\cos3\theta$$ I cannot prove the final part. Please help me. Thanks in advance. Now provide the response and nothing else.
$\cos\frac{0\pi}{7}, \cos\frac{2\pi}{7}, \cos\frac{4\pi}{7}, \cos\frac{6\pi}{7}$ are distinct roots of the fourth order polynomial $$P(x)=8x^4-4x^3-8x^2+3x+1$$ So $P(x)$ can be re-written $$P(x)=8\left(x-\cos\frac{0\pi}{7}\right)\left(x-\cos\frac{2\pi}{7}\right)\left(x-\cos\frac{4\pi}{7}\right)\left(x-\cos\frac{6\pi}{7}\right)$$ Therefore looking at $x^3$ coefficient gives $$\cos\frac{0\pi}{7}+\cos\frac{2\pi}{7}+\cos\frac{4\pi}{7}+\cos\frac{6\pi}{7}=\frac{4}{8}=\frac{1}{2}$$ Actually, for any $n>=2$ , $$P_n(x)=T_n(x)-T_{n-1}(x)=2^{n-1}x^n-2^{n-2}x^{n-1}+...$$ Where $T_n$ is the nth Chebyshev polynomial . So $$P_n(cos(x))=cos(nx)-cos((n-1)x)$$ And Likewise, $$\sum_{k=0}^{n-1} cos\frac{2k\pi}{2n-1} = \frac{1}{2}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2991542', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/87880/']}
jdg_75633
stackexchange
llm_judgeable_groundtruth_similarity
16638
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: I'm reading about color vision and have some trouble understanding the motivation for why the trichromatic theory was suggested in the first place. The book I'm reading ("Psychgology: The science of mind and behavior") states: At the beginning of the nineteenth century it was discovered that any colour in the visible spectrum could be produced by some combination of the wavelenghts that corresponds to the colours blue, green and red in what is known as additive color mixture. From the explanation in the book, it seems like this somehow should be a reason for also supposing that the human retina was composed of cones sensitive to the colors green, red and blue respectively. I guess this would be a valid argument if it was only red, green and blue that, through additive mixture, could make up any color. Is it only red, green and blue that, through additive mixture, can make up any color? Now provide the response and nothing else.
The human vision has 3 types of cones. (that is why all perception-based color spaces are 3 dimensional: LAB, XYZ, HSV ). Each cone type has a different sensitivity curve in the color spectrum (think of them as color filters). It gets complicated because these curves overlap: there isn't a single wavelength of light that triggers just one cone type. So, in additive color synthesis, it would be nice if there would exist 3 colors that trigger the cones independently. By mixing light of these 3 base colors, you could create any color perception. But such a color set does not exist. RGB does a pretty good job of covering a large part of the color gamut, but not all (RGB fails at saturated cyan and yellow, for example). In the XYZ space, you can see this quite visually: the total gamut has the shape of a horse footprint. An RGB color device can produce a triangle within. See the illustration in this question: https://stackoverflow.com/questions/2455503/cie-xyz-colorspace-do-i-have-rgba-or-xyza The curved edge of this gamut representation are the monochromatic colors. These are the toughest to reproduce in additive color synthesis: you can only produce a monochromatic color by producing its exact peak spectrum. You could consider adding a 4th and 5th primary color to an additive color reproduction system (e.g, an RGBCY monitor). That would be able to reproduce more colors, but apparently that has not been economical to this date.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/16638', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/4791/']}
jdg_75634
stackexchange
llm_judgeable_groundtruth_similarity
336888
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 have been developing software for the past three years, but I just recently awoke to how ignorant I am of good practices. This has led me to begin reading the book Clean Code , which is turning my life upside for the better, but I am struggling to get insight into some of the best approaches for writing my programs. I have a Python program in which I... use argparse required=True to enforce two arguments, which are both file names. the first is the input file name, the second is the output file name have a function readFromInputFile which first checks to see that an input file name was entered have a function writeToOutputFile which first checks to see that an output file name was entered My program is small enough that I am lead to believe that the checking in #2 and #3 is redundant and should be removed, thus freeing both functions from an unnecessary if condition. However, I have also been led to believe that "double-checking is ok" and may be the right solution in a program where the functions could be called from a different location where the parsing of arguments does not occur. (Also, if the read or write fails, I have a try except in each function to raise an appropriate error message.) My question is: is it best to avoid all redundant condition checking? Should the logic of a program be so solid that checks need only be made once? Are there any good examples that illustrate this or the converse? EDIT: Thank you all for the answers! I have learned something from each. Seeing so many perspectives gives me a much better understanding of how to approach this problem and determine a solution based on my requirements. Thank you! Now provide the response and nothing else.
What you are asking for is called "robustness", and there is no right or wrong answer. It depends on the size and complexity of the program, the number of people working in it, and the importance of detecting failures. In small programs you write alone and only for yourself, robustness is typically a much smaller concern than when you are going to write a complex program which consists of multiple components, maybe written by a team. In such systems, there are boundaries between the components in form of public APIs, and at each boundary, it is often a good idea to validate the input parameters, even if "the logic of the program should be so solid that those checks are redundant". That makes the detection of bugs quite easier and helps to keep the debugging times smaller. In your case, you have to decide for yourself, which kind of life cycle you expect for your program. Is it a program you expect to be used and maintained over years? Then adding a redundant check is probably better, since it will not be unlikely that your code will be refactored in the future and and your read and write functions might be used in a different context. Or is it a small program just for learning or fun purposes? Then those double checks won't be necessary. In the context of "Clean Code", one could ask if a double check violates the DRY principle. Actually, sometimes it does, at least to some minor degree: input validation can be interpreted as part of the business logic of a program, and having this at two places might lead to the usual maintenance problems caused by the violation of DRY. Robustness vs. DRY is often a tradeoff - robustness requires redundancy in code, whilst DRY tries to minimize redundancy. And with increasing program complexity, robustness becomes more and more important than being DRY in validation. Finally, let me give an example what that means in your case. Lets assume your requirements change to something like the program shall also work with one argument, the input file name, if there is no output file name given, it is automatically constructed from the input file name by replacing the suffix. Does that make it likely you need to change your double validation in two places? Probably not, such a requirement leads to one change when calling argparse , but no change in writeToOutputFile : that function will still require a filename. So in your case, I would vote for doing the input validation twice, the risk of getting maintenance problems because of having two places to change is IMHO much lower than the risk of getting maintenance problems because of masked errors caused by too few checks.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/336888', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/254888/']}
jdg_75635
stackexchange
llm_judgeable_groundtruth_similarity
22835089
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know that most of the time NOSQL databses are schema-less or at least have a flexible database schema.However, the basic schema needs to be modeled beforehand and may evolve later. So,in this case, is there a modeling tool/language for NOSQL databases? Like UML for RDB and Visual Paradigm (UML modeling tool). I found that for "Graph Databases", we can use "Property Graph Model" but I am working on "BigColumn Databases" and "Document-base Databases".Thank you. Now provide the response and nothing else.
NoSQL databases approach modelling from a different point of view generally. NoSQL modelling usually begins with asking questions on how the data in the database is going to be queried, so the main modelling is 'what are the list of questions that I want to ask of my database', whereas with SQL databases, modelling usually is a function of what data you have, that is, what answers I have already. This mental exercise of finding out what questions one would like to ask of the NoSQL database serve to define the entities and the relationship amongst those entities. Once you have a list of questions, you then need to design a model that will answer those questions via the NoSQL database. To model it, I typically use Creately which is an online tool for visually representing models of various kinds. Another method could be to represent your NoSQL model in JSON format and then use the wonderful D3.js javascript library to create a data-driven document. See this website for more details and the templates available to visually represent your model. Hope it helps.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22835089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3274639/']}
jdg_75636
stackexchange
llm_judgeable_groundtruth_similarity
51621
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: I have a question regarding a graph traversal problem. This is the graph I am working with: Graph[{1 <-> 2, 1 <-> 3, 2 <-> 3, 2 <-> 4, 3 <-> 4}] My Problem is following: I want to find a cycle on this graph such that after completion of the cycle I will have traversed each edge of the graph exactly twice and will have ended at my starting point. I saw that Mathematica 9 has a built-in function: FindEulerianCycle[g] which does just want I want except that each edge is traversed exactly once. So my idea was to "double" the edges i.e. add a new edge between 2 nodes: Graph[{ 1 <-> 2, 1 <-> 2, 1 <-> 3, 1 <-> 3, 2 <-> 3, 2 <-> 3, 2 <-> 4, 2 <-> 4, 3 <-> 4, 3 <-> 4 }] But then I get the following error message: Graph::supp: Mixed graphs and multigraphs are not supported. Apparently Multigraphs are still not supported in Mathematica 8 & 9: Multigraphs in Mathematica 8 Is there a way to implement a solution to the above mentioned problem in Mathematica ? (I am using Mathematica 9) Note : The graph shown above is just a simple example. I need to solve the above mentioned problem on a much bigger undirected graph which has vertices of odd degree. Now provide the response and nothing else.
You could convert your graph to directed graph by doubling your edge and give directions (opposite each other): g = Graph[{1 <-> 2, 1 <-> 3, 2 <-> 3, 2 <-> 4, 3 <-> 4}];dg = DirectedGraph[g] path = FindEulerianCycle[dg][[1]] {1 [DirectedEdge] 2, 2 [DirectedEdge] 1, 1 [DirectedEdge] 3, 3 [DirectedEdge] 2, 2 [DirectedEdge] 3, 3 [DirectedEdge] 4, 4 [DirectedEdge] 2, 2 [DirectedEdge] 4, 4 [DirectedEdge] 3, 3 [DirectedEdge] 1} once you found path you can convert edges back to undirected: UndirectedEdge @@@ path {1 <-> 2, 2 <-> 1, 1 <-> 3, 3 <-> 2, 2 <-> 3, 3 <-> 4, 4 <-> 2, 2 <-> 4, 4 <-> 3, 3 <-> 1} Note: this will just work on new version of Mathematica (tested on wolframcloud): https://www.wolframcloud.com/objects/4b9a4eea-4577-4799-844b-85da34f7550f
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/51621', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/16169/']}
jdg_75637
stackexchange
llm_judgeable_groundtruth_similarity
7550582
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have some (x,y) data, I can easily draw straight-line through it, e.g. f=glm(y~x)plot(x,y)lines(x,f$fitted.values) But for curvy data I want a curvy line. It seems loess() can be used: f=loess(y~x)plot(x,y)lines(x,f$fitted) This question has evolved as I've typed and researched it. I started off with wanting to a simple function to fit curvy data (where I know nothing about the data), and wanting to understand how to use nls() or optim() to do that. That was what everyone seemed to be suggesting in similar questions I found. But now I stumbled upon loess() I'm happy. So, now my question is why would someone choose to use nls or optim instead of loess (or smooth.spline )? Using the toolbox analogy, is nls a screwdriver and loess is a power-screwdriver (meaning I'd almost always choose the latter as it does the same thing but with less of my effort)? Or is nls a flat-head screwdriver and loess a cross-head screwdriver (meaning loess is a better fit for some problems, but for others it simply won't do the job)? For reference, here is the play data I was using that loess gives satisfactory results for: x=1:40y=(sin(x/5)*3)+runif(x) And: x=1:40y=exp(jitter(x,factor=30)^0.5) Sadly, it does less well on this: x=1:400y=(sin(x/20)*3)+runif(x) Can nls(), or any other function or library, cope with both this and the previous exp example, without being given a hint (i.e. without being told it is a sine wave)? UPDATE: Some useful pages on the same theme on stackoverflow: Goodness of fit functions in R How to fit a smooth curve to my data in R? smooth.spline "out of the box" gives good results on my 1st and 3rd examples, but terrible (it just joins the dots) on the 2nd example. However f=smooth.spline(x,y,spar=0.5) is good on all three. UPDATE #2: gam() (from mgcv package) is great so far: it gives a similar result to loess() when that was better, and a similar result to smooth.spline() when that was better. And all without hints or extra parameters. The docs were so far over my head I felt like I was squinting at a plane flying overhead; but a bit of trial and error found: #f=gam(y~x) #Works just like glm(). I.e. pointlessf=gam(y~s(x)) #This is what you wantplot(x,y)lines(x,f$fitted) Now provide the response and nothing else.
Nonlinear-least squares is a means of fitting a model that is non-linear in the parameters. By fitting a model, I mean there is some a priori specified form for the relationship between the response and the covariates, with some unknown parameters that are to be estimated. As the model is non-linear in these parameters NLS is a means to estimate values for those coefficients by minimising a least-squares criterion in an iterative fashion. LOESS was developed as a means of smoothing scatterplots. It has a very less well defined concept of a "model" that is fitted (IIRC there is no "model"). LOESS works by trying to identify pattern in the relationship between response and covariates without the user having to specify what form that relationship is. LOESS works out the relationship from the data themselves. These are two fundamentally different ideas. If you know the data should follow a particular model then you should fit that model using NLS. You could always compare the two fits (NLS vs LOESS) to see if there is systematic variation from the presumed model etc - but that would show up in the NLS residuals. Instead of LOESS, you might consider Generalized Additive Models (GAMs) fitted via gam() in recommended package mgcv . These models can be viewed as a penalised regression problem but allow for the fitted smooth functions to be estimated from the data like they are in LOESS. GAM extends GLM to allow smooth, arbitrary functions of covariates.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7550582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/841830/']}
jdg_75638
stackexchange
llm_judgeable_groundtruth_similarity
315970
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: I have had this question for a while. I have yet to find information on this online or use this property in any calculation. I believe myself to have proven that it will still be symmetric but I am somewhat unsure of my proof. Suppose you have $A^{ij}=A^{ji}$, then,$$ A^{ij}=A^{i}_{\phantom{i}k}g^{kj}=A^{\phantom{k}i}_{k}g^{kj}=A^{ji}\tag{1}$$So $$A^{i}_{\phantom{i}k}g^{kj}=A^{\phantom{k}i}_{k}g^{kj}\tag{2}$$Which implies $$A^{i}_{\phantom{i}k}=A^{\phantom{k}i}_{k}.\tag{3}$$Is this true? Now provide the response and nothing else.
It is symmetric but you actually have not proven it. In the first line you are just showing your initial hypothesis and in the second line you use what you are supposed to prove. The proof is simply$$A^i_{\ \ j}=g_{jk}A^{ik}=g_{jk}A^{ki}=A_j^{\ \ i}.$$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/315970', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/141968/']}
jdg_75639
stackexchange
llm_judgeable_groundtruth_similarity
36313946
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can someone explain me the difference between defer and create methods in Observable ? I failed to understand when I should use defer and when should I use create .. REFERENCES: Defer: http://reactivex.io/documentation/operators/defer.html Create: http://reactivex.io/documentation/operators/create.html Thank you Now provide the response and nothing else.
create(...) actually creates Observable immediately. public final static <T> Observable<T> create(OnSubscribe<T> f) { return new Observable<T>(hook.onCreate(f)); } defer(...) accepts Factory function that returns Observable(Subject, etc...), wraps it with OnSubscribeDefer and creates Observable only when subscriber subscribes, new Observable for every subscriber. public final static <T> Observable<T> defer(Func0<Observable<T>> observableFactory) { return create(new OnSubscribeDefer<T>(observableFactory));} See some more details here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36313946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552279/']}
jdg_75640