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 | 478862 |
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 want to prove the following $$\sum_{k=0}^{n}\frac{\binom{n}{k}}{k+1}=\frac{2^{n+1}-1}{n+1}$$I need some hint how to start. thanks!
Now provide the response and nothing else.
| Following your hint to introduce integrals we have$$\sum_{k=0}^n \frac{1}{k+1} \binom{n}{k} = \sum_{k=0}^n \binom{n}{k} \int_0^1 x^k dx$$which is$$\int_0^1 \sum_{k=0}^n \binom{n}{k} x^k dx =\int_0^1 (x+1)^n dx =\left. \frac{(x+1)^{n+1}}{n+1} \right|_0^1 =\frac{2^{n+1}-1}{n+1}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/478862', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/63283/']} | jdg_80941 |
stackexchange | llm_judgeable_groundtruth_similarity | 6954413 |
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 table in a database one is register table another is type table.I'm trying to create a form that will include a drop down menu derived from the 'type' table and the values of the form will be inserted in the 'register' table. When a option is selected the id of the type will be inserted in to foreign id field of the 'register' table where the values of the form is actually posted. I'm really stuck with this problem. please help. my form looks like this enter code here <form action="form1.php" method="post"> Name: <input type="text" name="name" /><br/><br/> Username: <input type="text" name="username" /><br/><br/> Password: <input type="password" name="password" /><br/><br/> Email: <input type="text" name="email" /><br/><br/> You are: <select name="type" size="3 multiple"> <option value="1" selected="selected">Super admin</option> <option value="2">Admin</option> <option value="3">User</option> </select> <input type="submit" name="submit" value="Submit" /> </form> and the tables Table project . type CREATE TABLE IF NOT EXISTS `project`.`type` ( `id` INT NOT NULL AUTO_INCREMENT , `type` VARCHAR(45) NULL , PRIMARY KEY (`id`) )ENGINE = InnoDB; Table project . register CREATE TABLE IF NOT EXISTS `project`.`register` ( `id` INT NOT NULL , `name` VARCHAR(45) NULL , `username` VARCHAR(45) NULL , `password` VARCHAR(45) NULL , `email` VARCHAR(45) NULL , `phone` VARCHAR(45) NULL , `type_id` INT NOT NULL , PRIMARY KEY (`id`) , UNIQUE INDEX `id_UNIQUE` (`id` ASC) , INDEX `fk_register_type1` (`type_id` ASC) , CONSTRAINT `fk_register_type1` FOREIGN KEY (`type_id` ) REFERENCES `project`.`type` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION)ENGINE = InnoDB;
Now provide the response and nothing else.
| One way is to connect with an account that has permissions only in the required databases. Not sysadmin which is what you are doing now. This would be normal for developers If you want to run as sysadmin, add this line to each script IF DB_NAME() = 'master' RAISERROR ('Oi! Stop!', 20, 1) WITH LOGGO This will kill the connection Edit: I like Quassnoi's solution because it doesn't require sysadmin rights.But, you can't give feedback or revert. So, I've been playing with this. It checks most boxes amusing message no sysadmin needed re-runnable (kind of) There is one issue that an SSMS USE (via the drop down) is ignored (as per Quassnoi's notes), but it's getting there. Any more ideas anyone? SET NOEXEC OFF;GODECLARE @isOK bit;BEGIN TRY IF DB_NAME() IN ('master', 'protectedDB1', '...') RAISERROR ('To Catch Block Only', 16, 1); SET @isOK = 1;END TRYBEGIN CATCH SET @isOK = 0; RAISERROR ('Oi! Stop!', 16, 1);END CATCHIF @isOK = 0 SET NOEXEC ON;GOSELECT 1;GO | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6954413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/869258/']} | jdg_80942 |
stackexchange | llm_judgeable_groundtruth_similarity | 73235 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to have a confirmation message every time I type exit command in the command-prompt. To do this, I have tried to use trap in .bashrc file but it seem like trap is not a solution as it run the original command anyway. Is there a way I can have this? Here is my bashrc script code which could not get the job done: function _exit() # Function to run upon exit of shell.{ read -p "${RED}Are you sure? " REPLY if [[ $REPLY =~ ^[Yy]$ ]]; then echo -e "${RED}Bye${NC}" exit 0 else #I do not know what to do here to not exit return fi }trap _exit EXIT
Now provide the response and nothing else.
| If the shell is zsh or bash (though not in sh mode), make exit a function. Functions have precedence over shell builtins (even special ones like exit ) in zsh or bash (though not in POSIX shells). So just rename your function to exit and use command exit within the function instead. Otherwise you had endless recursion, of course. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/73235', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/36597/']} | jdg_80943 |
stackexchange | llm_judgeable_groundtruth_similarity | 11263 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There are a bunch of different alignment tools out there , and I don't want to get bogged down in the maths behind them as this not only between software but varies from software version to version. There are two main divides in the programs; some use local alignments and others use global alignments. My question is threefold: What are the fundamental differences between the two? What are the advantages and disadvantages of each? When should one use either a global or local sequence alignment?
Now provide the response and nothing else.
| The very basic difference between a local and a global alignments is that in a local alignment, you try to match your query with a substring (a portion) of your subject (reference). Whereas in a global alignment you perform an end to end alignment with the subject (and therefore as von mises said, you may end up with a lot of gaps in global alignment if the sizes of query and subject are dissimilar). You may have gaps in local alignment also. Local Alignment 5' ACTACTAGATTACTTACGGATCAGGTACTTTAGAGGCTTGCAACCA 3' |||| |||||| ||||||||||||||| 5' TACTCACGGATGAGGTACTTTAGAGGC 3' Global Alignment 5' ACTACTAGATTACTTACGGATCAGGTACTTTAGAGGCTTGCAACCA 3' ||||||||||| ||||||| |||||||||||||| |||||||5' ACTACTAGATT----ACGGATC--GTACTTTAGAGGCTAGCAACCA 3' I shall give the example of the well known dynamic programming algorithms.In the Needleman-Wunsch (Global) algorithm, the score tracking is done from the (m,n) co-ordinate corresponding to the bottom right corner of the scoring matrix (i.e. the end of the aligned sequences) whereas in the Smith-Waterman (local), it is done from the element with highest score in the matrix (i.e. the end of the highest scoring pair). You can check these algorithms for details. You can adopt any scoring schemes and there is no fixed rule for it. Global alignments are usually done for comparing homologous genes whereas local alignment can be used to find homologous domains in otherwise non-homologous genes. | {} | {'log_upvote_score': 6, 'links': ['https://biology.stackexchange.com/questions/11263', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/3553/']} | jdg_80944 |
stackexchange | llm_judgeable_groundtruth_similarity | 1262708 |
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 simple batch file like this: echo offtaskkill /im "test.exe" /f > nulpause If "test.exe" is not running, I get this message: ERROR: The process "test.exe" not found. Why does this error message get displayed, even though I have redirected output to NUL? How can I suppress that output?
Now provide the response and nothing else.
| Because error messages often go to stderr not stdout . Change the invocation to this: taskkill /im "test.exe" /f >nul 2>&1 and all will be better. That works because stdout is file descriptor 1, and stderr is file descriptor 2 by convention. (0 is stdin , incidentally.) The 2>&1 copies output file descriptor 2 from the new value of 1, which was just redirected to the null device. This syntax is (loosely) borrowed from many Unix shells, but you do have to be careful because there are subtle differences between the shell syntax and CMD.EXE. Update: I know the OP understands the special nature of the "file" named NUL I'm writing to here, but a commenter didn't and so let me digress with a little more detail on that aspect. Going all the way back to the earliest releases of MSDOS, certain file names were preempted by the file system kernel and used to refer to devices. The earliest list of those names included NUL , PRN , CON , AUX and COM1 through COM4 . NUL is the null device. It can always be opened for either reading or writing, any amount can be written on it, and reads always succeed but return no data. The others include the parallel printer port, the console, and up to four serial ports. As of MSDOS 5, there were several more reserved names, but the basic convention was very well established. When Windows was created, it started life as a fairly thin application switching layer on top of the MSDOS kernel, and thus had the same file name restrictions. When Windows NT was created as a true operating system in its own right, names like NUL and COM1 were too widely assumed to work to permit their elimination. However, the idea that new devices would always get names that would block future user of those names for actual files is obviously unreasonable. Windows NT and all versions that follow (2K, XP, 7, and now 8) all follow use the much more elaborate NT Namespace from kernel code and to carefully constructed and highly non-portable user space code. In that name space, device drivers are visible through the \Device folder. To support the required backward compatibility there is a special mechanism using the \DosDevices folder that implements the list of reserved file names in any file system folder. User code can brows this internal name space using an API layer below the usual Win32 API; a good tool to explore the kernel namespace is WinObj from the SysInternals group at Microsoft. For a complete description of the rules surrounding legal names of files (and devices) in Windows, this page at MSDN will be both informative and daunting. The rules are a lot more complicated than they ought to be, and it is actually impossible to answer some simple questions such as "how long is the longest legal fully qualified path name?". | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1262708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/672/']} | jdg_80945 |
stackexchange | llm_judgeable_groundtruth_similarity | 1255842 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Show that if a set is compact then it is closed. definitions: Let $A\subset \mathbb{R}$. A point $p\in\mathbb{R}$ is an accumulation point or limit point of $A$ if and only if every open set $G$ containing $p$ contains a point of $A$ different from $p$. A subset $A$ of $\mathbb{R}$ is closed if and only if $A$ contains each of its points of accumulation. proof: Suppose $A\subset \mathbb{R}$ is compact and $A\subset \bigcup O_\alpha$ where $O_\alpha$ is open. Since, $A\subset \bigcup O_\alpha$ there exists $\alpha_1,\dots,\alpha_n$ such that $$A\subset O_{\alpha_{1}}\cup O_{\alpha_{2}}\cup \ldots \cup O_{\alpha_{n}}$$Now suppose we have a point $p\in\mathbb{R}$. Let $G = \bigcup_{i=1}^{n}O_{\alpha_{i}}$, and $p\subset G$. Then $p$ is an accumulation point of $A$ since every open set $G$ contains $p$ can also contain a point of $A$ different from $p$. I am not sure if this is the right approach but it makes sense to me, I just don't know how to go on from here. Any suggestions would be greatly appreciated.
Now provide the response and nothing else.
| Several mistakes here: What is $\alpha$? How are $O_\alpha$? Are they just any collection of sets covering $A$? You take a point $p\in \mathbb R$ and prove that if $P\in G$, then $p$ is an accumulation point of $A$, which is not true: Take $A=[0,1]$ and take $O_1=(-1,1), O_2=(0,2)$. Then, $G=(-1,2)$ and we can take $p=-\frac12$, but $p$ is then not an accumulation point of $A$. Even if it were true, you would then prove that every point in $G$ is an accumulation point of $A$, which does not prove that $A$ is closed. For example, if $G=(0,1)$ and $A=(0,1)$, then every point $p\in G$ is an accumulation point of $A$, but $A$ is not closed. I believe your proof is wrong from the beginning. First of all, you are not proving what you need to prove. You need to prove that $A$ is closed, and you may do this by proving that every accumulation point of $A$ is in $A$. Second of all, you are using compactness in the wrong place. Compactness tells you that: For EVERY collection $\{O_\alpha\}$ which covers $A$, there exists a finite subcollection which also covers $A$. Therefore, the idea here is not to take the collection at the beginning. The idea is this: Take a poin $p$ which is an accumulation point of $A$. Prove that $p\in A$. You may for example do this by assuming that $a\notin A$, then using compactness of $A$ to reach a contradiction. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1255842', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/217910/']} | jdg_80946 |
stackexchange | llm_judgeable_groundtruth_similarity | 287043 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Consider the problem of finding the limit of the following diagram: $$ \require{AMScd} \begin{CD}& & & & E\\ & & & & @VVV\\ && C @>>> D\\ & & @VVV\\A @>>> B\end{CD} $$ The abstract definition of the limit involves an adjunction related to collapsing the entire index category to a point. However, one could break this operation into two stages: first collapsing the upper three objects to a point reduces it to $$ \require{AMScd} \begin{CD} & & C \times_D E\\ & & @VVV\\A @>>> B\end{CD} $$ and then we finish computing the limit as $A \times_B (C \times_D E)$. This is a particularly convenient thing, since it implies a way to work locally with more complicated diagrams where you ultimately want a limit — i.e. take limits or perform other modifications to smaller pieces of the diagram while leaving the rest unchanged. However, not every variation works out so nicely. If we try the same thing but instead collapse the middle three objects to a point, the intermediate diagram becomes $$ \require{AMScd} \begin{CD} & & C \times_D E\\ & & @VVV\\A \times_B C@>>> C\end{CD} $$ So, trying to perform this operation isn't local at all; it modifies the value of the diagram at the other two vertices. To clarify what I mean, this diagram together with the appropriate "cone" is (I believe) universal among all diagrams with "cones" of the form $$ \require{AMScd} \begin{CD} & & \bullet &\to& E\\ & & @VVV @VVV\\\bullet @>>> \bullet & \to & D\\ \downarrow & & \downarrow & \searrow @AAA\\ A @>>> B @<<< C\end{CD} $$ It seems clear what the the abstract theory behind this sort of calculation should be; just factor the usual adjunction into a sequence of adjunctions. But my interest in such things is very much not in the abstract — these are the sorts of operations one would like to have as a practical calculus of diagrams. So my question is if such a calculus is known? Is there worked out how to predict and recognize which sorts of operations really should be local? Or for those operations that are not local, to easily work out how the rest of the diagram gets modified? (and the bonus question: how much of this carries over to homotopy limits?)
Now provide the response and nothing else.
| Let me try to turn my comments into an answer (I think it's also essentially what Vladimir was saying). Suppose you have some diagram $F: K \to \mathcal{C}$. To compute the limit of $F$ is the same as computing the right Kan extension $\epsilon_*F$ along the map $\epsilon: K \to \bullet$. The process you're describing is to compute this Kan extension by factoring the map $\epsilon$ into a bunch of maps $K=K_0 \to K_1 \to K_2 \to \cdots \to \bullet$ and Kan extending one at a time. That's perfectly allowed. You'd like to keep track of the values of your diagram as you Kan extend. In general, for a functor $p: K \to L$, the value of the right Kan extension $p_*F$ at a point $x \in L$ is given by the limit over the category $K_{x/}$, i.e. the category whose objects are pairs $(k, x \to p(k))$ and whose morphisms are morphisms in $K$ making the appropriate diagram commute. In general one might ask: when is a limit of a functor $G$ over some diagram $D$ given by just one of the values $G(d)$? A sufficient condition for this to occur is that $d \in D$ be initial. Putting these two facts together we learn that: $p_*F(x)$ is given by a known value of $F$ if $K_{x/}$ has an initial object. Now you'd like some explicit procedure, I guess, for computing the limit over $K$ in this iterative way where you don't have to change too much at once. Here is one way that works. For ease let's take a skeletal, finite $K$. First consider the diagram $K_1$ obtained from $K$ by asking that every endomorphism be the identity. The right Kan extension to this step computes the 'fixed points' of each object under the action of the endomorphisms. If you want, you could do it one object at a time. Now begin collapsing parallel arrows one step at a time. This will always be a collapse of the desired type. Indeed, if $a\rightrightarrows b$ is a pair of arrows in $K_i$ and we collapse them to build $K_{i+1}$, then the overcategories $(K_{i+1})_{x/}$ will evidently have initial object $x$ if $x \ne a$. If $x = a$ then we'll be computing an equalizer. Now you've got a category $K_N$ where every object has only the identity endomorphism, and there is at most one arrow between any two objects. So you've got a poset! Now you can begin pruning exactly as you did in your example. Arrange the poset by height. Say it has height $n$. If $n$ is zero, then you've got a discrete poset- take the product. Otherwise, if you see two objects of height $(n-1)$ which hit an object of height $n$, form $K_{N+1}$ by collapsing those three objects to a point. This procedure replaces the three objects by the pullback and changes nothing else. Keep doing that until there are no more such objects of height $n$. Either you've decreased the height to $(n-1)$, or there are objects of height $n$ with only one thing of height $(n-1)$ hitting it. Taking each in turn, collapse those pairs to a point. This won't do anything except delete those height $n$ values from your diagram. Now you have something of height $(n-1)$. Repeat until you get down to height 0, then take the product of everything you see. There are many variations on this theme... you could do things in a different order, or you could embed into a larger diagram which is often convenient, etc. etc. Of course, there's also the standard formula for a limit as an equalizer of two products, but I imagine you knew that already. Also- everything I said works for homotopy limits over ordinary categories. If you want to do homotopy limits over an $\infty$-category, you can still do something like this. In fact, said in the language of $\infty$-categories or quasicategories, this whole procedure is maybe more evident: take your quasicategory, which is a simplicial set $K$, and write it as an iterated pushout along cell inclusions (maybe transfinitely many). Then a homotopy colimit over $K$ can be computed by iteratively by using pushouts, or if you come across an empty diagram you'll need an initial object, and then taking filtered colimits along the way. One can take care of limits by working in the opposite category. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/287043', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_80947 |
stackexchange | llm_judgeable_groundtruth_similarity | 44048855 |
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 made a slack app in which I have a bot. I have selected channels:history, channels:read, channels:write under my permission scope, and also I have passed scopes "scope":"bot channel:history channel:read channel:write" while doing my oauth2 verification (using python), and I got a response where the scope is "scope":"identify,bot,channels:history,channels:read,channels:write" along with client and bot access tokens. Now when I do an api call to fetch history of a channel in which my bot is invited to, I get { ok: false, error: 'missing_scope', needed: 'channels:history', provided: 'identify,bot:basic' } Can someone please tell me where I am going wrong. How can I PROVIDE the channels:history scope in my api call. This is really driving me nuts. Should I be using the client access token, ie xoxp-xxxx, instead of bot token, ie xoxb-xxxx ?' Thanks!
Now provide the response and nothing else.
| For people having this problem in the future; your integrated bot has full access to the slack api, whereas a bot in a slack app don't, as it will used publicly. When you successfully finish oauth2, you should get 2 tokens, user access token and bot token . The user token is used to read history from any channel/groups, and the bot access token is used to write to them. This means you constantly have to be switching from user token to bot access token in your app. Also, remember that bot-user MUST be a member of a private channel which you want him to connect to. Hope that helps. Ps, if any found a better way going about this, feel free to answer below. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44048855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7278236/']} | jdg_80948 |
stackexchange | llm_judgeable_groundtruth_similarity | 30235542 |
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 university graduate database and would like to extract a random sample of data of around 1000 records. I want to ensure the sample is representative of the population so would like to include the same proportions of courses eg I could do this using the following: select top 500 id from degree where coursecode = 1 order by newid()unionselect top 300 id from degree where coursecode = 2 order by newid()unionselect top 200 id from degree where coursecode = 3 order by newid() but we have hundreds of courses codes so this would be time consuming and I would like to be able to reuse this code for different sample sizes and don't particularly want to go through the query and hard code the sample sizes. Any help would be greatly appreciated
Now provide the response and nothing else.
| You want a stratified sample. I would recommend doing this by sorting the data by course code and doing an nth sample. Here is one method that works best if you have a large population size: select d.*from (select d.*, row_number() over (order by coursecode, newid) as seqnum, count(*) over () as cnt from degree d ) dwhere seqnum % (cnt / 500) = 1; EDIT: You can also calculate the population size for each group "on the fly": select d.*from (select d.*, row_number() over (partition by coursecode order by newid) as seqnum, count(*) over () as cnt, count(*) over (partition by coursecode) as cc_cnt from degree d ) dwhere seqnum < 500 * (cc_cnt * 1.0 / cnt) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30235542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2706919/']} | jdg_80949 |
stackexchange | llm_judgeable_groundtruth_similarity | 175903 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How would I solve the following double angle identity. $$\cos 3x =4\cos^3x-3\cos x $$ I know $\,\cos 3x = \cos(2x+x)$ So know I have $\,\cos 2x +\cos x \,$ , Which is $\,(2\cos^2x-1)\cos x$ But I am not sure what to do next.
Now provide the response and nothing else.
| $$e^{ix}=\cos x+i\sin x\Rightarrow e^{3ix}=(\cos x+i\sin x)^3\Rightarrow\cos 3x+i\sin 3x=(\cos x+i\sin x)^3$$ Now expand the cube and equate the real and imaginary parts of both sides to get the answer. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/175903', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/35021/']} | jdg_80950 |
stackexchange | llm_judgeable_groundtruth_similarity | 757900 |
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:
Is it possible to solve a summation with a variable base of log? $$S_n = \sum_{i = 2}^{n}\log_i{(n)}$$ Should I use the derivative of $\log_i{(n)}$?
Now provide the response and nothing else.
| While I don't believe there is a nice closed form for $S_n$, you can write the sum in terms of known functions and constants up to a very small error. Specifically, $$\sum_{i=2}^{N}\log_{i}(N)=\text{li(N)}\log N+C\log N+O(1),$$ where $\text{li}(N)$ is the logarithmic integral and $C$ is a constant equal to $$C=\frac{1}{\log2}+\int_{2}^{\infty}\frac{\{x\}}{x\log^{2}x}dx.$$ Proof: Writing $$\sum_{i=2}^{N}\log_{i}(N)=\log N\sum_{i=2}^{N}\frac{1}{\log i},$$ our goal is then to find an asymptotic for the sum of $1/\log i$. Writing this as a Riemann Stieltjies integral we have $$\sum_{i=2}^{N}\frac{1}{\log i}=\int_{2^{-}}^{N^{+}}\frac{1}{\log x}d\left[x\right]=\int_{2}^{N}\frac{1}{\log x}dx-\int_{2^{-}}^{N^{+}}\frac{1}{\log x}d\left\{ x\right\}.$$ By integration by parts, $$\int_{2^{-}}^{N^{+}}\frac{1}{\log x}d\left\{ x\right\} =\frac{\left\{ x\right\} }{\log x}\biggr|_{x=2^{-}}^{x=N^{+}}+\int_{2}^{N}\frac{\left\{ x\right\} }{x\log^{2}x}dx$$ $$=\frac{1}{\log2}+\int_{2}^{\infty}\frac{\{x\}}{x\log^{2}x}dx-\int_{N}^{\infty}\frac{\left\{ x\right\} }{x\log^{2}x}dx,$$ and since $$\int_{N}^{\infty}\frac{\{x\}}{x\log^{2}x}dx=O\left(\frac{1}{\log N}\right),$$ we have that $$\sum_{i=2}^{N}\frac{1}{\log i}=\text{li}(N)+C+O\left(\frac{1}{\log N}\right)$$ where $\text{li}(N)$ is the logarithmic integral and $$C=\frac{1}{\log2}+\int_{2}^{\infty}\frac{\{x\}}{x\log^{2}x}dx.$$ Thus it follows that $$\sum_{i=2}^{N}\log_{i}(N)=\text{li(N)}\log N+C\log N+O(1).$$ (Note that the asymptotic is then $\sum_{i=2}^{N}\log_{i}(N)\sim N.$) Remark: In fact, we could apply integration by parts again to work out the $O(1)$ term exactly and evaluate the sum up to an error of $O\left(\frac{1}{N}\right)$. This general process of writing the sum $\sum_{k\leq N} f(k)$ as a series whose main term is $\int_{1}^N f(x)dx$ is known as Euler-Maclaurin summation . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/757900', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/132230/']} | jdg_80951 |
stackexchange | llm_judgeable_groundtruth_similarity | 39879672 |
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 update certain attributes of html element using typescript. Is it possible to do so? Here's my code HTML:- <a ref="#" id="userProfileName" style="padding-top: 0px; padding-bottom: 0px; padding-right: 10px; padding-left: 10px;"><img src="" alt="" id="userProfilePic" class="profile-img" style="width: 56px; height: 50px;"></a> Typescript:- document.getElementById('userProfilePic').src = profile.picture;document.getElementById('userProfileName').textContent = profile.given_name; Error I'm getting:- error TS2339: Property 'src' does not exist on type 'HTMLElement'.
Now provide the response and nothing else.
| The document.getElementById function returns an element of type HTMLElement which does not have the src property. You need to type assert it to HTMLImageElement : (document.getElementById('userProfilePic') as HTMLImageElement).src = profile.picture; The same goes for the HTMLAnchorElement but textContent can be accessed straight from the HTMLElement so no need to cast. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39879672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2727884/']} | jdg_80952 |
stackexchange | llm_judgeable_groundtruth_similarity | 60152922 |
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 connect to WebSockets server and log it's messages. With React class component I'd put this logic in componentDidMount lifecycle hook and move on happily, but I'm not sure how to properly implement it with hooks. Here's my first attempt. import React, {useEffect} from 'react';export default function AppWs() { useEffect(() => { let ws = new WebSocket('wss://ws.kraken.com/'); ws.onopen = () => console.log('ws opened'); ws.onclose = () => console.log('ws closed'); ws.onmessage = e => { const message = JSON.parse(e.data); console.log('e', message); }; return () => { ws.close(); } }, []); return ( <div>hooks + ws</div> )} I added connection and log logic to useEffect , provided empty array with dependencies, and everything worked great. Until I needed to add pause state to pause logging. export default function AppWs() { const [isPaused, setPause] = useState(false); useEffect(() => { let ws = new WebSocket('wss://ws.kraken.com/'); ws.onopen = () => console.log('ws opened'); ws.onclose = () => console.log('ws closed'); ws.onmessage = e => { if (isPaused) return; const message = JSON.parse(e.data); console.log('e', message); }; return () => { ws.close(); } }, []); return ( <div> <button onClick={() => setPause(!isPaused)}>{isPaused ? 'Resume' : 'Pause'}</button> </div> )} ESLint started to yell at me that I should add isPaused state as a dependency to useEffect . Well, ok, done. But I noticed re-connection to WS server after every time I click the button. This is clearly not what I want. My next iteration was to use two useEffect s: one for connection and one for message processing. export default function AppWs() { const [isPaused, setPause] = useState(false); const [ws, setWs] = useState(null); useEffect(() => { const wsClient = new WebSocket('wss://ws.kraken.com/'); wsClient.onopen = () => { console.log('ws opened'); setWs(wsClient); }; wsClient.onclose = () => console.log('ws closed'); return () => { wsClient.close(); } }, []); useEffect(() => { if (!ws) return; ws.onmessage = e => { if (isPaused) return; const message = JSON.parse(e.data); console.log('e', message); }; }, [isPaused, ws]); return ( <div> <button onClick={() => setPause(!isPaused)}>{isPaused ? 'Resume' : 'Pause'}</button> </div> )} This works as expected, but I have a feeling that I miss something and this task can be solved easier, with one useEffect .Please help to refactor the code on convince me that I'm using React hooks in a proper way. Thanks!
Now provide the response and nothing else.
| As you are only setting the web socket once, I think a better approach is to use a ref instead of a state: The order of useEffect is important. As suggested by George in the comments, in the first useEffect ws.current is saved to a variable to make sure that when close is called it refers to the same instance. export default function AppWs() { const [isPaused, setPause] = useState(false); const ws = useRef(null); useEffect(() => { ws.current = new WebSocket("wss://ws.kraken.com/"); ws.current.onopen = () => console.log("ws opened"); ws.current.onclose = () => console.log("ws closed"); const wsCurrent = ws.current; return () => { wsCurrent.close(); }; }, []); useEffect(() => { if (!ws.current) return; ws.current.onmessage = e => { if (isPaused) return; const message = JSON.parse(e.data); console.log("e", message); }; }, [isPaused]); return ( <div> <button onClick={() => setPause(!isPaused)}> {isPaused ? "Resume" : "Pause"} </button> </div> );} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/60152922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5476578/']} | jdg_80953 |
stackexchange | llm_judgeable_groundtruth_similarity | 28237952 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an AngularJS service which communicates with the server and returns translations of different sections of the application: angular .module('utils') .service('Translations', ['$q','$http',function($q, $http) { translationsService = { get: function(section) { if (!promise) { var q = $q.defer(); promise = $http .get( '/api/translations', { section: section }) .success(function(data,status,headers,config) { q.resolve(result.data); }) .error(function(data,status,headers,config){ q.reject(status); }); return q.promise; } } }; return translationsService; }]); The name of the section is passed as the section parameter of the get function. I'm using AngularJS ui-router module and following design pattern described here So I have the following states config: angular.module('app') .config(['$stateProvider', function($stateProvider) { $stateProvider .state('users', { url: '/users', resolve: { translations: ['Translations', function(Translations) { return Translations.get('users'); } ] }, templateUrl: '/app/users/list.html', controller: 'usersController', controllerAs: 'vm' }) .state('shifts', { url: '/shifts', resolve: { translations: ['Translations', function(Translations) { return Translations.get('shifts'); } ] }, templateUrl: '/app/shifts/list.html', controller: 'shiftsController', controllerAs: 'vm' }) This works fine but as you may notice I have to explicitly specify translations in the resolve parameter. I think that's not good enough as this duplicates the logic. Is there any way to resolve translations globally and avoid the code duplicates. I mean some kind of middleware. I was thinking about listening for the $stateChangeStart , then get translations specific to the new state and bind them to controllers, but I have not found the way to do it. Any advice will be appreciated greatly. Important note:In my case the resolved translations object must contain the translations data, not service/factory/whatever. Kind regards.
Now provide the response and nothing else.
| Let me show you my approach. There is a working plunker Let's have a translation.json like this: { "home" : "trans for home", "parent" : "trans for parent", "parent.child" : "trans for child"} Now, let's introduce the super parent state root $stateProvider .state('root', { abstract: true, template: '<div ui-view=""></div>', resolve: ['Translations' , function(Translations){return Translations.loadAll();}] }); This super root state is not having any url (not effecting any child url) . Now, we will silently inject that into every state: $stateProvider .state('home', { parent: 'root', url: "/home", templateUrl: 'tpl.html', }) .state('parent', { parent: 'root', url: "/parent", templateUrl: 'tpl.html', }) As we can see, we use setting parent - and do not effect/extend the original state name . The root state is loading the translations at one shot via new method loadAll() : .service('Translations', ['$http' ,function($http) { translationsService = { data : {}, loadAll : function(){ return $http .get("translations.json") .then(function(response){ this.data = response.data; return this.data; }) }, get: function(section) { return data[section]; } }; return translationsService;}]) We do not need $q at all. Our super root state just resolves that once... via $http and loadAll() method. All these are now loaded, and we can even place that service into $rootScope : .run(['$rootScope', '$state', '$stateParams', 'Translations', function ($rootScope, $state, $stateParams, Translations) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; $rootScope.Translations = Translations;}]) And we can access it anyhwere like this: <h5>Translation</h5><pre>{{Translations.get($state.current.name) | json}}</pre> Wow... that is solution profiting almost from each feature coming with UI-Router... I'd say. All loaded once. All inherited because of $rootScope and view inheritance... all available in any child state... Check that all here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28237952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3174320/']} | jdg_80954 |
stackexchange | llm_judgeable_groundtruth_similarity | 13551116 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hey I have been programming for a few years now and just recently I was wondering what is best to do in a method that is always going to return something: if($age < 18) { return 'Under 18';}else { return 'Adult';} Or is it better to use: if($age < 18) { return 'Under 18';}return 'Adult'; In the latter if they are under 18 the program will return 'Under 18' and terminate the rest of the function so is there any need for that else{} in the first example? Thanks.
Now provide the response and nothing else.
| I use a base controller that exposes a DataBase property that derived controllers can access. public abstract class BaseController : Controller{ public BaseController() { Database = new DatabaseContext(); } protected DatabaseContext Database { get; set; } protected override void Dispose(bool disposing) { Database.Dispose(); base.Dispose(disposing); }} All of the controllers in my application derive from BaseController and are used like this: public class UserController : BaseController{ [HttpGet] public ActionResult Index() { return View(Database.Users.OrderBy(p => p.Name).ToList()); }} Now to answer your questions: When should I make a new DbContext / should I have one global context that I pass around? The context should be created per request. Create the context, do what you need to do with it then get rid of it. With the base class solution I use you only have to worry about using the context. Do not try and have a global context (this is not how web applications work). Can I have one global Context that I reuse in all places? No, if you keep a context around it will keep track of all the updates, additions, deletes etc and this will slow your application down and may even cause some pretty subtle bugs to appear in your application. You should probably chose to either expose your repository or your Context to your controller but not both. Having two contexts being access from the same method is going to lead to bugs if they both have different ideas about the current state of the application. Personally, I prefer to expose DbContext directly as most repository examples I have seen simply end up as thin wrappers around DbContext anyway. Does this cause a performance hit? The first time a DbContext is created is pretty expensive but once this has been done a lot of the information is cached so that subsequent instantiations are a lot quicker. you are more likely to see performance problems from keeping a context around than you are from instantiating one each time you need access to your database. How is everyone else doing this? It depends. Some people prefer to use a dependency injection framework to pass a concrete instance of their context to their controller when it is created. Both options are fine. Mine is more suitable for a small scale application where you know the specific database being used isn't going to change. some may argue that you can't know this and that is why the dependency injection method is better as it makes your application more resilient to change. My opinion on this is that it probably won't change (SQL server & Entity Framework are hardly obscure) and that my time is best spent writing the code that is specific to my application. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13551116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1494881/']} | jdg_80955 |
stackexchange | llm_judgeable_groundtruth_similarity | 30084577 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a custom data type that in practice can be either float or double . On every OS except OSX, I am able to successfully build this C++11 template: #include <cmath>#include <cstdlib>#include <cstdint>template< class REAL_T >inline REAL_T inhouse_abs(REAL_T i_val){ return std::abs((REAL_T)i_val);}int main(){ int32_t ui = 2; inhouse_abs(ui); return 0;} However, clang 6.0 (3.5 LLVM) reports an ambiguous function call. If I change abs to fabs , the error is resolved on OSX, but now an identical error shows up on my Linux clang, gcc, and Visual Studio. Error on Visual Studio with fabs: 349 error C2668: 'fabs' : ambiguous call to overloaded function UPDATE This example compiled on our OS X systems, although in the nearly identical project it does not. The solution was including <cstdlib> explicitly in the source, rather than back in another header. The reason is unclear, but seems to be xcode/clang not following our header includes properly.
Now provide the response and nothing else.
| The issue is that libc++ is not entirely C++11 compliant with the integral overload for std::abs in cmath : double fabs( Integral arg ); (7) (since C++11) Including cstdlib solves your problem since that header has overloads specifically for integer types. For reference the draft C++11 standard section 26.8 [c.math] paragraph 11 says: Moreover, there shall be additional overloads sufficient to ensure: and includes the following item: Otherwise, if any argument corresponding to a double parameter has type double or an integer type, then all arguments corresponding to double parameters are effectively cast to double. This is situation very likely to change due to LWG active issue 2192: Validity and return type of std::abs(0u) is unclear . I am guessing libc++ choose not to provide the overloads in cmath due to the issue brought up in this defect report. See Is std::abs(0u) ill-formed? for more details on this. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30084577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2673386/']} | jdg_80956 |
stackexchange | llm_judgeable_groundtruth_similarity | 1318658 |
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:
Please help me solve the following integral. I'm not sure where to start in fact, I haven't done math for 7 years and now I have to jump back in the integrals. I'm not sure if I have to integrate by part or by substitution. Wolfram Alpha tells me to start with the long division, but I'm not quite sure what it means. I would like to give you guys more information, but the thing is, I don't even know where to start, so it's kind of hard to give more details. Could you please at least tell me where to start? I'm looking in my manuals, and I just can't find it. Thank you very much! $$\int\frac{3x^3+2x+7}{x^2+3}dx$$
Now provide the response and nothing else.
| As you already mentioned you can start by "long division": $$\int \frac{3x^3+2x+7}{x^2+3}dx=\int 3x-\frac{7(x-1)}{(x^2+3)} \space \space dx$$ For a good video on polynomial division see here: LINK Now you can separate your integral: $$-7\int \frac{(x-1)}{(x^2+3)} \space dx+3\int x \space dx=\color{red}{-7\int \frac{x}{x^2+3} \space dx}+\color{blue}{7\int \frac{1}{x^2+3}\space dx}+3\int x \space dx $$ I am assuming you know how to integrate the last integral. The red and blue integral can be solved by substitution. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1318658', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/245278/']} | jdg_80957 |
stackexchange | llm_judgeable_groundtruth_similarity | 52857825 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to Kubernetes and started reading through the documentation.There often the term 'endpoint' is used but the documentation lacks an explicit definition. What is an 'endpoint' in terms of Kubernetes? Where is it located? I could image the 'endpoint' is some kind of access point for an individual 'node' but that's just a guess.
Now provide the response and nothing else.
| While you're correct that in the glossary there's indeed no entry for endpoint, it is a well defined Kubernetes network concept or abstraction. Since it's of secondary nature, you'd usually not directly manipulate it. There's a core resource Endpoint defined and it's also supported on the command line: $ kubectl get endpointsNAME ENDPOINTS AGEkubernetes 192.168.64.13:8443 10d And there you see what it effectively is: an IP address and a port. Usually, you'd let a service manage endpoints (one EP per pod the service routes traffic to) but you can also manually manage them if you have a use case that requires it. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/52857825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6574264/']} | jdg_80958 |
stackexchange | llm_judgeable_groundtruth_similarity | 30110344 |
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 generate a PDF with our department logo in it. When I try to use the WickedPdf class in my controller (using the method described at https://github.com/mileszs/wicked_pdf ): def some_action image_tag_string = image_tag('logo.jpg') pdf = WickedPdf.new.pdf_from_string(image_tag_string) save_path = Rails.root.join('testpdfs','logotest.pdf') File.open(save_path, 'wb') do |file| file << pdf endend ...the application saves the PDF to the target directory, but it has a blue-and-white '?' mark where the image should be. If I do this instead: image_tag_string = wicked_pdf_image_tag('logo.jpg') pdf = WickedPdf.new.pdf_from_string(image_tag_string) I get the following error: NoMethodError: undefined method `wicked_pdf_image_tag' for #<... It would appear that my Rails app is also missing / not linking to a helper file belonging to the wicked-pdf gem. Answers to similar questions on StackOverflow recommend writing a custom "image-tag" helper to locate the image or installing wkhtmltopdf. For me, image-tag shows the logo just fine when placed in a View (whatever.html.erb). "logo.jpg" is already located in both the asset pipeline and #{RailsRoot}/public/images. Finally, I am using wkhtmltopdf 0.9.9, wicked-pdf 0.11.0, and rails 4 on Ubuntu 14.04. In a nutshell - what am I doing wrong that causes WickedPDF to fail to render the image?
Now provide the response and nothing else.
| First thing create a pdf template to render and use your wicked_pdf tags in that template..for example- app/views/layout/application.pdf.erb- <!doctype html><html> <head> <meta charset='utf-8' /> </head> <body onload='number_pages'> <div id="content"> <%= yield %> </div> </body></html> app/views/pdf/pdf_view.pdf.erb- <div> <%= wicked_pdf_image_tag 'logo.jpg' %></div> use this template instead def save pdf = WickedPdf.new.pdf_from_string( render_to_string( template: 'example/pdf_view.pdf.erb', layout: 'layouts/application.pdf.erb')) send_data(pdf, filename: 'file_name.pdf', type: 'application/pdf', disposition: 'attachment') end This might help you.. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30110344', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4317091/']} | jdg_80959 |
stackexchange | llm_judgeable_groundtruth_similarity | 2245928 |
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 TextBox with a ContextMenu in it. When the user right clicks inside the TextBox and chooses the appropriate MenuItem, I would like to grab the SelectedText in my viewmodel. I have not found a good way to do this the "MVVM" way. So far I have my appliction utilizing Josh Smith's way of MVVM. I am looking to tranfer over to Cinch. Not sure if the Cinch framework will handle issues like this. Thoughts?
Now provide the response and nothing else.
| There's no straightforward way to bind SelectedText to a data source, because it's not a DependencyProperty... however, it quite easy to create an attached property that you could bind instead. Here's a basic implementation : public static class TextBoxHelper{ public static string GetSelectedText(DependencyObject obj) { return (string)obj.GetValue(SelectedTextProperty); } public static void SetSelectedText(DependencyObject obj, string value) { obj.SetValue(SelectedTextProperty, value); } // Using a DependencyProperty as the backing store for SelectedText. This enables animation, styling, binding, etc... public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.RegisterAttached( "SelectedText", typeof(string), typeof(TextBoxHelper), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, SelectedTextChanged)); private static void SelectedTextChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { TextBox tb = obj as TextBox; if (tb != null) { if (e.OldValue == null && e.NewValue != null) { tb.SelectionChanged += tb_SelectionChanged; } else if (e.OldValue != null && e.NewValue == null) { tb.SelectionChanged -= tb_SelectionChanged; } string newValue = e.NewValue as string; if (newValue != null && newValue != tb.SelectedText) { tb.SelectedText = newValue as string; } } } static void tb_SelectionChanged(object sender, RoutedEventArgs e) { TextBox tb = sender as TextBox; if (tb != null) { SetSelectedText(tb, tb.SelectedText); } }} You can then use it like that in XAML : <TextBox Text="{Binding Message}" u:TextBoxHelper.SelectedText="{Binding SelectedText}" /> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2245928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/271206/']} | jdg_80960 |
stackexchange | llm_judgeable_groundtruth_similarity | 18281 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
For example if I use WinRAR to encrypt a file and put a password on the archive how secure is it? I keep a personal journal and am thinking of doing this, or is there a better way? It's just one huge .docx file.
Now provide the response and nothing else.
| Summary: yes, but use VeraCrypt instead. From the documentation : WinRAR offers you the benefit of industry strength archive encryption using AES (Advanced Encryption Standard) with a key of 128 bits. So yes, the data is encrypted. This is only one of the elements of security, however. Another important element is how the key is derived from the password: what kind of key strengthening is performed? The slower the derivation of the key from the password, the more costly it is for an attacker to find the password (and hence the key) by brute force. A weak password is toast anyway, but good key strengthening can make the difference for a reasonably complex but still memorable password . WinRAR uses 262144 rounds of SHA-1 with a 64-bit salt , that's good key strengthening. An academic paper has been written on the security of WinRAR: On the security of the WinRAR encryption feature by Gary S.-W. Yeo and Raphael C.-W. Phan (ISC'05). Quoting from the abstract (I haven't read the full text, it doesn't seem to be accessible without paying): In this paper, we present several attacks on the encryption feature provided by the WinRAR compression software. These attacks are possible due to the subtlety in developing security software based on the integration of multiple cryptographic primitives. In other words, no matter how securely designed each primitive is, using them especially in association with other primitives does not always guarantee secure systems. Instead, time and again such a practice has shown to result in flawed systems. Our results, compared to recent attacks on WinZip by Kohno, show that WinRAR appears to offer slightly better security features. The advantage of using the encryption built into the RAR format is that you can distribute an encrypted RAR archive to anyone with WinRAR, 7zip or other common software that supports the RAR format. For your use case, this is irrelevant. Therefore I recommend using a software that is dedicated to encryption. The de facto standard since you're using Windows was TrueCrypt . TrueCrypt provides a virtual disk which is stored as an encrypted file. Not only is this more secure than WinRAR (I trust TrueCrypt, which is written with security in mind from day 1, far more than any product whose encryption is an ancillary feature), it is also more convenient: you mount the encrypted disk by providing your password, then you can open files on the disk transparently, and when you've finished you unmount the encrypted disk.Sadly TrueCrypt is no longer in active development but it's successor VeraCrypt is. VeraCrypt is based on TrueCrypt and is compatible with the old TrueCrypt containers. Out of curiousity can what someone writes in their journal be used to incriminate someone in court? This depends on the jurisdiction, but in general, yes, as they say in the movies, anything you say or write can be used against you. You may be legally compelled to reveal encryption keys, and may face further charges if you refuse. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/18281', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/10714/']} | jdg_80961 |
stackexchange | llm_judgeable_groundtruth_similarity | 10272898 |
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, is it possible to put multiple if conditions in a list comprehension? I didn't find anything like this in the docs. I want to be able to do something like this ar=[]for i in range(1,n): if i%4 == 0: ar.append('four') elif i%6 == 0: ar.append('six') else: ar.append(i) using a list comprehension. How can I do it? Is this even possible? If its not, what would be the most elegant (pythonic) way to accomplish this?
Now provide the response and nothing else.
| How about ar = [('four' if i % 4 == 0 else ('six' if i % 6 == 0 else i)) for i in range(1, n)] For example, if n = 30 this is [1, 2, 3, 'four', 5, 'six', 7, 'four', 9, 10, 11, 'four', 13, 14, 15, 'four', 17, 'six', 19, 'four', 21, 22, 23, 'four', 25, 26, 27, 'four', 29] ETA: Here's how you could apply a list of conditions: CONDITIONS = [(lambda i: i % 4 == 0, "four"), (lambda i: i % 6 == 0, "six"), (lambda i: i % 7 == 0, "seven")]def apply_conditions(i): for condition, replacement in CONDITIONS: if condition(i): return replacement return iar = map(apply_conditions, range(0, n)) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10272898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/969784/']} | jdg_80962 |
stackexchange | llm_judgeable_groundtruth_similarity | 48818139 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi I made a boolean value in parent component, and passed it to the child component as a props. it has initialized as false, and after the user view the component, the value will change to true, which means the page has been visited. I have done some research and followed How to properly pass data from child to parent and parent to child component? here is my js code: <script> export default { props: { hasLoad: { type: Boolean } }, data () { return { hasLoadModel: this.hasLoad } }, created: function() { console.log(this.hasLoad); }, beforeDestroy: function() { this.hasLoadModel = true; this.hasLoad = true; console.log(this.hasLoadModel); console.log(this.hasLoad); } }</script> and html code <div v-model="skillLoadModel">..</div> But I still get [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. I have tried to change the value at either of beforeDestroy or Destroyed, or do not use v-model, but none of them works. The value has changed after I left the page, but when I reenter the page, the value has reset to default value. Can someone help me please?Thanks
Now provide the response and nothing else.
| You definitely don't want to be reaching through the hierarchy like that. You are breaking encapsulation. You want a global event bus . And here's a secret: there's one built in, called $root . Have your OrderSummary do this.$root.emit('openPopup'); and set up a listener in your TheLogin's created hook: this.$root.on('openPopup', () => this.$emit('open')); In general, you should try to avoid using refs. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48818139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2221105/']} | jdg_80963 |
stackexchange | llm_judgeable_groundtruth_similarity | 2261079 |
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 some trouble with leading and trailing white space in a data.frame. For example, I look at a specific row in a data.frame based on a certain condition: > myDummy[myDummy$country == c("Austria"),c(1,2,3:7,19)] [1] codeHelper country dummyLI dummyLMI dummyUMI [6] dummyHInonOECD dummyHIOECD dummyOECD <0 rows> (or 0-length row.names) I was wondering why I didn't get the expected output since the country Austria obviously existed in my data.frame . After looking through my code history and trying to figure out what went wrong I tried: > myDummy[myDummy$country == c("Austria "),c(1,2,3:7,19)] codeHelper country dummyLI dummyLMI dummyUMI dummyHInonOECD dummyHIOECD18 AUT Austria 0 0 0 0 1 dummyOECD18 1 All I have changed in the command is an additional white space after Austria. Further annoying problems obviously arise. For example, when I like to merge two frames based on the country column. One data.frame uses "Austria " while the other frame has "Austria" . The matching doesn't work. Is there a nice way to 'show' the white space on my screen so that I am aware of the problem? And can I remove the leading and trailing white space in R? So far I used to write a simple Perl script which removes the whites pace, but it would be nice if I can somehow do it inside R.
Now provide the response and nothing else.
| Probably the best way is to handle the trailing white spaces when you read your data file. If you use read.csv or read.table you can set the parameter strip.white=TRUE . If you want to clean strings afterwards you could use one of these functions: # Returns string without leading white spacetrim.leading <- function (x) sub("^\\s+", "", x)# Returns string without trailing white spacetrim.trailing <- function (x) sub("\\s+$", "", x)# Returns string without leading or trailing white spacetrim <- function (x) gsub("^\\s+|\\s+$", "", x) To use one of these functions on myDummy$country : myDummy$country <- trim(myDummy$country) To 'show' the white space you could use: paste(myDummy$country) which will show you the strings surrounded by quotation marks (") making white spaces easier to spot. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/2261079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/258334/']} | jdg_80964 |
stackexchange | llm_judgeable_groundtruth_similarity | 46477802 |
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 Bootstrap 4 layout similar to this: https://www.codeply.com/go/yLO99L66MD When there are too many nav items, I want them to be hidden, so I added this: nav {overflow:hidden} . This does the job, but the problem is that it also hides my dropdown menu. How can I hide extra menu items but still allow dropdowns to show up for visible items? <nav class="navbar navbar-expand-md navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a> <div class="dropdown-menu" aria-labelledby="dropdown01"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item"> <a class="nav-link" href="#">aaaaaaaa aaaaa </a> </li> <li class="nav-item"> <a class="nav-link" href="#">bbbbbb bbbbb</a> </li> <li class="nav-item"> <a class="nav-link" href="#">cccccccc cccccccc </a> </li> <li class="nav-item"> <a class="nav-link" href="#">dddd ddddddddd </a> </li> <li class="nav-item"> <a class="nav-link" href="#">eeeeeeeeeeeeeeeeee cv kbc vxckjvhkxcv </a> </li> </ul> </div></nav><div class="container"> <div class="starter-template"> <h1>Bootstrap starter template</h1> <p class="lead">Use this document as a way to quickly start any new project. <br> All you get is this text and a mostly barebones HTML document.</p> </div></div><!-- /.container -->
Now provide the response and nothing else.
| You can use the navbar as this given example. When you resize the browser the nav items will be moved inside to the drop-down if it not have an enough space. Demo [1]: http://jsfiddle.net/swasatz/3fn4d5oq/ Snippet Demo Open the snippet in full page mode and resize the browser to see the changes. $(document).ready(function () { var menu = $("#nav-bar-filter"), subMenu = $(".subfilter"), more = $("#more-nav"), parent = $(".filter-wrapper"), ww = $(window).width(), smw = more.outerWidth(); menu.children("li").each(function () { var w = $(this).outerWidth(); if (w > smw) smw = w + 20; return smw }); more.css('width', smw); function contract() { var w = 0, outerWidth = parent.width() - smw - 50; for (i = 0; i < menu.children("li").size(); i++) { w += menu.children("li").eq(i).outerWidth(); if (w > outerWidth) { menu.children("li").eq(i - 1).nextAll() .detach() .css('opacity', 0) .prependTo(".subfilter") .stop().animate({ 'opacity': 1 }, 300); break; } } } function expand() { var w = 0, outerWidth = parent.width() - smw - 20; menu.children("li").each(function () { w += $(this).outerWidth(); return w; }); for (i = 0; i < subMenu.children("li").size(); i++) { w += subMenu.children("li").eq(i).outerWidth(); if (w > outerWidth) { var a = 0; while (a < i) { subMenu.children("li").eq(a) .css('opacity', 0) .detach() .appendTo("#nav-bar-filter") .stop().animate({ 'opacity': 1 }, 300); a++; } break; } } } contract(); $(window).on("resize", function (e) { ($(window).width() > ww) ? expand() : contract(); ww = $(window).width(); });}); body { font-family: verdana; min-width: 250px;}ul#more-nav, ul#nav-bar-filter { display: inline-block; vertical-align: top;}ul { list-style-type: none; padding: 0; margin: 0;}li { padding: 4px 8px 4px 8px; margin: 0;}#nav-bar-filter li { display: inline-block; font-weight: bold;}a { text-decoration: none; color: #666; font-size: 13px;}.filter-wrapper { width: 100%; background: #eee; padding: 5px 10px 5px 10px;}#more-nav { float: right;}.subfilter{ padding-top: 10px;}.subfilter li { margin: 0 0 0 20px; padding: 5px 0 0 0;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="twelve columns filter-wrapper"> <ul class="nav-bar-filter" id="nav-bar-filter"> <li><a href="#">All</a> </li> <li><a href="#">Small</a> </li> <li><a href="#">Medium</a> </li> <li><a href="#">Extra large</a> </li> <li><a href="#">Text</a> </li> <li><a href="#">Small-1</a> </li> <li><a href="#">Medium-1</a> </li> <li><a href="#">Extra large text</a> </li> <li><a href="#">Large text</a> </li> <li><a href="#">Another text</a> </li> <li><a href="#">text</a> </li> </ul> <ul id="more-nav"> <li><b><a href="#">More ></a></b> <ul class="subfilter"></ul> </li> </ul></div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46477802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1063188/']} | jdg_80965 |
stackexchange | llm_judgeable_groundtruth_similarity | 7407182 |
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 found out that my javascript-intensive web site doesn't work reliably (or at all) in IE9. It works, (usually, but not always) with the compatibility mode meta tag in the header, but I just want to build a page that I know will work well in IE9 and then have the usual page redirect to it when IE9 is detected. The usual page is fine in IE 7 and 8 (and every other browser I've tried it on). Can anyone give me some javascript that will do that? Thank you! Here's my usual page: http://ianmartinphotography.com/test-site/test/
Now provide the response and nothing else.
| The simplest way would be to use IE Conditionals . Note: IE10 and beyond have removed support for this feature. For modern browsers the widely accepted way of conditionally displaying content for compatibility purposes is using feature detection . Modernizr is a popular library built for handling feature detection. For example: <!--[if IE 9]><script type="text/javascript"> window.location = "http://www.ie9version.com";</script><![endif]--> Examples from the conditional site: <!--[if IE]><p>You are using Internet Explorer.</p><![endif]--><![if !IE]><p>You are not using Internet Explorer.</p><![endif]><!--[if IE 7]><p>Welcome to Internet Explorer 7!</p><![endif]--><!--[if !(IE 7)]><p>You are not using version 7.</p><![endif]--><!--[if gte IE 7]><p>You are using IE 7 or greater.</p><![endif]--><!--[if (IE 5)]><p>You are using IE 5 (any version).</p><![endif]--><!--[if (gte IE 5.5)&(lt IE 7)]><p>You are using IE 5.5 or IE 6.</p><![endif]--><!--[if lt IE 5.5]><p>Please upgrade your version of Internet Explorer.</p><![endif]--><!--[if true]>You are using an <em>uplevel</em> browser.<![endif]--><![if false]>You are using a <em>downlevel</em> browser.<![endif]><!--[if true]><![if IE 7]><p>This nested comment is displayed in IE 7.</p><![endif]><![endif]--> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7407182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/265507/']} | jdg_80966 |
stackexchange | llm_judgeable_groundtruth_similarity | 201657 |
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 am a young programmer (finished computer science university but still under a year of working in the industry) and I recently got a job working on some C code for a decent size web service. Looking at the code the only places I saw comments were when people were stashing their old code. Function and variable names are similarly informative most of the time - futex_up(&ws->g->conv_lock[conv->id%SPIN]); . Confronting a senior programmer about the situation and explaining that adding comments and meaningful names would make the code more maintainable and readable in the future, I got this reply: In general, I hate comments. Most of them time, like the case you mention with the return value, people use comments to get around reading the code. The comments don't say anything other than what the guy thought the code does at the time he put in the comment (which is often prior to his last edit). If you put in comments, people won't read the code as much. Then bugs don't get caught, and people don't understand the quirks, bottlenecks, etc. of the system. That's provided the comments are actually updated with code changes, which is of course totally unguaranteed. I want to force people to read the code. I hate debuggers for a similar reason. They are too convenient and allow you to step through dirty code with watches and breakpoints and find the so-called problem, when the real problem was that there are bugs in the code because the code has not been simplified enough. If we didn't have the debugger, we would refuse to read ugly code and say, I have to clean this up just so I can see what it is doing. By the time you are done cleaning up, half the time the bug just goes away. While what he wrote goes against a lot I have been taught in the university, it does make some sense. However, since experience in the studies sometimes doesn't work in real life, I would like to get an opinion of people more vetted in code. Is the approach of avoiding commenting code to make people actually read the code and understand what is going on make sense in a medium-sized coding environment (one that can be reasonably read in whole by every person working on it within a month or two), or is it a recipe for a long-term disaster? What are the advantages and disadvantages of the approach?
Now provide the response and nothing else.
| Well written code should be sufficiently self-documenting that you don't need any comments explaining what the code does, because it is obvious from reading the code itself.This implies also that all functions and variables have descriptive names, although it might be needed to learn the lingo of the problem and solution domains. This does not mean that well-written code should be completely without comments, because the important comments are those explaining why a particular, non-trivial, function/block/etc is implemented as it is and why not a different solution has been chosen. The problem with comments describing the code itself is that they tend to get outdated, because the code gets changed to fix a bug, but the comments remain untouched. This is far less the case with comments describing the reasoning for coming to the current solution. | {} | {'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/201657', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/37473/']} | jdg_80967 |
stackexchange | llm_judgeable_groundtruth_similarity | 52158521 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
<mat-sidenav-container class="sidenav-container"> <mat-sidenav #drawer class="sidenav" fixedInViewport="true" [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'" [mode]="(isHandset$ | async) ? 'push' : 'push'" [opened]="!(isHandset$ | async)"> <mat-toolbar color="primary">Menu</mat-toolbar> <mat-nav-list> <a mat-list-item href="#">Link 1</a> <a mat-list-item href="#">Link 2</a> <a mat-list-item href="#">Link 3</a> </mat-nav-list> </mat-sidenav> I do not understand what is written in the code (isHandset$ | async) please explain
Now provide the response and nothing else.
| 'Handset' is one of the breakpoint names of angular material layout. The list of breakpoint names is Handset, Tablet, Web, HandsetPortrait, TabletPortrait, WebPortrait, HandsetLandscape, TabletLandscape, WebLandscape. Please check https://material.io/design/layout/responsive-layout-grid.html#breakpoints for more information about material layout breakpoints In your example above, isHandset$ is coming from the corresponding component .ts file. Please look for code similar to below in your component file. isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset) .pipe( map(result => result.matches) ); When you resize the browser and when browser width matches with handset (mobile phone screen) width isHandset$ sets to true. ! (isHandset$ | async) in turn sets 'opened' attribute of sidenav drawer to false and collapses the sidenav drawer. As isHandset$ is an Observable property, therefore 'async' pipe is used for the asynchronous call. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52158521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8913536/']} | jdg_80968 |
stackexchange | llm_judgeable_groundtruth_similarity | 2856624 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say we use NASM as they do in this answer: how to write hellow world in assembly under windows . I got a couple of thoughts and questions regarding assembly combined with c# or any other .net languages for that matter. First of all I want to be able to create a library that has the following function HelloWorld that takes this parameter: Name In C# the method signature would looke like this: void HelloWorld(string name) and it would print out something like Hello World from name I've searched around a bit but can't find that much good and clean material for this to get me started. I know some basic assembly from before mostly gas though. So any pointers in the right direction is very much apprechiated. To sum it up Create a routine in ASM ( NASM ) that takes one or more parameters Compile and create a library of the above functionality Include the library in any .net language Call the included library function Bonus features How does one handle returned values? Is it possible to write the ASM-method inline? When creating libraries in assembly or c, you do follow a certain "pre defined" way, the c calling convetion, correct?
Now provide the response and nothing else.
| Something like this should get you a working DLL: extern _printfsection .textglobal _hello_hello: push ebp mov ebp, esp mov eax, [ebp+12] push eax push helloWorld call _printf add esp, 8 pop ebp retexport _hellohelloWorld: db 'Hello world from %s', 10, 0 You then just need to call the 'hello' function using P/Invoke. It doesn't clean up after itself, so you need to set CallingConvention to Cdecl; you also need to tell it you're using ANSI strings. Untested, but it should work fine. using System.Runtime.InteropServices;namespace Test { public class Test { public static Main() { Hello("C#"); } [DllImport("test.dll", EntryPoint="hello", CallingConvention=CallingConvention.Cdecl, CharSet=CharSet.Ansi)] public static extern Hello(string from_); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2856624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39106/']} | jdg_80969 |
stackexchange | llm_judgeable_groundtruth_similarity | 29730321 |
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 get css requires to work in webpack using the ExtractTextPlugin but with no success I want a separate css file rather than inlining any css. Here is my webpack config: var path = require('path');var webpack = require('webpack');var ExtractTextPlugin = require('extract-text-webpack-plugin');module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './scripts/index' ], output: { path: path.join(__dirname, 'build'), filename: 'bundle.js', publicPath: '/scripts/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new ExtractTextPlugin('styles/styles.css', { allChunks: true }) ], resolve: { extensions: ['', '.js', '.jsx'] }, module: { loaders: [{ test: /\.jsx?$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'scripts') }, { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') }] }}; index.js: import React from 'react';import App from './App';React.render(<App />, document.getElementById('root')); App.js: import React from 'react';require('../styles/app.css');export default class App extends React.Component { render() { return ( <h1>Hello, world.</h1> ); }} index.html: <html> <head> <link rel="stylesheet" href="/styles/styles.css"> </head> <body> <div id='root'></div> </body> <script src="/scripts/bundle.js"></script></html> styles.css is returning 404 Any idea what could be going wrong here. If I don't use the ExtractTextPlugin and just do this in config: module: { loaders: [ { test: /\.css$/, loader: "style-loader!css-loader" } ] } then I get the css applied to the page correctly but obviously this is not coming from a css file This is my first attempt at using webpack so probably doing some noob mistake Any ideas?
Now provide the response and nothing else.
| ExtractTextPlugin needs to be added in two spots: in the Loader, and as a Plugin. Here's the example pulled from the stylesheets documentation . // webpack.config.jsvar ExtractTextPlugin = require("extract-text-webpack-plugin");module.exports = { // The standard entry point and output config entry: { posts: "./posts", post: "./post", about: "./about" }, output: { filename: "[name].js", chunkFilename: "[id].js" }, module: { loaders: [ // Extract css files { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") }, // Optionally extract less files // or any other compile-to-css language { test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader") } // You could also use other loaders the same way. I. e. the autoprefixer-loader ] }, // Use the plugin to specify the resulting filename (and add needed behavior to the compiler) plugins: [ new ExtractTextPlugin("[name].css") ]} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29730321', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/223719/']} | jdg_80970 |
stackexchange | llm_judgeable_groundtruth_similarity | 13750436 |
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 model where there are two fields that can technically be null. The field names are :is_activated and :activated_at . :activated_at is only required if :is_activated is set to true . It does not need to be present if :is_activated is false . What's the appropriate way in Rails to set this validation directly into ActiveRecord?
Now provide the response and nothing else.
| You can use a Proc on the :activated_at validator. validates :activated_at, :presence, if: Proc.new { |a| a.is_activated? } Recommended Reading: http://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html Finally, you should consider renaming :is_activated to simply :activated . This is considered better practice in Rails. The is_ prefix is used in other languages for boolean attributes because their method names don't support a ? character. Ruby does, and Rails generates ___? methods on boolean attributes. Because of this it's better to just call the attribute :activated and check it with activated? . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13750436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/175836/']} | jdg_80971 |
stackexchange | llm_judgeable_groundtruth_similarity | 15449504 |
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 TableLayoutPanel and I want to add a control to the cell that I click on. The problem is that I can't determine the cell that I click on at run time. How do I determine the cell being clicked on?
Now provide the response and nothing else.
| You can use GetColumnWidths and GetRowHeights methods to calculate the cell row and column index: Point? GetRowColIndex(TableLayoutPanel tlp, Point point){ if (point.X > tlp.Width || point.Y > tlp.Height) return null; int w = tlp.Width; int h = tlp.Height; int[] widths = tlp.GetColumnWidths(); int i; for (i = widths.Length - 1; i >= 0 && point.X < w; i--) w -= widths[i]; int col = i + 1; int[] heights = tlp.GetRowHeights(); for (i = heights.Length - 1; i >= 0 && point.Y < h; i--) h -= heights[i]; int row = i + 1; return new Point(col, row);} Usage: private void tableLayoutPanel1_Click(object sender, EventArgs e){ var cellPos = GetRowColIndex( tableLayoutPanel1, tableLayoutPanel1.PointToClient(Cursor.Position));} But notice that the click event only is raised if the cell does not already contain a control. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15449504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1880686/']} | jdg_80972 |
stackexchange | llm_judgeable_groundtruth_similarity | 12593576 |
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 generator producing a list of strings. Is there a utility/adapter in Python that could make it look like a file? For example, >>> def str_fn():... for c in 'a', 'b', 'c':... yield c * 3... >>> for s in str_fn():... print s... aaabbbccc>>> stream = some_magic_adaptor(str_fn())>>> while True:... data = stream.read(4)... if not data:... break... print dataaaabbbccc Because data may be big and needs to be streamable (each fragment is a few kilobytes, the entire stream is tens of megabytes), I do not want to eagerly evaluate the whole generator before passing it to stream adaptor.
Now provide the response and nothing else.
| Here's a solution that should read from your iterator in chunks. class some_magic_adaptor: def __init__( self, it ): self.it = it self.next_chunk = "" def growChunk( self ): self.next_chunk = self.next_chunk + self.it.next() def read( self, n ): if self.next_chunk == None: return None try: while len(self.next_chunk)<n: self.growChunk() rv = self.next_chunk[:n] self.next_chunk = self.next_chunk[n:] return rv except StopIteration: rv = self.next_chunk self.next_chunk = None return rvdef str_fn(): for c in 'a', 'b', 'c': yield c * 3ff = some_magic_adaptor( str_fn() )while True: data = ff.read(4) if not data: break print data | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12593576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23643/']} | jdg_80973 |
stackexchange | llm_judgeable_groundtruth_similarity | 33359 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Atmospheric oxygen is in O2 and a gas. Then we inhale the air, our efficient lungs do the magic to filter out the oxygen and push them into the blood stream. When we say hemo and globin transport the oxygen using the iron ions. In what state oxygen is transported in the blood? as a gas or a liquid or an ion? It is hard for me to conceive of the idea that oxygen would be in gaseous form in the blood. "GAS in blood?" e.g. Arterial Blood Gas Test Also, how does the lungs convert the gas into something that is compatible to be in blood? References: Amount of Oxygen in the Blood
Now provide the response and nothing else.
| Regarding the state of oxygen in blood: It is in solution in the blood plasma (which mostly consists of water), in the form of single molecules. Think of water which you leave exposed to air: carbon dioxide will be captured and dissolved (along with the other gases in air), but these molecules are not gaseous or liquid, but rather "in solution", which is different from the "classical" states. Back to oxygen: As your reference already states, most of the oxygen in solution will bind to hemoglobin. The actual state of oxygen in that complex has been debated, but it is believed to be reduced by the hemoglobin iron to the superoxide anion, coordinated to Fe$^{3+}$. See Wikipedia on this. Also, the lungs do not "convert" the atmospheric oxygen to anything, they rather allow, due to their very large surface area, the quick exchange of oxygen/carbon dioxide in solution and in the air. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/33359', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/7450/']} | jdg_80974 |
stackexchange | llm_judgeable_groundtruth_similarity | 411026 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am planning to analyse a survey. I have been told that if I clean the data (e.g. data subsetting, value recoding, creating new variables from existing etc.) and afterwards create a survey design object ( svydesign function in "survey" package of R with id, strata, weights, fpc), I may get not correct point estimates and CI. I have been advised to make the survey design object first and then clean the data in that object. Can you please explain to me why this is necessary?
Now provide the response and nothing else.
| There are two separate issues here. Sometimes, including with NHANES data, you do need to subset before defining the survey design object, because not all the records in the data set are part of the sample you are analysing. In NHANES, everyone in the data file will have a health questionnaire, but only a subset will have a clinical examination, and there may be smaller subsets with specific biochemical measurements. You need to remove records from the file that are not part of the sample you are analysing. For example, I might use something like nhanesmec <- subset(nhanes, !is.na(WTMEC2YR)) to analyse data from the clinical examination. Records with missing WTMEC2YR are not part of the MEC sample and so should not go into the survey design object. On the other hand, if you have observations that are part of the sample , you should not remove them even if they have missing or implausible data, and you should not, eg, remove records for men if you want to do analyses only for women. The reason is complicated, and makes almost no difference for NHANES. However, you asked. Let's ignore stratified sampling for now and just consider cluster sampling. The survey was designed to sample a specific, preplanned number of clusters. When we're thinking about how different the results could be with a hypothetical replication of the survey [the frequentist definition of sampling uncertainty] we want to think about hypothetical replications that have the same preplanned number of clusters. If you subset the data and end up removing one of the clusters, you no longer have the preplanned number of clusters. The number of clusters is now random, and you'd need to model the resulting variability due to number of clusters. The computations to get the correct variances are equivalent to setting the weight to zero when you want to omit an observation, rather than just omitting it; we keep the number of clusters the same. If you look at the output of summary on a subsetted survey design object you can see the object keeps track of how many clusters (PSUs) it has data for (which is random), and also how many it started with (which is fixed). Using Anthony's example library(survey)data(api)dstrat_after<-svydesign(id=~1,strata=~stype, weights=~pw, data=apistrat, fpc=~fpc)dstrat_after <- subset( dstrat_after , comp.imp == 'Yes' )summary(dstrat_after) you will see as part of the output Stratum Sizes: E H Mobs 75 17 24design.PSU 100 50 50actual.PSU 75 17 24 If you subset before setting up the survey design object, there's no way for the object to know the planned number of observations or clusters, so there's no way for it to get the right standard errors. And finally: this only makes a difference when your subset has fewer primary sampling units than the full sample. In Anthony's example the PSUs are individual records, so the subset does have fewer. In NHANES the PSUs are cities or counties, so you'd have to remove a lot of observations before you lost a PSU. Also, since the design has only two PSUs per stratum, if you did lose a PSU you'd have other problems with estimating standard errors and would have to look up survey.lonely.psu . So, for NHANES it's unlikely to actually matter. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/411026', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/37540/']} | jdg_80975 |
stackexchange | llm_judgeable_groundtruth_similarity | 188815 |
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:
We have square lattice with dimensions $n × n$, such that $n \ge 2$. Some of the squares on this lattice are coloured black. How can we show that there are at least 3 connected black squares if there are $$1+\frac{n^{2}}{2}$$ black squares when $n$ is even and $$\frac{n(n+1)}{2}$$ black squares when $n$ is odd?
Now provide the response and nothing else.
| Yes. There is such a group. It is a semi-direct product of cyclic groups of respective orders 15 and 2. The reason why this works is that the mapping $x\mapsto x^4$ is an automorphismof order 2 of the cyclic group generated by $a$. Therefore we have a homomorphism from $C_2$to $\mathrm{Aut}(C_{15})$, and can build the semi-direct product in the usual way. If you want a concrete version of such a group, here it is as a subgroup of $S_{15}$. Let $a$ be the 15-cycle (here $A=10,B=11,\ldots$)$$a=(123456789ABCDEF),$$so $a^4=(159D26AE37BF48C)$.Then let $b$ be the product of six disjoint 2-cycles$$b=(25)(39)(4D)(7A)(8E)(CF).$$The usual conjugation trick of permutations then shows that$$bab^{-1}=bab=a^4.$$The group has 30 elements. They are either of the form $a^i$ or of the form $ba^i$, $0\le i<15$. To make sure. We don't have too many choices for the integer $m$ in the relation$bab^{-1}=a^m$. This is because it has to fit together with the fact that $b^2=1$,so $b^2$ has to commute with $a$.The following calculation uses this$$a=1a1=b^2ab^{-2}=b(bab^{-1})b^{-1}=ba^mb^{-1}=(bab^{-1})^m=(a^m)^m=a^{m^2}.$$For this to hold, we must have $m^2\equiv1\pmod{15}$. This leaves are four choices (pairwise non-congruent modulo $15$): $m=1$, $m=-1$, $m=4$ and $m=-4$. Of these, the first choice leads to the direct product$C_{15}\times C_2$, the choice $m=-1$ gives us the dihedral group $D_{15}$ of 30 elements.The third choice gives the group in question. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/188815', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39077/']} | jdg_80976 |
stackexchange | llm_judgeable_groundtruth_similarity | 23086933 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is a link to a picture of the dropdown: http://i.stack.imgur.com/tQs4Z.png I have been researching this for a bit, but have been unable to find a suitable solution. The dropdown has a list of checkboxes that can be checked. Multiple selections are possible. Below is the HTML for the dropdown, which includes a "required field" asterisk and the Title of the dropdown. Sorry about the formatting is it comes out funky. I believe it would be easier if it were a Select element, but being as it is an Input, I wanted to reach out and see the best way of handling such elements. I should mention, I am using WebDriver for MS Visual Studio 2010 C#. Additionally, I found this which, while related, does not seem to be working with the checkboxes dropdown. <tr> <td align="right" valign="top" style="background-color:White;"> <span id="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_lblRequired" class="RequiredIndicator">*</span> </td> <td valign="top" style="background-color:White;">2</td> <td valign="top" style="background-color:White;">Question 2 Cities?</td> <td align="left" valign="top" style="border-color:White;border-width:1px;border-style:Solid;"> <input type="hidden" name="ctl03$ctl00$ctl00$Tabbed_ContentPlaceHolder$ContentPlaceHolder1$ContentPlaceHolder1$ctl00$ctl00$gvQuestions$ctl03$hdnQId" id="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_hdnQId" value="2"> <input type="hidden" name="ctl03$ctl00$ctl00$Tabbed_ContentPlaceHolder$ContentPlaceHolder1$ContentPlaceHolder1$ctl00$ctl00$gvQuestions$ctl03$hdnVId" id="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_hdnVId" value="3"> <input type="hidden" name="ctl03$ctl00$ctl00$Tabbed_ContentPlaceHolder$ContentPlaceHolder1$ContentPlaceHolder1$ctl00$ctl00$gvQuestions$ctl03$hdnAId" id="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_hdnAId" value="3"> <div id="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_cblListItems2" class="RadComboBox RadComboBox_Classic" style="width:150px;white-space:normal;"> <table summary="combobox" border="0" style="border-width: 0px; border-collapse: collapse; width: 150px;"> <tbody> <tr> <td class="rcbInputCell rcbInputCellLeft" style="width:100%;"> <input name="ctl03$ctl00$ctl00$Tabbed_ContentPlaceHolder$ContentPlaceHolder1$ContentPlaceHolder1$ctl00$ctl00$gvQuestions$ctl03$cblListItems2" type="text" class="rcbInput radPreventDecorate" id="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_cblListItems2_Input" value="" autocomplete="off"> </td> <td class="rcbArrowCell rcbArrowCellRight"> <a id="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_cblListItems2_Arrow" style="overflow: hidden;display: block;position: relative;outline: none;">select</a> </td> </tr> </tbody> </table> <div class="rcbSlide" style="z-index:6000;"> <div id="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_cblListItems2_DropDown" class="RadComboBoxDropDown RadComboBoxDropDown_Classic " style="display:none;"> <div class="rcbScroll rcbWidth" style="width:100%;"> <ul class="rcbList" style="list-style:none;margin:0;padding:0;zoom:1;"> <li class="rcbItem"><label><input type="checkbox" class="rcbCheckBox">Denver</label></li> <li class="rcbItem"><label><input type="checkbox" class="rcbCheckBox">Los Angeles</label></li> <li class="rcbItem"><label><input type="checkbox" class="rcbCheckBox">New York City</label></li> </ul> </div> </div> </div> <input id="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_cblListItems2_ClientState" name="ctl03_ctl00_ctl00_Tabbed_ContentPlaceHolder_ContentPlaceHolder1_ContentPlaceHolder1_ctl00_ctl00_gvQuestions_ctl03_cblListItems2_ClientState" type="hidden" autocomplete="off" value={"logEntries":[],"value":"292","text":"","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}> </div> </td></tr>
Now provide the response and nothing else.
| if you do a employee = new Employee(param1, param2); you may as well skip @InjectMocks . It is supposed to do the following: @InjectMocksClassUnderTest cut;@MockDependency1 dep1;@MockDependency2 dep2;@Beforepublic void setup() { initMocks(this);} omitting @InjectMocks the same behaviour can be achieved with the following code: ClassUnderTest cut;@MockDependency1 dep1;@MockDependency2 dep2;@Beforepublic void setup() { initMocks(this); cut = new ClassUnderTest(dep1, dep2);} In your specific case, you should mock param1 and param2 . Never call the constructor manually when using @InjectMocks . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23086933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3533751/']} | jdg_80977 |
stackexchange | llm_judgeable_groundtruth_similarity | 22637515 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is something I have been confused about for a while and I am not sure how I can learn more about it. Let's say I have the following program: main :: IO ()main = do x <- liftM read getLine y <- liftM read getLine print (x % y) If I run this with the input 6 and 2 , it will print 3 % 1 . At what point does the simplification happen (namely the division by the gcd)? Is it implemented in show ? If so, then is the underlying representation of the rational still 6 % 2 ? If not, then does (%) do the simplification? I was under the impression that (%) is a data constructor, so how would a data constructor do anything more than "construct"? More importantly, how would I actually go about doing similar things with my own data constructors? I appreciate any help on the topic.
Now provide the response and nothing else.
| Ratio is actually implemented in GHC.Real (on GHC, obviously), and is defined as data Ratio a = !a :% !a deriving (Eq) The bangs are just there for strictness. As you can see, the function % is not a data constructor, but :% is. Since you aren't supposed to construct a Ratio directly, you use the % function, which calls reduce. reduce :: (Integral a) => a -> a -> Ratio a{-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}reduce _ 0 = ratioZeroDenominatorErrorreduce x y = (x `quot` d) :% (y `quot` d) where d = gcd x y(%) :: (Integral a) => a -> a -> Ratio ax % y = reduce (x * signum y) (abs y) The rule is that if an operator starts with a colon : , then it is a constructor, otherwise it is just a normal operator. In fact, this is part of the Haskell standard, all type operators must have a colon as their first character. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22637515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3217013/']} | jdg_80978 |
stackexchange | llm_judgeable_groundtruth_similarity | 912837 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that if i have a short exact sequence of chain complexes $$0\rightarrow A\rightarrow B\rightarrow C\rightarrow 0$$ then i can extend it to long exact sequence of homology groups as $$\cdots\rightarrow H_n(A)\rightarrow H_n(B)\rightarrow H_n(C)\rightarrow H_{n-1}(A)\rightarrow H_{n-1}(B)\rightarrow H_{n-1}(C)\rightarrow\cdots$$ I some how see that this is kind of motivation for studying derived functors but i am not very sure about this kind of relation.. It would be helpful if some one can say something about this...
Now provide the response and nothing else.
| I will answer your question in what follows, but first it might be useful to say something about what derived functors are and what the point is. The idea of derived functors is that if you have a functor which preserves (say) left exactness when applied to a short exact sequence, but not right exactness(e.g. $Hom(X, \text{--})$ for a module $X$ ), then its derived functors do produce an exact sequence, but now a long exact sequence. As you probably know, the long exact sequence is$$0 \to F(A) \to F(B) \to F(C) \to R^1F(A) \to R^1F(B) \to R^1(C) \to R^2(A) \to \cdots$$ Here I am writing $R^iF$ to denote the $i$th derived functor (a right derivedfunctor in this case, since the functor $F$ is left exact; so the letter $R$is for "right"). Note that the derived functors are a so-called $\delta$- functor :not only do we have the sequence of functors $R^iF$, but the abovelong e.s.'s are themselves functorial in the s.e.s. $0 \to A \to B \to C \to 0.$(The "$\delta$" in $\delta$-functor is a reference to the collection of connecting morphisms$R^iF(C) \to R^{i+1}F(A)$, which are commonly denoted $\delta$.) There are a few comments to make: The existence of these l.e.s.'s doesn't characterize the $R^iF$ as a $\delta$-functor. E.g. if you had the collection $R^iF,$ I could define another functor$\widetilde{R}^iF$ as follows: in all degrees $i$ except $i = 1$,set $\widetilde{R}^iF =R^iF,$ but in degree $1$, define$\widetilde{R}^iF(A) = R^iF(A) \oplus A$ (for any object $A$).Define the connecting morphisms on the extra summand we put in to be just $0$.So the new l.e.s. is the same as the old one, except that we have just directsummed in a copy of the original s.e.s. into the degree $1$ part of the l.e.s.of $R^iF$'s. This is dealt with by the following point. The $R^iF$ are taken to be minimal, in some appropriate sense. Precisely,they are a universal $\delta$-functor for $F$, i.e. they map canonicallyto any other $\delta$-functor. (This is discussed in Hartshorne's algebraicgeometry book at the beginning of Ch. III, but in many other places too,I presume.) So, intuitively, they don't contain any extra garbage that we might haveadded gratuitously in some degree. Although it's not obvious if you're learning this for the first time,to construct the universal $\delta$-functor, you can use injectiveresolutions of objects, and apply $F$ (the original, underived, functor)to these resolutions. (This gives a cochain complex, whose cohomologyyields the $R^iF$'s.) To get the l.e.s.'s: first provethat a s.e.s. of objects gives a s.e.s. of resolutions.Then, since s.e.s.'s of injective objects are split, and since $F$ will take a split s.e.s. to a (split) s.e.s., applying $F$ gives a s.e.s. of complexes.Passing to cohomology, and using the fact recalled in your question,gives the l.e.s. of derived functors. So the connection between the fact you recalled in your question,and derived functors, actually doesn't come until a fairly technicalpart of the story, namely in the actual construction of the derivedfunctors via injective resolutions. Note that although sometimes you use resolutions to compute the derivedfunctors, often you use more indirect means, and so the construction viainjective resolutions is often not a key point to focus on in applications(even though it underlies the theory). What is the point of the whole story? Why do we go to all the trouble of constructing these derived functors, looking at the l.e.s.'s, and so on? E.g. why don't people just do the naive thing of looking at the four term exact sequence$$0 \to F(A) \to F(B) \to F(C) \to \text{ cokernel } \to 0.$$The point is that this cokernel depends not just on $A$, $B$, or $C$,but on all three of them, and in fact on the whole data of the s.e.s. $0 \to A \to B \to C \to 0.$ So basically, it's not a very flexible object, and there isn't a lotof theory you can develop about it directly. What happens in the theory of derived functors is that the information inthis cokernel is diffused into the theory in a much more subtle, flexible, anduseful way. E.g. in the l.e.s. of derived functors, the terms only depend on one ofthe objects $A$, $B$ ,or $C$. It is only the morphisms (especially theconnecting morphisms) that depend on the whole data of the s.e.s. In particular, suppose in some particular case we want to show that$ 0 \to F(A) \to F(B) \to F(C) \to 0$ is exact. The general theory shows that what we have to do is prove thatthe connecting morphism $F(C) \to R^1F(A)$ equals zero. One way we can do this is just to show that $R^1F(A) = 0$ itself. Thisdepends only on $A$, and so doesn't depend on the original s.e.s. at all.In particular, it is something we could try to check by making a computationrelated to $A$, without having to think at all about $B$ or $C$ or the originals.e.s. Possibly we could compute directly with injective resolutions, or perhaps we could try to use some other more indirect method: e.g. we couldtry to put $A$ into some other s.e.s. we know more about, and use the derivedfunctor l.e.s. for that s.e.s. to get information about the values of the$R^iF(A)$. Even if we can't prove that $R^1F(A)$ vanishes, we can still hope to getinformation (e.g. if we can bound its size, then we can bound the size of thecokernel of $F(B) \to F(C)$). By diffusing the information throughthe various derived functor values and the connecting morphisms, the theory ofderived functors provides a much more useful tool then you get from a more naiveapproach to these questions. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/912837', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_80979 |
stackexchange | llm_judgeable_groundtruth_similarity | 346862 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a service offering iSCSI/iPXE boot targets over the Internet? i.e. on a blank machine with an internet connection available to it, it can be configured to look at a public internet host and pull down an OS image as if you'd got a local iPXE server or similar bootstrapping setup. Edit: It's clear now that block level iSCSI booting is not the right technology for booting over unreliable networks and a local cache defeats the plug-and-go paradigm I was aiming for. Using iPXE to pull a more intelligent (handles unreliable and/or high latency connections) boot image via HTTP looks like a decent start, but flashing the NIC or chainloading adds a disappointing amount of complexity to the task. Setting USB booting in the factory and then sending out USB keys with linux images that do the deployment and installation heavy lifting is a much more sane approach to wrangling iSCSI or PXE into doing something they're not designed for.
Now provide the response and nothing else.
| Trying to boot from a publicly hosted iSCSI target would be 100% terrible. Insufficient bandwidth, high latency (relatively) and potential for intermittent connection... = recipe for disaster. iSCSI and any other block-level network-boot architecture requires near-0 latency, in addition to a high-amount of bandwidth to be successful. Buying a dedicated 1gbit connection for each server directly attached to a 3rd party service to host your disk drives... would be more cost-prohibitive than simply buying your own iSCSI/FC/?? infrastructure. Alternatively... file-level access is much more do-able... but you'd have much tighter constraints to make it function at all. (it would download a disk-image... uncompress it in RAM... then boot a minimal OS which then would have access to network-based files...) | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/346862', 'https://serverfault.com', 'https://serverfault.com/users/86718/']} | jdg_80980 |
stackexchange | llm_judgeable_groundtruth_similarity | 49153923 |
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 used to get all the plugins using IPluginRegistry when it is deprecated and now in the new version, some of its methods implementations are removed like getPluginRegistry. IPluginRegistry pReg = Platform.getPluginRegistry();IPluginDescriptor[] plugins = pReg.getPluginDescriptors();IPluginPrerequisite[] pPrereqs = plugins[i].getPluginPrerequisites(); Is there any alternative for above code ? Also i can't able to get the Plugin from plugin-id like below in eclipse 4.3, The getPlugin(plugin_id) method is deprecated and removed their implementation in new version. Is there any alternative for below code too ? Plugin plugin = Platform.getPlugin(pluginId);boolean bool = plugin instanceOf MyCustomPlugin; MyCustomPlugin.java public abstract MYCustomPlugin extends AbstractUIPlugin{} If i use the bundle like below, i was able to get only package name without plugin name like com.plugins.pluginPack instead of com.plugins.pluginPack.MyCustomPlugin . I need complete plugin instead of just the package name. Bundle bundle = Platform.getBundle(pluginId); I appreciate if someone helps me out !!Thanks.
Now provide the response and nothing else.
| I stumbled upon this, too. And I am actually pretty shocked that the GridFsTemplate has been designed like this...Anyway, my ugly "solution" to this so far: public GridFsResource download(String fileId) { GridFSFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId))); return new GridFsResource(file, getGridFs().openDownloadStream(file.getObjectId()));}private GridFSBucket getGridFs() { MongoDatabase db = mongoDbFactory.getDb(); return GridFSBuckets.create(db);} Note: You have to inject the MongoDbFactory for this to work... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49153923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1456152/']} | jdg_80981 |
stackexchange | llm_judgeable_groundtruth_similarity | 3704711 |
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:
Compute the following determinant $$\begin{vmatrix}a_{1}-b_{1}+x & a_{1}-b_{2} & \ldots & a_{1}-b_{n} \\a_{2}-b_{1} & a_{2}-b_{2}+x & \ldots & a_{2}-b_{n} \\ \vdots & \vdots & \ddots & \vdots \\a_{n}-b_{1} & a_{n}-b_{2} & \ldots & a_{n}-b_{n}+x\end{vmatrix}.$$ I tried for $n=3$ and I used the fact that $\det$ funcion is liniar in eachcolumn. \begin{align*}&\begin{vmatrix}a_{1}-b_{1}+x & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2}+x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}+x\end{vmatrix}\\& =\begin{vmatrix}a_{1}-b_{1} & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2}+x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}+x\end{vmatrix}+%\begin{vmatrix}x & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2}+x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}+x\end{vmatrix}\\& =%\begin{vmatrix}a_{1}-b_{1} & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2} & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}+x\end{vmatrix}+%\begin{vmatrix}a_{1}-b_{1} & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}+x\end{vmatrix}\\& +%\begin{vmatrix}x & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2} & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}+x\end{vmatrix}+%\begin{vmatrix}x & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}+x\end{vmatrix}\\& =%\begin{vmatrix}a_{1}-b_{1} & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2} & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}%\end{vmatrix}+%\begin{vmatrix}a_{1}-b_{1} & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2} & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & x\end{vmatrix}\\& +%\begin{vmatrix}a_{1}-b_{1} & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}%\end{vmatrix}+%\begin{vmatrix}a_{1}-b_{1} & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & x\end{vmatrix}\\& +%\begin{vmatrix}x & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2} & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}%\end{vmatrix}+%\begin{vmatrix}x & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2} & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & x\end{vmatrix}\\& +%\begin{vmatrix}x & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}%\end{vmatrix}+%\begin{vmatrix}x & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & x\end{vmatrix}\\& =%\begin{vmatrix}a_{1}-b_{1} & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2} & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}%\end{vmatrix}+%\begin{vmatrix}a_{1}-b_{1} & a_{1}-b_{2} & a_{1}-b_{3}\\a_{2}-b_{1} & x & a_{2}-b_{3}\\a_{3}-b_{1} & a_{3}-b_{2} & a_{3}-b_{3}%\end{vmatrix}\\& +%\begin{vmatrix}x & 2\left( a_{1}-b_{2}\right) & a_{1}-b_{3}\\a_{2}-b_{1} & a_{2}-b_{2}+x & a_{2}-b_{3}\\a_{3}-b_{1} & 2\left( a_{3}-b_{2}\right) & a_{3}-b_{3}%\end{vmatrix}+%\begin{vmatrix}x+a_{1}-b_{1} & 2\left( a_{1}-b_{2}\right) & a_{1}-b_{3}\\2\left( a_{2}-b_{1}\right) & x+a_{2}-b_{2} & a_{2}-b_{3}\\2\left( a_{3}-b_{1}\right) & 2\left( a_{3}-b_{2}\right) & x\end{vmatrix}\end{align*} From here I didn't see any pattern or some manipulations to do in order to compute the determinant. The first determinants after the last $=$ sign is equal to zero after some calculation using Sarrus rule. How can one compute this determinant?
Now provide the response and nothing else.
| This equals $\det (xI+A-B)$ where $$A=\pmatrix{a_1&a_1&\cdots&a_1\\a_2&a_2&\cdots&a_2\\\vdots&\vdots&\ddots&\vdots\\a_n&a_n&\cdots&a_n}$$ and $$B=\pmatrix{b_1&b_2&\cdots&b_n\\b_1&b_2&\cdots&b_n\\\vdots&\vdots&\ddots&\vdots\\b_1&b_2&\cdots&b_n}.$$ Then $\det(xI+A-B)$ is the characteristic polynomial of $C=B-A$ . But both $A$ and $B$ have rank $\le 1$ , so $C$ has rank $\le 2$ . So all $d\times d$ minors of $C$ vanish for $d\ge3$ and so $$\det(xI-C)=x^{n}-t_1x^{n-1}+t_2x^{n-2}.$$ Here $t_1$ is the trace of $C$ : $$t_1=\sum_i(b_i-a_i).$$ Also, $$t_2=\sum_{i<j}\left[(b_i-a_i)(b_j-a_j)-(b_i-a_j)(b_j-a_i)\right].$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3704711', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/435354/']} | jdg_80982 |
stackexchange | llm_judgeable_groundtruth_similarity | 26830617 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following class. It allows me to execute commands through java. public class ExecuteShellCommand {public String executeCommand(String command) { StringBuffer output = new StringBuffer(); Process p; try { p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine())!= null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } return output.toString();}} When I run commands, the result of the previous command isn't saved. For example: public static void main(String args[]) { ExecuteShellCommand com = new ExecuteShellCommand(); System.out.println(com.executeCommand("ls")); System.out.println(com.executeCommand("cd bin")); System.out.println(com.executeCommand("ls"));} Gives the output: binsrcbinsrc Why doesn't the second 'ls' command show the contents of the 'bin' directory?
Now provide the response and nothing else.
| You start a new process with Runtime.exec(command) . Each process has a working directory. This is normally the directory in which the parent process was started, but you can change the directory in which your process is started. I would recommend to use ProcessBuilder ProcessBuilder pb = new ProcessBuilder("ls");pb.inheritIO();pb.directory(new File("bin"));pb.start(); If you want to run multiple commands in a shell it would be better to create a temporary shell script and run this. public void executeCommands() throws IOException { File tempScript = createTempScript(); try { ProcessBuilder pb = new ProcessBuilder("bash", tempScript.toString()); pb.inheritIO(); Process process = pb.start(); process.waitFor(); } finally { tempScript.delete(); }}public File createTempScript() throws IOException { File tempScript = File.createTempFile("script", null); Writer streamWriter = new OutputStreamWriter(new FileOutputStream( tempScript)); PrintWriter printWriter = new PrintWriter(streamWriter); printWriter.println("#!/bin/bash"); printWriter.println("cd bin"); printWriter.println("ls"); printWriter.close(); return tempScript;} Of course you can also use any other script on your system. Generating a script at runtime makes sometimes sense, e.g. if the commands that are executed have to change. But you should first try to create one script that you can call with arguments instead of generating it dynamically at runtime. It might also be reasonable to use a template engine like velocity if the script generation is complex. EDIT You should also consider to hide the complexity of the process builder behind a simple interface. Separate what you need (the interface) from how it is done (the implementation). public interface FileUtils { public String[] listFiles(String dirpath);} You can then provide implementations that use the process builder or maybe native methods to do the job and you can provide different implementations for different environments like linux or windows. Finally such an interface is also easier to mock in unit tests. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26830617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2620746/']} | jdg_80983 |
stackexchange | llm_judgeable_groundtruth_similarity | 2304904 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How to integrate $\displaystyle \int_a^b t \cdot \sqrt{\frac{t - a}{b - t}} \,dt$? I literally have no idea how to integrate this integral. I've tried all basic methods, but it seems like a quite hard problem for a beginner.
Now provide the response and nothing else.
| Do the following substitution $$t=a\cos^2 \theta+b \sin^2 \theta \implies \mathrm dt=(b-a) \sin 2 \theta \, \mathrm d \theta$$ Your function $\displaystyle \sqrt{\frac{t - a}{b - t}}$ will be tremendously simplified to $\tan \theta$. Hence, your integral will be simplified : \begin{align}\int_a^b t \cdot \sqrt{\frac{t - a}{b - t}} \, \mathrm dt&=\int_0^{{\pi}/{2}} (a\sin^2 \theta+b \cos^2 \theta) \cdot \tan \theta \,((b-a) \sin 2 \theta \, \mathrm d \theta)\\&= ~a\int_0^{{\pi}/{2}} \frac{\sin^3 \theta}{\cos \theta}\, \cdot (b-a) \sin 2 \theta \, \mathrm d \theta+ b\int_0^{{\pi}/{2}}\frac{ \sin 2 \theta}{2} \, (b-a) \sin 2 \theta \, \mathrm d \theta\\&=~(b-a) \left(2a \int_0^{{\pi}/{2}} {\sin^4 \theta}\, \mathrm d \theta + \frac b2 \int_0^{{\pi}/{2}}{ \sin^2 2 \theta} \, \mathrm d \theta \right)\\&=~(b-a) \left(2a \cdot\frac{3\pi}{16} + \frac b2 \cdot\frac{\pi}{4}\right) \\&=\frac\pi8 (b-a) (3a+b)\end{align} | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2304904', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296388/']} | jdg_80984 |
stackexchange | llm_judgeable_groundtruth_similarity | 36345282 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Trying to mock a method that is called within another method. // code partpublic virtual bool hello(string name, int age){ string lastName = GetLastName();}public virtual string GetLastName() { return "xxx"; }// unit test partMock<Program> p = new Mock<Program>();p.Setup(x => x.GetLastName()).Returns("qqq"); I want the method GetLastName to always return "qqq".
Now provide the response and nothing else.
| This should work, assuming those are the full method implementations public class MyProgram{ public bool hello(string name, int age) { string lastName = GetLastName(); return string.Format("hello {0}", lastName); } public virtual string GetLastName() { return "xxx"; }}public class MyProgramTests{ [TestMethod] public void MyTest() { string stringToReturn = "qqq"; Mock<MyProgram> name = new Mock<MyProgram>(); name.CallBase = true; name.Setup(x => x.GetLastName()).Returns(stringToReturn ); var results = name.Object.hello(It.IsAny<string>(), It.IsAny<int>()); string expected = string.Format("hello {0}", results); Assert.AreEqual(expected, results); }} I'm still not quite following your comment: What does the parameter really mean of Mock What should ?? be? excuse me, I don't quite understand the syntax. To clarify, mock means that when I put break points in my code I the breakpoints should skip the methods that I am mocking. Am I right? Mock<T> allows you to mock a type of T - T being a generic indicator, also meaning pretty much anything that's a class. In the traditional, you would be mocking an interface , not an actual class , but in the example above, we're mocking a class. For the sample unit test posted, the purpose of the unit test is to test the implementation of hello(string, int) . We know that hello(string, int) relies on another method within that class called GetLastName() . GetLastName() s implementation, while important, is not important to the scope of unit testing hello(string, int) . For this reason, we mock the call and its return - in order to test the functionality of hello(string, int) without having to worry about its dependency's implementation. I have surrounded the above with actual class names to hopefully make it more obvious that we're mocking the class MyProgram and providing a new implementation (mock) of GetLastName() Thanks for the answer. What if I want to test a method that calls another method that calls another method? For eg. what if the method hello called another method? The same principle applies, when you're building your unit tests (assuming they are unit tests, and not integration tests or other, you always want to concentrate on testing one public method. What's the difference between unit and integration tests? public class Foo{ public string Bar() { return string.Format("{0}Bar", Baz(5));; } public virtual string Baz(int someNumber) { return string.Format("{0}Baz", DoStuff(someNumber).ToString()); } public virtual int DoStuff(int someNumber) { return someNumber+1; }} If we're unit testing Bar() we do not care about the implementation of Baz(int) or even worse DoStuff(int) . Note we don't care about the implementation , we do care that they return values. From Bar() s perspective, the only thing that is important is the Baz(int) returns a string. What string? It doesn't matter to Bar() s unit test. Sample test for Bar() : [TestMethod]public void Bar_ReturnsBazValueWithBarAppended{ // Arrange string testBazReturn = "test"; Mock<Foo> mock = new Mock<Foo>(); mock.CallBase = true; mock .Setup(s => s.Baz(It.IsAny<int>()) .Returns(testBazReturn); // Act var results = mock.Object.Bar(); // Assert Assert.AreEqual(string.Format("{0}{1}", testBazReturn, "Bar"), results); mock.Verify(v => v.Baz(It.IsAny<int>())); // Verifies that Baz was called} Notice in the above, our actual implementations of Baz(int) , and DoStuff(int) do not matter, as we are disregarding the actual implementation of Baz(int) , and DoStuff(int) doesn't even come into play. Now, if we were to test Baz(int) we just follow the same mentality: [TestMethod]public void Baz_ReturnsDoStuffValueWithBazAppended{ // Arrange int testDoStuffReturn = 1; Mock<Foo> mock = new Mock<Foo>(); mock.CallBase = true; mock .Setup(s => s.DoStuff(It.IsAny<int>()) .Returns(testDoStuffReturn); // Act var results = mock.Object.Baz(5); // Assert Assert.AreEqual(string.Format("{0}{1}", results, "Baz"), results); // Validates the result mock.Verify(v => v.DoStuff(It.IsAny<int>())); // Verifies that DoStuff was called} In the above, now that we're unit testing Baz(int) , we don't care about Bar() , and the only thing we care about in DoStuff(int) is that it returns a value (but not how it arrives at that value.) And finally DoStuff(int) : [TestMethod]public void DoStuff_ReturnsParameterPlusOne(){ // Arrange Foo foo = new Foo(); int passed = 1; int expected = passed + 1; // Act var results = foo.DoStuff(passed); // Assert Assert.AreEqual(expected, results);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36345282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5865672/']} | jdg_80985 |
stackexchange | llm_judgeable_groundtruth_similarity | 38740648 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using Xcode 8.0 beta 4. In previous version, UIViewController have method to set the status bar style public func preferredStatusBarStyle() -> UIStatusBarStyle However, I found it changed to a "Get ONLY varaiable" in Swift 3. public var preferredStatusBarStyle: UIStatusBarStyle { get } How can provide the style to use in my UIViewController?
Now provide the response and nothing else.
| [UPDATED] For Xcode 10+ & Swift 4.2+ This is the preferred method for iOS 7 and higher In your application's Info.plist , set View controller-based status bar appearance to YES . Override preferredStatusBarStyle ( Apple docs ) in each of your view controllers. For example: override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent} If you have preferredStatusBarStyle returning a different preferred status bar style based on something that changes inside of your view controller (for example, whether the scroll position or whether a displayed image is dark), then you will want to call setNeedsStatusBarAppearanceUpdate() when that state changes. iOS before version 7, deprecated method Apple has deprecated this , so it will be removed in the future. Use the above method so that you don't have to rewrite it when the next iOS version is released. If your application will support In your application's Info.plist , set View controller-based status bar appearance to NO . In appDelegate.swift , the didFinishLaunchingWithOptions function, add: UIApplication.shared.statusBarStyle = .lightContent For Navigation Controller If you use a navigation controller and you want the preferred status bar style of each view controller to be used and set View controller-based status bar appearance to YES in your application's info.plist extension UINavigationController { open override var preferredStatusBarStyle: UIStatusBarStyle { return topViewController?.preferredStatusBarStyle ?? .default }} | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/38740648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5571327/']} | jdg_80986 |
stackexchange | llm_judgeable_groundtruth_similarity | 6227061 |
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 replace a set of words that look like: SomeText to Some_Text ?
Now provide the response and nothing else.
| This can easily be achieved using a regular expression: $result = preg_replace('/\B([A-Z])/', '_$1', $subject); a brief explanation of the regex: \B asserts position at a word boundary. [A-Z] matches any uppercase characters from A-Z. () wraps the match in a back reference number 1. Then we replace with '_$1' which means replace the match with an [underscore + backreference 1] | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6227061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/376947/']} | jdg_80987 |
stackexchange | llm_judgeable_groundtruth_similarity | 295085 |
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 $\kappa$ be an infinite cardinal, and let $\text{Top}(\kappa)$ be the lattice of all topologies on $\kappa$, ordered by $\subseteq$. Let $\text{Top}^{T_1}(\kappa)$ be the lattice of all $T_1$-topologies on $\kappa$. Is there an injective lattice homomorphism $\varphi: \text{Top}(\kappa)\to \text{Top}^{T_1}(\kappa)$?
Now provide the response and nothing else.
| Is there an injective lattice homomorphism $\varphi: \text{Top}(\kappa)\to \text{Top}^{T_1}(\kappa)$? The answer is Yes, there is such an embedding. I will argue that if $\kappa$ is aninfinite cardinal, then there is a complete lattice embedding$\varphi: \text{Top}(\kappa)\to \text{Top}^{T_1}(\kappa\times\kappa)$.This is enough to answer the question, for the following reason.Any bijection $\beta:\kappa\times\kappa\to\kappa$ induces a lattice isomorphism $\overline{\beta}: \text{Top}(\kappa\times\kappa)\to \text{Top}(\kappa)$ which maps the cofinite topology on $\kappa\times\kappa$ to the cofinite topology on $\kappa$. A topology is $T_1$ iff it contains the cofinite topology, so $\overline{\beta}$ restricts to a lattice isomorphism from $\text{Top}^{T_1}(\kappa\times\kappa)$ to $\text{Top}^{T_1}(\kappa)$.Thus, any (complete) lattice embedding $\text{Top}(\kappa)\to \text{Top}^{T_1}(\kappa\times\kappa)$ can be altered to a (complete) lattice embedding $\text{Top}(\kappa)\to \text{Top}^{T_1}(\kappa)$ by composing with such a $\overline{\beta}$. If $U\subseteq \kappa$, then by a cofinite extension of $U$ I mean a subset$X\subseteq U\times \kappa$ where, for each $u\in U$, the set$\{\lambda<\kappa\;|\;(u,\lambda)\in X\}$ is cofinite in $\kappa$.To make sure this is clear, let me explain this a second wayusing the projection maps $\pi_1, \pi_2\colon \kappa\times\kappa\to\kappa$.$X$ is a cofinite extension of $U$ if(i) $\pi_1(X)=U$, and (ii) for every $u\in U$ we have$\pi_2((\{u\}\times\kappa)\cap X)$ is cofinite in $\kappa$. If $\tau$ is a topology, let $\widehat{\tau}$be the collection of all cofinite extensionsof sets in $\tau$. I claim that I. For any topology $\tau$ on $\kappa$, $\widehat{\tau}$ is a $T_1$ topology on $\kappa\times\kappa$. II. The map $\tau\mapsto \widehat{\tau}$ is a complete lattice embedding of $\text{Top}(\kappa)$ into $\text{Top}^{T_1}(\kappa\times\kappa)$. These are not hard to prove and they establish the result. In the following justifications, if $X$ is a cofiniteextension of $U$, then I may refer to the fibers of $X$, by which I mean fibers of $X$ underthe first projection $\pi_1$. If $x\in\pi_1(X)$,then the fiber of $X$ over $x$ is $(\{x\}\times\kappa)\cap X$,which is a subset of $\kappa\times\kappa$.(So, a cofinite extension of $U\subseteq \kappa$is a subset if $U\times \kappa$ with cofinite fibers.) Sketch of proof of I. (Least and largest subsets)The least and largestsubsets $\emptyset$ and $\kappa\times\kappa$ of the set$\kappa\times\kappa$ are cofinite extensions of theleast and largest subsets$\emptyset$ and $\kappa$ of $\kappa$. (Finite intersection)If $X, Y\in \widehat{\tau}$, then they are cofiniteextensions of some $\pi_1(X)=U, \pi_1(Y)=V\in\tau$.Then $X\cap Y$ is a cofinite extension of $U\cap V\in\tau$,so $X\cap Y\in\widehat{\tau}$. (Arbitrary union)If $X_i\in\widehat{\tau}$, then they are cofinite extensions ofsome $U_i\in\tau$.Then $\cup X_i$ is a cofinite extension of $\cup U_i\in\tau$,so $\cup X_i\in\widehat{\tau}$. ($T_1$)Every cofinite subset of $\kappa\times\kappa$is a cofinite extension of $\kappa$,so any topology of the form$\widehat{\tau}$ on $\kappa\times\kappa$contains all cofinite sets.This means that any such topology is $T_1$. \\\ Sketch of proof of II. Given topologies $\tau_i$ on $\kappa$ we must argue that (Inj) the map $\tau\mapsto \widehat{\tau}$ is injective, (M) $\widehat{\bigcap \tau_i}=\bigcap\widehat{\tau_i}$, and (J) $\widehat{\bigvee \tau_i}=\bigvee\widehat{\tau_i}$. The map $\tau\mapsto \widehat{\tau}$ isis easily seen to be order-preserving (and 1-1), so I focus on the claims (M)' $\widehat{\bigcap \tau_i}\supseteq\bigcap\widehat{\tau_i}$, and (J)' $\widehat{\bigvee \tau_i}\subseteq\bigvee\widehat{\tau_i}$. Let's start with (M)'. Choose a set$X\in \bigcap\widehat{\tau_i}$ and let $U=\pi_i(X)$.Then $U\in \bigcap \tau_i$ for all $i$, and $X$ is a cofinite extension of $U$,so $X\in \widehat{\bigcap\tau_i}$. Now (J)'. Suppose that $X\in \widehat{\bigvee\tau_i}$.Then $X$ is a cofinite extension of some set in $\bigvee\tau_i$,and a typical such set has the form$\bigcup_i (U_{i1}\cap \cdots\cap U_{ik_i})$ where $U_{ij}\in\tau_j$.In will now suffice for us to show that $X$ can also be representedin the form$\bigcup_i (\overline{U}_{i1}\cap \cdots\cap \overline{U}_{ik_i})$where $\overline{U}_{ij}$ is a cofiniteextension of some set in some $\tau_j$.Of course, we will choose$\overline{U}_{ij}$ to be acofinite extension of the set $U_{ij}\in\tau_j$,but we must explain how to choose the fibersof $\overline{U}_{ij}$.If some $x\in U_{ij}$ also belongsto $\pi_1(X)$, then choose the fiberover $x$ in $\overline{U}_{ij}$so that it agrees with the fiber over $x$ in $X$,which must be cofinite in $\kappa$.For any other $x\in U_{ij}$ it doesn't matter how you choosethe fiber over $x$ in $\overline{U}_{ij}$except that it must be cofinite. (To be specific, choose this fiber to be all of $\kappa$.) We have now chosen $\overline{U}_{ij}\in\widehat{\tau_j}$so that $\bigcup (\overline{U}_{i1}\cap \cdots\cap \overline{U}_{ik_i})$has the same first projectionand the same fibers as $X$, hence it equals $X$.This represents $X$ as an element of $\bigvee \widehat{\tau_i}$. \\\ | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/295085', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8628/']} | jdg_80988 |
stackexchange | llm_judgeable_groundtruth_similarity | 32026 |
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:
What does it mean to say a language is context-free?
Now provide the response and nothing else.
| A context-free grammar is defined as a grammar in which every production rule is of the form $A \rightarrow \alpha$, where $A$ is a variable and $\alpha$ is a sequence of variables and terminals. Formally, a context-free grammar can be defined as a 4-tuple $(V, \Sigma, R, S)$, where $V$ is a finite set consisting of the variables , $\Sigma$ is a finite set consisting of the terminals , $R$ is a set of production rules (in the form mentioned above), and $S \in V$ is the starting variable . The language of a context-free grammar is the set of strings that can be derived from its start variable. A context-free language is any language that is generated by a context-free grammar. For example, $\{ 0^n1^n : n \ge 0 \}$ is context-free because it is generated by the context-free grammar $(\{S\}, \{0, 1\}, R, S)$, where the set of rules, $R$, is $$S \rightarrow 0S1 \mid \varepsilon.$$ (Note: I am using $\varepsilon$ to denote the empty or null string.) As seen in this example, the set of context-free languages contains languages that are not regular. Also, since it is easy to mimic a DFA with a context-free grammar, the set of regular languages is a proper subset of the set of context-free languages. Pushdown automata are the automata cousins of context-free grammars; they accept context-free languages and there exist algorithms to convert between the two models. Note that the language $\{ a^nb^nc^n : n \ge 0 \}$ is not context-free (try to write a context-free grammar to generate this language and you will get a feeling for why). It can be proven that the language is not context-free with the pumping-lemma for context-free languages , which I will leave as an exercise for the reader. There are more powerful grammars, such as context-sensitive grammars , which allow the production rules to have the form $\beta A \gamma \rightarrow \beta\alpha\gamma$, where $\alpha$, $\beta$, and $\gamma$ are sequences of variables and terminals. Context-sensitive grammars are as powerful as linear bounded automata (LBA). | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/32026', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_80989 |
stackexchange | llm_judgeable_groundtruth_similarity | 32565768 |
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 MVC-5 I could edit the routetable after initial startup by accessing RouteTable.Routes . I wish to do the same in MVC-6 so I can add/delete routes during runtime (usefull for CMS). The code to do it in MVC-5 is: using (RouteTable.Routes.GetWriteLock()){ RouteTable.Routes.Clear(); RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); RouteTable.Routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );} But I can't find RouteTable.Routes or something similar in MVC-6. Any idea how I can still change the route collection during runtime? I want to use this principle to add, for example, an extra url when a page is created in the CMS. If you have a class like: public class Page{ public int Id { get; set; } public string Url { get; set; } public string Html { get; set; }} And a controller like: public class CmsController : Controller{ public ActionResult Index(int id) { var page = DbContext.Pages.Single(p => p.Id == id); return View("Layout", model: page.Html); }} Then when a page is added to the database I recreate the routecollection : var routes = RouteTable.Routes;using (routes.GetWriteLock()){ routes.Clear(); foreach(var page in DbContext.Pages) { routes.MapRoute( name: Guid.NewGuid().ToString(), url: page.Url.TrimEnd('/'), defaults: new { controller = "Cms", action = "Index", id = page.Id } ); } var defaultRoute = routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );} In this way I can add pages to the CMS that do not belong in conventions or strict templates. I can add a page with url /contact , but also a page with url /help/faq/how-does-this-work .
Now provide the response and nothing else.
| The answer is that there is no reasonable way to do this, and even if you find a way it would not be a good practice. An Incorrect Approach to the Problem Basically, the route configuration of MVC versions past was meant to act like a DI configuration - that is, you put everything there in the composition root and then use that configuration during runtime. The problem was that you could push objects into the configuration at runtime (and many people did), which is not the right approach. Now that the configuration has been replaced by a true DI container, this approach will no longer work. The registration step can now only be done at application startup. The Correct Approach The correct approach to customizing routing well beyond what the Route class could do in MVC versions past was to inherit RouteBase or Route. AspNetCore (formerly known as MVC 6) has similar abstractions, IRouter and INamedRouter that fill the same role. Much like its predecessor, IRouter has just two methods to implement. namespace Microsoft.AspNet.Routing{ public interface IRouter { // Derives a virtual path (URL) from a list of route values VirtualPathData GetVirtualPath(VirtualPathContext context); // Populates route data (including route values) based on the // request Task RouteAsync(RouteContext context); }} This interface is where you implement the 2-way nature of routing - URL to route values and route values to URL. An Example: CachedRoute<TPrimaryKey> Here is an example that tracks and caches a 1-1 mapping of primary key to URL. It is generic and I have tested that it works whether the primary key is int or Guid . There is a pluggable piece that must be injected, ICachedRouteDataProvider where the query for the database can be implemented. You also need to supply the controller and action, so this route is generic enough to map multiple database queries to multiple action methods by using more than one instance. using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.Caching.Memory;using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Threading.Tasks;public class CachedRoute<TPrimaryKey> : IRouter{ private readonly string _controller; private readonly string _action; private readonly ICachedRouteDataProvider<TPrimaryKey> _dataProvider; private readonly IMemoryCache _cache; private readonly IRouter _target; private readonly string _cacheKey; private object _lock = new object(); public CachedRoute( string controller, string action, ICachedRouteDataProvider<TPrimaryKey> dataProvider, IMemoryCache cache, IRouter target) { if (string.IsNullOrWhiteSpace(controller)) throw new ArgumentNullException("controller"); if (string.IsNullOrWhiteSpace(action)) throw new ArgumentNullException("action"); if (dataProvider == null) throw new ArgumentNullException("dataProvider"); if (cache == null) throw new ArgumentNullException("cache"); if (target == null) throw new ArgumentNullException("target"); _controller = controller; _action = action; _dataProvider = dataProvider; _cache = cache; _target = target; // Set Defaults CacheTimeoutInSeconds = 900; _cacheKey = "__" + this.GetType().Name + "_GetPageList_" + _controller + "_" + _action; } public int CacheTimeoutInSeconds { get; set; } public async Task RouteAsync(RouteContext context) { var requestPath = context.HttpContext.Request.Path.Value; if (!string.IsNullOrEmpty(requestPath) && requestPath[0] == '/') { // Trim the leading slash requestPath = requestPath.Substring(1); } // Get the page id that matches. TPrimaryKey id; //If this returns false, that means the URI did not match if (!GetPageList().TryGetValue(requestPath, out id)) { return; } //Invoke MVC controller/action var routeData = context.RouteData; // TODO: You might want to use the page object (from the database) to // get both the controller and action, and possibly even an area. // Alternatively, you could create a route for each table and hard-code // this information. routeData.Values["controller"] = _controller; routeData.Values["action"] = _action; // This will be the primary key of the database row. // It might be an integer or a GUID. routeData.Values["id"] = id; await _target.RouteAsync(context); } public VirtualPathData GetVirtualPath(VirtualPathContext context) { VirtualPathData result = null; string virtualPath; if (TryFindMatch(GetPageList(), context.Values, out virtualPath)) { result = new VirtualPathData(this, virtualPath); } return result; } private bool TryFindMatch(IDictionary<string, TPrimaryKey> pages, IDictionary<string, object> values, out string virtualPath) { virtualPath = string.Empty; TPrimaryKey id; object idObj; object controller; object action; if (!values.TryGetValue("id", out idObj)) { return false; } id = SafeConvert<TPrimaryKey>(idObj); values.TryGetValue("controller", out controller); values.TryGetValue("action", out action); // The logic here should be the inverse of the logic in // RouteAsync(). So, we match the same controller, action, and id. // If we had additional route values there, we would take them all // into consideration during this step. if (action.Equals(_action) && controller.Equals(_controller)) { // The 'OrDefault' case returns the default value of the type you're // iterating over. For value types, it will be a new instance of that type. // Since KeyValuePair<TKey, TValue> is a value type (i.e. a struct), // the 'OrDefault' case will not result in a null-reference exception. // Since TKey here is string, the .Key of that new instance will be null. virtualPath = pages.FirstOrDefault(x => x.Value.Equals(id)).Key; if (!string.IsNullOrEmpty(virtualPath)) { return true; } } return false; } private IDictionary<string, TPrimaryKey> GetPageList() { IDictionary<string, TPrimaryKey> pages; if (!_cache.TryGetValue(_cacheKey, out pages)) { // Only allow one thread to poplate the data lock (_lock) { if (!_cache.TryGetValue(_cacheKey, out pages)) { pages = _dataProvider.GetPageToIdMap(); _cache.Set(_cacheKey, pages, new MemoryCacheEntryOptions() { Priority = CacheItemPriority.NeverRemove, AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(this.CacheTimeoutInSeconds) }); } } } return pages; } private static T SafeConvert<T>(object obj) { if (typeof(T).Equals(typeof(Guid))) { if (obj.GetType() == typeof(string)) { return (T)(object)new Guid(obj.ToString()); } return (T)(object)Guid.Empty; } return (T)Convert.ChangeType(obj, typeof(T)); }} CmsCachedRouteDataProvider This is the implementation of the data provider that is basically what you need to do in your CMS. public interface ICachedRouteDataProvider<TPrimaryKey>{ IDictionary<string, TPrimaryKey> GetPageToIdMap();}public class CmsCachedRouteDataProvider : ICachedRouteDataProvider<int>{ public IDictionary<string, int> GetPageToIdMap() { // Lookup the pages in DB return (from page in DbContext.Pages select new KeyValuePair<string, int>( page.Url.TrimStart('/').TrimEnd('/'), page.Id) ).ToDictionary(pair => pair.Key, pair => pair.Value); }} Usage And here we add the route before the default route, and configure its options. // Add MVC to the request pipeline.app.UseMvc(routes =>{ routes.Routes.Add( new CachedRoute<int>( controller: "Cms", action: "Index", dataProvider: new CmsCachedRouteDataProvider(), cache: routes.ServiceProvider.GetService<IMemoryCache>(), target: routes.DefaultHandler) { CacheTimeoutInSeconds = 900 }); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); // Uncomment the following line to add a route for porting Web API 2 controllers. // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");}); That's the gist of it. You could still improve things a bit. I would personally use a factory pattern and inject the repository into the constructor of CmsCachedRouteDataProvider rather than hard coding DbContext everywhere, for example. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32565768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/637425/']} | jdg_80990 |
stackexchange | llm_judgeable_groundtruth_similarity | 15113562 |
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 written a Chrome extension. I cannot use localStorage.setItem and localStorage.getItem for storing and retrieving because background and browser action runs in different environment [ as seen here ]. So I decided to use the Chrome storage API: var storage = chrome.storage.local;var myTestVar = 'somevar';var obj = {};obj[myTestVar] = $("#somevar").val();storage.set(obj); which produced the following error: Uncaught TypeError: Cannot read property 'local' of undefined What am I doing wrong?
Now provide the response and nothing else.
| Make sure that all necessary permissions have been declared in the manifest file. "storage" , in your case. In general, the following steps should fix the problem of apparently undefined Chrome APIs: Read the documentation of the API you're using and get yourself familiar with the prerequisites, usually manifest permissions ( e.g. chrome.storage #manifest ). Check if your (user's) Chrome version supports the API, by looking at What's new . Check if the script is running in the right context . Most APIs are only available to the extension's process. (the chrome.storage API can also be used in content script though) Otherwise, resort to your usual debugging skills: Typos, variable shadowing, ... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15113562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1719752/']} | jdg_80991 |
stackexchange | llm_judgeable_groundtruth_similarity | 47405541 |
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 3D numpy array looks like this shape(3,1000,100)[[[2,3,0,2,6,...,0,-1,-1,-1,-1,-1],[1,4,6,1,4,5,3,...,1,2,6,-1,-1],[7,4,6,3,1,0,1,...,2,0,8,-1,-1],...[8,7,6,4,...,2,4,5,2,1,-1]],...,[1,5,6,7,...,0,0,0,0,1]]] Each lane of array end with 0 or multiple(less than 70 I'm sure) -1 . For now, I want to select only 30 values before the -1 for each lane, to make a subset of original numpy array with shape of (3,1000,30) Should be similar like this, [[[...,0], [...,1,2,6], [...,2,0,8], ... [...,2,4,5,2,1]], ..., [...,0,0,0,0,1]]] Is it possible to do it with some numpy functions? Hope without a for loop:)
Now provide the response and nothing else.
| Here's one making use of broadcasting and advanced-indexing - def preceedingN(a, N): # mask of value (minus 1 here) to be found mask = a==-1 # Get the first index with the value along the last axis. # In case its not found, choose the last index idx = np.where(mask.any(-1), mask.argmax(-1), mask.shape[-1]) # Get N ranged indices along the last axis ind = idx[...,None] + np.arange(-N,0) # Finally advanced-index and get the ranged indexed elements as the o/p m,n,r = a.shape return a[np.arange(m)[:,None,None], np.arange(n)[:,None], ind] Sample run - Setup for reproducible input : import numpy as np# Setup sample input arraynp.random.seed(0)m,n,r = 2,4,10a = np.random.randint(11,99,(m,n,r))# Select N elements off each rowN = 3idx = np.random.randint(N,a.shape[-1]-1,(m,n))a[idx[...,None] < np.arange(a.shape[-1])] = -1a[0,0] = range(r) # set first row of first 2D slice to range (no -1s there) Input, output : >>> aarray([[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [81, 23, 69, 76, 50, 98, 57, -1, -1, -1], [88, 83, 20, 31, 91, 80, 90, 58, -1, -1], [60, 40, 30, 30, 25, 50, 43, 76, -1, -1]], [[43, 42, 85, 34, 46, 86, 66, 39, -1, -1], [11, 47, 64, 16, -1, -1, -1, -1, -1, -1], [42, 12, 76, 52, 68, 46, 22, 57, -1, -1], [25, 64, 23, 53, 95, 86, 79, -1, -1, -1]]])>>> preceedingN(a, N=3)array([[[ 7, 8, 9], [50, 98, 57], [80, 90, 58], [50, 43, 76]], [[86, 66, 39], [47, 64, 16], [46, 22, 57], [95, 86, 79]]]) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47405541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8816642/']} | jdg_80992 |
stackexchange | llm_judgeable_groundtruth_similarity | 8974364 |
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 draw a canvas graphic like this flash animation: http://www.cci.com.tr/tr/bizi-taniyin/tarihcemiz/ I drew six arcs and I want to write six words in these arcs. Any ideas?
Now provide the response and nothing else.
| I have a jsFiddle to apply text to any arbitrary Bezier curve definition. Enjoy http://jsfiddle.net/Makallus/hyyvpp8g/ var first = true;startIt();function startIt() { canvasDiv = document.getElementById('canvasDiv'); canvasDiv.innerHTML = '<canvas id="layer0" width="300" height="300"></canvas>'; //for IE canvas = document.getElementById('layer0'); ctx = canvas.getContext('2d'); ctx.fillStyle = "black"; ctx.font = "18px arial black"; curve = document.getElementById('curve'); curveText = document.getElementById('text'); $(curve).keyup(function(e) { changeCurve(); }); $(curveText).keyup(function(e) { changeCurve(); }); if (first) { changeCurve(); first = false; }}function changeCurve() { points = curve.value.split(','); if (points.length == 8) drawStack();}function drawStack() { Ribbon = { maxChar: 50, startX: points[0], startY: points[1], control1X: points[2], control1Y: points[3], control2X: points[4], control2Y: points[5], endX: points[6], endY: points[7] }; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save(); ctx.beginPath(); ctx.moveTo(Ribbon.startX, Ribbon.startY); ctx.bezierCurveTo(Ribbon.control1X, Ribbon.control1Y, Ribbon.control2X, Ribbon.control2Y, Ribbon.endX, Ribbon.endY); ctx.stroke(); ctx.restore(); FillRibbon(curveText.value, Ribbon);}function FillRibbon(text, Ribbon) { var textCurve = []; var ribbon = text.substring(0, Ribbon.maxChar); var curveSample = 1000; xDist = 0; var i = 0; for (i = 0; i < curveSample; i++) { a = new bezier2(i / curveSample, Ribbon.startX, Ribbon.startY, Ribbon.control1X, Ribbon.control1Y, Ribbon.control2X, Ribbon.control2Y, Ribbon.endX, Ribbon.endY); b = new bezier2((i + 1) / curveSample, Ribbon.startX, Ribbon.startY, Ribbon.control1X, Ribbon.control1Y, Ribbon.control2X, Ribbon.control2Y, Ribbon.endX, Ribbon.endY); c = new bezier(a, b); textCurve.push({ bezier: a, curve: c.curve }); } letterPadding = ctx.measureText(" ").width / 4; w = ribbon.length; ww = Math.round(ctx.measureText(ribbon).width); totalPadding = (w - 1) * letterPadding; totalLength = ww + totalPadding; p = 0; cDist = textCurve[curveSample - 1].curve.cDist; z = (cDist / 2) - (totalLength / 2); for (i = 0; i < curveSample; i++) { if (textCurve[i].curve.cDist >= z) { p = i; break; } } for (i = 0; i < w; i++) { ctx.save(); ctx.translate(textCurve[p].bezier.point.x, textCurve[p].bezier.point.y); ctx.rotate(textCurve[p].curve.rad); ctx.fillText(ribbon[i], 0, 0); ctx.restore(); x1 = ctx.measureText(ribbon[i]).width + letterPadding; x2 = 0; for (j = p; j < curveSample; j++) { x2 = x2 + textCurve[j].curve.dist; if (x2 >= x1) { p = j; break; } } }} //end FillRibonfunction bezier(b1, b2) { //Final stage which takes p, p+1 and calculates the rotation, distance on the path and accumulates the total distance this.rad = Math.atan(b1.point.mY / b1.point.mX); this.b2 = b2; this.b1 = b1; dx = (b2.x - b1.x); dx2 = (b2.x - b1.x) * (b2.x - b1.x); this.dist = Math.sqrt(((b2.x - b1.x) * (b2.x - b1.x)) + ((b2.y - b1.y) * (b2.y - b1.y))); xDist = xDist + this.dist; this.curve = { rad: this.rad, dist: this.dist, cDist: xDist };}function bezierT(t, startX, startY, control1X, control1Y, control2X, control2Y, endX, endY) { //calculates the tangent line to a point in the curve; later used to calculate the degrees of rotation at this point. this.mx = (3 * (1 - t) * (1 - t) * (control1X - startX)) + ((6 * (1 - t) * t) * (control2X - control1X)) + (3 * t * t * (endX - control2X)); this.my = (3 * (1 - t) * (1 - t) * (control1Y - startY)) + ((6 * (1 - t) * t) * (control2Y - control1Y)) + (3 * t * t * (endY - control2Y));}function bezier2(t, startX, startY, control1X, control1Y, control2X, control2Y, endX, endY) { //Quadratic bezier curve plotter this.Bezier1 = new bezier1(t, startX, startY, control1X, control1Y, control2X, control2Y); this.Bezier2 = new bezier1(t, control1X, control1Y, control2X, control2Y, endX, endY); this.x = ((1 - t) * this.Bezier1.x) + (t * this.Bezier2.x); this.y = ((1 - t) * this.Bezier1.y) + (t * this.Bezier2.y); this.slope = new bezierT(t, startX, startY, control1X, control1Y, control2X, control2Y, endX, endY); this.point = { t: t, x: this.x, y: this.y, mX: this.slope.mx, mY: this.slope.my };}function bezier1(t, startX, startY, control1X, control1Y, control2X, control2Y) { //linear bezier curve plotter; used recursivly in the quadratic bezier curve calculation this.x = ((1 - t) * (1 - t) * startX) + (2 * (1 - t) * t * control1X) + (t * t * control2X); this.y = ((1 - t) * (1 - t) * startY) + (2 * (1 - t) * t * control1Y) + (t * t * control2Y);} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table> <TR> <TH>Bezier Curve</TH> <TD> <input size="80" type="text" id="curve" name="curve" value="99.2,177.2,130.02,60.0,300.5,276.2,300.7,176.2"> </TD> </TR> <TR> <TH>Text</TH> <TD> <input size="80" type="text" id="text" name="text" value="testing 1234567890"> </TD> </TR> <TR> <TD colspan=2> <div id="canvasDiv"></div> </TD> </TR></table> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8974364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1165241/']} | jdg_80993 |
stackexchange | llm_judgeable_groundtruth_similarity | 8799072 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
when i installed new version of xampp and then tranfered my all database and data files. but after completion i can't display css of site. what is actual problem? I have seen all setting of setting.php , Clear cache And all but all are vein. help me?
Now provide the response and nothing else.
| This is not a feature right now to be able to do in one shot (see the comments in the DEL documentation ). Unfortunately, you are only left with using KEYS , looping through the results, and then using DEL to remove each one. How about using bash a bit to help? for key in `echo 'KEYS user*' | redis-cli | awk '{print $1}'` do echo DEL $keydone | redis-cli To step through it: echo 'KEYS user*' | redis-cli | awk '{print $1}' -- get all the keys and strip out the extra text you don't want with awk. echo DEL $key -- for each one, create an echo statement to remove it. | redis-cli -- take the DEL statements and pass them back into the cli. Not suggesting this is the best approach (you might have some issues if some of your usernames have spaces in them, but hopefully you get the point). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8799072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1069199/']} | jdg_80994 |
stackexchange | llm_judgeable_groundtruth_similarity | 158878 |
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 am confused by rolling friction. Suppose you have a cylinder rolling which starts at rest at the top of an incline plane and begins to roll down the plane without slipping. Is work done by the incline on the cylinder? I know from doing some problems that the total kinetic energy (translational and rotational) is $mgh$, which is true only if the only work done on the cylinder is by gravity. But also, the cylinder must have nonzero angular acceleration, so friction must be exerting torque on the cylinder, so work must be done by friction. One of these statements is wrong.
Now provide the response and nothing else.
| Work is force times distance. If there is no slip, the force of friction acts over a distance of 0. There is no work. Gravity does work. As the cylinder rolls down the hill, it accelerates. It gains kinetic energy in two forms: translation and rotation. Gravity would do the same work on an identical cylinder that slide down the same slope without friction. The kinetic energy of the two would be the same at each position. The rolling cylinder would travel more slowly than the sliding cylinder. But it would also spin. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/158878', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/63691/']} | jdg_80995 |
stackexchange | llm_judgeable_groundtruth_similarity | 6378646 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
on my quest to learn and improve my JavaScript I came across a script that has a switch / case statement and I noticed some variables are incremented using ++ with the variable before the ++ and then some variables have the ++ after the variable. What's the difference between these? Here's an example of what I'm trying to explain notice the m and y variables. switch(f){ case 0:{ ++m; if(m==12){ m=0; y++; } break; } case 1:{ --m; if(m==-1){ m=11; y--; } break; } case 2:{ ++y; break; } case 3:{ --y; break; } case 4:{ break; } }
Now provide the response and nothing else.
| ++i returns the value of i after it has been incremented. i++ returns the value of i before incrementing. When the ++ comes before its operand it is called the "pre-increment" operator, and when it comes after it is called the "post-increment" operator. This distinction is only important if you do something with the result. var i = 0, j = 0;alert(++i); // alerts 1alert(j++); // alerts 0 One thing to note though is that even though i++ returns the value before incrementing, it still returns the value after it has been converted to a number. So var s = "1";alert(typeof s++); // alerts "number"alert(s); // alerts 2, not "11" as if by ("1" + 1) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6378646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/421020/']} | jdg_80996 |
stackexchange | llm_judgeable_groundtruth_similarity | 3227537 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
By intuition, I found that the result of evaluating the following expression $$ \frac{1}{M} \frac{\sum_{N=0}^M \frac{M!}{(M-N)!N!} N e^{cN}}{\sum_{N=0}^M \frac{M!}{(M-N)!N!} e^{cN}} $$ does not depend on the positive value of the integer $M$ , i.e. it only depends on $c\in\mathbb R$ . I corroborated this with the help of a simple Python script. How to show analytically that this is true?
Now provide the response and nothing else.
| By the Binomial Theorem , the denominator is $(e^c+1)^M$ . The numerator can also be manipulated to apply the Binomial Theorem: \begin{align*}\sum_{N=0}^M \frac{M!}{(M-N)!N!} Ne^{cN} &= \sum_{N=1}^M \frac{M\cdot (M-1)!}{((M-1)-(N-1))!(N-1)!}e^{c(N-1)}\cdot e^c\\&=Me^c \sum_{N=1}^M \binom{M-1}{N-1}e^{c(N-1)}\\&=Me^c \sum_{K=0}^{M-1} \binom{M-1}{K}e^{cK}\\&=Me^c (e^c+1)^{M-1}.\end{align*} So the whole expression simplifies to: $$\frac{e^c}{e^c+1}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3227537', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/225568/']} | jdg_80997 |
stackexchange | llm_judgeable_groundtruth_similarity | 22323385 |
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 root, and I saw there are a lot of contents in /etc/crontab , which I thought is the root's cron job configurations. When I use crontab -e , I saw nothing in the editor; after I quit crontab -e , what I added was not found in /etc/crontab . So, where is root's cron job configuration stored? And other users?
Now provide the response and nothing else.
| It is stored in the directory: /var/spool/cron/crontabs Containing one file per user. From man crontab (at least on my Ubuntu 13): There is one file for each user's crontab under the /var/spool/cron/crontabs directory. Users are not allowed to edit the files under that directory directly to ensure that only users allowed by the system to run periodic tasks can add them, and only syntactically correct crontabs will be written there. This is enforced by having the directory writable only by the crontab group and configuring crontab command with the setgid bid set for that specific group. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22323385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2698577/']} | jdg_80998 |
stackexchange | llm_judgeable_groundtruth_similarity | 13339615 |
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 trying to pack circles of different sizes into a rectangular container , not packing in circular container that d3.js bundled with, under d3.layout.pack . here's the layout I want to achieve: I've found this paper on this matter, but I am not a math guy to understand the article throughly and convert them into code… Anyone can suggest where I should start to convert this into d3.js layout plugin, or if you have visualized bubbles similar to this layout, please suggest any direction you took to solve that. Thank you.
Now provide the response and nothing else.
| Here is a go at the implementation of your algorithm. I tweaked it quite a bit, but I think it does basically the same thing. Bounding circles I used a trick to make the computation more regular. Instead of segments defining the bounding box, I used circles with "infinite" radii, that can be considered a good approximation of lines: The picture shows what the 4 bounding circles look like when the radius is decreased. They are computed to pass through the corners of the bounding box and converge toward the actual sides when the radius grows. The "corner" circles (as the algorithm calls them) are all computed as tangents to a pair of circles, thus eliminating the special circle+segment or segment+segment cases. This also simplifies the start condition greatly. The algorithm simply starts with the four bounding circles and adds one circle at a time, using the greedy heuristic lambda parameter to pick the "best" location. Best fit strategy The original algorithm does not produce the smallest rectangle to hold all the circles (it simply tries to fit a bunch of circles into a given rectangle). I have added a simple dichotomic search on top of it to guess the minimal surface (which yields the smallest bounding rectangle for a given aspect ratio). The code Here is a fiddle var Packer = function (circles, ratio){ this.circles = circles; this.ratio = ratio || 1; this.list = this.solve();}Packer.prototype = { // try to fit all circles into a rectangle of a given surface compute: function (surface) { // check if a circle is inside our rectangle function in_rect (radius, center) { if (center.x - radius < - w/2) return false; if (center.x + radius > w/2) return false; if (center.y - radius < - h/2) return false; if (center.y + radius > h/2) return false; return true; } // approximate a segment with an "infinite" radius circle function bounding_circle (x0, y0, x1, y1) { var xm = Math.abs ((x1-x0)*w); var ym = Math.abs ((y1-y0)*h); var m = xm > ym ? xm : ym; var theta = Math.asin(m/4/bounding_r); var r = bounding_r * Math.cos (theta); return new Circle (bounding_r, new Point (r*(y0-y1)/2+(x0+x1)*w/4, r*(x1-x0)/2+(y0+y1)*h/4)); } // return the corner placements for two circles function corner (radius, c1, c2) { var u = c1.c.vect(c2.c); // c1 to c2 vector var A = u.norm(); if (A == 0) return [] // same centers u = u.mult(1/A); // c1 to c2 unary vector // compute c1 and c2 intersection coordinates in (u,v) base var B = c1.r+radius; var C = c2.r+radius; if (A > (B + C)) return []; // too far apart var x = (A + (B*B-C*C)/A)/2; var y = Math.sqrt (B*B - x*x); var base = c1.c.add (u.mult(x)); var res = []; var p1 = new Point (base.x -u.y * y, base.y + u.x * y); var p2 = new Point (base.x +u.y * y, base.y - u.x * y); if (in_rect(radius, p1)) res.push(new Circle (radius, p1)); if (in_rect(radius, p2)) res.push(new Circle (radius, p2)); return res; } ///////////////////////////////////////////////////////////////// // deduce starting dimensions from surface var bounding_r = Math.sqrt(surface) * 100; // "infinite" radius var w = this.w = Math.sqrt (surface * this.ratio); var h = this.h = this.w/this.ratio; // place our bounding circles var placed=[ bounding_circle ( 1, 1, 1, -1), bounding_circle ( 1, -1, -1, -1), bounding_circle (-1, -1, -1, 1), bounding_circle (-1, 1, 1, 1)]; // Initialize our rectangles list var unplaced = this.circles.slice(0); // clones the array while (unplaced.length > 0) { // compute all possible placements of the unplaced circles var lambda = {}; var circle = {}; for (var i = 0 ; i != unplaced.length ; i++) { var lambda_min = 1e10; lambda[i] = -1e10; // match current circle against all possible pairs of placed circles for (var j = 0 ; j < placed.length ; j++) for (var k = j+1 ; k < placed.length ; k++) { // find corner placement var corners = corner (unplaced[i], placed[j], placed[k]); // check each placement for (var c = 0 ; c != corners.length ; c++) { // check for overlap and compute min distance var d_min = 1e10; for (var l = 0 ; l != placed.length ; l++) { // skip the two circles used for the placement if (l==j || l==k) continue; // compute distance from current circle var d = placed[l].distance (corners[c]); if (d < 0) break; // circles overlap if (d < d_min) d_min = d; } if (l == placed.length) // no overlap { if (d_min < lambda_min) { lambda_min = d_min; lambda[i] = 1- d_min/unplaced[i]; circle[i] = corners[c]; } } } } } // select the circle with maximal gain var lambda_max = -1e10; var i_max = -1; for (var i = 0 ; i != unplaced.length ; i++) { if (lambda[i] > lambda_max) { lambda_max = lambda[i]; i_max = i; } } // failure if no circle fits if (i_max == -1) break; // place the selected circle unplaced.splice(i_max,1); placed.push (circle[i_max]); } // return all placed circles except the four bounding circles this.tmp_bounds = placed.splice (0, 4); return placed; }, // find the smallest rectangle to fit all circles solve: function () { // compute total surface of the circles var surface = 0; for (var i = 0 ; i != this.circles.length ; i++) { surface += Math.PI * Math.pow(this.circles[i],2); } // set a suitable precision var limit = surface/1000; var step = surface/2; var res = []; while (step > limit) { var placement = this.compute.call (this, surface);console.log ("placed",placement.length,"out of",this.circles.length,"for surface", surface); if (placement.length != this.circles.length) { surface += step; } else { res = placement; this.bounds = this.tmp_bounds; surface -= step; } step /= 2; } return res; }}; Performance The code is not optimized, to favor readability (or so I hope :)). The computation time rises pretty steeply. You can safely place about 20 circles, but anything above 100 will make your browser crawl. For some reason, it is way faster on FireFox than on IE11. Packing efficiency The algorithm works quite poorly on identically-sized circles (it cannot find the famous honeycomb pattern for 20 circles in a square), but pretty well on a wide distribution of random radii. Aesthetics The result is pretty ungainly for identical-sized circles. There is no attempt to bunch the circles together, so if two possibilities are deemed equivalent by the algorithm, one is just picked at random. I suspect the lambda parameter could be refined a bit to allow for a more aesthetic choice in case of equal values. Possible evolutions With the "infinite radii" trick, it becomes possible to define an arbitrary bounding polygon. If you provide a function to check if a circle fits into the said polygon, there is no reason the algorithm should not produce a result. Whether this result would be efficient is another question :). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13339615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1142122/']} | jdg_80999 |
stackexchange | llm_judgeable_groundtruth_similarity | 855653 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this problem that I cannot figure out how to solve. It is from Szeliski's computer vision book ( http://szeliski.org/Book/drafts/SzeliskiBook_20100903_draft.pdf ) p.94 (electronic version) and is as follows: If you are given more than two lines and want to find a point $\widetilde{x}$ that minimizes the sum of squared distances to each line, $$D = \sum_{i}(\widetilde{x} \cdot \widetilde{l}_i)^2$$ how can you compute this quantity? (Hint: Write the dot product as $\widetilde{x}^T\widetilde{l_i}$ and turn the squared quantity into a quadratic form, $\widetilde{x}^TA\widetilde{x}$.) The tilde sign is used to denote points in homogenous coordinates. I have turned the expression into this expression, which is the authors hint: $$\sum_{i}(\widetilde{x}^T\widetilde{l_i})(\widetilde{x}^T\widetilde{l_i}) = \sum_{i}(\widetilde{x}^T\widetilde{l_i})(\widetilde{l_i}^T\widetilde{x}) = \sum_{i}\widetilde{x}^TA\widetilde{x}$$ A is then: $\widetilde{l_i}\widetilde{l_i}^T$ How do I proceed from here? How does rewriting the sum to a sum of quadratic from help me? I can take the derivative and find a x that minimizes the squared sum? The lines are in 2D expressed using homogenous coordinates resulting in 3D vectors. Does anyone know how to solve this using the quadratic form expression (using matrix stuff)
Now provide the response and nothing else.
| $$e^x = \sum \frac {x^n} {n!} $$Starting with this definition, it is obvious that $e^x > 0$ when $x \geq 0$. To show that $e^{-x} > 0$ it is enough to show that $e^{-x} \cdot e^x = 1$. $$\sum_{n=0} \frac {(-x)^n} {n!} \cdot \sum_{m=0} \frac {x^m} {m!} = \sum_{m,n} \frac {(-x)^nx^m} {n!m!} = \sum _k \sum_{m+n = k} \frac{((-x)+x)^{n+m}}{(n+m)!} = 1$$ Here the second equality is due to $(a+b)^n = \sum_k \binom n k a^{n-k}b^k$ and the last one is due to $0^0 = 1$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/855653', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/161598/']} | jdg_81000 |
stackexchange | llm_judgeable_groundtruth_similarity | 18954130 |
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 is possible to use GUID as primary Keys in SQLITE Database?If Possible which datatype can be used?
Now provide the response and nothing else.
| SQLite itself does not support GUID as internal type. Except that, it does! (sort of). Remember, in SQLite any string can be used as type name, and that includes GUID or UUID (read more about SQLite datatypes ). According to those rules, GUID type has affinity NONE , which is the same as for BLOB fields. With this in mind, you can create column of GUID type, and use following rules to access it: Store it as string like X'01020304050607080910111213141516' (X notation is used to represent 16 byte BLOB value).To insert, use: INSERT INTO mytable (uuid)VALUES (X'01020304050607080910111213141516'); Read it as 16-byte BLOB . quote(uuid) can be used to format output using X notation: SELECT quote(uuid)FROM mytable Such column can be also used as primary key. Unfortunately, there is no AUTOINCREMENT functionality like it exists for integer primary keys - you will have to handle it yourself. You can use something as simple as randomblob(16) for that, but it is not quite UUID as defined by standard . Confusingly, you can also store text representation of UUID in the same field (SQLite won't stop you from doing that), but it will take at least 2x more space: BLOB is 16 bytes, UUID as text is at least 32 bytes. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18954130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2134137/']} | jdg_81001 |
stackexchange | llm_judgeable_groundtruth_similarity | 278797 |
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:
Continuations are extremely useful in functional programming languages (e.g. the Cont monad in Haskell) because they allow a simple and regular notation for imperative-style code. They're also useful in some older imperative languages because they can be used to implement missing language features (e.g. exceptions, coroutines, green threads). But for a modern object-oriented language with support built in for these features, what arguments would there be for also adding support for first-class continuations (whether the more modern delimited style reset and shift or scheme-like call-with-current-continuation )? Are there arguments against adding support other than performance and complexity of implementation?
Now provide the response and nothing else.
| Let's let Eric Lippert answer this one: The obvious question at this point is: if CPS is so awesome then whydon’t we use it all the time? Why have most professional developersnever heard of it, or, those who have, think of it as something onlythose crazy Scheme programmers do? First of all, it is simply hard for most people who are used tothinking about subroutines, loops, try-catch-finally and so on toreason about delegates being used for control flow in this way. I amreviewing my notes on CPS from CS442 right now and I see that in 1995I wrote down a profQUOTE: “With continuations you have to sort ofstand on your head and pull yourself inside out”. Professor Duggan (*)was absolutely correct in saying that. Recall from a couple days agothat our tiny little example of CPS transformation of the C#expression M(B()?C():D()) involved four lambdas. Not everyone is goodat reading code that uses higher-order functions. It imposes a largecognitive burden. Moreover: one of the nice things about having specific control flowstatements baked in to a language is that they let your code clearlyexpress the meaning of the control flow while hiding the mechanisms –the call stacks and return addresses and exception handler lists andprotected regions and so on. Continuations make the mechanisms ofcontrol flow explicit in the structure of the code. All that emphasison mechanism can overwhelm the meaning of the code. In the next article , he explains how asynchrony and continuations are exactly equivalent to one another, and goes over a demonstration of taking a simple, (but blocking,) synchronous network operation and rewriting it in asyncronous style, making sure to cover all the hidden gotchas that have to be covered in order to get it right. It turns into a massive mess of code. His summary at the end: Holy goodness, what a godawful mess we’ve made. We've expanded twolines of perfectly clear code into two dozen lines of the mostgodawful spaghetti you've ever seen. And of course it still doesn’teven compile because the labels aren’t in scope and we have a definiteassignment error. We;d still need to further rewrite the code to fixthose problems. Remember what I was saying about the pros and cons of CPS? PRO: Arbitrarily complex and interesting control flows can be built out of simple parts – check. CON: The reification of control flow via continuations is hard to read and hard to reason about – check. CON: The code that represents the mechanisms of control flow completely overwhelms the meaning of the code – check. CON: The transformation of ordinary code control flow into CPS is the kind of thing that compilers are good at, and almost no one elseis – check. This is not some intellectual exercise. Real people end up writingcode morally equivalent to the above all the time when they deal withasynchrony. And, ironically, even as processors have gotten faster andcheaper, we spend more and more of our time waiting for stuff thatisn’t processor-bound. In many programs, much of the time spent iswith the processor pegged to zero waiting for network packets to makethe trip from England to Japan and back again, or for disks to spin,or whatever. And I haven't even talked about what happens if you want to composeasynchronous operations further. Suppose you want to makeArchiveDocuments an asynchronous operation that takes a delegate. Nowall the code that calls it has to be written in CPS as well. The taintjust spreads. Getting asynchronous logic right is important, it’s only going to be more important in the future, and the tools we have given you make you “stand on your head and turn yourself inside out” as Professor Dugganwisely said. Continuation passing style is powerful, yes, but there's got to be abetter way of making good use of that power than the code above. Both articles, and the following series on a new C# language feature that moves all this mess into the compiler and lets you write your code as normal control flow with a special keyword to mark certain parts as asynchronous, are well worth reading even if you're not a C# developer. I'm not, but it was still quite the enlightening experience when I ran across it for the first time. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/278797', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/66037/']} | jdg_81002 |
stackexchange | llm_judgeable_groundtruth_similarity | 58925276 |
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 understanding is that a middleware function is a route handler with the exception that it may invoke the next function parameter to pass control on to the middleware function on the stack. Is this the only difference between a standard route handler and a middleware function?
Now provide the response and nothing else.
| Most of what you're talking about is semantics. In ExpressJS, middleware can be a route handler or a route handler can behave as middleware. So, there is not a hard and fast line between the two. But, when people refer to middleware or a route handler in a programming discussion, they usually mean something slightly different for each... Middleware As generic terms, middleware is code that examines an incoming request and prepares it for further processing by other handlers or short circuits the processing (like when it discovered the user is not authenticated yet). Some examples: Session Management. Parse cookies, look for session cookie, lookup session state for that cookie and add session info to the request so that other handlers down the line have ready access to the session object without any additional work on their part. In express, this would be express.session() . Authentication. Check if the user is trying to access a portion of the site that requires authentication. If so, check if their authentication credentials are good. If not, send an error response and prevent further processing. If so, allow further processing. Parsing of Cookies. Parse incoming cookies into an easy-to-use data structure a request handler can have easy access to cookie data without each having to parse them on their own. This type of middleware is built into Express and happens automatically. Parsing and Reading of POST/PUT bodies. If the incoming request is a POST or PUT, the body of the request may contain data that is needed for processing the request and needs to be read from the incoming stream. Middleware can centralize this task reading the body, then parsing it according to the data type and putting the result into a known request parameter (in Express this would be req.body ). Express has some ready-to-use middleware for this type of body parsing with express.json() or express.urlencoded() . A middleware library like multer is for handling file uploads. Serve static files (HTML, CSS, JS, etc...). For some groups of URLs, all the server needs to do is to serve a static file (no custom content added to the file). This is common for CSS files, JS files and even some HTML files. Express provides middleware for this which is called express.static() . Route Handler As a generic term, a route handler is code that is looking for a request to a specific incoming URL such as /login and often a specific HTTP verb such as POST and has specific code for handling that precise URL and verb. Some examples: Serve a specific web page. Handle a browser request for a specific web page. Handle a specific form post. For example, when the user logs into the site, a login for is submitted to the server. This would be handled by a request handler in Express such as app.post("/login", ...) . Respond to a specific API request . Suppose you had an API for a book selling web-site. You might provide in that API the ability to get info on a book by its ISBN number. So, you design an api that supports a query for a particular book such as /api/book/list/0143105426 where 0143105426 is the ISBN number for the book (a universal book identifier). In that case, you'd create a request handler in Express for a URL that looks like that: app.get('/api/book/list/:isbn', ...) . The request handler in Express could then programmatically examine req.parms.isbn to get the request isbn number, look it up in the database and return the desired info on the book. So, those are somewhat generic descriptions of middleware vs. request handlers in any web server system in any language. In Express, there is no hard and fast distinction between the two. Someone would generally call something middleware that examines a bunch of different requests and usually prepares the request for further processing. Someone would generally call something a route handler that is targeted at a specific URL (or type of URL) and whose main purpose is to send a response back to the client for that URL. But, the way you program Express, the distinction is pretty blurry. Express offers features for handling routes such as: app.use()app.get()app.post()app.put()app.delete()app.all() Anyone of these can be used for either middleware or a route handler. Which would would call a given block of code has more to do with the general intent of the code than exactly which tools in Express it uses. More typically, one would use app.use() for middleware and app.get() and app.post() for route handlers. But there are use cases for doing it differently than that as it really depends upon the particular situation and what you're trying to do. You can even pass more than one handler to a given route definition where the first one is middleware and followed by a route handler. app.get("/admin", verifyAuth, (req, res) => { // process the /admin URL, auth is already verified req.sendFile("...");}); It is common for middleware to be active for a large number of different requests. For example, you might have an authentication middleware that prevents access to 95% of the site if the user isn't already logged in (say everything except the a few generally information pages such as the homepage and the login and account creation pages). It is also common to have middleware that is active for all HTTP verbs such as GET, POST, DELETE, PUT, etc... In express, this would usually be app.use() or app.all() . Request handlers are usually only for one particular verb such as app.get() or app.post() . You might have session middleware that loads a session object (if one is available) for every single request on the site and then passes control on to other handlers that can, themselves, decide whether they need to access the session object or not. It is common for request handlers to be targeted at a specific URL and only active for that specific URL. For example, the /login URL would typically have one request handler that renders that particular page or responds to login form requests. Path Matching for app.use() is Different In Express, there's one other subtle difference. Middleware is typically specified with: app.use(path, handler); And, a route is typically specified with: app.get(path, handler);app.post(path, handler);app.put(path, handler);// etc... app.use() is slightly more greedy than app.get() and the others in how it matches the path. app.get() requires a full match. app.use() is OK with a partial match. Here are some examples: So, for a URL request /category : app.use("/category", ...) matches app.get("/category", ...) matches For a URL request /category/fiction : app.use("/category", ...) matches app.get("/category", ...) does not match You can see that app.use() accepts a partial URL match, app.get() and it's other cousins do not accept a partial URL match. Now, of course, you can use app.get() for middleware if you want and can use app.use() for request handlers if you want, but typically one would use app.use() for middleware and app.get() and its cousins for request handlers. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58925276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_81003 |
stackexchange | llm_judgeable_groundtruth_similarity | 7430976 |
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 checked this question and it solved my initial problems. But I don't want the partial view to be rendered only when the user clicks a link, I want to render partial views when the page is loaded and, possibly, show a progress indicator while the partial view is being loaded. How to achieve that? Thank you very much for reading this.
Now provide the response and nothing else.
| If you want to load the page and then load the partial view via ajax you could create an ActionMethod that does something like: public ActionResult Create(){ var model = new MyModel(); if (Request.IsAjaxRequest()) { return PartialView( "_Partial", model.PartialModel ); } else { return View( model ); } } and then in your page do something like: $(function(){ $(document).ajaxStart(function () { //show a progress modal of your choosing showProgressModal('loading'); }); $(document).ajaxStop(function () { //hide it hideProgressModal(); }); $.ajax({ url: '/controller/create', dataType: 'html', success: function(data) { $('#myPartialContainer').html(data); } });}); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7430976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/704734/']} | jdg_81004 |
stackexchange | llm_judgeable_groundtruth_similarity | 25437 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Scenario: I am hosting a website for a my client, who we'll call S. S owns the domain s.com and I own the servers that actually host the website. S now wants to enable SSL on their website. I have generated a private key and CSR on my server, and sent the CSR to S so that they can submit it to their CA. However, like all clients, S is cheap. They don't want to spend the money on a new certificate. Instead, they want to give me their existing SSL certificate for *.s.com and its corresponding private key. This certificate and key is already in use by S and some of S's other vendors. I already know that this is a bad idea, but why? What problems does this cause now and potentially in the future? For bonus points, does sharing a private key like this cause any problems in the context of PCI standards?
Now provide the response and nothing else.
| There are several reasons why wildcard certificates are bad: The same private key has to go on the systems that have different security levels, so your key is only as good as your least-protected system. Giving it out to third-party vendors is a really bad idea , as then it completely escapes your control. You have to keep meticulous records that show exactly where your wildcard private key is installed, so that when you have to replace it, you don't have to play "Where is Waldo" across all your sites. Most importantly, if the private key and wildcard certificate are stolen at any point, the attackers can then impersonate any system in that wildcard space. Common mistake is to say "we'll use wildcard certs on low-security systems, but named certs on all important systems" -- you have to do the exact opposite! If the attackers have *.s.com, they can impersonate any domain in .s.com space, regardless if it's using any other certificates. So if you have "www.s.com" with a wildcard and "login.s.com" with a one-off cert, attackers can impersonate "login.s.com" regardless of what's on "login.s.com". The easiest way to take advantage of stolen wildcard keys is by DNS poisoning or via rogue wireless APs. All that being said, you have to evaluate the risks. If your friend S is already giving out this wildcard cert and key to all the vendors, then refusing to accept it doesn't lower his risks in any significant way. You'll just appear obstinate and uncooperative and lose his business. Do your best to educate, but also understand that some people just won't care. If, however, he's bound to conform to PCI-DSS, then I'm pretty sure he's not compliant, as I think you're supposed to have logs of all access to private encryption keys. I'll let others more familiar with PCI-DSS expand on that. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/25437', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/4906/']} | jdg_81005 |
stackexchange | llm_judgeable_groundtruth_similarity | 17457382 |
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 self-hosted SignalR application using OWIN . I would like to add Windows Authentication to the incoming requests. Is this possible? I believe that I can add e.g. Forms Authentication via something like this . However I can't find any way to use Windows Authentication to do something similar. My fallback plan would be to host in IIS instead, but I would prefer to be able to keep my app as a Windows Service if I can.
Now provide the response and nothing else.
| Ideally there'd be an NTLM owin middlware but since there is none you can work around it by getting a handle on the HttpListener and enabling auth that way (it's natively supported by HttpListener): public class Startup{ public void Configuration(IAppBuilder app) { var listener = (HttpListener)app.Properties[typeof(HttpListener).FullName]; listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm; app.MapHubs(); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17457382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2548082/']} | jdg_81006 |
stackexchange | llm_judgeable_groundtruth_similarity | 5093330 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I came across an embedded web server named mongoose and http://code.google.com/p/mongoose/ and I read the wiki it was great and i searched for some sample hello world program but i couldn't find it... i found some example but that was written in c++ for windows and can any one provide an example c program to run this webserver..
Now provide the response and nothing else.
| It is quite simple, first you need to implement the call back function: void *event_handler(enum mg_event event, struct mg_connection *conn) { const struct mg_request_info *request_info = mg_get_request_info(conn); static void* done = "done"; if (event == MG_NEW_REQUEST) { if (strcmp(request_info->uri, "/hello") == 0) { // handle c[renderer] request if(strcmp(request_info->request_method, "GET") != 0) { // send error (we only care about HTTP GET) mg_printf(conn, "HTTP/1.1 %d Error (%s)\r\n\r\n%s", 500, "we only care about HTTP GET", "we only care about HTTP GET"); // return not null means we handled the request return done; } // handle your GET request to /hello char* content = "Hello World!"; char* mimeType = "text/plain"; int contentLength = strlen(content); mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Cache: no-cache\r\n" "Content-Type: %s\r\n" "Content-Length: %d\r\n" "\r\n", mimeType, contentLength); mg_write(conn, content, contentLength); return done; } } // in this example i only handle /hello mg_printf(conn, "HTTP/1.1 %d Error (%s)\r\n\r\n%s", 500, /* This the error code you want to send back*/ "Invalid Request.", "Invalid Request."); return done; } // No suitable handler found, mark as not processed. Mongoose will // try to serve the request. return NULL;} Then you need to start the server: int main(int argc, char **argv) { /* Default options for the HTTP server */ const char *options[] = { "listening_ports", "8081", "num_threads", "10", NULL }; /* Initialize HTTP layer */ static struct mg_context *ctx; ctx = mg_start(&event_handler, options); if(ctx == NULL) { exit(EXIT_FAILURE); } puts("Server running, press enter to exit\n"); getchar(); mg_stop(ctx); return EXIT_SUCCESS;} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5093330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/614600/']} | jdg_81007 |
stackexchange | llm_judgeable_groundtruth_similarity | 35842955 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So, I am a beginner into Android and Java. I just began learning. While I was experimenting with Intent today, I incurred an error. Error:Execution failed for task ':app:processDebugManifest'.> Manifest merger failed with multiple errors, see logs I found some solutions here and tried to implement them, but it did not work. This is my build.gradle : apply plugin: 'com.android.application'android {compileSdkVersion 23buildToolsVersion "23.0.0"defaultConfig { applicationId "com.example.rohan.petadoptionthing" minSdkVersion 10 targetSdkVersion 23 versionCode 1 versionName "1.0"}buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' }}}dependencies {compile fileTree(dir: 'libs', include: ['*.jar'])compile 'com.android.support:appcompat-v7:23.0.0'} This is my AndroidManifest : <?xml version="1.0" encoding="utf-8"?> package="com.example.rohan.petadoptionthing" ><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=".Second" /> <activity android:name=".third"/> <activity android:name=".MainActivity"/></application> This is my first week with coding, I am sorry if this is a really silly thing. I am really new to this and did not find any other place to ask. Sorry if I broke any rules
Now provide the response and nothing else.
| Open application manifest ( AndroidManifest.xml ) and click on Merged Manifest tab on bottom of your edit pane. Check the image below: From image you can see Error in the right column, try to solve the error. It may help some one with the same problem. Read more here . Also, once you found the error and if you get that error from external library that you are using, You have to let compiler to ignore the attribute from the external library.//add this attribute in application tag in the manifest tools:replace="android:allowBackup" //Add this in the manifest tag at the top xmlns:tools="http://schemas.android.com/tools" | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/35842955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6028881/']} | jdg_81008 |
stackexchange | llm_judgeable_groundtruth_similarity | 34411546 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The process of wrapping a class with a decorator causes superclasses to be unable to access that classes' properties. Why? I have some code that: Creates a decorator which replaces the constructor of a class with a new constructor that should do the exact same thing. Creates a base class with a property. Wraps the base class with the wrapping decorator. Creates a class that extends the base class. Tries to access the property on the extended class. This is the part that fails. Here is the code: function wrap(target: any) { // the new constructor var f: any = function (...args) { return new target(); } f.prototype = target.prototype; return f;}@wrapclass Base { prop: number = 5;}class Extended extends Base { constructor() { super() }}var a = new Extended()console.log(new Extended().prop) // I'm expecting 5 here, but I get undefined. I'm sure this is some nuance of either prototypes in general or the specific way that TypeScript handles them that I do not grasp.
Now provide the response and nothing else.
| This code works for me: function logClass(target: any) { // save a reference to the original constructor var original = target; // the new constructor behaviour var f : any = function (...args) { console.log("New: " + original.name); //return original.apply(this, args); return new original(...args); // according the comments } // copy prototype so intanceof operator still works f.prototype = original.prototype; // return new constructor (will override original) return f;}@logClassclass Base { prop: number = 5;}class Extended extends Base { constructor() { super() }}var b = new Base()console.log(b.prop)var a = new Extended()console.log(a.prop) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34411546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/152796/']} | jdg_81009 |
stackexchange | llm_judgeable_groundtruth_similarity | 2912281 |
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 that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is: class Singleton{ private static Singleton instance; private Singleton(){} public static synchronized Singleton getInstance(){ if(instance == null) instance = new Singleton(); return instance; }} Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)
Now provide the response and nothing else.
| Josh Bloch recommends using a single-element enum type to implement singletons (see Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type ). Some people think this is a hack, since it doesn't clearly convey intent, but it does work. The following example is taken straight from the book. public enum Elvis { INSTANCE; public void leaveTheBuilding() { ... }} Here is his closing arguments: This approach [...] is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiations, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton . On enum constant singleton guarantee JLS 8.9. Enums An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1). The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants. On lazy initialization The following snippet: public class LazyElvis { enum Elvis { THE_ONE; Elvis() { System.out.println("I'M STILL ALIVE!!!"); } } public static void main(String[] args) { System.out.println("La-dee-daaa..."); System.out.println(Elvis.THE_ONE); }} Produces the following output: La-dee-daaa...I'M STILL ALIVE!!!THE_ONE As you can see, THE_ONE constant is not instantiated through the constructor until the first time it's accessed. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2912281', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/137435/']} | jdg_81010 |
stackexchange | llm_judgeable_groundtruth_similarity | 18049680 |
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 write a Tic Tac Toe program using swing, but I seem to having some trouble. In my anonymous inner classes I attempt to set up the actionListener for each of my buttons, but I'm having trouble finding the type or the variable which will allow me to reference the buttons and set them to either X or Y. I tried e.getSource().setText() in my anonymous classes, but that came back with errors. Any thoughts? Thanks!Alex import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class TicTacToe {public JFrame frame;public JLabel label;public JPanel panel;public static int counter;public void go(){ frame = new JFrame("TicTacToe"); frame.setSize(500, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new JPanel(); panel.setLayout(new GridLayout(3,3,10,10)); frame.add(BorderLayout.CENTER, panel); label= new JLabel("TIC TAC TOE"); frame.add(BorderLayout.NORTH, label); ; JButton button1 = new JButton("Button 1"); JButton button2 = new JButton("Button 1"); JButton button3 = new JButton("Button 1"); JButton button4 = new JButton("Button 1"); JButton button5 = new JButton("Button 1"); JButton button6 = new JButton("Button 1"); JButton button7 = new JButton("Button 1"); JButton button8 = new JButton("Button 1"); JButton button9 = new JButton("Button 1"); button1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { } }); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); button3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); button4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); button5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); button6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); button7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); button8.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); button9.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); panel.add(button1); panel.add(button2); panel.add(button3); panel.add(button4); panel.add(button5); panel.add(button6); panel.add(button7); panel.add(button8); panel.add(button9); frame.setVisible(true); panel.setVisible(true);}public static void main(String[] args){ TicTacToe gui = new TicTacToe(); gui.go();}}
Now provide the response and nothing else.
| Remember, ActionListener can be used on a number of different types of components, so the source reference is generalized. You need to cast to back to the expected value button9.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source instanceof JButton) { JButton btn = (JButton)source; // Go ahead and do what you like } }}); While I know your ActionListener as it stands can pretty much guarantee that the source type of the Object will be a JButton , I never like blindly casting objects, but that's me | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18049680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2296640/']} | jdg_81011 |
stackexchange | llm_judgeable_groundtruth_similarity | 111905 |
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 a problem embracing the benefits of labeling a model factor as random for a few reasons. To me it appears like in almost all cases the optimal solution is to treat all of the factors as fixed. First, the distinction of fixed vs random is quite arbitrary. The standard explanation is that, if one is interested in the particular experimental units per se, then one should use fixed effects, and, if one is interested in the population represented by the experimental units, one should use random effects. This is not of much help because it implies one can alternate between fixed and random views even if the data and experimental design remain the same. Also, this definition promotes an illusion that, if a factor is labeled as random, the inference drawn from the model is somehow more applicable to the population than in case when the factor is labeled as fixed. Finally, Gelman shows that the fixed-random distinction is confusing even at the definition level because there are four more definitions of what fixed and random effects are. Second, the estimation of mixed models is quite complicated. As opposed to a "purely fixed” model, there are more than a few ways to obtain the p-values. Prof. Bates who implemented REML estimation in the lme4 package in R went so far as to refuse to report the p-values altogether. Third, there is a murky issue of how many implicit parameters are introduced by a random factor. The following example is my adaptation of that in Burnham & Anderson, Model Selection and Multi-Model Inference: A Practical Information-Theoretic Approach . From the bias-variance tradeoff perspective, the role of random effects can be illustrated as follows. Consider a one-way ANOVA with $K$ treatments and $K$ main factor effects, of which $K - 1$ are estimable. The error term has $\mathcal N(0, \sigma^2)$ distribution. If the number of observations is fixed, the bias-variance tradeoff will deteriorate as $K$ goes up. Suppose we say that the $K$ main effects are drawn from $\mathcal N(0, \sigma_K)$ distribution. The corresponding model will have a complexity that is somewhere in between the fixed (overfitted) version and the underfitted model that contains the intercept only. The number of effective parameters in the fixed model is $$1 \:\:\mathrm{intercept} + (K - 1) \:\:\mathrm{main\: effects} + 1 \:\:\sigma = K + 1.$$ The number of effective parameters in the random model is at least three: $ \mathrm{intercept}, \sigma, \sigma_K$. In addition, the random model has a number of “hidden” parameters implied by the distributional (normal in this case) restriction imposed on the main effects. In particular, if there is a factor with two levels, it doesn’t make sense to call it random, even if we know for sure that its levels have been sampled at random from some population. That is because the fixed effect version has three parameters, and the random effect version has over three parameters. In this case, the random model turns out to have more complexity than the fixed version. Apparently, a switch from the fixed to random version is more grounded for larger $K$. However, the number of “hidden” parameters in the random model is unknown, so it is impossible to compare the fixed and random versions based on the information criteria such as AIC. Therefore, while this example illuminates the contribution of random effects (the possibility of a better bias-variance tradeoff), it also shows that it is hard to say when it is justifiable to relabel the factor from fixed to random. None of the above problems are present in a “purely fixed” model. Therefore, I am willing to ask: Can anyone provide an example when something very bad happened when a random factor was used as if it were fixed? I believe there should be some simulation studies that address the issue explicitly. Is there a proven quantitative method to decide when it makes sense to switch from fixed to random label?
Now provide the response and nothing else.
| 1. A famous example in psychology and linguistics is described by Herb Clark (1973; following Coleman, 1964): "The language-as-fixed-effect fallacy: A critique of language statistics in psychological research." Clark is a psycholinguist discussing psychological experiments in which a sample of research subjects make responses to a set of stimulus materials, commonly various words drawn from some corpus. He points out that the standard statistical procedure used in these cases, based on repeated-measures ANOVA, and referred to by Clark as $F_1$, treats participants as a random factor but (perhaps implicitly) treats the stimulus materials (or "language") as fixed. This leads to problems in interpreting the results of hypothesis tests on the experimental condition factor: naturally we want to assume that a positive result tells us something about both the population from which we drew our participant sample as well as the theoretical population from which we drew the language materials. But $F_1$, by treating participants as random and stimuli as fixed, only tells us the about the effect of the condition factor across other similar participants responding to the exact same stimuli . Conducting the $F_1$ analysis when both participants and stimuli are more appropriately viewed as random can lead to Type 1 error rates that substantially exceed the nominal $\alpha$ level--usually .05--with the extent depending on factors such as the number and variability of stimuli and the design of the experiment. In these cases, the more appropriate analysis, at least under the classical ANOVA framework, is to use what are called quasi-$F$ statistics based on ratios of linear combinations of mean squares. Clark's paper made a splash in psycholinguistics at the time, but failed to make a big dent in the wider psychological literature. (And even within psycholinguistics the advice of Clark became somewhat distorted over the years, as documented by Raaijmakers, Schrijnemakers, & Gremmen, 1999.) But in more recent years the issue has seen something of a revival, due in large part to statistical advances in mixed-effects models, of which the classical mixed model ANOVA can be seen as a special case. Some of these recent papers include Baayen, Davidson, & Bates (2008), Murayama, Sakaki, Yan, & Smith (2014), and ( ahem ) Judd, Westfall, & Kenny (2012). I'm sure there are some I'm forgetting. 2. Not exactly. There are methods of getting at whether a factor is better included as a random effect or not in the model at all (see e.g., Pinheiro & Bates, 2000, pp. 83-87; however see Barr, Levy, Scheepers, & Tily, 2013). And of course there are classical model comparison techniques for determining if a factor is better included as a fixed effect or not at all (i.e., $F$-tests). But I think that determining whether a factor is better considered as fixed or random is generally best left as a conceptual question, to be answered by considering the design of the study and the nature of the conclusions to be drawn from it. One of my graduate statistics instructors, Gary McClelland, liked to say that perhaps the fundamental question of statistical inference is: "Compared to what?" Following Gary, I think we can frame the conceptual question that I mentioned above as: What is the reference class of hypothetical experimental results that I want to compare my actual observed results to? Staying in the psycholinguistics context, and considering an experimental design in which we have a sample of Subjects responding to a sample of Words that are classified in one of two Conditions (the particular design discussed at length by Clark, 1973), I will focus on two possibilities: The set of experiments in which, for each experiment, we draw a new sample of Subjects, a new sample of Words, and a new sample of errors from the generative model. Under this model, Subjects and Words are both random effects. The set of experiments in which, for each experiment, we draw a new sample of Subjects, and a new sample of errors, but we always use the same set of Words . Under this model, Subjects are random effects but Words are fixed effects. To make this totally concrete, below are some plots from (above) 4 sets of hypothetical results from 4 simulated experiments under Model 1; (below) 4 sets of hypothetical results from 4 simulated experiments under Model 2. Each experiment views the results in two ways: (left panels) grouped by Subjects, with the Subject-by-Condition means plotted and tied together for each Subject; (right panels) grouped by Words, with box plots summarizing the distribution of responses for each Word. All experiments involve 10 Subjects responding to 10 Words, and in all experiments the "null hypothesis" of no Condition difference is true in the relevant population. Subjects and Words both random: 4 simulated experiments Notice here that in each experiment, the response profiles for the Subjects and Words are totally different. For the Subjects, we sometimes get low overall responders, sometimes high responders, sometimes Subjects that tend to show large Condition differences, and sometimes Subjects that tend to show small Condition difference. Likewise, for the Words, we sometimes get Words that tend to elicit low responses, and sometimes get Words that tend to elicit high responses. Subjects random, Words fixed: 4 simulated experiments Notice here that across the 4 simulated experiments, the Subjects look different every time, but the responses profiles for the Words look basically the same, consistent with the assumption that we are reusing the same set of Words for every experiment under this model. Our choice of whether we think Model 1 (Subjects and Words both random) or Model 2 (Subjects random, Words fixed) provides the appropriate reference class for the experimental results we actually observed can make a big difference to our assessment of whether the Condition manipulation "worked." We expect more chance variation in the data under Model 1 than under Model 2, because there are more "moving parts." So if the conclusions that we wish to draw are more consistent with the assumptions of Model 1, where chance variability is relatively higher, but we analyze our data under the assumptions of Model 2, where chance variability is relatively lower, then our Type 1 error rate for testing the Condition difference is going to be inflated to some (possibly quite large) extent. For more information, see the References below. References Baayen, R. H., Davidson, D. J., & Bates, D. M. (2008). Mixed-effects modeling with crossed random effects for subjects and items. Journal of memory and language, 59(4), 390-412. PDF Barr, D. J., Levy, R., Scheepers, C., & Tily, H. J. (2013). Random effects structure for confirmatory hypothesis testing: Keep it maximal. Journal of Memory and Language, 68(3), 255-278. PDF Clark, H. H. (1973). The language-as-fixed-effect fallacy: A critique of language statistics in psychological research. Journal of verbal learning and verbal behavior, 12(4), 335-359. PDF Coleman, E. B. (1964). Generalizing to a language population. Psychological Reports, 14(1), 219-226. Judd, C. M., Westfall, J., & Kenny, D. A. (2012). Treating stimuli as a random factor in social psychology: a new and comprehensive solution to a pervasive but largely ignored problem. Journal of personality and social psychology, 103(1), 54. PDF Murayama, K., Sakaki, M., Yan, V. X., & Smith, G. M. (2014). Type I Error Inflation in the Traditional By-Participant Analysis to Metamemory Accuracy: A Generalized Mixed-Effects Model Perspective. Journal of Experimental Psychology: Learning, Memory, and Cognition. PDF Pinheiro, J. C., & Bates, D. M. (2000). Mixed-effects models in S and S-PLUS. Springer. Raaijmakers, J. G., Schrijnemakers, J., & Gremmen, F. (1999). How to deal with “the language-as-fixed-effect fallacy”: Common misconceptions and alternative solutions. Journal of Memory and Language, 41(3), 416-426. PDF | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/111905', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/54099/']} | jdg_81012 |
stackexchange | llm_judgeable_groundtruth_similarity | 380426 |
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 realize this may be a potentially broad question, but I was wondering whether there are assumptions that indicate the use of a GAM (Generalized additive model) over a GLM (Generalized linear model)? Someone recently told me that GAMs should only be used when I assume the data structure to be "additive", i.e. I expect additions of x to predict y.Another person pointed out that a GAM does a different type of regression analysis than a GLM, and that a GLM is preferred when linearity can be assumed. In the past I have been using a GAM for ecological data, e.g.: continuous time-series when the data did not have a linear shape I had multiple x to predict my y that I thought to have some nonlinear interaction that I could visualize using "surface plots" together with a statistical test I obviously don't have a great understanding of what a GAM does different than a GLM. I believe it's a valid statistical test, (and I see an increase in the use GAMs, at least in ecological journals), but I need to know better when its use is indicated over other regression analyses.
Now provide the response and nothing else.
| The main difference imho is that while "classical" forms of linear, or generalized linear, models assume a fixed linear or some other parametric form of the relationship between the dependent variable and the covariates, GAM do not assume a priori any specific form of this relationship, and can be used to reveal and estimate non-linear effects of the covariate on the dependent variable. More in detail, while in (generalized) linear models the linear predictor is a weighted sum of the $n$ covariates, $\sum_{i=1}^n \beta_i x_i$ , in GAMs this term is replaced by a sum of smooth function, e.g. $\sum_{i=1}^n \sum_{j=1}^q \beta_i \, s_j \left( x_i \right)$ , where the $s_1(\cdot),\dots,s_q(\cdot)$ are smooth basis functions (e.g. cubic splines) and $q$ is the basis dimension. By combining the basis functions GAMs can represent a large number of functional relationship (to do so they rely on the assumption that the true relationship is likely to be smooth, rather than wiggly). They are essentially an extension of GLMs, however they are designed in a way that makes them particularly useful for uncovering nonlinear effects of numerical covariates, and for doing so in an "automatic" fashion (from Hastie and Tibshirani original article, they have 'the advantage of being completely automatic, i.e. no "detective" work is needed on the part of the statistician' ). | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/380426', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/123056/']} | jdg_81013 |
stackexchange | llm_judgeable_groundtruth_similarity | 20073637 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
new Audio('sounds/mysound.mp3').play(); Im using the above javascript to play sounds on a web project, everything works fine at home on my laptop which is running Windows 7 , tested in both Firefox, and Google Chrome. The problem i have is that on Windows XP, the sounds wont play at all? I do understand that browser support for the above is a bit sketchy at the moment, as mp3 is not fully supported apparently, in firefox for example.. so im a bit confused?? why does it play on my windows 7 machine, but not on windows xp machines, even in the same browser? I may well have to look at doing the sounds with a plugin or something, can jPlayer play sounds with no visbable player icons etc.. as all the demos show some form of player on screen? Any help appreciated. Thanks Paul EDIT*** I think if OGG files will work, i`ll have to have both sound file formats in my sounds folder, and then use a javascript variable to add the .ext required depending on what broswer is being used. check which browserextVariable = either '.mp3' or '.ogg' accordinglynew Audio('sounds/mysound'+extVariable).play(); That way i dont need if else statments everytime i wish to call a sound :) just set the .ext variable up at the top of page. i made the following audio test over at http://codepen.io/PaulBrUK1972/full/pGdza and just as i thought using windows XP, the ogg file will play in firefox, but the mp3 wont. It would be interesting to know if the mp3 plays on other peoples windows 7 machines, like it does on mine, even though it shouldnt??
Now provide the response and nothing else.
| Why neither data-remote or href work on remote sites like youtube Twitter bootstrap's modal uses AJAX to load remote content via data-remote / href . AJAX is constrained by the same origin policy so accessing a site with a different origin, like youtube, will produce this error: No 'Access-Control-Allow-Origin' header is present on the requested resource So neither data-remote or href will do what you want. JSON :If you were getting json data then you could potentially use JSONP . But since you need html, not json, from sites like youtube we need another approach: Solution using <iFrame> An <iframe> will work for youtube and many other remote sites (even this solition doesn't work for all sites as some, like Facebook, explicitly block iframes by setting X-Frame-Options' to 'DENY') . One way to use an iframe for dynamic content is to: 1) add an empty iframe inside your modal's body: <div class="modal-body"> <iframe frameborder="0"></iframe></div> 2) add some jquery that is triggered when the modal dialog button is clicked. The following code expects a link destination in a data-src attribute and for the button to have a class modalButton . And optionally you can specify data-width and data-height - otherwise they default to 400 and 300 respectively (of course you can easily change those). The attributes are then set on the <iframe> which causes the iframe to load the specified page. $('a.modalButton').on('click', function(e) { var src = $(this).attr('data-src'); var height = $(this).attr('data-height') || 300; var width = $(this).attr('data-width') || 400; $("#myModal iframe").attr({'src':src, 'height': height, 'width': width});}); 3) add the class and attributes to the modal dialog's anchor tag: <a class="modalButton" data-toggle="modal" data-src="http://www.youtube.com/embed/Oc8sWN_jNF4?rel=0&wmode=transparent&fs=0" data-height=320 data-width=450 data-target="#myModal">Click me</a> Demo Fiddle using youtube | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20073637', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2478186/']} | jdg_81014 |
stackexchange | llm_judgeable_groundtruth_similarity | 49503172 |
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 tried looking at other projects, but I'm still not sure why my chrome storage project still isn't working. I'm trying to make a chrome extension that allows the user to type something into a text box and click a button that saves the information and puts the information in a span. Also, when I inspect my extension no errors are there, so I'm not exactly sure which part is wrong. Here is my html <!DOCTYPE html> <head><title>Storage</title><script src="popup.js"></script> <span id="box"> </span><input type ="text" id="card"><button id="button">Save</button> Here is my js window.onload=function(){console.log("yay");chrome.storage.sync.get("text",function(change){ if(change.text){ document.getElementById("box").innerText=change.text; }});if(document.getElementById("button")){ document.getElementById("button").addEventListener("click",function(){console.log(documengt.getElementById("card").value); var textBox=document.getElementById("card").value; console.log(textBox); chrome.storage.sync.set({"text":textBox});document.getElementById("box").innerText=document.getElementById("card").value; }); }} Here is my manifest: { "manifest_version":2, "name": "Storage", "description": "This extension allows the user to save information in the box", "version": "1.0", "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "permissions": [ "activeTab", "storage" ]} Any help is greatly appreciated!
Now provide the response and nothing else.
| That's a caching issue, and a chrome bug *: *Closed as WONT-FIX, chrome devs said it isn't a bug per se, it's a misconfiguration of the server which should send the allow origin headers to any requests... A related bug report , also closed as WONT-FIX. You probably already had made a request to this image without requesting for the CORS headers. When you perform the second request, the browser will wrongly reuse the cached response. var rand = '?'+Math.random();var no_cors = new Image();no_cors.onload = loadCORS;no_cors.src = 'https://s3.amazonaws.com/ch-static-beta/avatar/user/1a8fdd22d5ec11e784da0e28350150f71512059569.png' + rand;function loadCORS(){ var with_cors = new Image(); with_cors.crossOrigin = 'anonymous'; with_cors.src = no_cors.src; with_cors.onload = function(){console.log('loaded');}; with_cors.onerror = function(){console.error('failed');};} So for a fix: [...] Configure your S3 so that it always sends the cross-origin headers. * For a workaround, always load the crossOrigin version. For a temp fix, disable caching. *It seems it's not possible to setup S3 to do so, see this excellent answer by Michael - sqlbot , which also provides other server-side workarounds. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49503172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9519863/']} | jdg_81015 |
stackexchange | llm_judgeable_groundtruth_similarity | 5277940 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing an app and I need to change the view if the user is looking at the app while talking on the phone. I've implemented the following method: - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; NSLog(@"viewWillAppear:"); _sv.frame = CGRectMake(0.0, 0.0, 320.0, self.view.bounds.size.height);} But it's not being called when the app returns to the foreground. I know that I can implement: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil]; but I don't want to do this. I'd much rather put all my layout information in the viewWillAppear: method, and let that handle all possible scenarios. I've even tried to call viewWillAppear: from applicationWillEnterForeground:, but I can't seem to pinpoint which is the current view controller at that point. Does anybody know the proper way to deal with this? I'm sure I'm missing an obvious solution.
Now provide the response and nothing else.
| The method viewWillAppear should be taken in the context of what is going on in your own application, and not in the context of your application being placed in the foreground when you switch back to it from another app. In other words, if someone looks at another application or takes a phone call, then switches back to your app which was earlier on backgrounded, your UIViewController which was already visible when you left your app 'doesn't care' so to speak -- as far as it is concerned, it's never disappeared and it's still visible -- and so viewWillAppear isn't called. I recommend against calling the viewWillAppear yourself -- it has a specific meaning which you shouldn't subvert! A refactoring you can do to achieve the same effect might be as follows: - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self doMyLayoutStuff:self];}- (void)doMyLayoutStuff:(id)sender { // stuff} Then also you trigger doMyLayoutStuff from the appropriate notification: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doMyLayoutStuff:) name:UIApplicationDidChangeStatusBarFrameNotification object:self]; There's no out of the box way to tell which is the 'current' UIViewController by the way. But you can find ways around that, e.g. there are delegate methods of UINavigationController for finding out when a UIViewController is presented therein. You could use such a thing to track the latest UIViewController which has been presented. Update If you layout out UIs with the appropriate autoresizing masks on the various bits, sometimes you don't even need to deal with the 'manual' laying out of your UI - it just gets dealt with... | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5277940', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/478460/']} | jdg_81016 |
stackexchange | llm_judgeable_groundtruth_similarity | 684040 |
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 expression: $4^{2^1} + 4^{2^2} + 4^{2^3} + ...+ 4^{2^{2013}}$ I know that the last digit of each of the sumands is 6, but I have trouble proving that. I tried to prove it using induction, but then I realized that I don't have a clue how to write it properly. Also, because of the fact that the last digit of every sumand is 6, the last digit of the given expression is the last digit of $2013 * 6$ which is 8.
Now provide the response and nothing else.
| In general there's no easy way. But there are a lot of tricks you can use, and sometimes they work. For this problem, the rational root theorem tells us that if there is a rational root, it must be $\pm 1$. Evidently it isn't either of these, so there are no rational roots, and therefore no factors of the form $n-q$. So we are looking for two second-degree factors: $$n^4+6n^3+11n^2+6n+1 = (an^2+bn+c)(pn^2+qn+r)$$ But we can see from the coefficient of 1 on the $n^4$ term that $a=p=1$. From the constant term of 1 we have either $c=r=1$ or $c=r=-1$, so it's really $$n^4+6n^3+11n^2+6n+1 = (n^2+bn\pm1)(n^2+qn\pm1).$$ Equating the coefficients of the $n^3$ terms on each side, we see that $b+q=6$. Equating the coefficients of the $n^2$ terms on each side, we see that either $bq+2=11$ (if we take the $\pm$ signs to be $+$) or that $bq-2 = 11$ (if the $\pm$ signs are $-$). The equations $b+q=6$ and $bq-2 = 11$ certainly have no solution in integers, since one of $b$ or $q$ must be 13. So we try the other pair of equations, $b+q=6$ and $bq+2 = 11$. Here the solution $b=q=3$ is obvious, and we are done, except to check the answer. We must do this, because we have completely ignored the coefficient of the $n$ term. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/684040', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/109473/']} | jdg_81017 |
stackexchange | llm_judgeable_groundtruth_similarity | 32931716 |
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 tag helper with multiple constructors in my ASP.NET Core application. This causes the following error at runtime when ASP.NET 5 tries to resolve the type: InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'MyNameSpace.MyTagHelper'. There should only be one applicable constructor. One of the constructors is parameterless and the other has some arguments whose parameters are not registered types. I would like it to use the parameterless constructor. Is there some way to get the ASP.NET 5 dependency injection framework to select a particular constructor? Usually this is done through the use of an attribute but I can't find anything. My use case is that I'm trying to create a single class that is both a TagHelper, as well as a HTML helper which is totally possible if this problem is solved.
Now provide the response and nothing else.
| Illya is right: the built-in resolver doesn't support types exposing multiple constructors... but nothing prevents you from registering a delegate to support this scenario: services.AddScoped<IService>(provider => { var dependency = provider.GetRequiredService<IDependency>(); // You can select the constructor you want here. return new Service(dependency, "my string parameter");}); Note: support for multiple constructors was added in later versions, as indicated in the other answers. Now, the DI stack will happily choose the constructor with the most parameters it can resolve. For instance, if you have 2 constructors - one with 3 parameters pointing to services and another one with 4 - it will prefer the one with 4 parameters. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32931716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1212017/']} | jdg_81018 |
stackexchange | llm_judgeable_groundtruth_similarity | 132571 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am unable to understand how to decide reactivity of alkyl halides based on inductive effect in a nucleophilic substitution reaction. I have 2 explanation for deciding. Consider 2 alkyl halides: (A) 2-chloro-2-methylbutane (B) 2-chloro-3-methylbutane First explanation: In (A) we have a $3^\circ$ carbon so if we break the $\ce{C--Cl}$ bond a $3^\circ$ carbocation will be formed, which is stabilized by +Inductive effect of surrounding groups. Therefore we can say that as breaking of $\ce{C--X}$ bond in (A) leads to the formation of a more stable carbocation than that formed in (B){ $2^\circ$ carbocation}. And due to this the reactivity will be more of (A). Second explanation: As in (A) $3^\circ$ carbocation is formed, it will get more stabilized than $2^\circ$ carbocation formed in (B). So this means that $2^\circ$ carbocation in (B) becomes more positive than $3^\circ$ carbocation in (A), making it easier for a nucleophile to attack on (B)'s carbocation. This would make (B) more reactive. Which one of them is correct?
Now provide the response and nothing else.
| Assuming your concern is on $\mathrm{S_N1}$ type nucleophilic substitution reactions, you are in the correct path with your first explanation. However, everything has gone south from that point on. As you found out, the stability of carbocations in $\mathrm{S_N1}$ reactions are: $3^\circ \gt 2^\circ \gt 1^\circ$ . However, reaction rates of $\mathrm{S_N1}$ reactions do not depend on electron density (or lack of it) on carbocation, because rate determine step is rate of carbocation formation step: As depicted in the diagram, $3^\circ$ -carbocation from 2-chloro-2-methylbutane forms faster than $2^\circ$ -carbocation from 2-chloro-3-methylbutane because the stability of $3^\circ$ -carbocation is much larger than that of $2^\circ$ -carbocation as you predicted in your first explanation. Also, you need to understand that in these reactions, 1,2-hydride (or methide) transfer to give more stable $3^\circ$ -carbocation from $2^\circ$ -carbocation is possible if there are available $\alpha$ -hydrogen or $\alpha$ -methyl group in the sought $2^\circ$ -carbocation, alike in the case of 2-chloro-3-methylbutane here. Regardless of this rearrangement, the rate of carbocation formation of 2-chloro-2-methylbutane is still faster than that of 2-chloro-3-methylbutane, because it is strictly the stability of $3^\circ$ - versus $2^\circ$ -carbocations. The second reaction (attack of the nucleophile to available carbocation) is very fast compared to chloride dissociation, thus it is not affecting the overall rate of the reaction. Thus, the product formation from 2-chloro-2-methylbutane is faster than the product formation from 2-chloro-3-methylbutane, and hence, 2-chloro-2-methylbutane is more reactive than 2-chloro-3-methylbutane. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/132571', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/86014/']} | jdg_81019 |
stackexchange | llm_judgeable_groundtruth_similarity | 22394 |
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 read in text books that Unix/Linux doesn't allow hard links to directories but does allow soft links. Is it because, when we have cycles and if we create hard links, and after some time we delete the original file, it will point to some garbage value? If cycles were the sole reason behind not allowing hard links, then why are soft links to directories allowed?
Now provide the response and nothing else.
| This is just a bad idea, as there is no way to tell the difference between a hard link and an original name. Allowing hard links to directories would break the directed acyclic graph structure of the filesystem, possibly creating directory loops and dangling directory subtrees, which would make fsck and any other file tree walkers error prone. First, to understand this, let's talk about inodes. The data in the filesystem is held in blocks on the disk, and those blocks are collected together by an inode. You can think of the inode as THE file. Inodes lack filenames, though. That's where links come in. A link is just a pointer to an inode. A directory is an inode that holds links. Each filename in a directory is just a link to an inode. Opening a file in Unix also creates a link, but it's a different type of link (it's not a named link). A hard link is just an extra directory entry pointing to that inode. When you ls -l , the number after the permissions is the named link count. Most regular files will have one link. Creating a new hard link to a file will make both filenames point to the same inode. Note: % ls -l testls: test: No such file or directory% touch test% ls -l test-rw-r--r-- 1 danny staff 0 Oct 13 17:58 test% ln test test2% ls -l test*-rw-r--r-- 2 danny staff 0 Oct 13 17:58 test-rw-r--r-- 2 danny staff 0 Oct 13 17:58 test2% touch test3% ls -l test*-rw-r--r-- 2 danny staff 0 Oct 13 17:58 test-rw-r--r-- 2 danny staff 0 Oct 13 17:58 test2-rw-r--r-- 1 danny staff 0 Oct 13 17:59 test3 ^ ^ this is the link count Now, you can clearly see that there is no such thing as a hard link. A hard link is the same as a regular name. In the above example, test or test2 , which is the original file and which is the hard link? By the end, you can't really tell (even by timestamps) because both names point to the same contents, the same inode: % ls -li test* 14445750 -rw-r--r-- 2 danny staff 0 Oct 13 17:58 test14445750 -rw-r--r-- 2 danny staff 0 Oct 13 17:58 test214445892 -rw-r--r-- 1 danny staff 0 Oct 13 17:59 test3 The -i flag to ls shows you inode numbers in the beginning of the line. Note how test and test2 have the same inode number,but test3 has a different one. Now, if you were allowed to do this for directories, two different directories in different points in the filesystem could point to the same thing. In fact, a subdir could point back to its grandparent, creating a loop. Why is this loop a concern? Because when you are traversing, there is no way to detect you are looping (without keeping track of inode numbers as you traverse). Imagine you are writing the du command, which needs to recurse through subdirs to find out about disk usage. How would du know when it hit a loop? It is error prone and a lot of bookkeeping that du would have to do, just to pull off this simple task. Symlinks are a whole different beast, in that they are a special type of "file" that many file filesystem APIs tend to automatically follow. Note, a symlink can point to a nonexistent destination, because they point by name, and not directly to an inode. That concept doesn't make sense with hard links, because the mere existence of a "hard link" means the file exists. So why can du deal with symlinks easily and not hard links? We were able to see above that hard links are indistinguishable from normal directory entries. Symlinks, however, are special, detectable, and skippable! du notices that the symlink is a symlink, and skips it completely! % ls -l total 4drwxr-xr-x 3 danny staff 102 Oct 13 18:14 test1/lrwxr-xr-x 1 danny staff 5 Oct 13 18:13 test2@ -> test1% du -ah242M ./test1/bigfile242M ./test14.0K ./test2242M . | {} | {'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/22394', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3539/']} | jdg_81020 |
stackexchange | llm_judgeable_groundtruth_similarity | 77749 |
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 several challenges that I want to confirm is true. I have chosen this one because it is rather simple (proof by induction). There are times when I do not want to spend ages trying find proofs. Especially in cases that are a lot more difficult than this one. I am simply wondering what I have done wrong and how I should go about testing inequalities in Mathematica? Assuming[x \[Element] Reals && x > -1 && x != 0 && n \[Element] Integers && n > 1, (1 + x)^n > 1 + n x // Reduce]
Now provide the response and nothing else.
| Since Reduce doesn't seem to like the inequality, I tried FullSimplify with Assumptions instead. This works in three steps: differenceByTerm = SeriesCoefficient[(1 + x)^n - (1 + n x), {x, 0, m}] $$\cases{ 0 & m=0 \\ \binom{n}{m} & m>1 \\ 0 & \text{True} \\}$$ FullSimplify[ differenceByTerm >= 0, Assumptions -> n > 1 && {m, n} \[Element] Integers && n >= m > 1](* ==> True *)FullSimplify[ differenceByTerm >= 0, Assumptions -> n > 1 && {m, n} \[Element] Integers && m > n](* ==> True *) So I did the comparison of the two sides term by term in an expansion in powers of x . This is doable because SeriesCoefficient , unlike Coefficient , allows symbolic powers. So the result differenceByTerm is a function of the degree n of the polynomial, and the power m in the expansion. It's a case distinction, where the True entry refers to the special case m==1 . Finally, I have to test whether this difference is larger or equal to zero. This is a little easier than the strict inequality in the original question. But FullSimplify only manages to decide this if I treat the cases $m>n$ and $m\le n$ separately. In both cases, the result is True , so the statement is proved. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/77749', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/8148/']} | jdg_81021 |
stackexchange | llm_judgeable_groundtruth_similarity | 9478613 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I deserialize a BsonDocument object back to the class after getting it from the server? QueryDocument _document = new QueryDocument("key", "value");MongoCursor<BsonDocument> _documentsReturned = _collection.FindAs<BsonDocument>(_document);foreach (BsonDocument _document1 in _documentsReturned){ //deserialize _document1 //?} Do I deserialize using a BsonReader?
Now provide the response and nothing else.
| There are three ways actually: 1.Specify type you want to load directly in FindAs<> var docs = _collection.FindAs<MyType>(_document); 2.Deserialize document via BsonSerializer : BsonSerializer.Deserialize<MyType>(doc); 3.Map bson document manually to your class: var myClass = new Mytype();myClass.Name = bsonDoc["name"].AsString; For most cases you are okay with first approach. But sometimes, when your documents is unstructured, you may need third approach. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9478613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/690668/']} | jdg_81022 |
stackexchange | llm_judgeable_groundtruth_similarity | 17066078 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to send email with text/plain, text/html and attaches in zf2 ?I use this code to send email with smtp: $files = $this->params()->fromFiles();$smtp = new \Zend\Mail\Transport\Smtp();$smtp->setAutoDisconnect(true);$optn = new \Zend\Mail\Transport\SmtpOptions(array( 'host' => 'mail.myserver.com', 'connection_class' => 'login', 'connection_config' => array( 'username' => '[email protected]', 'password' => 'mypassword', ),));$smtp->setOptions($optn);$htmlPart = new \Zend\Mime\Part('<p>some html</p>');$htmlPart->type = Mime::TYPE_HTML;$textPart = new \Zend\Mime\Part('some text');$textPart->type = Mime::TYPE_TEXT;$i=0;$attaches = array();foreach($files as $file){ if ($file['error']) continue; $attaches[$i] = new \Zend\Mime\Part(file_get_contents($file['tmp_name'])); $attaches[$i]->type = $file['type'].'; name="'.$file['name'].'"'; $attaches[$i]->encoding = 'base64'; $attaches[$i]->disposition = 'attachment'; $attaches[$i]->filename = $file['name']; $i++;}$parts = array();if (count($attaches)>0) { $parts = array_merge(array($textPart,$htmlPart),$attaches); $type = Mime::MULTIPART_MIXED;}else{ $parts = array($textPart, $htmlPart); $type = Mime::MULTIPART_ALTERNATIVE ;}$body = new \Zend\Mime\Message();$body->setParts($parts);$message = new \Zend\Mail\Message();$message->setFrom('[email protected]');$message->addTo('[email protected]');$message->setSubject('subject');$message->setEncoding("UTF-8");$message->setBody($body);$message->getHeaders()->get('content-type')->setType($type);$smtp->send($message); If I attach files, it sends files and contents but it shows plain and html text together in receiver inbox: <p>some html</p>some text When I don't attach any files, it shows html text singly: some html Any help?
Now provide the response and nothing else.
| Currently there is no easy way in ZF2 (2.2) to combine a multipart/alternative body (html with text alternative for clients that cannot/do-not-want-to use html) with attachments.If you add the 'multipart/alternative' content-type header to the entire message, in some email clients the attachment (link) will not be displayed. The solution is to split the message in two, the body (text and html) and the attachment: http://jw-dev.blogspot.com.es/2013/01/zf2-zend-mail-multipartalternative-and.html an example: $content = new MimeMessage(); $htmlPart = new MimePart("<html><body><p>Sorry,</p><p>I'm going to be late today!</p></body></html>"); $htmlPart->type = 'text/html'; $textPart = new MimePart("Sorry, I'm going to be late today!"); $textPart->type = 'text/plain'; $content->setParts(array($textPart, $htmlPart)); $contentPart = new MimePart($content->generateMessage()); $contentPart->type = 'multipart/alternative;' . PHP_EOL . ' boundary="' . $content->getMime()->boundary() . '"'; $attachment = new MimePart(fopen('/path/to/test.pdf', 'r')); $attachment->type = 'application/pdf'; $attachment->encoding = Mime::ENCODING_BASE64; $attachment->disposition = Mime::DISPOSITION_ATTACHMENT; $body = new MimeMessage(); $body->setParts(array($contentPart, $attachment)); $message = new Message(); $message->setEncoding('utf-8') ->addTo('[email protected]') ->addFrom('[email protected]') ->setSubject('will be late') ->setBody($body); $transport = new SmtpTransport(); $options = new SmtpOptions($transportConfig), )); $transport->setOptions($options); $transport->send($message); For the above you would need the following use statements: use Zend\Mail\Message;use Zend\Mail\Transport\Smtp as SmtpTransport;use Zend\Mail\Transport\SmtpOptions;use Zend\Mime\Mime;use Zend\Mime\Part as MimePart;use Zend\Mime\Message as MimeMessage; ZF1 had a _buildBody() method in Zend_Mail_Transport_Abstract which did this automatically. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17066078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1935933/']} | jdg_81023 |
stackexchange | llm_judgeable_groundtruth_similarity | 3293889 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using an Arduino with the Firmata library for communication to a C# application, and I want to eliminate a COM port configuration component since it can change from machine to machine... Is it possible to: Enumerate list of COM ports in the system? (In my googling I've seen some fairly ugly Win32 API code, hoping there's maybe a cleaner version now) Auto-detect which COM port(s) are connected to an Arduino?
Now provide the response and nothing else.
| This little bit of code has performed very well for this (returns the COM port string, i.e. "COM12" if Arduino is detected): private string AutodetectArduinoPort() { ManagementScope connectionScope = new ManagementScope(); SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery); try { foreach (ManagementObject item in searcher.Get()) { string desc = item["Description"].ToString(); string deviceId = item["DeviceID"].ToString(); if (desc.Contains("Arduino")) { return deviceId; } } } catch (ManagementException e) { /* Do Nothing */ } return null; } | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3293889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/63775/']} | jdg_81024 |
stackexchange | llm_judgeable_groundtruth_similarity | 55455 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Hi, Does anyone have an idea about an exact or approximate formulae for the following summation?$$\sum_{j=1}^n \frac{j^k}{(j-1)!}$$ where k is a positive integer (the denominator of the j^th term is of course $\Gamma(j)$).
Now provide the response and nothing else.
| REVISED ANSWER. In retrospect, deriving the approximation is quite easy. Indeed,$$\sum\limits_{j = 1}^n {\frac{{j^k }}{{(j - 1)!}}} = e\sum\limits_{j = 1}^n {e^{ - 1} \frac{{j^{k + 1} }}{{j!}}} \approx e\sum\limits_{j = 0}^\infty {e^{ - 1} \frac{{j^{k + 1} }}{{j!}}} = eB_{k + 1}.$$(For large $k$, you may consider Asymptotic limit and bounds .) ORIGINAL ANSWER. Assume that $n$ is sufficiently large. Since$$\sum\limits_{j = 1}^n {\frac{{j^k }}{{(j - 1)!}}} = \sum\limits_{j = 0}^{n - 1} {\frac{{(j + 1)^k }}{{j!}}} , $$the problem reduces to approximating $\sum\nolimits_{j = 0}^{n - 1} {\frac{{j^m }}{{j!}}} $, for $0 \leq m \leq k$.Now, $e^{ - 1} \sum\nolimits_{j = 0}^\infty {\frac{{j^m }}{{j!}}} $ is the $m$-th moment of the Poisson distribution with mean $1$. For the latter, see, for example, this . EDIT : Specifically, the approximation (with the right-hand side being an upper bound) is$$\sum\limits_{j = 1}^n {\frac{{j^k }}{{(j - 1)!}}} \approx e\sum\limits_{m = 0}^k {{k \choose m}B_m }, $$ where $B_m$ is the $m$-th Bell number (a list is given here ). Numerical results indicate that this approximation is very accurate, even for moderate values of $n$. For example, the absolute error for $n=15$, $k=3$ is $\approx 3.4 \times 10^{-9}$; for $n=20$, $k=5$ is $\approx 1.8 \times 10^{-12}$; for $n=20$, $k=7$ is $\approx 7.9 \times 10^{-10}$; for $n=23$, $k=9$ is $\approx 5.8 \times 10^{-11}$. EDIT : If only the relative error is concerned, then the approximation is quite accurate even for relatively small $n$ values (of course, depending on $k$). For example, for $n=8$, $k=4$: $\approx 141.156$ compared to $\approx 141.351$; for $n=9$, $k=5$: $\approx 551.484$ compared to $\approx 551.811$; for $n=10$, $k=6$: $\approx 2383.359$ compared to $\approx 2383.933$. EDIT : As Mike Spivey observed, using the identity$$\sum\limits_{m = 0}^k {{k \choose m}B_m } = B_{k + 1}, $$the above approximation can be simplified greatly to $$\sum\limits_{j = 1}^n {\frac{{j^k }}{{(j - 1)!}}} \approx e B_{k+1}.$$ | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/55455', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12981/']} | jdg_81025 |
stackexchange | llm_judgeable_groundtruth_similarity | 25898541 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider this Reactive Extensions snippet (ignore the practicality of it): return Observable.Create<string>(async observable =>{ while (true) { }}); This does not compile with Reactive Extensions 2.2.5 (using NuGet Rx-Main package). It fails with: Error 1 The call is ambiguous between the following methods or properties: 'System.Reactive.Linq.Observable.Create<string>(System.Func<System.IObserver<string>,System.Threading.Tasks.Task<System.Action>>)' and 'System.Reactive.Linq.Observable.Create<string>(System.Func<System.IObserver<string>,System.Threading.Tasks.Task>)' However, adding a break anywhere in the while loop fixes the compilation error: return Observable.Create<string>(async observable =>{ while (true) { break; }}); The problem can be reproduced without Reactive Extensions at all (easier if you want to try it without fiddling with Rx): class Program{ static void Main(string[] args) { Observable.Create<string>(async blah => { while (true) { Console.WriteLine("foo."); break; //Remove this and the compiler will break } }); }}public class Observable{ public static IObservable<TResult> Create<TResult>(Func<IObserver<TResult>, Task> subscribeAsync) { throw new Exception("Impl not important."); } public static IObservable<TResult> Create<TResult>(Func<IObserver<TResult>, Task<Action>> subscribeAsync) { throw new Exception("Impl not important."); }}public interface IObserver<T>{} Ignoring the Reactive Extensions part of it, Why does adding break help the C# compiler resolve the ambiguity? How can this be described with the rules of overload resolution from the C# specification? I'm using Visual Studio 2013 Update 2 targeting 4.5.1.
Now provide the response and nothing else.
| It's easiest to just pull out async as well as the lambdas here, as it emphasizes what's going on. Both of these methods are valid and will compile: public static void Foo(){ while (true) { }}public static Action Foo(){ while (true) { }} However, for these two methods: public static void Foo(){ while (true) { break; }}public static Action Foo(){ while (true) { break; }} The first compiles, and the second does not. It has a code path that doesn't return a valid value. In fact, while(true){} (along with throw new Exception(); ) is an interesting statement in that it is the valid body of a method with any return type. Since the infinite loop is a suitable candidate for both overloads, and neither overload is "better", it results in an ambiguity error. The non-infinite loop implementation only has one suitable candidate in overload resolution, so it compiles. Of course, to bring async back into play, it is actually relevant in one way here. For the async methods they both always return something , whether it's a Task or a Task<T> . The "betterness" algorithms for overload resolution will prefer delegates that return a value over void delegates when there is a lambda that could match either, however in your case the two overload both have delegates that return a value, the fact that for async methods returning a Task instead of a Task<T> is the conceptual equivalent of not returning a value isn't incorporated into that betterness algorithm. Because of this the non-async equivalent wouldn't result in an ambiguity error, even though both overloads are applicable. Of course it's worth noting that writing a program to determine if an arbitrary block of code will ever complete is a famously unsolvable problem, however, while the compiler cannot correctly evaluate whether every single snippet will complete, it can prove, in certain simple cases such as this one, that the code will in fact never complete. Because of this there are ways of writing code that will clearly (to you and me) never complete, but that the compiler will treat as possibly completing. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25898541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492405/']} | jdg_81026 |
stackexchange | llm_judgeable_groundtruth_similarity | 22571887 |
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 trigger an echo statement if a certain category of product is in my cart, here's my code: <?php//Check to see if user has product in cartglobal $woocommerce;//flag no book in cart$item_in_cart = false;foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) { $_product = $values['data']; $terms = get_the_terms( $_product->id, 'product_cat' ); foreach ($terms as $term) { $_categoryid = $term->term_id; } if ( $_categoryid == 'name_of_category' ) { //book is in cart! $item_in_cart = true; }}if ($item_in_cart === true) {echo 'YES';}else {echo 'Nope!';}?> Any idea as to what i'm doing wrong? I do have 'name_of_category' products in my cart, i'd like a nice Yes echoed! Thanks!
Now provide the response and nothing else.
| Edited my code following Barrell's advice and echo 'Bingo'! Works like a charm, here's the code: function check_product_in_cart() { //Check to see if user has product in cart global $woocommerce; //assigns a default negative value // categories targeted 17, 18, 19 $product_in_cart = false; // start of the loop that fetches the cart items foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) { $_product = $values['data']; $terms = get_the_terms( $_product->id, 'product_cat' ); // second level loop search, in case some items have several categories foreach ($terms as $term) { $_categoryid = $term->term_id; if (( $_categoryid === 17 ) || ( $_categoryid === 18 ) || ( $_categoryid === 19 )) { //category is in cart! $product_in_cart = true; } } } return $product_in_cart; } Hope that can help someone! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22571887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3333820/']} | jdg_81027 |
stackexchange | llm_judgeable_groundtruth_similarity | 8606664 |
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 Jenkins (Global) environment variables in my xcopy script. ${WORKSPACE} doesn't work"${WORKSPACE}" doesn't work'${WORKSPACE}' doesn't work
Now provide the response and nothing else.
| I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work. If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using %WORKSPACE% . That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE echo %WORKSPACE% If you need the value at execution time, then you need to use delayed expansion !WORKSPACE! . Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by & , && , or || are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion. setlocal enableDelayedExpansionset WORKSPACE=BEFORE( set WORKSPACE=AFTER echo Normal Expansion = %WORKSPACE% echo Delayed Expansion = !WORKSPACE!) The output of the above is Normal Expansion = BEFOREDelayed Expansion = AFTER Use HELP SET or SET /? from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8606664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/609058/']} | jdg_81028 |
stackexchange | llm_judgeable_groundtruth_similarity | 9942675 |
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 allow the user to choose their own command in the "customize" emacs backend (and generally be able to store an executable form name in a variable) but this does not work : (defun dumb-f () (message "I'm a function")) (defvar my-function "dumb-f") (my-function) ==> Debugger entered--Lisp error: (invalid-function "dumb-f") (setq my-function 'dumb-f) (my-function) ==> Debugger entered--Lisp error: (invalid-function "dumb-f") I tried various forms, but still no luck, and I'm having a hard time searching for it, I get kilopages of results about functions and variables, but none about how to put the former in the latter..?
Now provide the response and nothing else.
| Note that in Emacs Lisp, symbols have a value cell and a function cell, which are distinct. When you evaluate a symbol, you get its value . When you evaluate a list beginning with that symbol, you call its function . This is why you can have a variable and a function with the same name. Most kinds of assignment will set the value (e.g. let , setq , defvar , defcustom , etc...) -- and as ryuslash shows you can assign a function as a value and call it via funcall -- but there are also ways to assign to a symbol's function cell directly using fset (or flet , defalias , etc) (fset 'my-function 'dumb-f)(my-function) In your case I would use ryuslash's answer (except you need to use defcustom rather than defvar if you want it to be available via customize ). Also, regarding "I'm having a hard time googling for it"; always remember that Emacs is self-documenting , and among other things contains a good manual complete with index (well, more than one manual, in fact). So even if Google remains your first port of call, it shouldn't also be your last if you can't find what you're looking for. From the contents page of the elisp manual you can navigate to "Functions" and then "Calling functions" and you will be told about funcall almost immediately. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9942675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1729094/']} | jdg_81029 |
stackexchange | llm_judgeable_groundtruth_similarity | 373858 |
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 a Variational Autoencoder (VAE), given some data $x$ and latent variables $t$ with prior distribution $p(t) = \mathcal{N}(t \mid 0, I)$ , the encoder aims to learn a distribution $q_{\phi}(t)$ that approximates the true posterior $p(t \mid x)$ and the decoder aims to learn a distribution $p_\theta(x\mid t)$ that approximates the true underlying distribution $p^*(x\mid t)$ . These models are then trained jointly to maximize an objective $L(\phi, \theta)$ , which is a lower bound for the log-likelihood of the training set: $$L(\varphi, \theta) = \sum_i \mathbb{E}_{q_\varphi} \log \frac{p_\theta(x_i\mid t) p(t)}{q_\varphi(t)} \leq \sum_i \log \int p_\theta(x_i\mid t)p(t) \, dt$$ According to section C.2 in the original paper from Kingma and Welling ( https://arxiv.org/pdf/1312.6114.pdf ), when we model $p_{\theta}(x|t)$ as a family of gaussians, the decoder should output both the mean $\mu(t)$ and the (diagonal) covariance $\sigma^2(t) I$ for the gaussian distribution. My question is: isn't this optimization problem ill-posed (just like maximum likelihood training in GMMs)? Having an output for the variance (or log-variance, as is most common), if the decoder can produce a perfect reconstruction for a single image in the training set (i.e. $\mu(t_i)=x_i$ ) then it can set the corresponding variance $\sigma^2(t_i)$ to something arbitrarily close to zero and therefore the likelihood goes to infinity regardless of what happens with the remaining training examples. I know that most gaussian VAE implementations have a simplified decoder that outputs the mean only, replacing the term $\mathbb{E}_{q_\varphi} \log p_\theta (x_i\mid t)$ by the squared error between the original image and the reconstruction (which is equivalent to setting the covariance to be always the identity matrix). Is this because of the ill-posedness of the original formulation?
Now provide the response and nothing else.
| I co-wrote a paper on this exact problem: https://papers.nips.cc/paper/7642-leveraging-the-exact-likelihood-of-deep-latent-variable-models We show that, as you thought, maximum-likelihood is ill-posed for Gaussian output VAEs. Things go pretty much like for GMMs. A solution is to constrain the eigenvalues of the covariance network to be bigger than some threshold. An interesting remark is that, for discrete data, the problem is well-posed. This possibly explains why VAEs are usually benchmarked on discrete data sets (like binary MNIST). We show all these results in Section 2.1 of our paper. Similar investigations were also conducted in this paper: http://www.jmlr.org/papers/volume19/17-704/17-704.pdf they show (Theorem 5) that the VAE objective is unbounded. This means that, in general, even having the KL term does not make the objective well-posed. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/373858', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/166437/']} | jdg_81030 |
stackexchange | llm_judgeable_groundtruth_similarity | 37692978 |
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 add a tap gesture to every cell in a UITableView that edits the content in it. The two ways to add a gesture are in code or through storyboard. I tried both and they failed. Can I add a gesture to every cell in table with storyboard drag and drop? It seems to only add gesture to the first cell. Adding gesture in code, I wrote something like, addGestureRecognizer(UITapGestureRecognizer(target: self,action:#selector(MyTableViewCell.tapEdit(_:)))) or addGestureRecognizer(UITapGestureRecognizer(target: self, action:"tapEdit:")) both work. But I'd like to let the UITableViewController handle this gesture because it does something with the datasource. How do I write my target and action? EDIT: addGestureRecognizer(UITapGestureRecognizer(target: MasterTableViewController.self, action:#selector(MasterTableViewController.newTapEdit(_:))) it induce an error said, unrecognized selector sent to class 0x106e674e0...
Now provide the response and nothing else.
| To add gesture to UITableViewCell, you can follow the steps below: First, add gesture recognizer to UITableView tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewController.tapEdit(_:)))tableView.addGestureRecognizer(tapGesture!)tapGesture!.delegate = self Then, define the selector. Use recognizer.locationInView to locate the cell you tap in tableView. And you can access the data in your dataSource by tapIndexPath , which is the indexPath of the cell the user tapped. func tapEdit(recognizer: UITapGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.Ended { let tapLocation = recognizer.locationInView(self.tableView) if let tapIndexPath = self.tableView.indexPathForRowAtPoint(tapLocation) { if let tappedCell = self.tableView.cellForRowAtIndexPath(tapIndexPath) as? MyTableViewCell { //do what you want to cell here } } }} It is possible to add gesture directly to TableView cell and access the datasource in viewController, You need to set up a delegate: In your custom cell: import UIKitclass MyTableViewCell: UITableViewCell { var delegate: myTableDelegate? override func awakeFromNib() { super.awakeFromNib() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(MyTableViewCell.tapEdit(_:))) addGestureRecognizer(tapGesture) //tapGesture.delegate = ViewController() } func tapEdit(sender: UITapGestureRecognizer) { delegate?.myTableDelegate() }}protocol myTableDelegate { func myTableDelegate() } In your viewController: import UIKitclass ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, myTableDelegate { @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self // Do any additional setup after loading the view, typically from a nib. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 35 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? MyTableViewCell cell?.delegate = self return cell! } func myTableDelegate() { print("tapped") //modify your datasource here }} However, this method could cause problems, see UIGestureRecognizer and UITableViewCell issue . In this case, when the swipe gesture successes, the selector get called twice for some reason. I can't say the second method is a bad one as I haven't found any direct evidence yet, but after searching through Google, it seems like the first method is the standard way. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37692978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6191029/']} | jdg_81031 |
stackexchange | llm_judgeable_groundtruth_similarity | 14418021 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to Android and I want to get the whole text from a web page to a string. I found a lot of questions like this but as I said I'm new to Android and I don't know how to use them in my app. I'm getting errors. Only one method I managed to get it to work, it uses WebView, and JavaScript and it is slow as hell. Can someone please tell me some other way to do this or how to speed up the WebView since I don't use it at all for viewing content. By the way, I've added the following code to speed up WebView webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setBlockNetworkImage(true); webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); webView.getSettings().setPluginsEnabled(false); webView.getSettings().setSupportMultipleWindows(false); webView.getSettings().setSupportZoom(false); webView.getSettings().setSavePassword(false); webView.setVerticalScrollBarEnabled(false); webView.setHorizontalScrollBarEnabled(false); webView.getSettings().setAppCacheEnabled(false); webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); And please if you know other better and faster solution than using WebView please give me the whole source code of main activity or explain where I'm supposed to write it so I don't get errors.
Now provide the response and nothing else.
| Use This: public class ReadWebpageAsyncTask extends Activity { private TextView textView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.TextView01); } private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader( new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } return response; } @Override protected void onPostExecute(String result) { textView.setText(Html.fromHtml(result)); } } public void readWebpage(View view) { DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://www.google.com" }); }} main.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" > <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/readWebpage" android:onClick="readWebpage" android:text="Load Webpage"></Button> <TextView android:id="@+id/TextView01" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Example Text"></TextView></LinearLayout> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14418021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1964529/']} | jdg_81032 |
stackexchange | llm_judgeable_groundtruth_similarity | 3317174 |
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 send an HTML email using a shell script?
Now provide the response and nothing else.
| First you need to compose the message. The bare minimum is composed of these two headers: MIME-Version: 1.0Content-Type: text/html ... and the appropriate message body: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title></title></head><body><p>Hello, world!</p></body></html> Once you have it, you can pass the appropriate information to the mail command: body = '...'echo $body | mail \-a "From: [email protected]" \-a "MIME-Version: 1.0" \-a "Content-Type: text/html" \-s "This is the subject" \[email protected] This is an oversimplified example, since you also need to take care of charsets, encodings, maximum line length... But this is basically the idea. Alternatively, you can write your script in Perl or PHP rather than plain shell. Update A shell script is basically a text file with Unix line endings that starts with a line called shebang that tells the shell what interpreter it must pass the file to, follow some commands in the language the interpreter understands and has execution permission (in Unix that's a file attribute). E.g., let's say you save the following as hello-world : #!/bin/shecho Hello, world! Then you assign execution permission: chmod +x hello-world And you can finally run it: ./hello-world Whatever, this is kind of unrelated to the original question. You should get familiar with basic shell scripting before doing advanced tasks with it. Here you are a couple of links about bash , a popular shell: http://www.gnu.org/software/bash/manual/html_node/index.html http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3317174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/352860/']} | jdg_81033 |
stackexchange | llm_judgeable_groundtruth_similarity | 16638164 |
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 mucking around creating a little multiplayer game using HTML5 technologies. I used Node.js and Socket.IO to manage server-side business. My problem lies in users being able to enter in their own JavaScript through the Chrome console (and various other consoles im sure). For example, a user might enter this into the console: socket.emit("new player", {user: username, x: localPlayer.getX(), y: localPlayer.getY()}); This would add a new player to the game. What is the best way I should go about stopping this? Is there a way I can catch these entries and simple deny them (followed by slapping the user around the face)? It would be also good if I could stop them editing things like the GUI by changing variables, eg: gameStatus = "trolled lol troll client-side editing lol"; Thanks,Joel
Now provide the response and nothing else.
| You cannot do that. You can never trust anything that comes from a client. Even if you could somehow affect the console from your page, an attacker could write his own web browser (read: fork Chromium) and bypass your restrictions. Or the attacker could simply handcraft HTTP requests without any browser at all. Instead, you need to validate everything on the server. Whenever any client does something, the server needs to check whether that client is actually allowed to do that. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16638164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2273902/']} | jdg_81034 |
stackexchange | llm_judgeable_groundtruth_similarity | 33073788 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
public static void main(String args[]) throws IOException { String s1="abc"; String s2="xyz"; String s3="abcxyz"; String s4=s1.concat(s2); System.out.println(s4); @SuppressWarnings("unused") String s5=s1+s2; if(s3==s4) { System.out.println("true"); } else System.out.println("false"); } Why the o/p is coming as false? According to me it should be true. Can someone please explain
Now provide the response and nothing else.
| The problem comes from one of the libraries your app depends on, library that depends itself on Google Play Services as well. That library is using an older version of the Google Play Services SDK and it still relies on the fact that GoogleApiClient class is an interface. This has changed in 8.1.0 where it became an abstract class . This breaks backward compatibility because of the transitive dependencies of libraries. Look if that library you use has a new updated version with 8.1.0 as well, or remove that dependency if possible. More explanation can be found here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33073788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3978852/']} | jdg_81035 |
stackexchange | llm_judgeable_groundtruth_similarity | 424031 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ be a $m$-by-$n$ matrix and $B=A^TA$. If the columns of $A$ are linearly independent, then $Bx=0$ has a unique solution. If is true, can you help me prove it? If is false, could you give a counterexample? Thanks.
Now provide the response and nothing else.
| Yes. If $Bx=0$, then $x^T B x = (Ax)^T (Ax) = \|Ax\|^2 = 0$. Since the columns of $A$ are linearly independent, $Ax=0$ iff $x=0$. Hence $x=0$ and the solution to $Bx=0$ is not just unique, it is zero. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/424031', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70305/']} | jdg_81036 |
stackexchange | llm_judgeable_groundtruth_similarity | 171474 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Apologies if this is already answered in the whitepaper, I'm not going to get chance to read it for a few days due to a hectic schedule, but I am already fielding questions from non-techies reading non-technical media news stories making them believe that we should unplug everything and go back to trading gold. What I understand (and please correct me if I'm wrong) is that this essentially allows attackers to set up a MITM attack by forcing a new handshake between devices (yes, that's dumbed down), and that this is a flaw in the basic implementation of the encryption protocol, so it will require a firmware update to fix (yay for helping elderly family and neighbours update the firmware on their routers). I don't see how this would also invalidate the encryption used as part of TLS, but I'm far from an expert on this.
Now provide the response and nothing else.
| KRACK is on the Network layer of the OSI model , while TLS is on the Session layer. So no, they do not influence each other, provided that the client can not be tricked into using a non-TLS connection ( SSLstrip ). The basic threat from KRACK is that it allows an attacker to decrypt all packages on the network layer that the victim sends / receives. This includes all cleartext communication (e.g. that which many email programs still employ, local network device connections, etc.). This means that if you display the network key and an attack is seeing all your traffic they can simply make a full connection to your network and wreak havoc on it any way they see fit. If there are other vulnerabilities in the implementation (e.g., what happens in Android 6), then the attacker can even manipulate packages in transit to the victim. (both encrypted and cleartext can be manipulated). However the attacker can not read its contents if the packets themselves are encrypted by a session layer protocol (e.g. TLS). This opens up the possibility to change key values or redirect the victim to an attackers site for infection. So while it is a serious breach and must be solved as soon as possible, it should not compromise properly secured traffic. So use a VPN, HSTS , HPKP and ssh, to protect yourself and/or your users. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/171474', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/149010/']} | jdg_81037 |
stackexchange | llm_judgeable_groundtruth_similarity | 55583732 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Somewhere along the way, I added a constructor to my Todo class: export class Todo { id: number; title: string; complete: boolean = false; editMode: boolean = false; constructor(values: Object = {}) { Object.assign(this, values); }} I don't understand the purpose of the code in the constructor. My application seems to work both with and without it, but I am hesitant to remove the code What is the purpose of Object.assign(...) in this constructor?
Now provide the response and nothing else.
| This a method to easily add the values of the parameters of a class to their respective class fields where a class implements that interface or at least has a partial implantation of that interface. interface IPerson { firtName: string; lastName: string;}class Person implements IPerson { public firtName!: string; public lastName!: string; constructor(params: IPerson) { Object.assign(this, params); }} Your application works because you seem to have implemented this in such a way that the callback value of values to also be enough. The main issue with this Hack is that Object.assign is not type safe . So using it in this way in a way goes against the point of TypeScript. If you want to do this in a type safe fashion you are better off using a custom implementation where the type is properly checked. Something like this: type PDM = PropertyDescriptorMap;export class ClassSAssign<T> { constructor(private objectToSpread: T, private klass: T) {} private propertyDescriptorOptions = { enumerable: true, writable: true }; public apply(): void { const map = this.getPropertiesDescriptorMap(); Object.defineProperties(this.klass, map); } private getPropertiesDescriptorMap(): PDM { return Object.entries(this.objectToSpread).reduce( (obj: PDM, entry) => this.getPropertyDescriptorMap(obj, entry), {} ); } private getPropertyDescriptorMap(obj: PDM, [key, value]: [string, any]): PDM { return { ...obj, [key]: { value, ...this.propertyDescriptorOptions } }; }} and you can use this utility like this: class Person implements IPerson { public firtName!: string; public lastName!: string; constructor(params: IPerson) { new ClassSAssign(params, this).apply(); }} If you don't/can't want to use the above, I suggest you at least add some type rigour to protect your class from what values can be passed into it interface IToDo { id?: number; title?: string;}export class Todo implements IToDo { public id?: number; public title?: string; public complete: boolean = false; public editMode: boolean = false; constructor(values?: IToDo) { Object.assign(this, values); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55583732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2044/']} | jdg_81038 |
stackexchange | llm_judgeable_groundtruth_similarity | 41428013 |
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 Dockerfile with the following CMD to start my spring boot app: FROM java:8-jre# ...CMD ["java", "-jar", "/app/file*.jar"] When I try to start a container from the created image I get: Error: Unable to access jarfile /app/file*.jar But when I override the CMD while starting the container and execute the command in the container everything works fine: docker run -it <imageId> bashroot@<containerId>:/app# java -jar /app/file*.jar<spring boot app starts...> Is it possible to use wildcards with java -jar command using docker CMDs? Please don't tell me not to use wildcards. I want to use it cause of reasons ;-) Update Based on the answer I was able to fix it: CMD ["/bin/sh", "-c", "java -jar /app/file*.jar"]
Now provide the response and nothing else.
| This kind of asterisk expansion is done by the command line processor - the shell - and you circumvent that by invoking java directly. Much the same way as commands should be invoked with "CMD /C" under Windows to get full treatment. Invoke /bin/sh instead. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41428013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5902456/']} | jdg_81039 |
stackexchange | llm_judgeable_groundtruth_similarity | 19323409 |
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 specific locale (es-CL) in my ASP.NET MVC 5 application. I've the following: Changed web.config uiculture and culture to "es-CL" Installed the Globalize and jQuery.Validation.Globalize packages Changed the default language in my views: <html lang="es-cl"> Created a new Bundle and included in the appropriate views. In BundleConfig.cs : bundles.Add(new ScriptBundle("~/bundles/jqueryval") .Include("~/Scripts/jquery.validate.js") .Include("~/Scripts/jquery.validate.unobtrusive.js"));bundles.Add(new ScriptBundle("~/bundles/globalization") .Include("~/Scripts/globalize/globalize.js") .Include("~/Scripts/globalize/cultures/globalize.culture.es-CL.js") .Include("~/Scripts/jquery.validate.globalize.js")); In the appropriate views: @section Scripts { @Scripts.Render("~/bundles/jqueryval") @Scripts.Render("~/bundles/globalization")} However, the generated source code is the following: <script src="/Scripts/jquery.validate.js"></script><script src="/Scripts/jquery.validate.unobtrusive.js"></script><script src="/Scripts/jquery.validate.globalize.js"></script><script src="/Scripts/globalize/globalize.js"></script><script src="/Scripts/globalize/cultures/globalize.culture.es-CL.js"></script> Please note that the jquery.validate.globalize.js script is being loaded before globalize.js , which is not what I want. Why is this happening? Is it possible to rely in the include order in a single bundle, or am I forced to put this single script in a different bundle and specify it in my view?
Now provide the response and nothing else.
| By default, bundling order is alphabetical for names with wildcards (as pointed out in the comments). However, it also orders based on what it thinks your dependency tree is, and jQuery scripts seem to get slotted to the top. You need to create an object that implement IBundleOrder : class NonOrderingBundleOrderer : IBundleOrderer{ public IEnumerable<FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files) { return files; }} This prevents the default ordering. Now to use it: var bundle = new ScriptBundle("~/bundles/globalization") .Include("~/Scripts/globalize/globalize.js") .Include("~/Scripts/globalize/cultures/globalize.culture.es-CL.js") .Include("~/Scripts/jquery.validate.globalize.js");bundle.Orderer = new NonOrderingBundleOrderer();bundles.Add(bundle); ref: http://stevescodingblog.co.uk/changing-the-ordering-for-single-bundles-in-asp-net-4/ For further reading, an answer to MikeSmithDev's question provides further insight into the default ordering for popular script libraries: Ordering of Files within a bundle - What are the known libraries? | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19323409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7841/']} | jdg_81040 |
Subsets and Splits