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
5664094
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Postgresql allows adding comments to objects such as tables. For example I've added a comment to table "mytable" by using this SQL command: COMMENT ON TABLE mytable IS 'This is my table.'; My question is:If I want to use a SQL-command to get all tables along with their respective comment - how would I do this? What would be the appropriate query for this? Thanks in advance!Cheers! Now provide the response and nothing else.
All comments are stored in pg_description To get the comments on a table, you need to join it to pg_class As an alternative you can also use the function obj_description() to retrieve this information: SELECT obj_description(oid)FROM pg_classWHERE relkind = 'r' Edit In psql you can simply use the \d+ command to show all tables including their comments. Or use the \dd command to show all comments in the system
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5664094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/621258/']}
jdg_69841
stackexchange
llm_judgeable_groundtruth_similarity
366863
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 was doing some work in scipy and a conversation came up w/a member of the core scipy group whether a non-negative discrete random variable can have a undefined moment. I think he is correct but do not have a proof handy. Can anyone show/prove this claim? (or if this claim is not true disprove) I don't have an example handy if the discrete random variable has support on $\mathbb{Z}$ but it seems that some discretized version of the Cauchy distribution should serve as an example to get an undefined moment. The condition of non-negativity (perhaps including $0$) is what seems to make the problem challenging (at least for me). Now provide the response and nothing else.
Let the CDF $F$ equal $1-1/n$ at the integers $n=1,2,\ldots,$ piecewise constant everywhere else, and subject to all criteria to be a CDF. The expectation is $$\int_{0}^\infty (1-F(x))\mathrm{d}x = 1/2 + 1/3 + 1/4 + \cdots$$ which diverges. In this sense the first moment (and therefore all higher moments) is infinite. (See remarks at the end for further elaboration.) If you're uncomfortable with this notation, note that for $n=1,2,3,\ldots,$ $${\Pr}_{F}(n) = \frac{1}{n} - \frac{1}{n+1.}$$ This defines a probability distribution since each term is positive and $$\sum_{n=1}^\infty {\Pr}_{F}(n) = \sum_{n=1}^\infty \left(\frac{1}{n} - \frac{1}{n+1}\right) = \lim_{n\to \infty} 1 - \frac{1}{n+1} = 1.$$ The expectation is $$\sum_{n=1}^\infty n\,{\Pr}_{F}(n) = \sum_{n=1}^\infty n\left(\frac{1}{n} - \frac{1}{n+1}\right) =\sum_{n=1}^\infty \frac{1}{n+1} = 1/2 + 1/3 + 1/4 + \cdots$$ which diverges. This way of expressing the answer it makes it clear that all solutions are obtained by such divergent series. Indeed, if you would like the distribution to be supported on some subset of the positive values $x_1, x_2, \ldots, x_n, \ldots,$ with probabilities $p_1, p_2, \ldots$ summing to unity, then for the expectation to diverge the series which expresses it, namely $$(a_n) = (x_n p_n),$$ must have divergent partial sums. Conversely, every divergent series $(a_n)$ of non-negative numbers is associated with many discrete positive distributions having divergent expectation. For instance, given $(a_n)$ you could apply the following algorithm to determine sequences $(x_n)$ and $(p_n)$ . Begin by setting $q_n = 2^{-n}$ and $y_n = 2^n a_n$ for $n=1, 2, \ldots.$ Define $\Omega$ to be the set of all $y_n$ that arise in this way, index its elements as $\Omega=\{\omega_1, \omega_2, \ldots, \omega_i, \ldots\},$ and define a probability distribution on $\Omega$ by $$\Pr(\omega_i) = \sum_{n \mid y_n = \omega_i}q_n.$$ This works because the sum of the $p_n$ equals the sum of the $q_n,$ which is $1,$ and $\Omega$ has at most a countable number of positive elements. As an example, the series $(a_n) = (1, 1/2, 1, 1/2, \ldots)$ obviously diverges. The algorithm gives $$y_1 = 2a_1 = 2;\ y_2 = 2^2 a_2 = 2;\ y_3 = 2^3 a_3 = 8; \ldots$$ Thus $$\Omega = \{2, 8, 32, 128, \ldots, 2^{2n+1},\ldots\}$$ is the set of odd positive powers of $2$ and $$p_1 = q_1 + q_2 = 3/4;\ p_2 = q_3 + q_4 = 3/16;\ p_3 = q_5 + q_6 = 3/64; \ldots$$ About infinite and non-existent moments When all the values are positive, there is no such thing as an "undefined" moment: moments all exist, but they can be infinite in the sense of a divergent sum (or integral), as shown at the outset of this answer. Generally, all moments are defined for positive random variables, because the sum or integral that expresses them either converges absolutely or it diverges (is "infinite.") In contrast to that, moments can become undefined for variables that take on positive and negative values, because--by definition of the Lebesgue integral--the moment is the difference between a moment of the positive part and a moment of the absolute value of the negative part. If both those are infinite, convergence is not absolute and you face the problem of subtracting an infinity from an infinity: that does not exist.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/366863', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/150025/']}
jdg_69842
stackexchange
llm_judgeable_groundtruth_similarity
750765
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 have a bare git repository stored on a (windows) network share. I use linux, and have the said network share mounted with CIFS. My coleague uses windows xp, and has the network share automounted (from ActiveDirectory, somehow) as a network drive. I wonder if I can use the repo from both computers, without concurrency problems. I've already tested, and on my end I can clone ok, but I'm afraid of what might happen if we both access the same repo (push/pull), at the same time. In the git FAQ there is a reference about using network file systems (and some problems with SMBFS), but I am not sure if there is any file locking done by the network/server/windows/linux - i'm quite sure there isn't. So, has anyone used a git repo on a network share, without a server, and without problems? Thank you, Alex PS: I want to avoid using an http server (or the git-daemon), because I do not have access to the server with the shares. Also, I know we can just push/pull from one to another, but we are required to have the code/repo on the share for back-up reasons. Update: My worries are not about the possibility of a network failure. Even so, we would have the required branches locally, and we'll be able to compile our sources. But, we usually commit quite often, and need to rebase/merge often. From my point of view, the best option would be to have a central repo on the share (so the backups are assured), and we would both clone from that one, and use it to rebase. But, due to the fact we are doing this often, I am afraid about file/repo corruption , if it happens that we both push/pull at the same time. Normally, we could yell at each other each time we access the remote repo :), but it would be better to have it secured by the computers/network. And, it is possible that GIT has an internal mechanism to do this (since someone can push to one of your repos, while you work on it), but I haven't found anything conclusive yet. Update 2: The repo on the share drive would be a bare repo, not containing a working copy. Now provide the response and nothing else.
Git requires minimal file locking, which I believe is the main cause of problems when using this kind of shared resource over a network file system. The reason it can get away with this is that most of the files in a Git repo--- all the ones that form the object database--- are named as a digest of their content, and immutable once created. So there the problem of two clients trying to use the same file for different content doesn't come up. The other part of the object database is trickier-- the refs are stored in files under the "refs" directory (or in "packed-refs") and these do change: although the refs/* files are small and always rewritten rather than being edited. In this case, Git writes the new ref to a temporary ".lock" file and then renames it over the target file. If the filesystem respects O_EXCL semantics, that's safe. Even if not, the worst that could happen would be a race overwriting a ref file. Although this would be annoying to encounter, it should not cause corruption as such: it just might be the case that you push to the shared repo, and that push looks like it succeeded whereas in fact someone else's did. But this could be sorted out simply by pulling (merging in the other guy's commits) and pushing again. In summary, I don't think that repo corruption is too much of a problem here--- it's true that things can go a bit wrong due to locking problems, but the design of the Git repo will minimise the damage. (Disclaimer: this all sounds good in theory, but I've not done any concurrent hammering of a repo to test it out, and only share them over NFS not CIFS)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/750765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73593/']}
jdg_69843
stackexchange
llm_judgeable_groundtruth_similarity
27505
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: Background: It is well known that the quantum mechanics of $n$ identical particles living on $\mathbb{R}^3$ can be obtained from the geometric quantization of the cotangent bundle of the manifold $M^n = \frac{\mathbb{R}^{3n}-\Delta}{S_n}$, where $\Delta$ is the set of coincidences and $S_n$ is the permutation group of $n$ elements acting naturally on the individual copies of $\mathbb{R}^3$, please see, for example, Souriau: Structure of dynamical systems . $T^*M^n$ is multiply connected with $\pi_1(T^*M^n) = S_n$. Given the canonical symplectic structure on $T^*M^n$,the set of inequivalent quantizations has a one to one correspondence to the set of character representations of the fundamental group $\mathrm{Hom}(\pi_1(M^n), U(1))= \mathbb{Z}_2$ corresponding to the identity and the parity characters. Thesequantizations correspond exactly to the pre-quantization of bosons and fermions. The boson and fermion Fock spaces modeled on$\mathrm{L}^2(R^3)$ emerge as the quantization of Hilbert spaces corresponding to these two possibilities. Many authors pointed out that the removal of the coincidence set from the configuration space may seem not to be physically well motivated. The standard reasoning for this choice is that without the removal, the configuration space becomes an orbifold rather than a manifold. Some authors indicate also that without the removal, the configuration space is simply connected thus does allow only Bose quantization (Please, see for example the reprinted article by Y.S. Wu in Fractional statistics and anyon superconductivity By Frank Wilczek . My question: Are there any known treatments or results of the problem of geometric quantization of the configuration space as an orbifold (without the removal of the coincidence set), in terms of orbifold line bundles, etc.?Partial results or special cases are welcome. Does this quantization allow the possibility of Fermi statistics? Now provide the response and nothing else.
Often, instead of $\mathbf{R}^{3n}/S_n$, you may want to resolve the singularity. Let me explain a toy model where that resolution appears naturally. Consider $n$ identical particles on $\mathbf{C}$ with the configuration space $M^n=(\mathbf{C}^n-\Delta)/S_n$. You can think of this space as the space of unordered eigenvalues of $n\times n$ matrices over $\mathbf{C}$, i.e. $M^n=Mat_n(\mathbf{C})^{diag}/GL_n(\mathbf{C})$, where $Mat_n(\mathbf{C})^{diag}$ is the space of diagonalizable matrices with distinct eigenvalues and $GL_n(\mathbf{C})$ acts by conjugation. A heuristic argument (which is precise when the action of $G$ is nice) shows that $T^*(M/G)\cong T^*M//G$, where $//$ is the Hamiltonian reduction. In my case, there is a well-known compactification of $T^*M^n$ called the Calogero-Moser space $C_n$ obtained by the Hamiltonian reduction of $T^* Mat_n(\mathbf{C})$ along some orbit. Cotangent bundles have natural quantizations (functions are replaced by differential operators on the base and the Hilbert space is just $L^2$ functions on the base), and the quantization of the Calogero-Moser space $C_n$ is obtained by a procedure called the quantum Hamiltonian reduction from the quantization of $T^*Mat_n(\mathbf{C})$. For a reference, see Etingof's lectures http://arxiv.org/abs/math/0606233v4 . In particular, see proposition 2.6. Note, that he is more precise than I am, and so considers the action by $PGL_n(\mathbf{C})$ since it does not have any center.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/27505', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2190/']}
jdg_69844
stackexchange
llm_judgeable_groundtruth_similarity
2016206
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 out the DateTime.TryParseExact method, and I have come over a case that I just don't get. I have some formats and some subjects to parse that each should match one of the formats perfectly: var formats = new[] { "%H", "HH", "Hmm", "HHmm", "Hmmss", "HHmmss", };var subjects = new[] { "1", "12", "123", "1234", "12345", "123456", }; I then try to parse them all and print out the results: foreach(var subject in subjects){ DateTime result; DateTime.TryParseExact(subject, formats, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result); Console.WriteLine("{0,-6} : {1}", subject, result.ToString("T", CultureInfo.InvariantCulture));} I get the following: 1 : 01:00:0012 : 12:00:00123 : 00:00:001234 : 12:34:0012345 : 00:00:00123456 : 12:34:56 And to my question... why is it failing on 123 and 12345? Shouldn't those have become 01:23:00 and 01:23:45? What am I missing here? And how can I get it to work as I would expect it to? Update: So, seems like we might have figured out why this is failing sort of. Seems like the H is actually grabbing two digits and then leaving just one for the mm , which would then fail. But, does anyone have a good idea on how I can change this code so that I would get the result I am looking for? Another update: Think I've found a reasonable solution now. Added it as an answer. Will accept it in 2 days unless someone else come up with an even better one. Thanks for the help! Now provide the response and nothing else.
Ok, so I think I have figured this all out now thanks to more reading, experimenting and the other helpful answers here. What's happening is that H , m and s actually grabs two digits when they can, even if there won't be enough digits for the rest of the format. So for example with the format Hmm and the digits 123 , H would grab 12 and there would only be a 3 left. And mm requires two digits, so it fails. Tadaa . So, my solution is currently to instead use just the following three formats: var formats = new[] { "%H", "Hm", "Hms", }; With the rest of the code from my question staying the same, I will then get this as a result: 1 : 01:00:0012 : 12:00:00123 : 12:03:001234 : 12:34:0012345 : 12:34:05123456 : 12:34:56 Which I think should be both reasonable and acceptable :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2016206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39321/']}
jdg_69845
stackexchange
llm_judgeable_groundtruth_similarity
416850
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: Can a permutation matrix ($P$) be used to change the rank of another matrix ($M$)?Is there any literature to this effect, or to the contrary? I've tried a few small examples and the resulting matrix ($M_2$) seems to always have the same rank as the input matrix ($M$) $M_2 = M P$ Now provide the response and nothing else.
Hint: The rank of a matrix is the number of linearly independent row vectors, or of linearly independent column vectors. Now think about what a permutation matrix does to the row or column vectors in the matrix if you multiply it from left or right.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/416850', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38972/']}
jdg_69846
stackexchange
llm_judgeable_groundtruth_similarity
62545
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: Is there any way to find out what I just killed? $ ps -A -o pid,cmd | grep someApp | grep -v grep2802 python someApp.py$ sudo kill 2302$ EDIT: To clarify, I need to know what PID 2302 was before I killed it. The ps line is to give context as to how I killed 2302 when I don't even know what it was. Now provide the response and nothing else.
There is no general way to know, but you may have clues. You sent a TERM signal, not a KILL signal, so that left the program the opportunity to run a signal handler. It might not have died at all, or it might have left a log entry somewhere. Check whether the process is still running ( ps 2302 ), and if not, check your system logs. There is a log of all processes if you have process accounting enabled. This is available on Linux through GNU acct , but with most distributions the package is not installed by default. If process accounting is enabled, run lastcomm (you may need to be root) to see the recently killed processes (latest first). With lastcomm , only the command name is tracked, not the PID or the arguments; you'll have to figure out which process it is by circumstantial matching. Under Linux, lastcomm shows the date the process exited but only with a granularity of 1 minute, and there is an X flag after the command name if the command was killed by a signal. GNU acct tracks more information, including the process ID, but the lastcomm command doesn't display it: you have to run dump-acct , which unfortunately does not indicate whether a command was killed by a signal. dump-acct /var/log/account/pacct | awk -F '|' '$10 ~ / *2302($| )/' There are other subsystems that can log processes, such as Linux's audit, but they are usually not configured to do so.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/62545', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9760/']}
jdg_69847
stackexchange
llm_judgeable_groundtruth_similarity
349524
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my SQL Server backend for my app, I want to create history tables for a bunch of my key tables, which will track a history of changes to the rows. My entire application uses Stored Procedures, there is no embedded SQL.The only connection to the database to modify these tables will be through the application and the SP interface.Traditionally, shops I've worked with have performed this task using triggers. If I have a choice between Stored Procedures and Triggers, which is better?Which is faster? Now provide the response and nothing else.
Triggers. We wrote a GUI (internally called Red Matrix Reloaded ) to allow easy creation/management of audit logging triggers. Here's some DDL of the stuff used: The AuditLog table CREATE TABLE [AuditLog] ( [AuditLogID] [int] IDENTITY (1, 1) NOT NULL , [ChangeDate] [datetime] NOT NULL CONSTRAINT [DF_AuditLog_ChangeDate] DEFAULT (getdate()), [RowGUID] [uniqueidentifier] NOT NULL , [ChangeType] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [TableName] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [FieldName] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [OldValue] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [NewValue] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Username] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [Hostname] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [AppName] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [UserGUID] [uniqueidentifier] NULL , [TagGUID] [uniqueidentifier] NULL , [Tag] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) Trigger to log inserts CREATE TRIGGER LogInsert_Nodes ON dbo.NodesFOR INSERTAS/* Load the saved context info UserGUID */DECLARE @SavedUserGUID uniqueidentifierSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)FROM master.dbo.sysprocessesWHERE spid = @@SPIDDECLARE @NullGUID uniqueidentifierSELECT @NullGUID = '{00000000-0000-0000-0000-000000000000}'IF @SavedUserGUID = @NullGUIDBEGIN SET @SavedUserGUID = NULLEND /*We dont' log individual field changes Old/New because the row is new. So we only have one record - INSERTED*/ INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue, NewValue) SELECT getdate(), --ChangeDate i.NodeGUID, --RowGUID 'INSERTED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName '', --FieldName i.ParentNodeGUID, --TagGUID i.Caption, --Tag null, --OldValue null --NewValue FROM Inserted i Trigger to log Updates CREATE TRIGGER LogUpdate_Nodes ON dbo.NodesFOR UPDATE AS/* Load the saved context info UserGUID */DECLARE @SavedUserGUID uniqueidentifierSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)FROM master.dbo.sysprocessesWHERE spid = @@SPIDDECLARE @NullGUID uniqueidentifierSELECT @NullGUID = '{00000000-0000-0000-0000-000000000000}'IF @SavedUserGUID = @NullGUIDBEGIN SET @SavedUserGUID = NULLEND /* ParentNodeGUID uniqueidentifier */ IF UPDATE (ParentNodeGUID) BEGIN INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue, NewValue) SELECT getdate(), --ChangeDate i.NodeGUID, --RowGUID 'UPDATED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName 'ParentNodeGUID', --FieldName i.ParentNodeGUID, --TagGUID i.Caption, --Tag d.ParentNodeGUID, --OldValue i.ParentNodeGUID --NewValue FROM Inserted i INNER JOIN Deleted d ON i.NodeGUID = d.NodeGUID WHERE (d.ParentNodeGUID IS NULL AND i.ParentNodeGUID IS NOT NULL) OR (d.ParentNodeGUID IS NOT NULL AND i.ParentNodeGUID IS NULL) OR (d.ParentNodeGUID <> i.ParentNodeGUID) END /* Caption varchar(255) */ IF UPDATE (Caption) BEGIN INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue, NewValue) SELECT getdate(), --ChangeDate i.NodeGUID, --RowGUID 'UPDATED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName 'Caption', --FieldName i.ParentNodeGUID, --TagGUID i.Caption, --Tag d.Caption, --OldValue i.Caption --NewValue FROM Inserted i INNER JOIN Deleted d ON i.NodeGUID = d.NodeGUID WHERE (d.Caption IS NULL AND i.Caption IS NOT NULL) OR (d.Caption IS NOT NULL AND i.Caption IS NULL) OR (d.Caption <> i.Caption) END.../* ImageGUID uniqueidentifier */IF UPDATE (ImageGUID)BEGIN INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue, NewValue) SELECT getdate(), --ChangeDate i.NodeGUID, --RowGUID 'UPDATED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName 'ImageGUID', --FieldName i.ParentNodeGUID, --TagGUID i.Caption, --Tag (SELECT Caption FROM Nodes WHERE NodeGUID = d.ImageGUID), --OldValue (SELECT Caption FROM Nodes WHERE NodeGUID = i.ImageGUID) --New Value FROM Inserted i INNER JOIN Deleted d ON i.NodeGUID = d.NodeGUID WHERE (d.ImageGUID IS NULL AND i.ImageGUID IS NOT NULL) OR (d.ImageGUID IS NOT NULL AND i.ImageGUID IS NULL) OR (d.ImageGUID <> i.ImageGUID)END Trigger to log Delete CREATE TRIGGER LogDelete_Nodes ON dbo.NodesFOR DELETEAS/* Load the saved context info UserGUID */DECLARE @SavedUserGUID uniqueidentifierSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)FROM master.dbo.sysprocessesWHERE spid = @@SPIDDECLARE @NullGUID uniqueidentifierSELECT @NullGUID = '{00000000-0000-0000-0000-000000000000}'IF @SavedUserGUID = @NullGUIDBEGIN SET @SavedUserGUID = NULLEND /*We dont' log individual field changes Old/New because the row is new. So we only have one record - DELETED*/ INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue,NewValue) SELECT getdate(), --ChangeDate d.NodeGUID, --RowGUID 'DELETED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName '', --FieldName d.ParentNodeGUID, --TagGUID d.Caption, --Tag null, --OldValue null --NewValue FROM Deleted d And in order to know which user in the software did the update, every connection "logs itself onto SQL Server" by calling a stored procedure: CREATE PROCEDURE dbo.SaveContextUserGUID @UserGUID uniqueidentifier AS/* Saves the given UserGUID as the session's "Context Information" */IF @UserGUID IS NULLBEGIN PRINT 'Emptying CONTEXT_INFO because of null @UserGUID' DECLARE @BinVar varbinary(128) SET @BinVar = CAST( REPLICATE( 0x00, 128 ) AS varbinary(128) ) SET CONTEXT_INFO @BinVar RETURN 0ENDDECLARE @UserGUIDBinary binary(16) --a guid is 16 bytesSELECT @UserGUIDBinary = CAST(@UserGUID as binary(16))SET CONTEXT_INFO @UserGUIDBinary/* To load the guid back DECLARE @SavedUserGUID uniqueidentifierSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)FROM master.dbo.sysprocessesWHERE spid = @@SPIDselect @SavedUserGUID AS UserGUID*/ Notes Stackoverflow code format removes most blank lines - so formatting sucks We use a table of users, not integrated security This code is provided as a convience - no critisism of our design selection allowed. Purists might insist that all logging code should be done in the business layer - they can come here and write/maintain it for us. blobs cannot be logged using triggers in SQL Server (there is no "before" version of a blob - there is only what is). Text and nText are blobs - which makes notes either unloggable, or makes them varchar(2000)'s. the Tag column is used as an arbitrary text to identify the row (e.g. if a customer was deleted, the tag will show "General Motors North America" in the audit log table. TagGUID is used to point to the row's "parent". For example logging InvoiceLineItems points back to the InvoiceHeader . This way anyone searching for audit log entries related for a specific invoice will find the deleted "line items" by the line item's TagGUID in the audit trail. sometimes the "OldValue" and "NewValue" values are written as a sub-select - to get a meaningful string. i.e." OldValue: {233d-ad34234..}NewValue: {883-sdf34...} is less useful in the audit trail than: OldValue: Daimler ChryslerNewValue: Cerberus Capital Management Final note : Feel free to not do what we do. This is great for us, but everyone else is free to not use it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/349524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24126/']}
jdg_69848
stackexchange
llm_judgeable_groundtruth_similarity
9615706
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Is destructor called if SIGINT or SIGSTP issued? My code like this: #include <iostream>#include <signal.h>#include <cstdlib>void handler(int) { std::cout << "will exit..." << std::endl; exit(0);}class A {public: A() {std::cout << "constructor" << std::endl;} ~A() {std::cout << "destructor" << std::endl;}};int main(void) { signal(SIGINT, &handler); A a; for (;;); return 0;} When I pressed Ctrl-C, it printed: constructor^Cwill exit... There is no "destructor" printed.So, how can I exit cleanly? Now provide the response and nothing else.
With difficulty. Already, the code you've written has undefinedbehavior; you're not allowed to output to a stream in a signal handler;for that matter, you're not allowed to call exit either. (I'm basingmy assertions here on the Posix standard. In pure C++, all you'reallowed to do is assign to a variable of sig_atomic_t type.) In a simple case like your code, you could do something like: sig_atomic_t stopFlag = 0;voidhandler( int ){ stopFlag = 1;}intmain(){ signal( SIGINT, &handler ); A a; while ( stopFlag == 0 ) { } std::cout << "will exit..." << std::endl; return 0;} Depending on the application, you may be able to do something like this,checking the stopFlag at appropriate places. But generally, if youtry this, there will be race conditions: you check stopFlag beforestarting an interuptable system call, then do the call; the signalarrives between the check and the call, you do the call, and it isn'tinterrupted. (I've used this technique, but in an application where theonly interruptable system call was a socket read with a very shorttimeout.) Typically, at least under Posix, you'll end up having to create a signalhandling thread; this can then be used to cleanly shut down all of theother threads. Basically, you start by setting the signal mask to blockall signals, then in the signal handling thread, once started, set it toaccept the signals you're interested in and call sigwait() . Thisimplies, however, that you do all of the usual actions necessary for aclean shutdown of the threads: the signal handling thread has to knowabout all other threads, call pthread_cancel on them, etc., and you'recompiler has to generate the correct code to handle pthread_cancel , oryou need to develop some other means of ensuring that all threads arecorrectly notified. (One would hope, today, that all compilers handle pthread_cancel correctly. But one never knows; doing so hassignificant runtime cost, and is not usually needed.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9615706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1105178/']}
jdg_69849
stackexchange
llm_judgeable_groundtruth_similarity
7451761
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 what I want the output to look like: Employee Emp# Manager Mgr# BLAKE 7698 KING 7839 CLARK 7782 KING 7839 JONES 7566 KING 7839 MARTIN 7654 BLAKE 7698 ALLEN 7499 BLAKE 7698 TURNER 7844 BLAKE 7698 JAMES 7900 BLAKE 7698 WARD 7521 BLAKE 7698 FORD 7902 JONES 7566 SMITH 7369 FORD 7902 SCOTT 7788 JONES 7566 ADAMS 7876 SCOTT 7788 MILLER 7934 CLARK 7782 Here's what I got: SQL> SELECT ename, empno, (SELECT ename FROM EMP WHERE empno = mgr)AS MANAGER, mgr from emp order by empno; ENAME EMPNO MANAGER MGR ---------- ---------- ---------- ---------- SMITH 7369 7902 ALLEN 7499 7698 WARD 7521 7698 JONES 7566 7839 MARTIN 7654 7698 BLAKE 7698 7839 CLARK 7782 7839 SCOTT 7788 7566 KING 7839 TURNER 7844 7698 ADAMS 7876 7788 ENAME EMPNO MANAGER MGR ---------- ---------- ---------- ---------- JAMES 7900 7698 FORD 7902 7566 MILLER 7934 7782 I can't find why the manager field is blank. Here's the table: SQL> select empno, ename, job,deptno, mgr from emp; EMPNO ENAME JOB DEPTNO MGR ---------- ---------- --------- ---------- ---------- 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7839 7782 CLARK MANAGER 10 7839 7566 JONES MANAGER 20 7839 7654 MARTIN SALESMAN 30 7698 7499 ALLEN SALESMAN 30 7698 7844 TURNER SALESMAN 30 7698 7900 JAMES CLERK 30 7698 7521 WARD SALESMAN 30 7698 7902 FORD ANALYST 20 7566 7369 SMITH CLERK 20 7902 EMPNO ENAME JOB DEPTNO MGR ---------- ---------- --------- ---------- ---------- 7788 SCOTT ANALYST 20 7566 7876 ADAMS CLERK 20 7788 7934 MILLER CLERK 10 7782 14 rows selected. Now provide the response and nothing else.
This is a classic self-join, try the following: SELECT e.ename, e.empno, m.ename as manager, e.mgrFROM emp e, emp mWHERE e.mgr = m.empno And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax: SELECT e.ename, e.empno, m.ename as manager, e.mgrFROM emp e, emp mWHERE e.mgr = m.empno(+) Or in ANSI SQL syntax: SELECT e.ename, e.empno, m.ename as manager, e.mgrFROM emp e LEFT OUTER JOIN emp m ON e.mgr = m.empno
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7451761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/770022/']}
jdg_69850
stackexchange
llm_judgeable_groundtruth_similarity
3960548
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the second line? (Seen while answering another question.) int * x = new int [1] ;int * y = new (x) int; After the second line x and y have the same value (point to a same place). What's the difference between y = x and the second line? Is it like a constructor or something? Now provide the response and nothing else.
It's placement new . It constructs a new int in the memory pointed to by x . If you try: int * x = new int [1];*x = 5;std::cout << *x << std::endl;int * y = new (x) int;*y = 7;std::cout << *x << std::endl; the output will be: 57
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3960548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2308801/']}
jdg_69851
stackexchange
llm_judgeable_groundtruth_similarity
34610421
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 wrote a program to calculate the PI number with Leibniz formula: [ I wrote a for-loop with type of initialization is "int" , the loop works fine but when i changed the initialization type to "long" the result is changed. This only happens when the loop times over a billion. This makes the "int - loop" calculates PI more accurate than "long - loop". I don't know why this happens. Please help me to understand this issue. Thanks! and here is my code. public static void main(String[] args) { double result1 = 0; double result2 = 0; double sign = 1; for (int i = 0; i <= 1607702095; i++) { result1 += sign/(2 * i + 1); sign *= -1; } sign = 1; for (long j = 0; j <= 1607702095; j++) { result2 += sign/(2 * j + 1); sign *= -1; } System.out.println("result1 " + result1 * 4); System.out.println("result2 " + result2 * 4); System.out.println("pi " + Math.PI);} And the result is: result1 3.141592653576877result2 3.1415926529660116pi 3.141592653589793 Now provide the response and nothing else.
Actually, your first loop would have int overflow in the calculation of (2 * i + 1) when i is large enough, so I wouldn't rely on the output of it. The second loop, on the other hand, produces a more correct output, since (2 * j + 1) doesn't overflow, since it performs long multiplication. This makes the "int - loop" calculates PI more accurate than "long - loop" That's probably just a coincidence, since the calculations in the int loop overflow.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34610421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5747353/']}
jdg_69852
stackexchange
llm_judgeable_groundtruth_similarity
18877580
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following snippet: "12-18" -Contains "-" You’d think this evaluates to true , but it doesn't. This will evaluate to false instead. I’m not sure why this happens, but it does. To avoid this, you can use this instead: "12-18".Contains("-") Now the expression will evaluate to true. Why does the first code snippet behave like that? Is there something special about - that doesn't play nicely with -Contains ? The documentation doesn't mention anything about it. Now provide the response and nothing else.
The -Contains operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections. From the documentation you linked to: -Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value. In the example you provided you're working with a collection containing just one string item. If you read the documentation you linked to you'll see an example that demonstrates this behaviour: Examples: PS C:\> "abc", "def" -Contains "def"TruePS C:\> "Windows", "PowerShell" -Contains "Shell"False #Not an exact match I think what you want is the -Match operator: "12-18" -Match "-" Which returns True . Important: As pointed out in the comments and in the linked documentation , it should be noted that the -Match operator uses regular expressions to perform text matching.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18877580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/770270/']}
jdg_69853
stackexchange
llm_judgeable_groundtruth_similarity
614485
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: There has been quite some debate amongst users with different backgrounds about the usage of the word photon . [ 1 , 2 ] The most apparent disagreement was on whether a photon has a wavelength. I don't want to start a discussion about which viewpoint is more correct, because quantum optics is clearly only a sub-field of the standard model. Instead I would like to understand what additional predictions about photons the standard model allows to make and how one can construct the properties of the quantum optics' photon from it. In the quantum optics community a photon is a quantum of excitation of an electromagnetic (EM) mode. The mode is a solution of (the relativistic) Maxwell's equations. Therefore asking about the wavelength of a photon boils down to the wavelength of the EM mode. The mode doesn't need to be a plane wave. Now the particle physics perspective – I don't know much about it, but there were some statements which confused me: Photons are point particles without a wavelength. Moreover, the entity quantum optics people term "photon" is a composite particle or quasiparticle . I especially wonder how the absence of a wavelength does not contradict the explanation of diffraction experiments. The diffraction of a quantum optics' photon follows quite naturally from the fact that the EM mode is different in the presence of e.g. a grating compared to without the grating. But how are the wave-like properties modelled in particle physics? Please note that I'm not asking about the wave-particle duality, but about the apparent contradiction of the mentioned statements with interference phenomena. Now provide the response and nothing else.
The models that describe photons used in quantum optics and in particle physics are one and the same: the Standard Model of particle physics (often replaceable with just its quantum electrodynamics component) as encased within the formalism of quantum field theory. Moreover, the definition of photons (more specifically, single-photon states of the field) are identical in both fields. To be unambiguous: in both quantum optics and particle physics, photons need not have a well-defined wavelength. The definition you give, a photon is a quantum of excitation of an electromagnetic (EM) mode; the mode is a solution of (the relativistic) Maxwell's equations, is essentially right. Quantum electrodynamics builds on top of the classical Maxwell equations, by building creation and annihilation operators $\hat a_q$ and $\hat a_q^\dagger$ associated with each mode (indexed by $q$ ), and it provides us with number operators for each mode, $\hat n_q=\hat a_q^\dagger \hat a_q$ , and a global number operator, $$\hat N = \sum \!\!\!\!\!\!\!\!\!\; \int\limits_q \ \hat a_q^\dagger \hat a_q.$$ Single-photon states of the field are the eigenstates of $\hat N$ with eigenvalue $1$ . Some of those states are also eigenstates of one of the individual $\hat n_q$ for a mode $q$ which has a well-defined frequency (resp. wavelength, momentum, but also possibly e.g. orbital angular momentum), in which case the photon itself will have a well-defined frequency (resp. wavelength, momentum, OAM). If that premise is not fulfilled, then the photon does not have that well-defined quantity. In other words, your quote Therefore asking about the wavelength of a photon boils down to the wavelength of the EM mode is not wrong as such, but it seems to implicitly assume that "asking about the wavelength of the EM mode" will always have a well-defined answer and (with frequency, wavelength, momentum, OAM, etc) the answer is sometimes yes but also sometimes no. For full clarity, the answer you linked to is dead wrong. There is no semantic confusion. What can happen is that some phenomenological particle physicists in older generations, trained in the consequences of the QFT framework but not necessarily in its full mathematical generality, can sometimes fail to appreciate the full breadth of generality of the consequences of the QFT formalism. There's a lot of value in the traditional perspectives of phenomenological particle physics, but when their conclusions are in conflict with the mathematical formalism of QFT that underlies the theory, then the conclusions drawn from those perspectives are wrong.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/614485', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/169454/']}
jdg_69854
stackexchange
llm_judgeable_groundtruth_similarity
9441892
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's my situation:I have been working on an ASP.NET MVC 3 application for a while. It has a database (built out of a db project; I'm going db-first) for which I have an edmx model and then a set of POCOs. My entities have plural names in the database and POCOs have singular names. Everything maps nicely without a problem. Or used to until I added a new table (called TransactionStatuses). Now all of the old entities still work but the new one does not. When I try to eagerly load it together with a related entity: var transactions = (from t in db.Transactions.Include(s => s.TransactionStatus) //TransactionStatus - navigation property in Transactions to TransactionStatuses where t.CustomerID == CustomerID select t).ToList(); I get Invalid object name 'dbo.TransactionStatus'. I even did a simpler test: List<TransactionStatus> statuses = db.TransactionStatuses.ToList(); = same result. I have updated (and even re-created) edmx from the db and have gone through it back and forth trying to figure out what is different about the mapping for dbo.TransactionStatus* es * which trips the whole thing up. If somebody can point me in the direction of a fix it'd be wonderful. P.S. Turning off pluralisation is not an option, thanks. Update : I figured it out - my answer below. Now provide the response and nothing else.
This is probably happening because even though the intention was to use the Database First flow, in actual fact the application is using Code First to do the mapping. Let me explain a bit more because this can be confusing. :-) When using Database First with the EF Designer and the DbContext templates in Visual Studio three very important things happen. First, the new Entity Data Model wizard adds a connection string to your app containing details of the Database First model (i.e. the EDMX) so that when the application is run it can find this model. The connection string will look something like this: <connectionStrings> <add name="MyEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\sqlexpress;initial catalog=MyEntities;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings> Second, the generated context class makes a call to the base DbContext constructor specifying the name of this connection string: public MyEntities(): base("name=MyEntities"){} This tells DbContext to find and use the "MyEntities" connection string in the config. Using "name=" means that DbContext will throw if it doesn't find the connection string--it won't just go ahead and create a connection by convention. If you want to use Database First, then you must use a connection string like the one that is generated. Specifically, it must contain the model data (the csdl, msl, ssdl from the EDMX) and you must make sure that DbContext finds it. Be very careful when changing the call to the base constructor. The third thing that happens is that OnModelCreating is overridden in the generated context and made to throw: protected override void OnModelCreating(DbModelBuilder modelBuilder){ throw new UnintentionalCodeFirstException();} This is done because OnModelCreating is only ever called when using Code First. This is because OnModelCreating is all about creating the model, but when you are using Database First the model already exists--there is nothing to create at runtime. So if OnModelCreating is called then it is probably because you started using Code First without meaning to, usually because of a change to the connection string or the call to the base constructor. Now, it might be that you want to use Code First to map to an existing database. This is a great pattern and fully supported (see http://blogs.msdn.com/b/adonet/archive/2011/03/07/when-is-code-first-not-code-first.aspx ) but you will need to make sure mappings are setup appropriately for this to work. If the mappings are not setup correctly then you will get exceptions like the one in this question.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9441892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398864/']}
jdg_69855
stackexchange
llm_judgeable_groundtruth_similarity
108353
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The force density in a plasma, according to MHD, is $$ \mathbf{F} = -\nabla P -\nabla(\frac{B^2}{2\mu_0}) + \frac{1}{\mu_0}(\mathbf{B}\cdot\nabla)\mathbf{B} $$ where first term is the thermal pressure gradient, the second term is the magnetic pressure gradient and the third term is the magnetic tension The magnetic tension tends to straighten out the field lines thus reducing their curvature. How do I see this from the form of the equation $\frac{1}{\mu_0}(\mathbf{B}\cdot\nabla)\mathbf{B}$? Now provide the response and nothing else.
I think the easiest way is to start off with the conservation of momentum in the conservation-law form:$$\frac{\partial\boldsymbol\pi}{\partial t}=\nabla\cdot\mathbb T=0$$where $\boldsymbol\pi=\rho\mathbf u$ and $$\mathbb T=\rho\mathbf u\mathbf u+\left(p+\frac12B^2\right)\mathbb I - \mathbf B\mathbf B$$is the stress tensor and, as discussed before, $\mathbf{aa}$ is the dyad product . The magnetic and pressure terms can be combined to a single tensor in "matrix" notation (assuming a flow along the $z$ axis)$$\left(\begin{array}{ccc}p+\frac12B^2 & 0 & 0 \\ 0 & p+\frac12B^2 & 0 \\ 0 & 0 & p-\frac12B^2\end{array}\right)\begin{array}{c}\perp \\ \\ \perp\\ \\ \parallel\end{array}$$with the $\perp,\,\parallel$ symbols indicate that those diagonal components are the component along perpendicular or parallel to the flow. Visually, this is akin to the following image (taken from Page 149 of the book Principles of Magnetohydrodynamics by Hans Goedblood & Stefaan Poedts) You can see that the magnetic field terms parallel to the tube are pulling it outwards, causing the tube to reduce its curvature (straightening it).
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/108353', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/37677/']}
jdg_69856
stackexchange
llm_judgeable_groundtruth_similarity
5352397
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 work in web development, but I don't have a great understanding of network protocols. I recall hearing an analogy that TCP, HTTP, and SSL can be thought of as a series of nested envelopes around the actual request content. I also have a fuzzy idea TCP consists of packets, which are verified on the other end. But I'm sort of picturing the HTTP request being chopped into packets, too... So basically, I don't understand this stuff well at all. Can anybody give a good overview of this? Also, is there a beginner-friendly book or other resource that you'd recommend? Now provide the response and nothing else.
Since I asked this question, I've learned more about this topic, so I'll take a crack at answering it myself. The easiest way to picture the protocol stack is as a letter, wrapped in a series of envelopes. Each envelope has a different role in getting the letter to its recipient, and envelopes are added and removed as needed along the journey. The Application Layer The letter itself is an application-layer request. For example, you've typed "StackOverflow.com" in your browser and pressed enter. Your browser needs to ask the StackOverflow server for its home page. So it writes a letter saying, "Dear StackOverflow, would you please send me your home page?" If the writer of the letter is your browser, the recipient of the letter is the web server program running on StackOverflow. The browser wants the web server to "write back" with a response in the form of a web page. Both the browser and server are applications - programs running on specific computers. Because browsers speak HTTP, that's what it uses to make the request: the letter says something like "GET http://stackoverflow.com ". The browser also writes down any cookie information it got from StackOverflow last time ("remember me? You told me my login ID was X") and adds some miscellaneous labeled information called "headers" (things like "I'm Firefox" and "I can accept HTML or text" and "it's OK with me if you compress the content with gzip"). All that information will help the server know how to personalize or customize its response. At that point, the browser is basically done. It hands this letter to the operating system and says, "would you please send this for me?" The OS says, "Sure." It then does some work to connect to StackOverflow (more on that in a minute), then tells the browser, "I'm working on it. By the way, here's a little mail bin I made for you, called a socket. When I hear back from StackOverflow, I'll put its letter in there and you can read it just like a file." The browser then happily awaits the response. The IP layer To send the request from the browser to StackOverflow, the operating system has to do several things. First, it has to look up the address for StackOverflow.com - specifically, the IP address. It does this using DNS (which I won't go into here). Once it knows the IP address, it will know how to wrap the request in one of the "envelopes" called the IP layer. Why do we need the IP layer? Well, once upon a time, we didn't. Why we need IP Have you ever seen an old movie where someone makes a phone call by asking the operator to connect them? The operator would physically connect the wire from Person #1's house to the wire for Person #2's house. Before the protocol stack was invented, connecting computers was a lot like that phone call: you needed a dedicated wire from point to point. So, for example, if the computer scientists at Stanford wanted to exchange data with the ones at Harvard, they'd pay a bunch of money to rent a dedicated wire between the two places (a "leased line"). Any data that went into one end came out reliably at the other end. However, this was very expensive: imagine paying for a separate line for every place you want to connect to! People realized that this wouldn't scale up. We needed a way to have a network that was shared by all users, like a giant spiderweb of wires spread out all over the map. That way, each user would only need one connection to the network and could reach any other user through it. But that presented a problem. If everyone's communications went on the same lines, how would the data get to the right place? Imagine a bunch of letters dumped on a conveyor belt. Obviously, every letter needs to be addressed to someone, or else they can't be delivered. That's the basic idea of IP: every machine needs to have an IP address that uniquely identifies it. Messages are placed in IP packets, which are like envelopes with addresses and return addresses. So, once the OS has looked up the IP address for Stackoverflow.com, it puts the HTTP request in an IP envelope. If it's a "long letter", too big for one envelope, the OS cuts it into pieces and puts it in several IP envelopes. Each envelope says something like "FROM: (your IP address); TO: (The Server's IP address." Like the HTTP request, the IP packet has some other miscellaneous header information, which we won't go into here, but the basic idea is just "to" and "from." So, at this point, the letter is ready to go, right? The messiness of IP Not quite. This letter could easily get lost! See, with IP, we no longer have a dedicated line from place to place. If we did, we'd be sure that our letters were getting delivered: as long as the line wasn't broken, everything would go through. But with IP, everyone's packets get dumped onto conveyor belts and carried along. The belts lead to little sorting stations, called "routers". If you imagine the routers like physical mail centers, you could picture one in, say, New York City. "Here's a letter headed for Mexico City. I don't know exactly how to get there, but the station in Houston should be able to get it closer, so I'll send it there. Ah, here's a letter that's going to Atlanta. I'll send it to Charlotte; they should be able to forward it a step closer." Generally this system works OK, but it's not as reliable as having your own dedicated line. Nearly anything could happen en route: a conveyor belt could break or catch fire, and everything on it could be lost. Or one could get bogged down for a while, so that its packets are delivered very late. Besides that, because these conveyor belts and stations are used by everyone, nobody's letters get treated specially. So what happens if a router gets more letters than it can possibly handle? For a while, it can stack them in a corner (maybe in RAM), but eventually, it runs out of space. What it does then may seem shocking: it starts throwing them away. Yep. That's it. You might think that it would at least be kind enough to send back a note to you, saying, "sorry, we couldn't deliver your letter." But it doesn't. If you think about it, if the router is overwhelmed, it's probably because there's too much traffic on the lines already. Adding apology notes would only make the problem worse. So it throws away your packet and doesn't bother telling anyone. Obviously, this is a problem for our HTTP request. We need it to get there, and we need the response to get back reliably, too. To make sure it gets there, we want some kind of "delivery confirmation" service. For that, we'll wrap another envelope around our HTTP request before putting into IP packets. That layer is called TCP. TCP TCP stands for "transfer control protocol." It exists to control what would otherwise be a messy, error-prone delivery process. As implied before, TCP lets us add some "delivery confirmation" to this messy delivery system. Before we wrap our HTTP request in IP packets, we first put it into TCP packets. Each one gets a number: packet 1 of 5, 2 of 5, etc. (The numbering scheme is actually more complicated and counts bytes rather than packets, but let's ignore that for now.) The basic idea of TCP is this: First, the client and server - in this case, your operating system and the StackOverflow server's operating system - do a "handshake" to establish a "connection". Both words needs quotes because the "handshake" is actually a few messages back and forth, proving that packets can get successfully there and back, and the "connection" is really nothing more than each side deciding that they'll keep track of the packets flowing between them. Next, they send packets back and forth; the client maybe requesting a web page, and the server maybe sending it back (in as many packets as that takes). As one side receives packets, it sends back confirmation messages, saying "so far I've received your packets up to packet 100" and so forth. If one party sends packets and doesn't hear a confirmation for a while, it will assume they were lost and re-send them. (Getting confirmations when things arrive at the other end is better than getting error reports when a router drops things along the way for a couple of reasons. One is that confirmations go back over a working connection, whereas errors would further clog a non-working connection. Another is that we don't have to trust the intermediary routers to do the right thing; the client and server are the ones who care most about this particular conversation, so they're the ones who take charge of being sure that it works.) Besides making sure that all the data gets to the other end, TCP also makes sure that the received data gets put back into the right order before handing it up the stack, in case earlier packets got resent and arrived later, or packets in the middle took a longer route, or whatever. That's basically it - having this kind of delivery confirmation makes the unreliable IP network reliable. Why wasn't it built straight into IP? UDP Well, confirmation has a drawback: it makes things slower. If something is missed, it must be repeated. In some cases, that would be a waste of time, because what you really want is a real-time connection. For example, if you're having a phone conversation over IP, or you're playing a real-time game over the internet, you want to know what's happening right now , even if it means you miss a bit of what happened a second ago. If you stop to repeat things, you'll fall out of sync with everyone else. In cases like that, you can use a cousin of TCP called UDP, which doesn't re-send lost packets. UDP stands for "user datagram protocol", but many people think of it as "unreliable data protocol". That's not an insult; sometimes reliability is less important than staying current. Since both of these are valid use cases, it makes sense that the IP protocol stayed neutral on the issue of reliability; those who use it can choose whether to add reliability or not. Both TCP and UDP add one other important piece of information to the request: a port number. Port numbers Remember, our original request is comes from a browser and is going to a web server program. But the IP protocol only has addresses that specify computers, not the applications running on them. The machine with StackOverflow's web server may also have other server programs that are listening for requests: a database server, an FTP server, etc. When that machine gets the request, how will it know which program should handle it? It will know because the TCP request has a port number on it. This is just a number, nothing fancy, but by convention, certain numbers are interpreted to mean certain things. For example, using a port number of 80 is a conventional way of saying "this is a request for a web server." Then the server machine's operating system will know to hand that request to the web server program and not, say, the FTP server program. When the TCP packets start streaming back to your computer, they will also have a port number, to let your machine know which program to give the response to. That number will vary based on the socket that your machine created initially. Wait, what's a socket? Sockets Remember earlier when the browser asked the OS to send the request? The OS said it would set up a "mail bin" for any response it got back. That bin is called a socket. You can think of a socket sort of like a file. A file is an interface that the OS provides. It says, "you can read and write data here, and I will take care of figuring out how to actually store it on the hard drive or USB key or whatever." The thing that uniquely identifies a file is the combination of path and filename. In other words, you can only have one file located in the same folder with the same name. Similarly, a socket is an interface the OS provides. It says, "you can write requests here and read responses." The thing that uniquely identifies a socket is the combination of four things: Destination IP Destination Port Source IP Source Port So, you can only have one socket on a system with the same combination of all of those. Notice that you could easily have several sockets open to the same destination IP and port - say, StackOverflow's web server - as long as they all have different source ports. The OS will guarantee that they do by choosing an arbitrary source port for each request, which is why you can have several tabs or several browsers all requesting the same web site simultaneously without anything getting confused; the packets coming back all say which port on your computer they're headed for, which lets the OS know "ah, this packet is for tab 3 in Firefox" or whatever. Summing up so far We've been thinking of the protocols as a series of envelops wrapped around the letter. In our example, the letter was an HTTP request, which got wrapped in TCP, then in IP. The IP packets get sent to the right destination computer. That computer removes the IP "envelope" and finds a TCP packet inside. The TCP packet has a port number, which lets the operating system know which port to collect its information in. It replies saying that it got that packet, and it puts its contents (the HTTP request) into the correct socket for the appropriate program to read from. When that program writes a reponse to the socket, the OS sends it back to the requester. So our "stack" is: An HTTP request (a "letter"). This is the application layer. Wrapped in TCP packets ("envelopes"). This is the transport layer. Wrapped in IP packets ("envelopes"). This is the IP layer. It's important to understand that this stack is totally customizable. All of these "protocols" are just standard ways of doing things. You can put anything you want inside of an IP packet if you think the receiving computer will know what to do with it, and you can put anything you want inside a TCP or UDP packet if you think the receiving application will know what to do with it. You could even put something else inside your HTTP request. You could say that some JSON data in there is the "phone number exchange protocol," and as long as both ends know what to do with it, that's fine, and you've just added a higher-level protocol. Of course, there's a limit to how "high" you can go in the stack - that is, you can put a smaller envelope inside HTTP, and a smaller one inside that, etc, but eventually you won't have any room to go smaller; you won't have any bits for actual content. But you can easily go "lower" in the stack; you can wrap more "envelopes" around the existing ones. Other protocol layers Once common "envelope" to wrap around IP is Ethernet. For example, when your computer decides to send IP packets to Google, it wraps them up as we've described so far, but to send them, it gives them to your network card. The network card may then wrap the IP packets in Ethernet packets (or token ring packets, if you've got an antique setup), addressing them to your router and sending them there. Your router removes those Ethernet "envelopes", checks the IP address, decides who the next closest router is, wraps another Ethernet envelope addressed to that router, and sends the packet along. Other protocols could be wrapped as well. Maybe two devices are only connected wirelessly, so they wrap their Ethernet packets in a Wi-Fi or Bluetooth or 4G protocol. Maybe your packets need to cross a village with no electricity, so someone physically prints the packets on paper with numbered pages, rides them across town on a bicycle, and scans them into another computer in the order of the page numbers. Voila! A print-to-OCR protocol. Or maybe, I don't know, TCP over carrier pigeon would be better. Conclusion The protocol stack is a beautiful invention, and it works so well that we generally take it for granted. It is a great example of abstracting functionality: each layer has its own work to do and can rely on others to deal with the rest. The application layer is only concerned with applications talking to each other: "Firefox wants to talk to the web server at StackOverflow.com." The transport layer is only concerned with getting a stream of packets delivered correctly from one app to another: "all the packets from port 123 on machine 1 need to get to port 80 on machine 2". The IP layer is only concerned with routing individual packets: "this packet needs to get to the following IP address." The link layer is only concerned with getting packets from one waypoint to the next: "this ethernet packet needs to get from the network card to the router." The physical layer is only concerned with signal transmission: "these pulses need to be sent over this wire." (Although these layer terms are borrowed from OSI , OSI was actually a competing standard to TCP/IP, and included things like the "session layer" and "presentation layer" that TCP/IP doesn't use. OSI was intended to be a more sane and standardized alternative to the scrappy hacked-together TCP/IP stack, but while it was still being discussed, TCP/IP was already working and was widely adopted.) Because the layers can be mixed and matched as needed, the stack is flexible enough to accommodate nearly any use we can think of, so it's probably going to be around for a long time. And hopefully now you can appreciate it a bit more.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5352397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4376/']}
jdg_69857
stackexchange
llm_judgeable_groundtruth_similarity
23748572
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is a way to initialize Numeric vector with NA values like. NumericVector x(10,NumericVector::get_na()) is there any similar way to initialize a matrix to NA values? Now provide the response and nothing else.
Here is a version that does not waste memory. #include <Rcpp.h>using namespace Rcpp ;// [[Rcpp::export]]NumericMatrix na_matrix(int n){ NumericMatrix m(n,n) ; std::fill( m.begin(), m.end(), NumericVector::get_na() ) ; return m ;} FWIW, in Rcpp11 , you can use some more expressive syntax: NumericMatrix m(n,n, NA) ; Thanks to this constructor
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23748572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1377976/']}
jdg_69858
stackexchange
llm_judgeable_groundtruth_similarity
459522
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: Suppose that the matrix $A$ is not diagonalizable. Show that for all $\epsilon>0$, there exists a diagonalizable matrix $A_{\epsilon}$ such that $||A-A_{\epsilon}||_{2}<\epsilon$. Can anyone help me prove this or give a hint? Now provide the response and nothing else.
This follows straight from the Schur decomposition. Let $A = U T U^*$ be nondiagonalizable. Here, $U$ is unitary and $T$ is triangular, with the elements $t_{ij}$. Let $\varepsilon_i$, $i = 1,\dots,n$ be such that $$t_{ii} + \varepsilon_i \ne t_{jj} + \varepsilon_j, \quad \text{for all $i \ne j$}$$ and $|\varepsilon_i|$ sufficiently small. I leave it to you to show that this can always be done. Define $T' := T + \operatorname{diag}(\varepsilon_1, \dots, \varepsilon_n)$ and $A_\varepsilon := U T' U^*$. Obviously, all eigenvalues of $A_\varepsilon$ are distinct, so $A_\varepsilon$ is diagonalizable.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/459522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/88734/']}
jdg_69859
stackexchange
llm_judgeable_groundtruth_similarity
2132639
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am missing something essential in my understanding of matrices as linear mappings (or matrices in general). To explain, I think I have a decent intuition for columnspace of a matrix. Basically, the columnspace can be thought of as the set of points other than the origin which can be mapped by the matrix of a linear mapping (I like to think of matrices in general as linear mappings). What I have trouble with is the significance and geometric interpretation of the rowspace of a matrix. By the definition, I can see that the rowspace and columnspace are analagous; the rowspace is merely the columnspace of the transpose of the matrix of the linear mapping. However, I cannot explain this anymore intuitively than above. To quote Albert Einstein, "if you don't understand it simply, you don't understand it well enough". I am looking for a simple explanation (or geometric interpretation that will contribute to my imagination of linear mappings). How would you explain this concept? To give you some context, I ran into problems when my course started to discuss the following: For an $n \times n$ matrix $P$, the following are equivalent: (1) The columns of $P$ form an orthonormal basis for $\mathbb{R}^n$ (2) $P^T = P^{-1}$ (3) The rows of $P$ form an orthonormal basis for $\mathbb{R}^n$. I understand the algebra perfectly, but I seek a level of intuition so that I would not need to fiddle around with algebra to discover these facts. How would you explain the above concepts intuitively or geometrically, without the need for algebra to make a case? Many thanks in advance. Now provide the response and nothing else.
As Ted Shifrin states in his comment to your question, the rowspace of a real matrix is the orthogonal complement of its nullspace. In fact, we have the following relationships for any (not necessarily square) real matrix $A$ : $$\mathscr{C}(A^T)=\mathscr{N}(A)^\perp \\ \mathscr{N}(A^T)=\mathscr{C}(A)^\perp.$$ There is an equivalent pair of statements about a linear map, its adjoint map and annihilators of subspaces. One consequence of these relationships is that the rowspace of a matrix is a maximal-dimension subspace of the domain for which the linear map defined by the matrix is injective. Another possible way to view the rowspace is as the space of representative elements of the quotient space $\mathbb R^m/\mathscr{N}(A)$ , where $m$ is the number of columns of $A$ . In light of this, the rowspace of a matrix can be considered the “natural” preimage of its column space.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2132639', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/338817/']}
jdg_69860
stackexchange
llm_judgeable_groundtruth_similarity
71850
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I prove that the Cartesian product of two countable sets is also countable? Now provide the response and nothing else.
In your answer you use Cantor's pairing function. It is an important function indeed. However using Cantor-Bernstein's theorem we only need to find an injection from $\mathbb N\times\mathbb N$ into $\mathbb N$. A useful example is: $$f(m,n) = 2^m\cdot 3^n$$ If $f(m,n)=f(l,k)$ then by the fundamental theorem of arithmetics we have that $m=l, n=k$. We now can find an injection $g\colon\mathbb N\to\mathbb N\times\mathbb N$, for example $g(n)=(0,n)$. Now Cantor-Bernstein's theorem tells us that if $f\colon A\to B$ and $g\colon B\to A$ are two injective functions, then there is a bijection from $A$ into $B$. From this to $\mathbb N^k$ being countable, you can either go with induction, as you suggested, or map $(m_1,\ldots,m_k)$ to $p_1^{m_1}\cdot\ldots p_k^{m_k}$, where $p_i$ is the $i$-th prime number.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/71850', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12510/']}
jdg_69861
stackexchange
llm_judgeable_groundtruth_similarity
6667201
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 define a two-dimensional array without an initialized length like this: Matrix = [][] But this gives an error: IndexError: list index out of range Now provide the response and nothing else.
You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this"list comprehension". # Creates a list containing 5 lists, each of 8 items, all set to 0w, h = 8, 5Matrix = [[0 for x in range(w)] for y in range(h)] #You can now add items to the list: Matrix[0][0] = 1Matrix[6][0] = 3 # error! range... Matrix[0][6] = 3 # valid Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index". print Matrix[0][0] # prints 1x, y = 0, 6 print Matrix[x][y] # prints 3; be careful with indexing! Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/6667201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838242/']}
jdg_69862
stackexchange
llm_judgeable_groundtruth_similarity
19197471
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 get the current date in MS-SQL Server 2008 R2? The format of the column in my database is DATETIME and dates are stored in the following format: +++++++++++++ Vrdate ++++++++++| || 2012-11-18 00:00:00.000 || 2012-11-19 00:00:00.000 || 2013-11-18 00:00:00.000 || 2012-12-01 00:00:00.000 || 2010-10-09 00:00:00.000 || 2012-11-11 00:00:00.000 || |+++++++++++++++++++++++++++++++ I searched but wasn't able to find the way to get the date in this format (i.e. which has the time associated with it in 00:00:00.00 ). I found GETDATE() function but that provides the current time along with the date as well, what I want is get the date in the following format: CurrentDate 00:00:00.00 How may I get this? Now provide the response and nothing else.
SELECT CAST(GETDATE() AS DATE) Returns the current date with the time part removed. DATETIME s are not "stored in the following format". They are stored in a binary format. SELECT CAST(GETDATE() AS BINARY(8)) The display format in the question is independent of storage. Formatting into a particular display format should be done by your application.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19197471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1931097/']}
jdg_69863
stackexchange
llm_judgeable_groundtruth_similarity
17339461
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 define a macro for unifying all fonts in my app: #define EXO_REGULAR_FONT(size) [UIFont fontWithName:@"Exo-Regular" size:size] and than using this macro like this: myLabel.font = EXO_REGULAR_FONT(15); But the compiler give me this error: (there is an arrow under 15). Any ideas to resolve ? Thanks Now provide the response and nothing else.
Change the name of your parameter: #define EXO_REGULAR_FONT(theFontSize) [UIFont fontWithName:@"Exo-Regular" size:theFontSize] From GCC manual : When the macro is expanded, each use of a parameter in its body is replaced by the tokens of the corresponding argument So when your macro is expanded, it inserts this in your code, hence the compilation error: [UIFont fontWithName:@"Exo-Regular" 15:15]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17339461', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1006113/']}
jdg_69864
stackexchange
llm_judgeable_groundtruth_similarity
111326
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In "The Potts model and the Tutte Polynomial", D.J.A. Welsh and C. Merino claim on pg. 1135, equation 18, that,\begin{align*}\sum_{i=0}^{n-1}f_i t^i = t^{n-1}T_G(1+\frac{1}{t},1)\end{align*}where $T_G(x,y)$ is the Tutte polynomial of some graph $G$ and $f_i$ denotes the number of forests of $G$ with exactly $i$ edges. Their paper is available online here . Welsh and Merino do not give any citations or proof for this claim. Does anyone know of such a proof? Also, is there a more explicit formula for $f_i$ in terms of $T_G(x,y)$? EDIT: I noticed recently that something must be wrong with the claimed formula because if $G$ is the disjoint union of $n$ isolated vertices, then $T_G(x,y) = 1$, so the righthand side becomes $t^{n-1}$; however the lefthand side is $1$. Implicitly Welsh and Merino are assuming that $G$ is connected or I do not know what is meant by the "size" of a forest. Now provide the response and nothing else.
Here are two quick ways of proving this: (1) Notice that one of the many equivalent definitions of the Tutte polynomial says$$T_G(x,y)=\sum_{A\subset E}(x-1)^{k(A)-k(E)}(y-1)^{k(A)+|A|-|V|}$$Where $A$ runs through subsets of the edges of $G$, and the function $k(A)$ measures the number of components of the graph $(V,A)$. Here you only need consider the terms where $k(A)+|A|=|V|$, which happens precisely when $(A,V)$ is a forest! (2) Remember that the Tutte polynomial satisfies the deletion-contraction relation$$T_{G}(x,y)=T_{G/e}(x,y)+T_{G-e}(x,y),$$when $e$ is neither a loop nor a bridge. So you only need to show that the generating function of forests of a graph also satisfies this recurrence, as well as the "initial conditions" that it agrees with $t^{|E|-1}T_G(1+\frac{1}{t},1)$ for $G$ a tree.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/111326', 'https://mathoverflow.net', 'https://mathoverflow.net/users/25028/']}
jdg_69865
stackexchange
llm_judgeable_groundtruth_similarity
1498605
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 $x,y,z$ be positive real numbers such that $x^2y^2+y^2z^2+z^2x^2\ge x^2y^2z^2$. Find the minimum value of$$\frac{x^2y^2} {z^3(x^2+y^2)}+\frac {y^2z^2} {x^3(y^2+z^2)}+\frac {z^2x^2} {y^3(z^2+x^2)}$$I'm pretty sure that the answer would be $\frac {\sqrt {3}} {2}$, when all parameters are $\sqrt {3}$. But I couldn't prove it after some hours of thinking. So can anyone help me?Any help would be welcome.Thanks:D. Now provide the response and nothing else.
Let$$a=\dfrac{1}{x},b=\dfrac{1}{y},c=\dfrac{1}{z},a^2+b^2+c^2\ge 1$$Use Cauchy-Schwarz $$\sum_{cyc}\dfrac{x^2y^2}{z^3(x^2+y^2)}=\sum_{cyc}\dfrac{c^3}{(a^2+b^2)}\ge \dfrac{(a^2+b^2+c^2)^2}{c(a^2+b^2)+a(b^2+c^2)+b(c^2+a^2)}$$since$$c(a^2+b^2)+a(b^2+c^2)+b(c^2+a^2)\le\dfrac{2}{3}(a+b+c)(a^2+b^2+c^2)\le\dfrac{2}{\sqrt{3}}(a^2+b^2+c^2)^{\frac{3}{2}}$$so$$LHS\ge \dfrac{\sqrt{3}}{2}\sqrt{a^2+b^2+c^2}\ge\dfrac{\sqrt{3}}{2}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1498605', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/280974/']}
jdg_69866
stackexchange
llm_judgeable_groundtruth_similarity
1272454
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 I have the following code which update a field of a struct using reflection. Since the struct instance is copied into the DynamicUpdate method, it needs to be boxed to an object before being passed . struct Person{ public int id;}class Test{ static void Main() { object person = RuntimeHelpers.GetObjectValue(new Person()); DynamicUpdate(person); Console.WriteLine(((Person)person).id); // print 10 } private static void DynamicUpdate(object o) { FieldInfo field = typeof(Person).GetField("id"); field.SetValue(o, 10); }} The code works fine. Now, let's say I don't want to use reflection because it's slow. Instead, I want to generate some CIL directly modifying the id field and convert that CIL into a reusable delegate (say, using Dynamic Method feature). Specially, I want to replace the above code with s/t like this: static void Main(){ var action = CreateSetIdDelegate(typeof(Person)); object person = RuntimeHelpers.GetObjectValue(new Person()); action(person, 10); Console.WriteLine(((Person)person).id); // print 10}private static Action<object, object> CreateSetIdDelegate(Type t){ // build dynamic method and return delegate} My question: is there any way to implement CreateSetIdDelegate excepts from using one of the following techniques? Generate CIL that invoke the setter using reflection (as the 1st code segment in this post). This makes no sense, given the requirement is to get rid of reflection, but it's a possible implementation so I just mention. Instead of using Action<object, object> , use a custom delegate whose signature is public delegate void Setter(ref object target, object value) . Instead of using Action<object, object> , use Action<object[], object> with the 1st element of the array being the target object. The reason I don't like 2 & 3 is because I don't want to have different delegates for the setter of object and setter of struct (as well as not wanting to make the set-object-field delegate more complicated than necessary, e.g. Action<object, object> ). I reckon that the implementation of CreateSetIdDelegate would generate different CIL depending whether the target type is struct or object, but I want it to return the same delegate offering the same API to user. Now provide the response and nothing else.
EDIT again : This works structs now. There's a gorgeous way to do it in C# 4, but you'll have to write your own ILGenerator emit code for anything before that. They added an ExpressionType.Assign to the .NET Framework 4. This works in C# 4 (tested): public delegate void ByRefStructAction(ref SomeType instance, object value);private static ByRefStructAction BuildSetter(FieldInfo field){ ParameterExpression instance = Expression.Parameter(typeof(SomeType).MakeByRefType(), "instance"); ParameterExpression value = Expression.Parameter(typeof(object), "value"); Expression<ByRefStructAction> expr = Expression.Lambda<ByRefStructAction>( Expression.Assign( Expression.Field(instance, field), Expression.Convert(value, field.FieldType)), instance, value); return expr.Compile();} Edit: Here was my test code. public struct SomeType{ public int member;}[TestMethod]public void TestIL(){ FieldInfo field = typeof(SomeType).GetField("member"); var setter = BuildSetter(field); SomeType instance = new SomeType(); int value = 12; setter(ref instance, value); Assert.AreEqual(value, instance.member);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1272454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17815/']}
jdg_69867
stackexchange
llm_judgeable_groundtruth_similarity
20657
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: Some people say that it's awful that humans eat animals. They feel that it's barbaric, because you're killing life and then on top of that, you're eating it, and that you should eat vegetation instead. But isn't vegetation life too? Personally, I see no difference between animals and veg as all life has cells, dna etc So my question is, is it possible for humans to live healthy long lives without eating any type of life, i.e no animals, no plants, no cells (dead or alive) etc? If it is possible, how would it be done? Now provide the response and nothing else.
The answer to your question is yes it is certainly possible. At one time it was thought that there was something special about "organic" chemicals which meant that they could not be artificially synthesised out of fundamental elements. In 1828 Frederick Wöhler synthesised urea (CO(NH 2 ) 2 ) which is often taken as the first demonstration that the organic v inorganic distinction was not a sound one (for more on this see the Wikipedia article on Wöhler synthesis . As far as we know all essential human nutrients can be synthesised from inorganic ingredients, even complex molecules such as Vitamin B 12 . Other contributors have pointed out that organic pathways for synthesising our food have evolved over long periods to be very efficient - at least in the conditions prevailing on Earth. You haven't ruled out copying biochemical pathways using chemicals that are entirely of inorganic origin. Anyone trying to do this seriously could create glucose (for example) by artificially creating enzymes (perhaps via artificial DNA) to do the job. The thing is that we already have self-replicating and repairing machines to do that already (plants). There might be circumstances when we needed to use artificial synthesis. I can think of two science-fiction stories that deal with this question, the first of which goes into some detail: The Moon is Hell by John W. Campbell, in which astronauts are stranded on the moon and forced to make food from what they find there. Technical Error by Arthur C. Clarke, in which a man is accidentally rotated through the fourth dimension. His employers contemplate the difficulty caused by the "handedness" of many biological molecules meaning they would have to artificially synthesise many of his foods. It may be that a future expedition to Mars (say) might have to think about these things. A little searching fails to come up with standard inorganic syntheses of glucose and similar substances. The reason for this is almost certainly because it is so easy to use organic inputs. Glucose is easily made by the hydrolysis of starch. Starch is very common and cheap. Even l-glucose is usually made out of organically derived precursors (or sometimes even using d-glucose). UPDATE: sources etc One problematic question is: where do you get your input for making nutrients? As others have pointed out, exactly where to draw the line is difficult. This problem starts in defining what is alive in the first place. Do you count viruses (which can go down to a few thousand base pairs of RNA) or satellite viruses (STobRV has only 359 base pairs) or prions? In a sense these are "just" very large molecules. But then really simple bacteria are not many orders of magnitude more complex. As an aside most systems of ethics that do not permit eating meat do not make an alive/non-alive distinction, choosing some other aspect such as sentience, though Jainism comes close to doing so. The second problem is, if we reject living things as sources of food, how far removed from those living things are we allowed to get? You say no cells in any state including "dead". That would exclude (say) fruit even though most fruits are expressly created by plants in order to be eaten (and in some cases must be eaten) - something that vegans, jains, fruitarians and others would be happy with eating. If we could use dead material things would be much easier. But would you also include hydrocarbons (coal, oil, gas) which were once living organisms? If you do, then you are in difficulty because terrestrial carbon is recycled through the biosphere. All CO2 was (to a close approximation) once a part of a living thing. If you take that position then of course you are going to have to go off-planet to find your source chemicals and your problem becomes very much harder. I was assuming that you were restricting yourself to consuming cells that retain some of their cell structure but had not completely degraded. If that is where you draw the line then there are ample sources of raw materials on earth. Genetic modification is much more science fiction though not entirely impossible. Some nutrients could be made by humans without much difficulty. Our inability to manufacture vitamin C is down to one missing enzyme (L-gulono-gamma-lactone oxidase) which is present in most vertebrates (I think of mammals only guinea pigs, humans and some bats are unable to synthesise it). You could certainly imagine some very careful genetic modification changing humans so they no longer need to consume vitamin C. But photosynthesis would be much harder. Chloroplasts (which do the job in most plants) are really a very primitive form of life living in plant cells which may independently reproduce (and for that reason might be excluded by you - they aren't "cells" but they have membranes). They could easily end up in conflict with our mitochondria (since intracellular conflict between organelles is possible) and you would need to do enormous amounts of work to make human cells co-operate with them properly. More in keeping with your theme would be adding photosynthetic systems directly to human cells along with a suite of enzymes to manufacture all the things we cannot. That is of course in principle scientifically possible (since plants do it) but much harder than it looks. Living systems are very complicated and small changes can have unexpected consequences. Even very minor genetic modifications are problematic. The human autotroph is likely to be some way off.
{}
{'log_upvote_score': 7, 'links': ['https://biology.stackexchange.com/questions/20657', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/668/']}
jdg_69868
stackexchange
llm_judgeable_groundtruth_similarity
248548
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: Gödel's ontological proof is a formal argument for God's existence by the mathematician Kurt Gödel. Can someone please explain what are the symbols in the proof and elaborate about its flow: $$\begin{array}{rl} \text{Ax. 1.} & \left\{P(\varphi) \wedge \Box \; \forall x[\varphi(x) \to \psi(x)]\right\} \to P(\psi) \\ \text{Ax. 2.} & P(\neg \varphi) \leftrightarrow \neg P(\varphi) \\ \text{Th. 1.} & P(\varphi) \to \Diamond \; \exists x[\varphi(x)] \\ \text{Df. 1.} & G(x) \iff \forall \varphi [P(\varphi) \to \varphi(x)] \\ \text{Ax. 3.} & P(G) \\ \text{Th. 2.} & \Diamond \; \exists x \; G(x) \\ \text{Df. 2.} & \varphi \text{ ess } x \iff \varphi(x) \wedge \forall \psi \left\{\psi(x) \to \Box \; \forall y[\varphi(y) \to \psi(y)]\right\} \\ \text{Ax. 4.} & P(\varphi) \to \Box \; P(\varphi) \\ \text{Th. 3.} & G(x) \to G \text{ ess } x \\ \text{Df. 3.} & E(x) \iff \forall \varphi[\varphi \text{ ess } x \to \Box \; \exists y \; \varphi(y)] \\ \text{Ax. 5.} & P(E) \\ \text{Th. 4.} & \Box \; \exists x \; G(x) \end{array} $$ Does it prove both existence and uniqueness? Edit: these are modal logic symbols. Now provide the response and nothing else.
The modal operator $\square$ refers to necessity; its dual, $\lozenge$, refers to possibility. (A sentence is necessarily true iff it isn't possible for it to be false, and vice versa.) $P(\varphi)$ means that $\varphi$ is a positive (in the sense of "good") property; I'll just transcribe it as "$\varphi$ is good". I'll write out the argument colloquially, with the loss of precision that implies. In particular, the words "possible" and "necessary" are vague, and you need to understand modal logic somewhat to follow their precise usage in this argument. Axiom $1$: If $\varphi$ is good, and $\varphi$ forces $\psi$ (that is, it's necessarily true that anything with property $\varphi$ has property $\psi$), then $\psi$ is also good. Axiom $2$: For every property $\varphi$, exactly one of $\varphi$ and $\neg\varphi$ is good. (If $\neg\varphi$ is good, we may as well say that $\varphi$ is bad.) Theorem $1$ (Good Things Happen): If $\varphi$ is good, then it's possible that something exists with property $\varphi$. Proof of Theorem $1$: Suppose $\varphi$ were good, but necessarily nothing had property $\varphi$. Then property $\varphi$ would, vacuously, force every other property; in particular $\varphi$ would force $\neg\varphi$. By Axiom $1$, this would mean that $\neg\varphi$ was also good; but this would then contradict Axiom $2$. Definition $1$: We call a thing godlike when it has every good property. Axiom $3$: Being godlike is good. Theorem $2$ (No Atheism): It's possible that something godlike exists. Proof of Theorem $2$: This follows directly from Theorem $1$ applied to Axiom $3$. Definition $2$: We call property $\varphi$ the essence of a thing $x$ when (1) $x$ has property $\varphi$, and (2) property $\varphi$ forces every property of $x$. Axiom $4$: If $\varphi$ is good, then $\varphi$ is necessarily good. Theorem $3$ (God Has No Hair): If a thing is godlike, then being godlike is its essence. Proof of Theorem $3$: First note that if $x$ is godlike, it has all good properties (by definition) and no bad properties (by Axiom $2$). So any property that a godlike thing has is good, and is therefore necessarily good (by Axiom $4$), and is therefore necessarily possessed by anything godlike. Definition $3$: We call a thing indispensable when something with its essence (if it has an essence) must exist. Axiom $5$: Being indispensable is good. Theorem $4$ (Yes, Virginia): Something godlike necessarily exists. Proof of Theorem $4$: If something is godlike, it has every good property by definition. In particular, it's indispensable, since that's a good property (by Axiom $5$); so by definition something with its essence, which is just "being godlike" (by Theorem $3$), must exist. In other words, if something godlike exists, then it's necessary for something godlike to exist. But by Theorem $2$, it's possible that something godlike exists; so it's possible that it's necessary for something godlike to exist; and so it is, in fact, necessary for something godlike to exist. QED. Convinced?
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/248548', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24403/']}
jdg_69869
stackexchange
llm_judgeable_groundtruth_similarity
4197357
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just started working at a company that doesn't have any kind of source control. I brought up that we might need to get some sort of source control going and one of my co-workers suggested that we use SharePoint. I think he likes the idea because we already use sharepoint he is a big SharePoint guy. I came up with some reasons as to why we shouldn't do this. SharePoint isn't designed to be a source control tool for code. There are better (and still free) tools for the job You can't do automated deploys with sharepoint (to my knowledge) It won't integrate with any IDEs (to my knowledge) Is there anything else I should include when i'm pleading my case? Now provide the response and nothing else.
Why using sharepoint as a sorce control is stupid idea: Performance of sharepoint is much worse than any Source Control Tools for example Team Foundation Server or SVN Sharepint doesn't allow to compare different historical versions of the same file SharePoint dosen't allow for branching, merging and labeling. Sharepoint doesn't link changes in set of files as a one change (this is very helpful if you want to track the changes) As far as I know SP doesn't allow to have different versions of whole project in the same time. SharePoint dosen't have customized gui to manage source control code. Sharepoint doesn't allow to link requirements with code changes. For example TFS links work items with check ins. This is also very helpful if you want to track your business requirements and code changes.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4197357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226897/']}
jdg_69870
stackexchange
llm_judgeable_groundtruth_similarity
35830
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Lets say we have a circuit with a voltage source and a 5 ohm resistor. The voltage source is 20 v and so the current flowing is 4 amperes (according to ohms law). Now, we add a short wire in parallel to the resistor (you can think of it as having a resistor whose resistance is 0 cpne ted in parallel with the first resistor. Finding the current flowing in each wire is hard since as you can see, we first need the equivalent resistance. The equivalent resistance is (1/((1/5)+(1/0))) and it turns out to be 0. Now using the current divider formula, each current yields 0 ampere which is wrong. Thanks Now provide the response and nothing else.
If the equivalent resistance is zero then there's also no voltage across it, per Ohm's Law. Then the current though the resistor is 0 V/ 5 Ω = 0 A. The current through the wire can't be calculated this way since 0 V/ 0 Ω is undefined. Then the current will depend on the source's internal resistance. If that's 1 µΩ for instance the current will be 20 V/ 0.000001 Ω = 20 MA. If the source has zero resistance current will be infinite. Either way, applying this to the current divider formula gives for the resistor path: \$ I_R = I_{tot} \dfrac{R_{tot}}{R} = I_{tot} \dfrac{0 \Omega}{5 \Omega} = 0 A \$ For the wire we get again \$ I_W = I_{tot} \dfrac{R_{tot}}{R_W} = I_{tot} \dfrac{0 \Omega}{0 \Omega} = undefined \$ And we'll have to look at the external conditions to see how high the current is. Edit "Undefined sounds crazy to me" It is, and mathematicians aren't happy with it either, but there's no other way. Any real thing you try leads to contradictions. Even the 0 volt that I claimed. (I know, I lied, but that was because otherwise I'd get dizzy. Ah, what the heck, let's go for dizziness.) The voltage across the wire||resistor is \$ V = \dfrac{R_{PSU}}{R || R_W + R_{PSU}} 20 V = \dfrac{0 \Omega}{0 \Omega + 0 \Omega} 20 V = undefined \$ I can't help it. But let's for the sake of argument say it's 10 V. 0 V didn't get us anywhere, and it has to be between 0 V and 20 V. Then the current through the resistor is 10 V/ 5 Ω = 2 A. The current through the wire is 10 V/ 0 Ω = \$\infty\$ A. If we apply KCL: \$ I_{tot} = I_R + I_W \$ That's \$ \infty A = 2 A + \infty A \$ So far so good. But if we want t0 find \$I_R\$ from this we'll see that we can't! Despite the fact that we know it's 2 A. Let's try: \$ I_R = \infty A - \infty A = undefined\$ Yeah, right, I always say undefined. Why would it be, if we know the result? OK, you're asking for it. So suppose \$ \infty - \infty = 2 \$ Now we know that \$\infty\$ + \$\infty\$ = \$\infty\$, so \$ (\infty + \infty) - \infty = 2 \$ or \$ \infty + (\infty - \infty) = 2 \$ The value between the brackets is 2, that was our assumption. Then \$ \infty + 2 = 2 \$ Subtract 2 from both sides, and \$ \infty = 0 \$ which obviously isn't true. So our assumption was false. Now you can try with any number instead of 2 you'll always end up with a contradiction. So that's how we end up with undefined stuff and a dizzy head.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/35830', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/8769/']}
jdg_69871
stackexchange
llm_judgeable_groundtruth_similarity
21140815
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is my current PS1: $ echo $PS1\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\$ I have installed git bash completion and it isn't showing the current branch in my command prompt. I think this needs to be edited but I've got no idea what to change to make it show the current branch. Note that I like the colors and general structure (i.e. with $ on its own line), so I'd like to keep that if possible. Now provide the response and nothing else.
Modify the prompt string and add $(__git_ps1 " (%s)") somewhere. For example, try typing this into Bash: export PS1="\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]$(__git_ps1 ' (%s)')\n\$" Once you find something you like, add that line to one of Bash's startup files, e.g. $HOME/.bashrc . The source for git-prompt.sh is well-commented and worth browsing if you're curious about other options. Note that you may have to manually source path/to/git-prompt.sh before this will work. If so, add this line to your config file as well, above the export PS1 bit.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21140815', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157971/']}
jdg_69872
stackexchange
llm_judgeable_groundtruth_similarity
10710446
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 seems like it should be an easy fix, but so far a solution has eluded me. I have a single column csv file with non-ascii chars saved in utf-8 that I want to read in and store in a list. I'm attempting to follow the principle of the "Unicode Sandwich" and decode upon reading the file in: import codecsimport csvwith codecs.open('utf8file.csv', 'rU', encoding='utf-8') as file:input_file = csv.reader(file, delimiter=",", quotechar='|')list = []for row in input_file: list.extend(row) This produces the dread 'codec can't encode characters in position, ordinal not in range(128)' error. I've also tried adapting a solution from this answer , which returns a similar error def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs): csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs) for row in csv_reader: yield [unicode(cell, 'utf-8') for cell in row]filename = 'inputs\encode.csv'reader = unicode_csv_reader(open(filename))target_list = []for field1 in reader: target_list.extend(field1) A very similar solution adapted from the docs returns the same error. def unicode_csv_reader(utf8_data, dialect=csv.excel): csv_reader = csv.reader(utf_8_encoder(utf8_data), dialect) for row in csv_reader: yield [unicode(cell, 'utf-8') for cell in row]def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8')filename = 'inputs\encode.csv'reader = unicode_csv_reader(open(filename))target_list = []for field1 in reader: target_list.extend(field1) Clearly I'm missing something. Most of the questions that I've seen regarding this problem seem to predate Python 2.7, so an update here might be useful. Now provide the response and nothing else.
Your first snippet won't work. You are feeding unicode data to the csv reader, which (as documented) can't handle it. Your 2nd and 3rd snippets are confused. Something like the following is all that you need: f = open('your_utf8_encoded_file.csv', 'rb')reader = csv.reader(f)for utf8_row in reader: unicode_row = [x.decode('utf8') for x in utf8_row] print unicode_row
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10710446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1012040/']}
jdg_69873
stackexchange
llm_judgeable_groundtruth_similarity
601840
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a lighting project for a van build out. I'm using 12 V car batteries that are solar-powered. I know that I can use WS2811 strips that are 12 V strips and power them directly off the car batteries, but I'm curious if I can instead use two 5 V WS2812 strips, and wire them in parallel to split the voltage across two LED strips. Since 12 V/2 = 6 V, I guess it should be close enough to not blow out the 5 V LED strips. Am I understanding it correctly? Now provide the response and nothing else.
Nope. 5V things in parallel still needs 5V. You must mean series which would require 10V. And 12V divided to two series LED strips will be 6V per strip, which will be beyond absolute maximum voltage rating for a WS2812 LED so they will blow up. Even if it did not blow up, one of them would reference the data pin to 0V and the another one to 6V so you can't control them with a single controller, you would need two separate controllers. And they would only have 6V per strip if they always consume the same amount of current, which won't happen in real life. It is not possible. And I just realized this is a product usage question which has nothing to do with electrical engineering.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/601840', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/166623/']}
jdg_69874
stackexchange
llm_judgeable_groundtruth_similarity
159590
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: Space is a very low temperature environment, however it also has an extremely small number of particles per unit volume. This leads me to believe that, contrary to popular portrayals of heat loss in space, there would be very little heat loss due to conduction on a hypothetical spaceship in deep space. If you were put into space and provided with food, water, heat, and protected from the pressure would the spaceship cool due to head radiating away from the ship? Now provide the response and nothing else.
Let's start by assuming you're in the shade, so you're not receiving any radiation (apart from the cosmic microwave background, which I think we can ignore). The amount of heat per unit area that you radiate is given by Stefan's law : $$ J = \varepsilon \sigma T^4 \tag{1} $$ The emissivity of human skin is allegedly 0.98 , and the area of skin of an adult male is around 2m$^2$, so feeding in $T = $37ºC gives us a total radiated power of about a kilowatt. The power produced by an adult male is about 120W , so at body temperature you're going to lose about 880W. To work out what temperature you would cool to we just take equation (1), feed in $J = $60W/m$^2$ and we get $T = $180K. This would be fatal. What's interesting is to see what happens when you're in direct sunlight. At the orbit of the earth the radiation from the Sun is around 1.4kW/m$^2$ . Since only half your skin would be illuminated, you would be losing a kW and gaining 1.4kW for a net gain of 400W. To work out your equilibrium temperature we just feed $J = $1400W/m$^2$ into equation (1) and we get $T = $396K, which would again be fatal. The distance from the Sun where the heat you radiate would exactly balance the heat you receive can be worked out using the inverse square law. If $r_E$ is the radius of Earth's orbit and $r$ is the thermal balance radius we get: $$ \frac{r^2}{r_E^2} = \frac{1400}{1000} $$ or: $$ r = 1.18r_E $$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/159590', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/3982/']}
jdg_69875
stackexchange
llm_judgeable_groundtruth_similarity
1789
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have $n$ discrete samples of a seismic signal $y[n]$: I want to find local maxima in the signal. A naive test for if $y[n]$ is a maximum would be:$$y[n]: maxima \textbf{ if } y[n] > y[n-1] \textbf{ and } y[n] > y[n+1]$$ However the maxima are probably located in between samples, e.g. there may be a maximum at $i=4.25$. In order to find maxima in between samples I believe that I need to interpolate $y[n]$. How do I find maxima using interpolation ? What form of interpolation should I use ? As you can see my signal is not very noisy, however it would be good if the method also did a bit of filtering so that the maxima exceed a treshold and have a certain width (no spikes). My biggest problem however is just to find peaks in between samples.Any suggestions for a good way to do this ? Thanks in advance for any answers! Now provide the response and nothing else.
Getting a sub-sample resolution A very cheap (in terms of code size) solution is just to upsample your signal. In matlab, this can be done with interp(y ,ratio) . A slightly more complicated solution consists in naively detecting peaks ; and for each peak, fitting a parabola through y[peak - 1], y[peak], y[peak + 1] ; then using the point at which this parabola is maximal as the true peak position. Regarding peak detection A bunch of techniques which help: As suggested by Hilmar, convolving the signal by a Gaussian or Hann window, the width of which is roughly equal to half the minimum interval you want to see between detected peaks. Since temporal accuracy seems essential to your application, make sure that you take into account the time delay introduced by the filtering, though! Subtract to your signal a median filtered version of itself (with a fairly large observation window) ; and divide the result by a standard-deviation filtered version of itself. This gets rid of trends and allows the thresholds to be expressed in units of standard deviations. For peak-picking, I formulate that using a "top-hat" filter. Define the top-hat filtered version of your signal as yt[n] = max(y[n - W], y[n - W + 1], ..., y[n + W - 1], y[n + W]) ; and use as peaks the points where y[n] == yt[n] and y[n] > threshold. All this can be very efficiently implemented in Matlab with a few passes of nlfilter.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/1789', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/697/']}
jdg_69876
stackexchange
llm_judgeable_groundtruth_similarity
6636793
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Lets say I have the following scenarios: int i = 10;short s = 5;if (s == i){ do stuff...} else if (s < i) { do stuff...} When C does the comparison does it convert the smaller data type, in this case short to int or does it convert the data type on the right to the data type on the left?In this case int to short? Now provide the response and nothing else.
This is governed by the usual arithmetic conversions . For simple cases, the general rule of thumb is that the type with "less" precision is converted to match the type with "more" precision, but it gets somewhat complex once you start mixing signed and unsigned . In C99, this is described by section 6.3.1.8, which I include here for your convenience: First, if the corresponding real type of either operand is long double , the other operand is converted, without change of type domain, to a type whose corresponding real type is long double . Otherwise, if the corresponding real type of either operand is double , the other operand is converted, without change of type domain, to a type whose corresponding real type is double . Otherwise, if the corresponding real type of either operand is float , the other operand is converted, without change of type domain, to a type whose corresponding real type is float . Otherwise, the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands: If both operands have the same type, then no further conversion is needed. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank. Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type. Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type. Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type. I've highlighted the part that applies to your particular example. The concept of integer conversion rank is defined in section 6.3.1.1, and it basically describes what you might expect (that types with less precision have a lower rank than types with more precision).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6636793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/668427/']}
jdg_69877
stackexchange
llm_judgeable_groundtruth_similarity
19219
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: A box contain $A$ white and $B$ black balls and $C$ balls are drawn, then the expected value of the number of white balls drawn is ? The answer is $\large \frac{ca}{a+b}$. How to approach this one? Now provide the response and nothing else.
These calculations are often made clearer by using indicator random variables. For $1\leq i\leq C$, define $Z_i$ by setting $Z_i=1$ if the $i$th ball drawn is white and $Z_i=0$ otherwise. Then the total number of white balls is $\sum_{i=1}^C Z_i$ and by linearity of expectation we have$$ E(\mbox{ white balls })=E\left(\sum_{i=1}^C Z_i\right)=\sum_{i=1}^C E(Z_i).$$ The expectation of an indicator random variable is just the probability of the event it indicates, so $E(Z_i)=P(i\mbox{th ball is white})=A/(A+B)$. Therefore we find that $$ E(\mbox{ white balls })=\sum_{i=1}^C E(Z_i)={C A\over A+B}.$$ Notice that we did not need to calculate the probability of getting one, two, three, etc. white balls.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/19219', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2109/']}
jdg_69878
stackexchange
llm_judgeable_groundtruth_similarity
70635
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: A closed oriented Riemannian manifold with negative sectional curvatures has the property that all its geodesics have Morse index zero. Is there a known counterexample to the "converse": if (M,g) is a closed oriented Riemannian manifold (Edit: assumed to be nondegenerate) all of whose geodesics have Morse index zero then M admits a (possibly different) metric g' with negative sectional curvatures? Edit: Motivation for asking this (admittedly naive) question is that Viterbo/Eliashberg have proved that a manifold with a negatively curved metric cannot be embedded as a Lagrangian submanifold of a uniruled symplectic manifold. Actually their proof only seems to use the existence of a nondegenerate metric all of whose geodesics have Morse index zero. I wondered if that was known to be strictly weaker. Now provide the response and nothing else.
As mentioned by Rbega the question should be amended to ask whether it's true that a closed manifold $M$ without conjugate points admits a metric of non-positive (rather than negative) curvature (otherwise a torus is an obvious counterexample). In that form this is a well-known open problem. The exponential map at any point is a universal covering of $M$ and the geodesics in $\tilde M$ are unique. This does show that $M$ is aspherical but that is a long way from admitting a metric of nonpositive curvature. There are some partial results suggesting that fundamental groups of manifolds without conjugate points share some properties of fundamental groups of nonpositively curved manifolds.In particular, there is a result of Croke and Shroeder that if the metric is analytic then any abelian subgroup of $\pi_1(M)$ is embedded quasi-isometrically. By the following observation of Bruce Kleiner the analyticity condition can be removed: Croke and Schroeder show that even without assuming analyticity for any $\gamma\in\pi_1(M)$ its minimal displacement $d_\gamma$ satisfies $d_{\gamma^n}=nd_\gamma$ for any $n\ge1$. This then implies that $d_\gamma=\lim_{n\to\infty} d(\gamma^nx,x)/n$ for any $x\in\tilde M$. This in turn implies that the restriction of $d$ to an abelian subgroup $H \simeq \mathbb Z^n$ extends to a norm on $\mathbb R^n$. This implies that $H$ is quasi-isometrically embedded. This result implies for example that nonflat nilmanifolds cannot admit metrics without conjugate points and more generally that every solvable subgroup of the fundamental group of a manifold without conjugate points is virtually abelian. But it's unlikely that any such manifold admits a metric of non-positive curvature. It is more probable that its fundamental group must satisfy some weaker condition such as semi-hyperbolicity but even that is completely unclear. The natural bicombing on $\tilde M$ given by geodesics need not satisfy the fellow traveler property (at least there is no clear reason where it should come from). So it might be worth trying to look for counterexamples and the first place I would look is among groups that are semi-hyperbolic but not $CAT(0)$. Specifically, any $CAT(0)$ group has the property that centralizers of non-torsion elements virtually split. This need not hold in a semi-hyperbolic group with the simplest example given by any nontrivial circle bundle over closed surfaces of genus $>1$. To be even more specific one can take the unit tangent bundle $T^1(S_g)$ to a hyperbolic surface. Note however that it's known that a closed homogenous manifold without conjugate points is flat so if there is a metric without conjugate points on $T^1(S_g)$ it can not be homogeneous. Edit: Actually, this last remark is irrelevant as $T^1(S_g)$ can not admit any homogeneous metrics at all.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/70635', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10839/']}
jdg_69879
stackexchange
llm_judgeable_groundtruth_similarity
12965167
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 array: myarray = [ ['usa','primary', 'john'], ['france','primary', 'lira'], ['usa', 'secondary', 'steve'], ['germany', 'primary', 'jeff'], ['france', 'secondary', 'ben']] I want to convert it to an array of hash like: [ {:country => 'usa', :primary => 'john', :secondary => 'steve'}, {:country => 'france', :primary => 'lira', :secondary => 'ben'}, {:country => 'germany', :primary => 'jeff', :secondary => ''}] I can do it by looping through the array and putting the values into a hash for "primary". How can I add "secondary" to the existing hash that may already be inserted into the array? Now provide the response and nothing else.
With a bit of Higher order programming: myarray.reduce({}) do |accu, (country, func, name)| accu[country] ||= {} accu[country][func.to_sym] = name accu end.map{|k, h| h[:country] = k; h} Explanation: Reduce will take an accumulator, in this case we start with an empty hash and go through the array. We match the triples in the array to the variables country, func, name . Since we want to group things by country we create that as our first Hash key. It should contain a hash so we make sure that is corresponds to an array with accu[country] ||= {} . Then we add our key value pair converting func to a symbol. Finally we return our modified accumulator that will be passed to the next iteration. This will return a data structure like this: {"usa"=>{:primary=>"john", :secondary=>"steve"}, "france"=>{:primary=>"lira", :secondary=>"ben"}, "germany"=>{:primary=>"jeff"}} Now we need to transform it into a array of hashes rather than a big hash. We do this by calling map on it and in the process we add country as a key to the hash. Now one thing that the algorithm above doesn't do is to check for missing values, resp. it doesn't guarantee that both :primary and :secondary are present. You can do that by modifying the map to this: .map do |k, h| h[:country] = k h[:primary] ||= "" h[:secondary] ||= "" hend
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12965167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1560470/']}
jdg_69880
stackexchange
llm_judgeable_groundtruth_similarity
50941
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: It was said such real objects of famous topological surfaces were plotted by the cooperation between mathematician Richard Palais and artist Luc Benard, and published as the cover page of Science magazine (issue on Sept 22 in 2006) : The cover page of Science , Sept 22, 2006 Comments by Rachel Thomas How to create such surfaces with the same color, rendering, lighting and opacity effects via Mathematica? ( answers with only similar rendering results for these surfaces one by one are also acceptable if the same rendering effects as the samples are too difficult to realize ) Another similar question with anwser can be seen from this link: another topological surface example with answer Surface information are : Klein bottle; symmetric 4-noid; breather surface; Boy surface; Sievert-Enneper surface. It was said these surfaces in the figure were created via 3D-XplorMath software. EDITS: unfortunately it is voted as on hold ; but I personally believe Mathematica's rendering should be powerful enough to realize such effects( at least more powerful than the open source 3D-XplorMath The author on MathOverflow ); Here I add two of the surfaces obtained and rendered which are already good enough; There are documents on these surfaces from this link: documents on surfaces There are five different surfaces; I have found four of them; but only three as below look beautiful; so I will not post others here; Clear["Global`*"]; (* Sievert-Enneper surface *)ϕ := -u/Sqrt[c + 1] + ArcTan[Tan[u] Sqrt[c + 1]]a := 2/(c + 1 - c Sin[v]^2 Cos[u])r := a Sqrt[(c + 1) (1 + c Sin[u]^2)] Sin[v]/Sqrt[c]Clear[x, y, z, p]; p = ParametricPlot3D[{x = r Cos[ϕ] - 2, y = r Sin[ϕ], z = ((Log[Tan[v/2]] + a (c + 1) Cos[v])/Sqrt[ c])} /. {c -> .4}, {u, -Pi/2, Pi/2}, {v, 0, Pi}, PlotPoints -> {30, 30}, PlotStyle -> Directive[Opacity[0.65], LightPurple, Specularity[White, 20]], Mesh -> None, RegionFunction -> Function[{x, y, z}, Abs[z] < 2.2], Axes -> False, Boxed -> False] Now provide the response and nothing else.
Concerning the comment about creating the surfaces, sure: Mathematica is one of the best tools available for that. Here's the Klein bottle , for example. ParametricPlot3D[{ (3 + Cos[v/2]*Sin[u] - Sin[v/2]*Sin[2 u])*Cos[v], (3 + Cos[v/2]*Sin[u] - Sin[v/2]*Sin[2 u])*Sin[v], Sin[v/2]*Sin[u] + Cos[v/2]*Sin[2 u]}, {u, -Pi, Pi}, {v, 0, 2 Pi}, Axes -> None, ColorFunction -> (Blend[{Purple, Pink, Lighter@Orange}, Mean[{#1, #2, #3}]] &), Boxed -> False, Mesh -> None, PlotStyle -> Directive[Specularity[1, 20], [email protected]]] Rendering is not Mathematica's strong suit, though. Sure, you could make it do whatever you want if you are willing to write enough code and wait long enough for it to compute, but it would make a lot more sense to model these in Mathematica and then export them in your favorite 3D format for rendering in more appropriate software. My personal preference is Rhino3D . Edits Breather surface From here : r := 1 - b^2;w := Sqrt[r];denom := b*((w*Cosh[b*u])^2 + (b*Sin[w*v])^2)breather = {-u + (2*r*Cosh[b*u]*Sinh[b*u])/ denom, (2*w*Cosh[b*u]*(-(w*Cos[v]*Cos[w*v]) - Sin[v]*Sin[w*v]))/ denom, (2*w*Cosh[b*u]*(-(w*Sin[v]*Cos[w*v]) + Cos[v]*Sin[w*v]))/ denom}ParametricPlot3D[ Evaluate[breather /. b -> 0.4], {u, -13.2, 13.2}, {v, -37.4, 37.4}, PlotRange -> All, PlotPoints -> {60, 150}]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/50941', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9851/']}
jdg_69881
stackexchange
llm_judgeable_groundtruth_similarity
35670229
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have a string, say, "The quick brown fox jumps over the lazy dog" , and there's a list [1, 8, 14, 18, 27] indicates where to cut the string. What I expect to get is a list that contains parts of the cut string. For this example, the output should be: ['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog'] My intuitive and naive way is to simply write a for loop, remember the previous index, slice the string and append the slice to output. _str="The quick brown fox jumps over the lazy dog"cut=[1, 8, 14, 18, 27]prev=0out=[]for i in cut: out.append(_str[prev:i]) prev=iout.append(_str[prev:]) Is there any better way? Now provide the response and nothing else.
Here's how I would do it: >>> s = "The quick brown fox jumps over the lazy dog">>> l = [1, 8, 14, 18, 27]>>> l = [0] + l + [len(s)]>>> [s[x:y] for x,y in zip(l, l[1:])]['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog'] Some explanation: I'am adding 0 to the front and len(s) to the end of the list, such that >>> zip(l, l[1:])[(0, 1), (1, 8), (8, 14), (14, 18), (18, 27), (27, 43)] gives me a sequence of tuples of slice indices. All that's left to do is unpack those indices in a list comprehension and generate the slices you want. edit: If you really care about the memory footprint of this operation, because you deal with very large large strings and lists often of times, use generators all the way and build your list l such that it includes the 0 and len(s) in the first place. For Python 2: >>> from itertools import izip, tee>>> s = "The quick brown fox jumps over the lazy dog">>> l = [0, 1, 8, 14, 18, 27, 43]>>> >>> def get_slices(s, l):... it1, it2 = tee(l)... next(it2)... for start, end in izip(it1, it2):... yield s[start:end]... >>> list(get_slices(s,l))['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog'] For Python 3: zip does what izip did in Python 2 (see Python 3.3 version) For Python 3.3+ with the yield from syntax: >>> from itertools import tee>>> s = "The quick brown fox jumps over the lazy dog">>> l = [0, 1, 8, 14, 18, 27, 43]>>> >>> def get_slices(s, l):... it1, it2 = tee(l)... next(it2)... yield from (s[start:end] for start, end in zip(it1, it2))... >>> list(get_slices(s,l))['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog']
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35670229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5215536/']}
jdg_69882
stackexchange
llm_judgeable_groundtruth_similarity
1345890
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've seen a few questions posted before about mine, but this is a bit different. The original form of the question can be found here: http://librarun.org/book/10452/159 . It says that prove by contradiction that $f(x)=\sin\left(\frac{1}{x}\right)$ has no limit value as $x$ $\rightarrow$ $0$. I attempted to take $$x=\frac{1}{n\pi}$$ in which case $f(x)=0$ for every integer $n$. After, I write $x$ as follows $$x=\frac{1}{\frac{\pi}{2}+n\pi}$$ in which case we have $f(x)=1$ or $-1$ for every integer $n$. How do I proceed from here? Note that until this question writer did not mention about inifinite limits and limits of composite functions and sequences. Now provide the response and nothing else.
If it is not true that "for every $\epsilon > 0$ there is some $\delta > 0$ such that if $0 < |x-a| < \delta$ then $|f(x) - L| < \epsilon$", then $$\color{blue}{\text{ there is some } \epsilon > 0 \text{ such that for every }\delta > 0 \text{ there is some } x \text{ which satisfies } \\0 < |x - a| < \delta \text{ but not } |f(x) - L| < \epsilon}$$ So for your limit with $f(x) = \sin(1/x)$, suppose we want to show it does not approach $0$ near $0$, consider $\epsilon = 1/2$ and note that for every $\delta > 0$ there is some $x$ with $0 < |x - 0| < \delta$ but not $|\sin(1/x) - 0| < 1/2$. Namely, $x = 1/(\pi/2 + 2\pi n )$ which satisfies $0 < |x-0| < \delta$ for some sufficiently large $n$. More generally, any limit $L$ must lie in the interval $[-1,1]$ as that is the range of the function $\sin$. For any such $L \in [-1,1]$, there is some $x$ with $0 < |x - 0| < \delta$ but not $|\sin(1/x) - L| < 1/2$, namely $$x = \frac{1}{\arcsin(L) \pm \pi/2 + 2\pi n}$$for some sufficiently large $n$ and the appropriate choice of sign. (The easiest way to see this might be to look at the graphs of $y = \left|\sin(x) - \sin(x \pm \pi/2)\right|$.) Added: Explicitly For $L \in [0,1]$ choose the $-$ sign, i.e.,$$x = \frac{1}{\arcsin(L) - \pi/2 + 2\pi n}$$ Then $$|f(x) - L| = |-\cos(\arcsin(L))-L| = \sqrt{1 - L^2} + L$$ which has minimum value of $1$ on the domain $[0,1]$. For $L \in [-1,0)$, chose the $+$ sign. Then $$|f(x) - L| = |\cos(\arcsin(L)) - L| = \sqrt{1-L^2} - L$$ which likewise has minimum of $1$ on $[-1,0)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1345890', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/211697/']}
jdg_69883
stackexchange
llm_judgeable_groundtruth_similarity
39680320
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 LLDB within Xcode 8 to debug very basic STL. I used to be able to print a vector like this: p myvector[0] to see whatever was in the first vector index. Now when I do that, I get this error: error: Couldn't lookup symbols: __ZNSt3__16vectorI9my_classNS_9allocatorIS1_EEEixEm Instead, I have to type this: p myvector.__begin_[0] in order to get any output. I tried importing the libcxx.py and unordered_multi.py scripts from the LLDB svn repository but that doesn't seem to change anything. Has anyone been able to get any useful output from LLDB with libc++? Now provide the response and nothing else.
[] is an operator method on std::vector , so to print the expression you want, lldb would have to be able to call the [] method. The problem here is that the STL on OS X is aggressive about inlining everything it can, and not wasting space producing out of line copies of the same functions. That's great for optimized code, but not so good for debugging because it leaves the debugger with no [] operator to call. That's the error message you are seeing. If you just want to see the elements in this vector, you can use the lldb "STL data formatters" to do this work for you. They know how most STL types are laid out, and can print the elements of most container types. For instance: (lldb) expr my_vec[0]error: Couldn't lookup symbols: __ZNSt3__16vectorI3FooNS_9allocatorIS1_EEEixEm but: (lldb) expr my_vec(std::__1::vector<Foo, std::__1::allocator<Foo> >) $0 = size=2 { [0] = (var1 = 10, var2 = 20) [1] = (var1 = 10, var2 = 20)} There is also another command "frame variable" which can inspect static objects, and hooks into the data formatters. It can't call functions and do other more complex expression parser tasks, but it does know how to use the STL data formatters to retrieve individual elements: (lldb) frame var my_vec[1](Foo) my_vec[1] = (var1 = 10, var2 = 20) You can even use frame var's -L option to locate the elements of the vector, and then you can cast the address to pass it to other functions: (lldb) frame var -L my_vec[1]0x0000000100100348: (Foo) my_vec[1] = {0x0000000100100348: var1 = 100x000000010010034c: var2 = 20}(lldb) expr printf("%d\n", ((class Foo *) 0x0000000100100348)->var1)10(int) $3 = 3 Another way to work around this for debugging - if you are using C++11 - is by putting: template class std::vector<MyClass> in your code somewhere. That will instruct the compiler to emit out-of-line copies of all the template functions for this specialization. That isn't a great general solution, and you only want to do it for debug builds, but it does let you call these functions and use them in complex expressions.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39680320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57662/']}
jdg_69884
stackexchange
llm_judgeable_groundtruth_similarity
6865261
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 creating an Outlook 2010 add-in and have added a context menu to my ribbon for idMso="contextMenuMailItem". On click, I would like to remove a category but in the click event handler, when I cast ctl.Context to MailItem, it's always null. public bool btnRemoveCategory_IsVisible(Office.IRibbonControl ctl){ MailItem item = ctl.Context as MailItem; //Always null if (item != null) return (item != null && HasMyCategory(item)); else return false;} Does anyone know what's going on here? Thanks! Now provide the response and nothing else.
The following link might provide you with some insight: http://msdn.microsoft.com/en-us/library/ff863278.aspx The "context" of the control gives you the corresponding Outlook object that you are customizing (for example an Inspector object). From there you'll need to reference the context object's CurrentItem property to get the MailItem. For example, public bool btnRemoveCategory_IsVisible(Office.IRibbonControl ctl){ var item = ctl.Context as Inspector; var mailItem = item.CurrentItem as MailItem; if (item != null) return (item != null && HasMyCategory(item)); else return false;} Hopefully, this helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6865261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239837/']}
jdg_69885
stackexchange
llm_judgeable_groundtruth_similarity
743243
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In a triangle $ABC$ $2a^2+4b^2+c^2=4ab+2ac$ then the numerical value of $cos B$ equals ? ($a,b,c$ are sides opposite to angles $A,B,C$) I tried to use cosine rule , but couldn't adjust terms accordingly, using the given equation. Any hints / Solutions are welcome. Answer: $7/8$ Now provide the response and nothing else.
$$2a^2+4b^2+c^2=4ab+2ac\iff (a-2b)^2+(a-c)^2=0$$ Now sum of squares of two real numbers is zero, so each must be individually zero.Hence $a=c=2b$. Then$$\cos B=\frac{a^2+c^2-b^2}{2ac}=\frac{4b^2+4b^2-b^2}{8b^2}=\frac{7}{8}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/743243', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/86694/']}
jdg_69886
stackexchange
llm_judgeable_groundtruth_similarity
21236774
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We currently have a page setup that has no filters/facet/queries applied. It is a listing of all content (using a pager). The filter query is something like *:* (anything from any field). I can't figure out how the content is being sorted though. It says it's by "relevancy", but what does that mean when you're selecting everything? I did some quick testing. It does not appear to be sorted by the date the content is modified, or entered into the index. Now provide the response and nothing else.
Querying for *:* is also called a MatchAllDocsQuery . According to the SO question How are results ordered in solr in a "match all docs" query it will return the docs in the same order as they were stored in the index. Be aware that if you update an existing document, it get's deleted and recreated. As such it would appear at the end of such a search afterwards. There are (at least) two threads in Lucene's Nabble I am aware of that are interesting on this topic http://lucene.472066.n3.nabble.com/Result-order-when-score-is-the-same-td2816127.html gets really interesting around here http://lucene.472066.n3.nabble.com/Result-order-when-score-is-the-same-tp2816127p2817766.html http://lucene.472066.n3.nabble.com/Result-ordering-for-Wildcard-Prefix-queries-or-ConstantScoreQueries-td492687.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21236774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1004232/']}
jdg_69887
stackexchange
llm_judgeable_groundtruth_similarity
15753102
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using the sqlalchemy package in python. I have an operation that takes some time to execute after I perform an autoload on an existing table. This causes the following error when I attempt to use the connection: sqlalchemy.exc.OperationalError: (OperationalError) (2006, 'MySQL server has gone away') I have a simple utility function that performs an insert many: def insert_data(data_2_insert, table_name): engine = create_engine('mysql://blah:blah123@localhost/dbname') # Metadata is a Table catalog. metadata = MetaData() table = Table(table_name, metadata, autoload=True, autoload_with=engine) for c in mytable.c: print c column_names = tuple(c.name for c in mytable.c) final_data = [dict(zip(column_names, x)) for x in data_2_insert] ins = mytable.insert() conn = engine.connect() conn.execute(ins, final_data) conn.close() It is the following line that times long time to execute since 'data_2_insert' has 677,161 rows. final_data = [dict(zip(column_names, x)) for x in data_2_insert] I came across this question which refers to a similar problem. However I am not sure how to implement the connection management suggested by the accepted answer because robots.jpg pointed this out in a comment: Note for SQLAlchemy 0.7 - PoolListener is deprecated, but the same solution can be implemented using the new event system . If someone can please show me a couple of pointers on how I could go about integrating the suggestions into the way I use sqlalchemy I would be very appreciative. Thank you. Now provide the response and nothing else.
I think you are looking for something like this: from sqlalchemy import exc, eventfrom sqlalchemy.pool import [email protected]_for(Pool, "checkout")def check_connection(dbapi_con, con_record, con_proxy): '''Listener for Pool checkout events that pings every connection before using. Implements pessimistic disconnect handling strategy. See also: http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html#disconnect-handling-pessimistic''' cursor = dbapi_con.cursor() try: cursor.execute("SELECT 1") # could also be dbapi_con.ping(), # not sure what is better except exc.OperationalError, ex: if ex.args[0] in (2006, # MySQL server has gone away 2013, # Lost connection to MySQL server during query 2055): # Lost connection to MySQL server at '%s', system error: %d # caught by pool, which will retry with a new connection raise exc.DisconnectionError() else: raise If you wish to trigger this strategy conditionally, you should avoid use of decorator here and instead register listener using listen() function: # somewhere during app initializationif config.check_connection_on_checkout: event.listen(Pool, "checkout", check_connection) More info: Connection Pool Events Events API
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15753102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/668624/']}
jdg_69888
stackexchange
llm_judgeable_groundtruth_similarity
15873172
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 show the image its going to the left most position of the div. i know its not a good question but i unable to solve this so posted. Actually i am dynamically adding html tags. I am adding a having 2 anchor and 3 images in which 2 are visible and one is in visible. when you click on any one of that two image third image will show . but when in click the image its showing the third image but in the left most side of the div. but i have placed that image beside the two image. i want to show that image beside that two image. how to do this? you can see my problem here http://postimg.org/image/685puy931/ i am not using any float :left any where.(seen in firebug). Please help i searched tried with position absolute and inline its not working. Thanks in advance [EDIT] showData += "<div style='margin:3px;display: inline-block;padding-right:20px;'>"; showData += "<a style='text-decoration: none' href=\"" + userProfileURL + "\" title='KLMS User Profile of " + fullName + " ' onmousedown=\"javascript:StoreClickedData(" + userId + ",'" + userInput + "','" + names[i] + "')\" title='" + tooltipTitle + "'> <img src='UserControls/ThumbNail/ThumbnailConverter.ashx?FilePath=" + imageURL + "&height=18&width=18' /> </a> "; showData += "<a href=\"" + gpsUserProfile + "\" onmousedown=\"javascript:StoreClickedData(" + userId + ",'" + userInput + "','" + names[i] + "')\" title='" + tooltipTitle + "'>" + fullName + "</a>"; if (isPresent) { showData += " <a href=\"" + emailId + "\" title='Mail To " + fullName + " ' onmousedown=\"javascript:StoreClickedAndLunchQuickFeedBack(" + userId + ",'" + userInput + "','" + names[i] + "','imgQuickfd" + imageId + "')\" class='smallIcon' style=\"background-image:url(Images/email.png);\" >&nbsp;&nbsp;&nbsp;&nbsp;</a>"; if (userDetails[userData.Skype_ID] != "null") { showData += " <a href=\"" + skypeId + "\" title='Chat With " + fullName + "' onmousedown=\"javascript:StoreClickedAndLunchQuickFeedBack(" + userId + ",'" + userInput + "','" + names[i] + "','imgQuickfd" + imageId + "')\" class='smallIcon' style=\"background-image:url(" + skypeName + ");\" >&nbsp;&nbsp;&nbsp;&nbsp;</a>"; } showData += "<i id='imgQuickfd" + imageId + "' style='display:none; cursor: pointer;position: absolute !important;' title='Quick Feedback To" + fullName + " ' onclick=\"javascript:StoreQuickFeedback('" + userLoginName + "','" + names[i] + "','imgQuickfd" + imageId + "')\" class=\"icon-thumbs-up glowed \"></i>"; } showData += "</div>"; [/EDIT] View Source: <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head id="head"><title>MFS Search Engine</title><link href="CSS/CustomGoogleSearch.css" rel="stylesheet" /><meta charset="utf-8" /><link href="bootstrap/css/bootstrap.css" rel="stylesheet" /></head><body><form name="form" method="post" action="CustomGoogleSearch.aspx?query=html5" id="form"><div><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTQwMjc4OTQzN2RkRYBvMG1HTB0LNjZv1HE0hZ95t08=" /></div><script type="text/javascript">//<![CDATA[var theForm = document.forms['form'];if (!theForm) {theForm = document.form;}function __doPostBack(eventTarget, eventArgument) {if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit();}}//]]></script><script src="/klms /WebResource.axd?d=YGVs8XyAWsEiLGuJ16c33zJSRK4YrDPiOWmkBO0Qq98589H5pLaw70AyFUVa3BleRpWNySSr ltpIawWYHK6tn8jtCeo1&amp;t=634656060808104849" type="text/javascript"></script><script src="/klms/WebResource.axd?d=rGkGTBKKUfifja4ZbpHfden_7XF4hf_qIjcSz4LqV8J7RmM4b5zUIgiT0uuMpRtVNMa-zLKNmfsh-e7Fd8RqdBTlqhM1&amp;t=634656060808104849" type="text/javascript"></script><div><input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /><input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /><input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBgLFvND9DQKIiKT4AQK4gogyAvjE9ooCAoLplowDAt3Q4McN/MAodltIcChy5WGQ8XeHsiQlCY8=" /></div> <noscript> <div class="jsEnable"> <a href="https://support.google.com/adsense/bin/answer.py?hl=en& answer=12654">How To Enable</a> <span>JavaScript is needed for this site (which is currently disabled in your browser). Please enable JavaScript.</span> </div> </noscript> <input type="hidden" name="hdnUserId" id="hdnUserId" value="595" /> <input type="hidden" name="hdnUserName" id="hdnUserName" value="Annapurnap" /> <input type="hidden" name="hdnRowCount" id="hdnRowCount" value="10" /> <input type="hidden" name="hdnAPIServerName" id="hdnAPIServerName" value="http://203.129.204.51:8080/collective-intellegenc" /> <input type="hidden" name="hdnSolrServerName" id="hdnSolrServerName" value="http://203.129.204.51:8080/solr" /><script type="text/javascript">//<![CDATA[WebForm_AutoFocus('searchInput');//]]></script></form><form id="formResult"> <div class="span18" id="divContent" style="width: 97%"> <div style="width: 100%; margin-top: -10px" class="inline"> <img id="imgGoogleCustomImage" class="googleCustomImage" style="float: right; margin-top: 0.25%" src="http://www.google.com/cse/images/google_custom_search_smwide.gif" /> <a href="/FeedbackList.aspx" style="float: right; padding-right: 5%;">*Feedback List </a> </div> <div id="divSearch" class="searchDiv"> <img src="Images/KLMS.png" id="imgLogo" /> <div> <div id="divTextBox"> <input type="search" name="q" size="31" id="searchInput" class="span6" autofocus="autofocus" autocomplete="off" /> </div> <div id="divButton"> <input type="button" id="btnSearch" name="sa" class="btn btn-primary span2" value="Search" onclick="Search();" /> </div> </div> </div> <div id="divResult" style="display: none; padding-top: 5%"> <div class="divItem" style="float: left; margin-right: 1%; display: none;"> <fieldset class="well" id="fieldsetItem"> <legend class="legend">Content that can help</legend> <div id="searchResultItem"> </div> <div id="divLinkPaging"></div> </fieldset> </div> <aside style="float: left; width: 99%"> <fieldset class="well" id="fieldsetPerson"> <legend class="legend">Persons who can help</legend> <div id="searchResultPerson"> </div> </fieldset> </aside> </div> <div id="divGoogleResult"> </div> <script src="JS/Plugins/jquery-1.8.2.min.js"></script> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <script src="JS/Plugins/paging.js"></script> <script src="https://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/Collection.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/Solr.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/ConnectServer.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/UserConnection_UsabilityScore_UserSearch.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/FixedSet.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/VariableSet.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/ShowCollectiveIntelligenceData.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/StoreSearchQuery.js"></script> </div></form> Now provide the response and nothing else.
Finding articulation vertices is an application of DFS. In a nutshell, Apply DFS on a graph. Get the DFS tree. A node which is visited earlier is a "parent" of those nodes which are reached by it and visited later. If any child of a node does not have a path to any of the ancestors of its parent, it means that removing this node would make this child disjoint from the graph. There is an exception: the root of the tree. If it has more than one child, then it is an articulation point, otherwise not. Point 3 essentially means that this node is an articulation point. Now for a child, this path to the ancestors of the node would be through a back-edge from it or from any of its children. All this is explained beautifully in this PDF .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15873172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1926138/']}
jdg_69889
stackexchange
llm_judgeable_groundtruth_similarity
8106765
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 use strtok to read in a first and last name and seperate it. How can I store the names where I can use them idependently in two seperate char arrays? #include <stdio.h>#include <string.h>int main (){ char str[] ="test string."; char * test; test = strtok (str," "); while (test != NULL) { printf ("%s\n",test); test= strtok (NULL, " "); } return 0;} Now provide the response and nothing else.
Here is my take at a reasonably simple tokenize helper that stores results in a dynamically growing array null-terminating the array keeps the input string safe (strtok modifies the input string, which is undefined behaviour on a literal char[], at least I think in C99) To make the code re-entrant, use the non-standard strtok_r #include <stdio.h>#include <string.h>#include <stdlib.h>char** tokenize(const char* input){ char* str = strdup(input); int count = 0; int capacity = 10; char** result = malloc(capacity*sizeof(*result)); char* tok=strtok(str," "); while(1) { if (count >= capacity) result = realloc(result, (capacity*=2)*sizeof(*result)); result[count++] = tok? strdup(tok) : tok; if (!tok) break; tok=strtok(NULL," "); } free(str); return result;}int main (){ char** tokens = tokenize("test string."); char** it; for(it=tokens; it && *it; ++it) { printf("%s\n", *it); free(*it); } free(tokens); return 0;} Here is a strtok -free reimplementation of that (uses strpbrk instead): char** tokenize(const char* str){ int count = 0; int capacity = 10; char** result = malloc(capacity*sizeof(*result)); const char* e=str; if (e) do { const char* s=e; e=strpbrk(s," "); if (count >= capacity) result = realloc(result, (capacity*=2)*sizeof(*result)); result[count++] = e? strndup(s, e-s) : strdup(s); } while (e && *(++e)); if (count >= capacity) result = realloc(result, (capacity+=1)*sizeof(*result)); result[count++] = 0; return result;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8106765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/271534/']}
jdg_69890
stackexchange
llm_judgeable_groundtruth_similarity
47803002
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 something which is an awful lot like a list comprehension in Python, except that it shares mutable state between iterations. Is there any way to do it with a list comprehension? def f(x): """ 5-bit LFSR """ return (x >> 1) ^ (0x12*(x&1))def batch(f, x, n): result = [x] for _ in xrange(1,n): x = f(x) result.append(x) return resultbatch(f, 1, 5) which returns [1, 18, 9, 22, 11] . Here the important thing is the batch function, not f(x) which is here just a simple example to illustrate the issue. Alternatively I could implement using a generator: def batch(f, x, n): yield x for _ in xrange(1,n): x = f(x) yield xlist(batch(f, 1, 5)) But it smells a little awkward. What I'm looking for is something like this... batch = [??? for _ in xrange(n)] Now provide the response and nothing else.
Is there any way to do it with a list comprehension? What I'm looking for is something like this... batch = [??? for _ in xrange(n)] Sure, no problem: >>> x = 1>>> n = 5>>> [prev.append(f(prev[0])) or prev.pop(0) for prev in [[x]] for _ in xrange(n)][1, 18, 9, 22, 11] Note: This is a bad idea. (I pretty much only did this because user2357112 said there is no way)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47803002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44330/']}
jdg_69891
stackexchange
llm_judgeable_groundtruth_similarity
93549
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: It is easy to visualize some Morse functions on surfaces (such as the torus) via the height function, but this seemingly doesn't work for 3-manifolds. I am looking for an explicit one on the 3-torus $\mathbb{T}^3$. In paritcular: It is true that every nice-enough 3-manifold admits a self-indexing Morse function $f:M\to[0,3]$ (with unique maximum and minimum), and from this we get a Heegaard diagram, with splitting surface $\Sigma=f^{-1}(\frac{3}{2})$. Now apparently, a converse also holds, so that given a Heegaard decomposition we can read off a self-indexing Morse function ( edit: perhaps multiple Morse functions, as per Ryan Budney's comment). With the known Heegaard decomposition of $\mathbb{T}^3$ (handlebodies $N$ and $\mathbb{T}^3-N$ for a small neighborhood $N$ about the generating 1-complex $S^1\cup S^1\cup S^1\subset\mathbb{T}^3$, and splitting surface $\partial N$), what is the corresponding Morse function? I can't write one down. Now provide the response and nothing else.
The Morse function on $(S^1)^3$ that gives the genus 3 Heegaard splitting (the standard one) is basically just a smoothed "distance from the 1-skeleton function". So if you think of $S^1$ as the unit circle in $\mathbb C$, then $$f : (S^1)^3 \to \mathbb R$$ is given by $$f(z_1,z_2,z_3) = |z_1-1|^2 + |z_2-1|^2 + |z_3-1|^2$$ where we're taking the norm/modulus squared of vectors in $\mathbb C$ in the above formula. The critical points are 8 triples $(z_1,z_2,z_3)$ of the form $(\pm 1, \pm 1, \pm 1)$, so you have the minimum $(1,1,1)$, maximum $(-1,-1,-1)$, index 1 critical points $(-1,1,1), (1,-1,1), (1,1,-1)$ and index two (the negatives of the index one critical points). If you really demand self-indexing then you'll need the function $\frac{f(z_1,z_2,z_3)}{4}$
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/93549', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12310/']}
jdg_69892
stackexchange
llm_judgeable_groundtruth_similarity
34296002
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 UIbutton created in code in an NSObject class which controls a game in a UIViewController class. The button works fine throughout most of the game, but at a certain point I want the button to fadein/out. Once the fadein/out starts animating the button is no longer interactive. I have set the .AllowUserInteraction option, but still no luck. I am stumped on this one, so any help much appreciated! Class GameController: NSObject {var gameView: UIView!var nextButton: UIButton!func gameViewSetUp() { // create the nextButton let imageNextButton = UIImage(named: "rightArrow") as UIImage? self.nextButton = UIButton(type: .Custom) nextButton.frame = CGRectMake(ScreenWidth-100,ScreenHeight-250,60,60) nextButton.setTitle("", forState: UIControlState.Normal) nextButton.setImage(imageNextButton, forState: .Normal) nextButton.contentMode = .ScaleAspectFill nextButton.backgroundColor = UIColor.clearColor() nextButton.layer.cornerRadius = 5.0 nextButton.layer.borderWidth = 2.5 nextButton.layer.borderColor = UIColor.clearColor().CGColor nextButton.addTarget(self, action: "nextPressed", forControlEvents: .TouchUpInside) nextButton.userInteractionEnabled = true gameView.addSubview(nextButton)func playStageX() { nextButtonWink() }}func nextButtonWink() { UIView.animateWithDuration(1.5, delay: 0, options: [.AllowUserInteraction, .Repeat, .CurveEaseInOut, .Autoreverse], animations: { // self.nextButton.userInteractionEnabled = true // I tried this as well but no impact. self.nextButton.alpha = 0 }, completion: nil)}class GameViewController: UIViewController {private var controller: GameControllerrequired init?(coder aDecoder: NSCoder) { controller = GameController() super.init(coder: aDecoder)}override func viewDidLoad() { super.viewDidLoad() let gameView = UIView(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight)) self.view.addSubview(gameView) controller.gameView = gameView } Now provide the response and nothing else.
Take out self.nextButton.alpha = 0 to test this out, I believe that button events will not fire when alpha is zero. When it comes to animations, the actual object's alpha will get set to zero before the animation starts, and what you are seeing is like a rendered interactive screenshot of your view as it animates If that is the case, then you need to set the alpha to something like 0.0100000003 or override the button to be interactive at alpha 0
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34296002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4727468/']}
jdg_69893
stackexchange
llm_judgeable_groundtruth_similarity
11773820
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using wysihtml5 wysiwyg editor. The problem is that image src attribute and link href attribute are stripped from html. At server I am already getting stripped html. How I can fix this problem? I am using advanced.js rulest. With all rules. Editor UPDATE 1 Well editor.getValue and jquery().val() for textarea give same values on form submit. means that form should be sent correctly. But I'v watched POST request which is sent from the browser. and it is without URLs. Something wrong. UPDATE 2 If I remove from ruleset everything connected with img, nevertheless it works inproperly. UPDATE 3 In response to Marrowmaw comment. I am expecting: <a href="http://domain.com/" title="Link: http://domain.com">Link</a> But I get <a href="" title="Link: Null">Link</a> UPDATE 4 <div id="wysihtml5-toolbar" style="display: none;"> <button class="btn" data-wysihtml5-command="bold"> {{ "Bold"|trans }} </button> <button class="btn" data-wysihtml5-command="italic"> {{ "Italic"|trans }} </button> <button class="btn" data-wysihtml5-command="createLink"> {{ "Link"|trans }}/{{ "Unlink"|trans }} </button> <button class="btn" data-wysihtml5-command="insertUnorderedList"> * </button> <button class="btn" data-wysihtml5-command="insertOrderedList"> 1,2,3 </button> <button class="btn" data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1"> {{ "Heading"|trans }} </button> <button class="btn" data-wysihtml5-command="insertImage"> {{ "Image"|trans }} </button> <div data-wysihtml5-dialog="createLink" style="display: none;"> <label> {{ "Link"|trans }}: <input data-wysihtml5-dialog-field="href" value="http://"> </label> <a data-wysihtml5-dialog-action="save">{{ "Save"|trans }}</a>&nbsp;<a data-wysihtml5-dialog-action="cancel">{{ "Cancel"|trans }}</a> </div> <!-- Dialog --> <div data-wysihtml5-dialog="insertImage" style="display: none;"> <label> URL: <input data-wysihtml5-dialog-field="src" value="http://"> </label> <label> Alternative text: <input data-wysihtml5-dialog-field="alt" value=""> </label> <label> {{ "Align"|trans }}: <select data-wysihtml5-dialog-field="className"> <option value="">{{ "default"|trans }}</option> <option value="wysiwyg-float-left">{{ "left"|trans }}</option> <option value="wysiwyg-float-right">{{ "right"|trans }}</option> </select> </label> <a data-wysihtml5-dialog-action="save">{{ "Save"|trans }}</a>&nbsp;<a data-wysihtml5-dialog-action="cancel">{{ "Cancel"|trans }}</a> </div> </div> <form action="{{ path('###_save_homepage') }}" method="POST" > <textarea id="wysihtml5-textarea" placeholder="{{ "Enter your text"|trans }}..." autofocus name="homepage" style="width:700px;height:400px;"> {{ homepage|raw }} </textarea> <input type="submit" value="{{ "Save"|trans }}" class="btn" /> </form> And JS init: <script type="text/javascript">jQuery(document).ready(function(){ var editor = new wysihtml5.Editor("wysihtml5-textarea", { // id of textarea element toolbar: "wysihtml5-toolbar", // id of toolbar element parserRules: wysihtml5ParserRules // defined in parser rules set }); });</script> Now provide the response and nothing else.
Try taking a look at the wysihtml5-x.x.x.js file you are referencing. They decided that they would only allow absolute URLs (in the name of guarding against XSS). The code below essentially allows you to take any value if you are comfortable with that trade off. Ctrl-F for "var attributeCheckMethods" and make the following changes -- source : var attributeCheckMethods = {url: (function() { /*var REG_EXP = /^https?:\/\//i;*/ return function(attributeValue) { /*if (!attributeValue || !attributeValue.match(REG_EXP)) { return null;*/ if (!attributeValue) { return ""; } /*return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); });*/ var parser = document.createElement('a'); parser.href = attributeValue; if ( parser.protocol == 'http:' || parser.protocol == 'https:' || parser.protocol == 'ftp:' ) return attributeValue; };})(),
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11773820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737629/']}
jdg_69894
stackexchange
llm_judgeable_groundtruth_similarity
50992188
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 wish to get rid of a lot of my repo's old history, so I did a shallow clone to get the last 50 commits only: git clone --depth=50 https://my.repo That worked OK, but when I create a new Gitlab repo and try to push it I get an error: git remote remove origingit remote add origin https://my.repogit push -u origin --all[...] ! [remote rejected] master -> master (shallow update not allowed) But I only want these 50 commits to be in my new repo's history. How can I tell git that it should just treat these 50 commits as the only commits in the new repo? Now provide the response and nothing else.
Here's what I ended up doing - it worked perfectly. Note that I was moving from my old host (Bitbucket) to my new one (Gitlab). My comments are above the commands: # First, shallow-clone the old repo to the depth we want to keepgit clone --depth=50 https://[email protected]/....git# Go into the directory of the clonecd clonedrepo# Once in the clone's repo directory, remove the old origingit remote remove origin# Store the hash of the oldest commit (ie. in this case, the 50th) in a varSTART_COMMIT=$(git rev-list master|tail -n 1)# Checkout the oldest commit; detached HEADgit checkout $START_COMMIT# Create a new orphaned branch, which will be temporarygit checkout --orphan temp_branch# Commit the initial commit for our new truncated history; it will be the state of the tree at the time of the oldest commit (the 50th)git commit -m "Initial commit"# Now that we have that initial commit, we're ready to replay all the other commits on top of it, in order, so rebase master onto it, except for the oldest commit whose parents don't exist in the shallow clone... it has been replaced by our 'initial commit'git rebase --onto temp_branch $START_COMMIT master# We're now ready to push this to the new remote repo... add the remote...git remote add origin https://gitlab.com/....git# ... and push. We don't need to push the temp branch, only master, the beginning of whose commit chain will be our 'initial commit'git push -u origin master After that, I did a fresh clone of the new repo and I got just the master branch with the 50 most recent commits - exactly what I wanted! :-) Commit history has gone from 250MB to 50MB. Woot.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50992188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178757/']}
jdg_69895
stackexchange
llm_judgeable_groundtruth_similarity
972775
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: Some time ago I asked How to find $\displaystyle{\int}_0^1\frac{\ln^3(1+x)\ln x}x\mathrm dx$ .Thanks to great effort of several MSE users, we now know that\begin{align}\int_0^1\frac{\ln^3(1+x)\,\ln x}xdx=&\,\frac{\pi^2}3\ln^32-\frac25\ln^52+\frac{\pi^2}2\zeta(3)+\frac{99}{16}\zeta(5)\\&\,-\frac{21}4\zeta(3)\ln^22-12\operatorname{Li}_4\!\left(\tfrac12\right)\ln2-12\operatorname{Li}_5\!\left(\tfrac12\right)\tag1\end{align}Now, a natural follow-up to that question is to bump the power of the logarithm and to ask: Question: What is a closed form for the next integral? $$I=\int_0^1\frac{\ln^3(1+x)\,\ln^2x}xdx\tag2$$ I think it is likely that $I$ has a closed form, because there are several very similar integrals having known closed forms:$$\int_0^1\frac{\ln^2(1+x)\,\ln^2x}xdx=\frac{\pi^2\,\zeta(3)}3-\frac{29\,\zeta(5)}8\tag3$$ $$\int_0^1\frac{\ln^3(1-x)\,\ln^2x}xdx=12\zeta^2(3)-\frac{23\pi^6}{1260}\tag4$$ \begin{align}\int_0^1\frac{\ln^3(1+x)\,\ln^2x}{x^2}dx=&\,\frac{3\zeta(3)}2+2\pi^2\zeta(3)+\frac{3\zeta(5)}2-\frac{21\zeta(3)}2\ln^22\\&\,-\frac{63\zeta(3)}2\ln2+\frac{23\pi^4}{60}-\frac{4\ln^52}5-\frac{3\ln^42}2\\&\,-4\ln^32+\frac{2\pi^2}3\ln^32+\frac{3\pi^2}2\ln^22-24\operatorname{Li}_5\!\left(\tfrac12\right)\\&\,-36\operatorname{Li}_4\!\left(\tfrac12\right)-24\operatorname{Li}_4\!\left(\tfrac12\right)\ln2\tag5\end{align} Now provide the response and nothing else.
I will be using the following results:$$2\sum^\infty_{n=1}\frac{H_n}{n^q}=(q+2)\zeta(q+1)-\sum^{q-2}_{j=1}\zeta(j+1)\zeta(q-j)\tag1$$$$\sum^\infty_{n=1}\frac{H_n}{n^22^n}=\zeta(3)-\frac{\pi^2}{12}\ln{2}\tag2$$$$\sum^\infty_{n=1}\frac{H_n}{n^32^n}={\rm Li}_4\left(\tfrac{1}{2}\right)+\frac{\pi^4}{720}-\frac{1}{8}\zeta(3)\ln{2}+\frac{1}{24}\ln^4{2}\tag3$$\begin{align}\sum^\infty_{n=1}\frac{H_n}{n^42^n}=&2{\rm Li}_5\left(\tfrac{1}{2}\right)+\frac{1}{32}\zeta(5)+{\rm Li}_4\left(\tfrac{1}{2}\right)\ln{2}-\frac{\pi^4}{720}\ln{2}+\frac{1}{2}\zeta(3)\ln^2{2}\\&-\frac{\pi^2}{12}\zeta(3)-\frac{\pi^2}{36}\ln^3{2}+\frac{1}{40}\ln^5{2}\tag4\end{align}Proofs of $(1)$, $(2)$ and $(4)$ can be found here , here and here respectively. Unfortunately, there has not been a mathematically sound proof of $(3)$ on MSE as of now. Using $\mathcal{I}$ to denote the integral in question,\begin{align}\mathcal{I}&=-\int^1_0\frac{\ln^3{x}\ln^2(1+x)}{1+x}{\rm d}x\\&=-\int^2_1\frac{\ln^2{x}\ln^3(x-1)}{x}{\rm d}x\\&=\underbrace{-\int^1_\frac{1}{2}\frac{\ln^2{x}\ln^3(1-x)}{x}{\rm d}x}_{\mathcal{I}_1}\underbrace{+3\int^1_{\frac{1}{2}}\frac{\ln^3{x}\ln^2(1-x)}{x}}_{\mathcal{I}_2}\underbrace{-3\int^1_{\frac{1}{2}}\frac{\ln^4{x}\ln(1-x)}{x}{\rm d}x}_{\mathcal{I}_3}-\frac{1}{6}\ln^6{2}\end{align}For $\mathcal{I}_1$, integration by parts gives$$\mathcal{I}_1=\frac{1}{3}\ln^6{2}-\int^1_\frac{1}{2}\frac{\ln^3{x}\ln^2(1-x)}{1-x}{\rm d}x$$On the other hand, $x\mapsto1-x$ yields$$\mathcal{I}_1=-\int^\frac{1}{2}_0\frac{\ln^3{x}\ln^2(1-x)}{1-x}{\rm d}x$$Combining these two equalities, we have\begin{align}\mathcal{I}_1&=\frac{1}{6}\ln^6{2}-\frac{1}{2}\int^1_0\frac{\ln^3{x}\ln^2(1-x)}{1-x}{\rm d}x\\&=\frac{1}{6}\ln^6{2}-\frac{1}{2}\frac{\partial^5\beta}{\partial a^3\partial b^2}(1,0^+)\\&=\frac{1}{6}\ln^6{2}-\frac{1}{2}\left[\frac{1}{b}+\mathcal{O}(1)\right]\left[\left(12\zeta^2(3)-\frac{23\pi^6}{1260}\right)b+\mathcal{O}(b^2)\right]_{b=0}\\&=\frac{23\pi^6}{2520}-6\zeta^2(3)+\frac{1}{6}\ln^6{2}\end{align}Even with the help of Wolfram Alpha, evaluating that fifth derivative was horribly unpleasant to say the least. As for $\mathcal{I}_2$,\begin{align}\mathcal{I}_2=&6\sum^\infty_{n=1}\frac{H_n}{n+1}\int^1_\frac{1}{2}x^n\ln^3{x}\ {\rm d}x\\=&6\sum^\infty_{n=1}\frac{H_n}{n+1}\frac{\partial^3}{\partial n^3}\left(\frac{1}{n+1}-\frac{1}{(n+1)2^{n+1}}\right)\\=&\color{#E2062C}{-\sum^\infty_{n=1}\frac{36H_n}{(n+1)^5}}+\color{#FF4F00}{\sum^\infty_{n=1}\frac{36H_n}{(n+1)^52^{n+1}}}+\color{#00A000}{\sum^\infty_{n=1}\frac{36\ln{2}H_n}{(n+1)^42^{n+1}}}+\color{#21ABCD}{\sum^\infty_{n=1}\frac{18\ln^2{2}H_n}{(n+1)^32^{n+1}}}\\&+\color{#6F00FF}{\sum^\infty_{n=1}\frac{6\ln^3{2}H_n}{(n+1)^22^{n+1}}}\\=&\color{#E2062C}{-\frac{\pi^6}{35}+18\zeta^2(3)}+\color{#FF4F00}{\sum^\infty_{n=1}\frac{36H_n}{n^52^{n}}-36{\rm Li}_6\left(\tfrac{1}{2}\right)}+\color{#00A000}{36{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{9}{8}\zeta(5)\ln{2}}\\&+\color{#00A000}{36{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}-\frac{\pi^4}{20}\ln^2{2}+18\zeta(3)\ln^3{2}-3\pi^2\zeta(3)\ln{2}-\pi^2\ln^4{2}+\frac{9}{10}\ln^6{2}}\\&+\color{#21ABCD}{\frac{\pi^4}{40}\ln^2{2}-\frac{9}{4}\zeta(3)\ln^3{2}+\frac{3}{4}\ln^6{2}}+\color{#6F00FF}{\frac{3}{4}\zeta(3)\ln^3{2}-\ln^6{2}}\\=&\sum^\infty_{n=1}\frac{36H_n}{n^52^{n}}-36{\rm Li}_6\left(\tfrac{1}{2}\right)-\frac{\pi^6}{35}+36{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{9}{8}\zeta(5)\ln{2}+36{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}\\&-\frac{\pi^4}{40}\ln^2{2}+18\zeta^2(3)-3\pi^2\zeta(3)\ln{2}+\frac{33}{2}\zeta(3)\ln^3{2}-\pi^2\ln^4{2}+\frac{13}{20}\ln^6{2}\end{align}For $\mathcal{I}_3$,\begin{align}\mathcal{I}_3=&3\sum^\infty_{n=1}\frac{1}{n}\int^1_\frac{1}{2}x^{n-1}\ln^4{x}\ {\rm d}x\\=&3\sum^\infty_{n=1}\frac{1}{n}\frac{\partial^4}{\partial n^4}\left(\frac{1}{n}-\frac{1}{n2^n}\right)\\=&\sum^\infty_{n=1}\left(\frac{72}{n^6}-\frac{72}{n^62^n}-\frac{72\ln{2}}{n^52^n}-\frac{36\ln^2{2}}{n^42^n}-\frac{12\ln^3{2}}{n^32^n}-\frac{3\ln^4{2}}{n^22^n}\right)\\=&-72{\rm Li}_6\left(\tfrac{1}{2}\right)+\frac{8\pi^6}{105}-72{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}-36{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}\\&-\frac{21}{2}\zeta(3)\ln^3{2}+\frac{3\pi^2}{4}\ln^4{2}-\frac{1}{2}\ln^6{2}\end{align}Thus\begin{align}\color{#BF00FF}{\mathcal{I}=}&\color{#BF00FF}{36\sum^\infty_{n=1}\frac{H_n}{n^52^n}-108{\rm Li}_6\left(\tfrac{1}{2}\right)+\frac{143\pi^6}{2520}-36{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{9}{8}\zeta(5)\ln{2}-\frac{\pi^4}{40}\ln^2{2}}\\&\color{#BF00FF}{+12\zeta^2(3)-3\pi^2\zeta(3)\ln{2}+6\zeta(3)\ln^3{2}-\frac{\pi^2}{4}\ln^4{2}+\frac{3}{20}\ln^6{2}}\end{align}We note that\begin{align}\zeta(\bar{5},1)=&\frac{1}{24}\int^1_0\frac{\ln^4{x}\ln(1+x)}{1+x}{\rm d}x\\=&\frac{1}{24}\int^2_1\frac{\ln{x}\ln^4(x-1)}{x}{\rm d}x\\=&-\frac{1}{24}\int^1_\frac{1}{2}\frac{\ln{x}\ln^4(1-x)}{x}{\rm d}x+\frac{1}{6}\int^1_\frac{1}{2}\frac{\ln^2{x}\ln^3(1-x)}{x}{\rm d}x-\frac{1}{4}\int^1_\frac{1}{2}\frac{\ln^3{x}\ln^2(1-x)}{x}{\rm d}x\\&+\frac{1}{6}\int^1_\frac{1}{2}\frac{\ln^4{x}\ln(1-x)}{x}{\rm d}x+\frac{1}{144}\ln^6{2}\\=&\underbrace{-\frac{1}{24}\int^\frac{1}{2}_0\frac{\ln^4{x}\ln(1-x)}{1-x}{\rm d}x}_{\mathcal{J}}-3\sum^\infty_{n=1}\frac{H_n}{n^52^n}+7{\rm Li}_6\left(\tfrac{1}{2}\right)-\frac{17\pi^6}{5040}+{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}\\&-\frac{3}{32}\zeta(5)\ln{2}-{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}+\frac{\pi^4}{480}\ln^2{2}-\frac{1}{2}\zeta^2(3)+\frac{\pi^2}{4}\zeta(3)\ln{2}-\frac{19}{24}\zeta(3)\ln^3{2}\\&+\frac{\pi^2}{24}\ln^4{2}-\frac{17}{360}\ln^6{2}\end{align}since we have already derived the values of the last three integrals. For the remaining integral,\begin{align}\mathcal{J}=&\frac{1}{24}\sum^\infty_{n=1}H_n\frac{\partial^4}{\partial n^4}\left(\frac{1}{(n+1)2^{n+1}}\right)\\=&\sum^\infty_{n=1}\frac{H_n}{(n+1)^52^{n+1}}+\sum^\infty_{n=1}\frac{\ln{2}H_n}{(n+1)^42^{n+1}}+\sum^\infty_{n=1}\frac{\ln^2{2}H_n}{2(n+1)^32^{n+1}}+\sum^\infty_{n=1}\frac{\ln^3{2}H_n}{6(n+1)^22^{n+1}}\\&+\sum^\infty_{n=1}\frac{\ln^4{2}H_n}{24(n+1)2^{n+1}}\\=&\sum^\infty_{n=1}\frac{H_n}{n^52^n}-{\rm Li}_6\left(\tfrac{1}{2}\right)+{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{1}{32}\zeta(5)\ln{2}+{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}-\frac{\pi^4}{720}\ln^2{2}\\&+\frac{1}{2}\zeta(3)\ln^3{2}-\frac{\pi^2}{12}\zeta(3)\ln{2}-\frac{\pi^2}{36}\ln^4{2}+\frac{1}{40}\ln^6{2}+\frac{\pi^4}{1440}\ln^2{2}-\frac{1}{16}\zeta(3)\ln^3{2}\\&+\frac{1}{48}\ln^6{2}+\frac{1}{48}\zeta(3)\ln^3{2}-\frac{1}{36}\ln^6{2}+\frac{1}{48}\ln^6{2}\\=&\sum^\infty_{n=1}\frac{H_n}{n^52^n}-{\rm Li}_6\left(\tfrac{1}{2}\right)+{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{1}{32}\zeta(5)\ln{2}+{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}-\frac{\pi^4}{1440}\ln^2{2}\\&+\frac{11}{24}\zeta(3)\ln^3{2}-\frac{\pi^2}{12}\zeta(3)\ln{2}-\frac{\pi^2}{36}\ln^4{2}+\frac{7}{180}\ln^6{2}\\\end{align}Hence we can express $\zeta(\bar{5},1)$ as\begin{align}\zeta(\bar{5},1)=&-2\sum^\infty_{n=1}\frac{H_n}{n^52^n}+6{\rm Li}_6\left(\tfrac{1}{2}\right)-\frac{17\pi^6}{5040}+2{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}-\frac{1}{16}\zeta(5)\ln{2}+\frac{\pi^4}{720}\ln^2{2}\\&-\frac{1}{2}\zeta^2(3)-\frac{1}{3}\zeta(3)\ln^3{2}+\frac{\pi^2}{6}\zeta(3)\ln{2}+\frac{\pi^2}{72}\ln^4{2}-\frac{1}{120}\ln^6{2}\end{align}This implies that\begin{align}\sum^\infty_{n=1}\frac{H_n}{n^52^n}=&3{\rm Li}_6\left(\tfrac{1}{2}\right)-\frac{1}{2}\zeta(\bar{5},1)-\frac{17\pi^6}{10080}+{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}-\frac{1}{32}\zeta(5)\ln{2}+\frac{\pi^4}{1440}\ln^2{2}\\&-\frac{1}{4}\zeta^2(3)-\frac{1}{6}\zeta(3)\ln^3{2}+\frac{\pi^2}{12}\zeta(3)\ln{2}+\frac{\pi^2}{144}\ln^4{2}-\frac{1}{240}\ln^6{2}\end{align}Plucking this back into the original integral, we get another form in terms of $\zeta(\bar{5},1)$\begin{align}\color{#BF00FF}{\mathcal{I}=}&\color{#BF00FF}{-\frac{\pi^6}{252}-18\zeta(\bar{5},1)+3\zeta^2(3)}\end{align}This is as close to a "closed form" as I can get. The sheer number of cancellations involved in the last step makes me think that my answer could be roundabout and inefficient. Note that no known simple closed form for $\zeta(\bar{5},1)$ exists, implying that closed forms for higher power integrals are unlikely to exist as well.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/972775', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/75621/']}
jdg_69896
stackexchange
llm_judgeable_groundtruth_similarity
21706436
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 class ( MyFacade ) that I injected parameter(s) with Ninject : class MyFacade{ IDemoInterface demo; public MyFacade(IDemoInterface demo) { this.demo = demo; } public void MyMethod() { Console.WriteLine(demo.GetInfo()); }} Of course, I have to setup the Ninject to inject the appropiate implementation of my parameter ( IDemoInterface ) I know, I can instantiate MyFacade object by doing kernel.Get<MyFacade>(); without setting anything else. Currently my facade doesn't have an interface (because it is my only implementation, maybe I will add its interface for standard proposes) if I want to make this facade singlenton, I know two ways: create a empty constructor and pass a parameter by doing this kernel.Get<IDemoInterface>(); or by setup Ninject like: kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope(); The second one look a better approach, but do you know any other way to setup it in a singleton way? Now provide the response and nothing else.
When setting up your bindings, you need to bind your dependencies. It is always better to setup your dependencies in your bindings, as opposed to doing a kernel.Get<T>() in a constructor. You are using IOC, so leverage the framework you are using to do the injection for you. In your second example binding, what you are missing is binding in your IDemoInterface . Your bindings should look like this: //bind the dependency to the implementation.kernel.Bind<IDemoInterface>().To<DemoInterface>();//since you bound your dependency, ninject should now have // all the dependencies required to instantiate your `MyFacade` object.kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21706436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/480700/']}
jdg_69897
stackexchange
llm_judgeable_groundtruth_similarity
58747303
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 Unit and e2e test my applications as much as possible and my goal is a coverage of 101%. Problem right now with my setup is, that the @Column decorator from typeorm uses an arrow function to set a default value like the current timestamp on a database update. This arrow function is not covered with jest test coverage. Message is: statement not covered I run the code coverage with: jest --coverage .My versions: "jest": "^24.9.0","typeorm": "^0.2.20" Jest configuration within package.json: { "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "rootDir": "src", "testRegex": ".spec.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "coverageDirectory": "../build/coverage", "testEnvironment": "node", "coverageThreshold": { "global": { "branches": 80, "functions": 80, "lines": 80, "statements": -10 } } },} My entity looks like this: import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';@Entity()export class Role { @PrimaryGeneratedColumn() id: number; @Column() tenantId: number; @Column({ type: 'timestamp', update: false, default: () => 'CURRENT_TIMESTAMP()' }) createdAt: Date; @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP()', onUpdate: 'CURRENT_TIMESTAMP()' }) updatedAt: Date;} Coverage for this entity: (to post an image i need 10 reputation -.-): https://i.ibb.co/FYQgstP/Screenshot-2019-11-07-11-46-45.png Now provide the response and nothing else.
I ran into a similar issue with GraphQL decorators. As all of these are functions, what you can do is create a file that holds all of the functions you'll be using, name them, and export them, so that you can actually test them as well and get the coverage with Jest. (The tests should literally be something like expect(namedFunction).toBe('CURRENT_TIMESTAMP()') or very similar. For an example you can see my function here and my tests here . EDIT 11/03/2020 The code examples are no more. That being said, you can do things like export const returnString = () => String;@Query(returnString) for GraphQL. A test for this would look like expect(returnString()).toBe(String);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58747303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2291097/']}
jdg_69898
stackexchange
llm_judgeable_groundtruth_similarity
12371450
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: int max(int n, ...) I am using cdecl calling convention where the caller cleans up the variable after the callee returns. I am interested in knowing how do the macros va_end , va_start and va_arg work? Does the caller pass in the address of the array of arguments as the second argument to max? Now provide the response and nothing else.
If you look at the way the C language stores the parameters on the stack, the way the macros work should become clear:- Higher memory address Last parameter Penultimate parameter .... Second parameterLower memory address First parameter StackPointer -> Return address (note, depending on the hardware the stack pointer maybe one line down and the higher and lower may be swapped) The arguments are always stored like this 1 , even without the ... parameter type. The va_start macro just sets up a pointer to the first function parameter, e.g.:- void func (int a, ...) { // va_start char *p = (char *) &a + sizeof a; } which makes p point to the second parameter. The va_arg macro does this:- void func (int a, ...) { // va_start char *p = (char *) &a + sizeof a; // va_arg int i1 = *((int *)p); p += sizeof (int); // va_arg int i2 = *((int *)p); p += sizeof (int); // va_arg long i2 = *((long *)p); p += sizeof (long); } The va_end macro just sets the p value to NULL . NOTES: Optimising compilers and some RISC CPUs store parameters in registers rather than use the stack. The presence of the ... parameter would switch off this ability and for the compiler to use the stack.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12371450', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/204623/']}
jdg_69899
stackexchange
llm_judgeable_groundtruth_similarity
154469
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so: namespace { int cannotAccessOutsideThisFile() { ... }} // namespace You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces are accessible within the file they're created in, as if you had an implicit using-clause to them. My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing? Now provide the response and nothing else.
The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2: The use of the static keyword isdeprecated when declaring objects in anamespace scope, the unnamed-namespaceprovides a superior alternative. Static only applies to names of objects, functions, and anonymous unions, not to type declarations. Edit: The decision to deprecate this use of the static keyword (affecting visibility of a variable declaration in a translation unit) has been reversed ( ref ). In this case using a static or an unnamed namespace are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question. Unnamed namespace 's still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details. Credit goes to Mike Percy for bringing this to my attention.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/154469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12193/']}
jdg_69900
stackexchange
llm_judgeable_groundtruth_similarity
6756931
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 this syntax recently for try-catch for function. struct A{ int a; A (int i) : a(i) // normal syntax { try {} catch(...) {} } A () // something different try : a(0) {} catch(...) {} void foo () // normal function try {} catch(...) {}}; Both syntax are valid . Is there any technical difference between these syntax apart from coding style ? Is one of the syntax superior to other by any aspect ? Now provide the response and nothing else.
The First Syntax: The scope of the try block starts after the Member Initialization list has been completed, So any exception thrown during Member Initialization will not be caught by this try-catch block. The second syntax: It ensures that if an exception gets thrown during Member Initialization list then you are able to catch the exception. The Third Syntax: It ensures that any exception thrown from betwen the starting brace of the try block inside the function body gets caught appropriately, It would mean any exception caused during the argument passing(if any can occur) will not be caught in this try-catch block. So yes they are disinctly different in what functionality they provide. EDIT: Some guidelines to be considered while using the second syntax(function-try-block) in constructors & destructors: As per the C++ Standard, If the catch block does not throw (either rethrow the original exception, or throw something new), and control reaches the end of the catch block of a constructor or destructor, then the original exception is automatically rethrown. In Simple words: A constructor or destructor function-try-block's handler code MUST finish by emitting some exception. Guideline 1: Constructor function-try-block handlers have only one purpose -- to translate an exception. (And maybe to do logging or some other side effects.) They are not useful for any other purpose. Throwing a exception from destructors is an bad idea, Take a look here to know why. Guideline 2: Destructor function-try-blocks have no practical use at all. There should never be anything for them to detect, and even if there were something to detect because of evil code, the handler is not very useful for doing anything about it because it can not suppress the exception. Guideline 3: Always clean up unmanaged resource acquisition in local try-block handlers within the constructor or destructor body, never in constructor or destructor function-try-block handlers. For Standardese Fans: C++ standard, clause 15.3, paragraph 15: If a return statement appears in a handler of the function-try-block of a constructor, the program is ill-formed. C++ standard, clause 15.3, paragraph 16: The exception being handled is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor. Otherwise, a function returns when control reaches the end of a handler for the function-try-block (6.6.3). Flowing off the end of a function-try-block is equivalent to a return with no value; this results in undefined behavior in a value-returning function (6.6.3). References: Have a look at this must read resource here for more details & explanation.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6756931', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/514235/']}
jdg_69901
stackexchange
llm_judgeable_groundtruth_similarity
4466153
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 set up a relationship as follows. Each Master item has one or more Detail items: public class Detail { public virtual Guid DetailId { get; set; } public virtual string Name { get; set; }}public class Master { public virtual Guid MasterId { get; set; } public virtual string Name { get; set; } public virtual IList<Detail> Details { get; set; }} And Mappings: public class MasterMap : ClassMap<Master> { public MasterMap() { Id(x => x.MasterId); Map(x => x.Name); HasMany(x => x.Details).Not.KeyNullable.Cascade.All(); }}public class DetailMap : ClassMap<Detail> { public DetailMap() { Id(x => x.Id); Map(x => x.Name); }} The Master database table is: masterId uniqueidentifier NOT NULLname nvarchar(max) NULL and Detail is: DetailId uniqueidentifier NOT NULLname nvarchar(max) NULLMasterId uniqueidentifier NULLforeign key (masterId) references [Master] I don't really care to have a link from Detail back to Master -- in otherwords, Detail objects on their own are just not interesting to my domain layer. They will always be accessed via their Master object. Using code like this: Master mast = new Master { MasterId = new Guid(), Name = "test", Details = new List<Detail> { new Detail { .DetailId = new Guid(), .Name = "Test1" }, new Detail { .DetailId = new Guid(), .Name = "Test1" } }};using (transaction == Session.BeginTransaction) { Session.Save(mast); transaction.Commit();} This works great, except for a crazy limitation outlined in this post : NHibernate does an INSERT and puts Detail.MasterId as NULL first, then does an UPDATE to set it to the real MasterId. Really, I don't want Detail entries with NULL MasterIds, so if I set the MasterId field to NOT NULL, the INSERT to Detail will fail, because as I said NHibernate is trying to put in MasterId = NULL. I guess my question boils down to this: How can I get the above code sample to work with my existing domain model (eg, without adding a Detail.Master property), and the Detail.MasterId field in the database set to NOT NULL? Is there a way to get Nhibernate to just put the correct MasterId in the initial INSERT, rather than running an UPDATE afterwards? Is there rationale somewhere for this design decision? -- I'm struggling to see why it would be done this way. Now provide the response and nothing else.
You can't. To quote the link from my answer on the other question you linked to: Very Important Note: If the <key> column of a <one-to-many> association is declared NOT NULL, NHibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked as inverse="true" . See the discussion of bidirectional associations later in this chapter. Edit: as Hazzik has rightly pointed out, this has changed in NHibernate 3 and above. The docs sadly haven't been updated, so here's Hazzik: [If you] set inverse="false" and not-null on <key> , NH3 and above will perform only two inserts insead of insert-insert-update.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4466153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7913/']}
jdg_69902
stackexchange
llm_judgeable_groundtruth_similarity
2029507
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say there is a list of integers [1,2,3,4,5] and a map function that multiplies each element with 10 and returns modified list as [10,20,30,40,50] , with out modifying the original list.How this can be done efficiently in c++. Now provide the response and nothing else.
Here's an example: #include <vector>#include <iostream>#include <algorithm>using namespace std;int multiply(int);int main() { vector<int> source; for(int i = 1; i <= 5; i++) { source.push_back(i); } vector<int> result; result.resize(source.size()); transform(source.begin(), source.end(), result.begin(), multiply); for(vector<int>::iterator it = result.begin(); it != result.end(); ++it) { cout << *it << endl; }}int multiply(int value) { return value * 10;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2029507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22076/']}
jdg_69903
stackexchange
llm_judgeable_groundtruth_similarity
27829
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: I know that masquerading is to impersonate a false identity and replaying is the same wherein unauthorized person uses the credentials of the authorized one to have the privileges.Then what is the difference between the two terms? Now provide the response and nothing else.
These two terms do not have meanings at the same level. Masquerading (or impersonation ; the two terms are equivalent) is any attack wherein the attackers acts (emits data packets or the like) as if he was some other user or entity in the system. Replay attacks are attacks where the attacker simply sends a data element (e.g. a data packet) which was previously sent by some other user, in the hope of reproducing the effect. Thus, a "replay attack" is often a specific kind of impersonation; or you can consider replay attacks to be a tool used to implement an impersonation attack.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/27829', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/13699/']}
jdg_69904
stackexchange
llm_judgeable_groundtruth_similarity
43817756
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 one of the angular 2 material's theme. I'm able to use the theme colors on material components like button, toolbar using color="primary". But I'm not able to figure out how to theme a div. I don't want to hardcode the hash in .css file since if i decide to change the theme it'll require changes at all places. Am i missing something? What's the best way to do this? Now provide the response and nothing else.
Indeed, you cannot use color="primary" on every HTML element. What I did is a class called color-primary @import '~@angular/material/theming';@include mat-core();$primary: mat-palette($mat-deep-purple, 600, 500, 900);$accent: mat-palette($mat-amber, A400, A300, A600);.color-primary { color: mat-color($primary);}.color-accent { color: mat-color($accent);} Of course, I've set the color here but you can create another class, for example : background-color-primary . (here's the link of my sample project : Pizza-Sync ).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43817756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2255622/']}
jdg_69905
stackexchange
llm_judgeable_groundtruth_similarity
3511429
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: Since using transfinite induction it's possible to demonstrate that for every ordinals $\zeta$ , we have $\zeta<\omega_\zeta$ , it seems that it isn't possible that there exist an infinite cardinal $\alpha$ (which can also be an initial ordinal) such that $\alpha=\aleph_\alpha$ : infact if it's true, it results that there exist two different ordinal ( $\alpha$ and $\omega_\alpha$ ) such that $\alpha<\omega_\alpha$ and $|\alpha|=|\omega_\alpha|$ , so while $\omega_\alpha$ is an initial ordinal it must be $\alpha=\omega_\alpha$ and for the hypothesis this is impossible. Now provide the response and nothing else.
Since using transfinite induction it's possible to demonstrate that for every ordinals $\zeta$ it's $\zeta<\omega_\zeta$ No, it isn't. What you can show is that $\zeta\le\omega_\zeta$ for all $\zeta$ , but that's quite different. Any attempted inductive argument to prove the claim above will run into trouble at limit stages. For example, just because $\alpha_n<\beta_n$ for all $n<\omega$ does not mean that $\sup\{\alpha_n:n\in\omega\}<\sup\{\beta_n:n\in\omega\}$ ; consider $$\alpha_n=n, \beta_n=2n.$$ So when $\lambda$ is a limt you cannot argue that $$\forall\zeta<\lambda(\omega_\zeta<\omega_\lambda)\quad\implies\quad\lambda<\omega_\lambda.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3511429', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/736008/']}
jdg_69906
stackexchange
llm_judgeable_groundtruth_similarity
1685120
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: does not work (Compilation error: missing return statement) public SqlMapClientTemplate getSqlTempl() throws UivException, SQLException{ try { SqlMapClient scl = (SqlMapClient) ApplicationInitializer.getApplicationContext().getBean("MySqlMapClient"); DataSource dsc = (DataSource) ServiceLocator.getInstance().getDataSource(PIH_EIV_ORCL); return new SqlMapClientTemplate (dsc, scl); } catch (NamingException ne) { log.error(ne.getMessage(), ne); }} works: public SqlMapClientTemplate getSqlTempl() throws UivException, SQLException{ try { SqlMapClient scl = (SqlMapClient) ApplicationInitializer.getApplicationContext().getBean("MySqlMapClient"); DataSource dsc = (DataSource) ServiceLocator.getInstance().getDataSource(PIH_EIV_ORCL); return new SqlMapClientTemplate (dsc, scl); } catch (NamingException ne) { log.error(ne.getMessage(), ne); throw new SQLException("Unable to get database connection: " + ne.getMessage()); }} why? Now provide the response and nothing else.
In first case the method is not returning anything after the catch block or inside the catch block. In second case the catch block is throwing an exception so compiler know that the method will return an object or throw an exception.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1685120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44286/']}
jdg_69907
stackexchange
llm_judgeable_groundtruth_similarity
37274347
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 just installed the pipeline plugin (on Jenkins 2.1). When I create a new job the Source Code Management tab is missing (and a few others).According to the article describing the Pipeline feature at it should look like: However this is how it looks like in my case: Where are the missing tabs, especially the Source Code Management one? Is it simply some missing config/plugin or a bug? I'm on Jenkins 2.1 Now provide the response and nothing else.
You may need to install Git plugin (or other SCM connector) before the SCM configuration options will show up. Once it (they) are added to Jenkins, you can continue with the job set up: In the Pipeline section, select Definition: Pipeline Script from SCM . Additional configuration elements will appear on the page, most notably an SCM drop-down selector. Until you install at least one SCM connector plugin (like Git plugin ), that selector will be empty. (Kinda hard to continue with the configuration without the SCM connector you want...) Once the SCM connector you want is properly plugged-in, the selector becomes populated with the available SCM options. After choosing the one you want, yet more configuration elements show up - whatever the selected SCM requires. For example, when using git you will see a Repository sub-sub-sub-section where you provide the connection URL and choose an (elsewhere in Jenkins managed) credential. And branch config. And repo-broswer. And more. After the SCM config bits, there's a configuration of the script file itself, conveniently auto-filled with the default of "Jenkinsfile". At that point, you should be good to go (presuming you have a Jenkinsfile already pushed to the root of your repo).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37274347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1001423/']}
jdg_69908
stackexchange
llm_judgeable_groundtruth_similarity
43971
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Pierce (2002) introduces the typing relation on page 92 by writing: The typing relation for arithmetic expressions, written "t : T", is defined by a set of inference rules assigning types to terms and the footnote says The symbol $\in$ is often used instead of :. My question is simply why type theorists prefer to use : over $\in$ ? If a type $T$ is a set of values then it makes perfect sense to write $t \in T$ , no new notation needed. Is this similar to how some cs writers prefer $3n^2 = O(n^2)$ even thought it is abuse of notation and should be written $3n^2 \in O(n^2)$ ? Now provide the response and nothing else.
The main reason to prefer the colon notation $t : T$ to the membership relation $t \in T$ is that the membership relation can be misleading because types are not (just) collections . [ Supplemental: I should note that historically type theory was written using $\in$ . Martin-Löf's conception of type was meant to capture sets constructively, and already Russell and Whitehead used $\epsilon$ for the class memebrship. It would be interesting to track down the moment when $:$ became more prevalent than $\in$ .] A type describes a certain kind of construction, i.e., how to make objects with a certain structure, how to use them, and what equations holds about them. For instance a product type $A \times B$ has introduction rules that explain how to make ordered pairs, and elimination rules explaining that we can project the first and the second components from any element of $A \times B$ . The definition of $A \times B$ does not start with the words "the collection of all ..." and neither does it say anywhere anything like "all elements of $A \times B$ are pairs" (but it follows from the definition that every element of $A \times B$ is propositionally equal to a pair). In constrast, the set-theoretic definition of $X \times Y$ is stated as "the set of all ordered pairs ...". The notation $t : T$ signifies the fact that $t$ has the structure described by $T$ . A type $T$ is not to be confused with its extension , which is the collection of all objects of type $T$ . A type is not determined by its extension, just like a group is not determined by its carrier set. Furthermore, it may happen that two types have the same extension, but are different, for instance: The type of all even primes larger than two: $\Sigma (n : \mathbb{N}) . \mathtt{isprime}(n) \times \mathtt{iseven}(n) \times (n > 2)$ . The type of all odd primes smaller than two: $\Sigma (n : \mathbb{N}) . \mathtt{isprime}(n) \times \mathtt{isodd}(n) \times (n < 2)$ . The extension of both is empty, but they are not the same type. There are further differences between the type-theoretic $:$ and the set-theoretic $\in$ . An object $a$ in set theory exists independently of what sets it belongs to, and it may belong to several sets. In contrast, most type theories satisfy uniqueness of typing: if $t : T$ and $t : U$ then $T \equiv U$ . Or to put it differently, a type-theoretic construction $t$ has precisely one type $T$ , and in fact there is no way to have just an object $t$ without its (uniquely determined) type. Another difference is that in set theory we can deny the fact that $a \in A$ by writing $\lnot (a \in A)$ or $a \not\in A$ . This is not possible in type theory, because $t : T$ is a judgement which can be derived using the rules of type theory, but there is nothing in type theory that would allow us to state that something has not been derived. When a child makes something from LEGO blocks they proudly run to their parents to show them the construction, but they never run to their parents to show them what they didn't make.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/43971', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/47144/']}
jdg_69909
stackexchange
llm_judgeable_groundtruth_similarity
8527292
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm building a RESTful API for a project I'm working on and I'd like to make the main application consume the API because: It will result in having one set of code to maintain Should we decide to expose the API for 3rd party devs it will already be done It opens up the possibility to make mobile applications that consume it I really want to learn how to do it The API will be hosted on a subdomain https://api.example.com and the main web application will be hosted at the root domain https://example.com . Conceptually I understand how everything works, but my main question is how the authentication flow will change if, at all. Ordinarily 3rd party apps would: Obtain a request token from https://api.example.com/request_token Redirect the user to authenticate on https://api.authenticate.com/authorize Get redirected back to the 3rd party application Obtain an access token from https://api.example.com/access_token Since I control both domains, can I do something similar to: Obtain a request token when the user lands on the login screen at https://www.example.com The user authenticates using a form on https://www.example.com that calls the same code as https://api.example.com/authorize If the credentials are valid, the request token is swapped for the access token Access token is saved in the session and expires when the user logs out like it normally would Step 3 feels like it's wrong since there will be duplicate code, but wouldn't it open me up to XSS attacks is the login form on https://www.example.com sent the data to https://api.example.com since they are technically different domains? Am I overcomplicating this? Now provide the response and nothing else.
I have come across the same issue and solved it like this. 1 For third party apps, using my API, they have to authenticate via OAuth on all requests. 2 For my own third party clients, (mobile, AIR etc) - they use OAuth, with the difference that I allow these to send username and password directly in the authorization step (so I can make a native login dialogue). This is provided that your API is over SSL/HTTPS. 3 For my web application, I use cookie authentication to access the APIs. I.e after having logged in, the user could simply call API:urls and get JSON/XML back. Nice for quick exploring the APIs also (although a real API Console like APIGee does a better job there).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8527292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1100835/']}
jdg_69910
stackexchange
llm_judgeable_groundtruth_similarity
39290363
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 one realm list and i want to sort the list alphabetically. Collections.sort(contacts, new java.util.Comparator<Contacts>() { @Override public int compare(Contacts l1, Contacts l2) { String s1 = l1.getName(); String s2 = l2.getName(); return s1.compareToIgnoreCase(s2); } }); But this logic not woking i am posting crash report below, please kindly go through it. java.lang.UnsupportedOperationException: Replacing and element is not supported.at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:826at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:757)at java.util.Collections.sort(Collections.java:1909) Please kindly go through my post and suggest me some solution. Now provide the response and nothing else.
Sorting in Realm is pretty straight forward. Here is an example: Let's assume you want to sort the contact list by name, you should sort it when your querying the results, you will get the results already sorted for you. There are multiple ways to achieve this Example: 1) Simple and Recommended way: // for sorting ascendingRealmResults<Contacts> result = realm.where(Contacts.class).findAllSorted("name");// sort in descending orderRealmResults<Contacts> result = realm.where(Contacts.class).findAllSorted("name", Sort.DESCENDING); Updated since realm 5.0.0 1) Simple and Recommended way: // for sorting ascending, Note that the Sort.ASCENDING value is the default if you don't specify the orderRealmResults<Contacts> result = realm.where(Contacts.class).sort("name").findAll();// sort in descending orderRealmResults<Contacts> result = realm.where(Contacts.class).sort("name", Sort. DESCENDING).findAll(); 2) for unsorted results If you are getting unsorted results you can sort them anywhere this way. RealmResults<Contacts> result = realm.where(Contacts.class).findAll();result = result.sort("name"); // for sorting ascending// and if you want to sort in descending orderresult = result.sort("name", Sort.DESCENDING); Have a look here you will find very detailed examples about Realm querying, sorting and other useful usage.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39290363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1453704/']}
jdg_69911
stackexchange
llm_judgeable_groundtruth_similarity
4009352
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to post on page - throught my site. . I didn't find anything that could help me in documentation. Also none of google results gave mi answer. function post_facebook($data=null){ $result = ""; require_once (ROOT. "/apps/configuration/models/ConfigurationItem.php"); require_once (ROOT . "/components/facebook/facebook.php"); $this->ConfigurationItem = new ConfigurationItem($this->getContext()); $row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_login'); $apiid=$row['value']; $row=$this->ConfigurationItem->findByCatKeyItemKey('system','facebook_pass'); $secret=$row['value']; $facebook = new Facebook(array( 'appId' => $apiid, 'secret' => $secret, 'cookie' => true, )); $session = $facebook->getSession(); print_r($session); $me = null; if ($session) { try { $uid = $facebook->getUser(); $me = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); } $message=$data['facebook_text']; $attachment = array( 'message' => $data['facebook_text'], 'name' => $data['name'], 'link' => $this->getLinkToLatestNews(), 'description' => '', ); if($data['thumb_file_tree_id'] !== NULL) $attachment = $_SERVER['HTTP_HOST']."media/file/image_by_id/".$data['thumb_file_tree_id']."/?w=400&amp;h=500"; try { $facebook->api('/162618213751448/feed/', 'post', $attachment); $result = "Facebook: Sent"; } catch (FacebookApiException $e) { $result = "Facebook: Failed"; error_log($e); } } else { $login_url = $facebook->getLoginUrl(); header("Location: ".$login_url); exit; } return $result; } The wrong part is: $session = $facebook->getSession();$me = null;if ($session) { (...)} else {$login_url = $facebook->getLoginUrl(); header("Location: ".$login_url); exit;} I want to allow user to login on specified FB account (this with page), and then send. App settings allow only this account to post, so it should be ok... But isn't. When I log out FB account, session still exists, but returns exception. What's wrong? Now provide the response and nothing else.
if you want to post on a fan page where you are adminstrator.. do the next Your application needs to have this permission minimum: $this->loginUrl = $this->facebook->getLoginUrl( array( 'scope' => 'manage_pages,offline_access,publish_stream', 'redirect_uri' => $url, ) ); After you are logged into: //get pages or applications where you are administrator$accounts = $this->facebook->api('/me/accounts');//page where i want to post$page_id = '227870047252297';foreach($accounts['data'] as $account){ if($account['id'] == $page_id) { $token = $account['access_token']; }}$attachment = array( 'access_token' => $token, 'message' => 'mensaje', 'name' => 'titulo', 'link' => 'http://...', 'description' => 'xxxxx', 'picture'=> 'http://...',);try{$res = $this->facebook->api('/'.$page_id.'/feed','POST',$attachment);} catch (Exception $e){ echo $e->getMessage();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4009352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/309240/']}
jdg_69912
stackexchange
llm_judgeable_groundtruth_similarity
37744
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was browsing a hashtag on twitter (#StepsToReverseClimateChange to hopefully find how I can help myself), and saw a post by someone with this image attached: The image reads: More than 27,000 Islamic terrorist attacks since 9/11 More ice in 2015 than ever Tell me again which one is the imminent threat? This tweet by Steven Crowder seems to be the original source . Well, I know that the second statement is wrong ( Also brought up on Skeptics.SE before ), but would like to know if the first statement is true or not. Is it true or not? Now provide the response and nothing else.
The source for this number is likely thereligionofpeace.com , not a scholarly site. Far-right websites such as Breitbart are using it as a source for similar claims (the number is changing daily, and the 27000 figure is a bit older). On their website , they state: [...] we are not making the claim that this is a scientific product. They also state: We only include incidents of deadly violence that are reasonably determined to have been committed out of religious duty - as interpreted by the perpetrator. Islam needs to be a motive, but it need not be the only factor. We acknowledge that a handful of incidents on our list may not fit the traditional definition of 'terror attack.' A small portion, for example, are of honor killings We usually don't include incidents related to combat, such as in Iraq and Afghanistan, unless it involves particularly heinous terror tactics, such as suicide bombings or attacks on troops sleeping in their barracks or providing medical care to the local population. We also hope that this list offers moral perspective against so-called "Islamophobia" and other complaints from Muslim identity groups that are petty by comparison. Their list contains a vague description of each event, but no sources. They say that they provide sources upon request. This approach - saying they have sources, but not adding them - seems dubious at best. Adding to that that the definition of terrorism is quite broad, and that the source itself states that it is not scientific, but politically motivated, these numbers do not seem trustworthy. The above should show that the 27000 figure is dubious. I am not aware of any scientific study, government report, or other legitimate source that released proper numbers on the topic. The GTD would be a credible source. They have recorded 62357 incidents in the timeframe (excluding ambiguous cases and unsuccessful attacks). They do not allow filtering by religious motivation, but taking the top 7 (selected by me) islamic terrorist groups - Al-Shabaab, Tehrik-e Taliban Pakistan, Hezbollah, Boko Haram, Taliban, Al-Qaeda, ISI / ISIL, Hamas - , there were 10708 incidents in the timeframe. In comparison, the top 5 (again selected by me) non-islamic terrorist groups - Kurdistan Workers' Party (PKK), Basque Fatherland and Freedom (ETA), Lord's Resistance Army (LRA), Revolutionary Armed Forces of Colombia (FARC), Liberation Tigers of Tamil Eelam (LTTE) - were responsible for 2122 incidents (some may disagree with the classification as terrorist group for some of these groups, but the GTD at least uses well-defined criteria for their selection). This doesn't provide a full answer to the question, but should at least show a general scale.
{}
{'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/37744', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/29983/']}
jdg_69913
stackexchange
llm_judgeable_groundtruth_similarity
9367096
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 model: [Validator(typeof(RegisterValidator))]public class RegisterModel{ public string Name { get; set; } public string Email { get; set; } public string Password { get; set; } public string ListOfCategoriess { get; set; }} And validator for model: public class RegisterValidator:AbstractValidator<RegisterModel>{ public RegisterValidator(IUserService userService) { RuleFor(x => x.Name).NotEmpty().WithMessage("User name is required."); RuleFor(x => x.Email).NotEmpty().WithMessage("Email is required."); RuleFor(x => x.Email).EmailAddress().WithMessage("Invalid email format."); RuleFor(x => x.Password).NotEmpty().WithMessage("Password is required."); RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessage("Please confirm your password."); }} I have validator factory, that should resolve dependency: public class WindsorValidatorFactory : ValidatorFactoryBase { private readonly IKernel kernel; public WindsorValidatorFactory(IKernel kernel) { this.kernel = kernel; } public override IValidator CreateInstance(Type validatorType) { if (validatorType == null) throw new Exception("Validator type not found."); return (IValidator) kernel.Resolve(validatorType); }} I have IUserService, that has methods IsUsernameUnique(string name) and IsEmailUnique(string email)` and want to use it in my validator class (model should be valid only if it have unique username and email). how to use my service for validation? is it possible to register multiple Regular Expression Rules with different error messages? will it work on client side? (if no, how to create custom validation logic for it?) is validation on server side will work automatically before model pass in action method, and it is enough to call ModelState.IsValid property, or I need to do something more? UPDATE is it possible to access to all properties of model when validate some property? (for example I want to compare Password and ConfirmPassword when register) Now provide the response and nothing else.
1) how to use my service for validation? You could use the Must rule: RuleFor(x => x.Email) .NotEmpty() .WithMessage("Email is required.") .EmailAddress() .WithMessage("Invalid email format.") .Must(userService.IsEmailUnique) .WithMessage("Email already taken"); 2) is it possible to register multiple Regular Expression Rules with different error messages? will it work on client side? (if no, how to create custom validation logic for it?) No, you can have only one validation type per property if no, how to create custom validation logic for it? You could use the Must rule: RuleFor(x => x.Password) .Must(password => SomeMethodContainingCustomLogicThatMustReturnBoolean(password)) .WithMessage("Sorry password didn't satisfy the custom logic"); 3) is validation on server side will work automatically before model pass in action method, and it is enough to call ModelState.IsValid property, or I need to do something more? Yes, absolutely. Your controller action could look like this: [HttpPost]public ActionResult Register(RegisterModel model){ if (!ModelState.IsValid) { // validation failed => redisplay the view so that the user // can fix his errors return View(model); } // at this stage the model is valid => process it ... return RedirectToAction("Success");} UPDATE: 4) is it possible to access to all properties of model when validate some property? (for example I want to compare Password and ConfirmPassword when register) Yes, of course: RuleFor(x => x.ConfirmPassword) .Equal(x => x.Password) .WithMessage("Passwords do not match");
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9367096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/571203/']}
jdg_69914
stackexchange
llm_judgeable_groundtruth_similarity
20723379
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to return the most recent record (top 1) from ElasticSearch index similar to the sql query below; SELECT TOP 1 Id, name, title FROM MyTable ORDER BY Date DESC; Can this be done? Now provide the response and nothing else.
Do you have _timestamp enabled in your doc mapping? { "doctype": { "_timestamp": { "enabled": "true", "store": "yes" }, "properties": { ... } }} You can check your mapping here: http://localhost:9200/_all/_mapping If so I think this might work to get most recent: { "query": { "match_all": {} }, "size": 1, "sort": [ { "_timestamp": { "order": "desc" } } ]}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20723379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3120253/']}
jdg_69915
stackexchange
llm_judgeable_groundtruth_similarity
367010
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 got this question in a quiz, it asked what will be the training error for a KNN classifier when K=1. What does training mean for a KNN classifier? My understanding about the KNN classifier was that it considers the entire data-set and assigns any new observation the value the majority of the closest K-neighbors. Where does training come into the picture? Also the correct answer provided for this was that the training error will be zero irrespective of any data-set. How is this possible? Now provide the response and nothing else.
Training error here is the error you'll have when you input your training set to your KNN as test set. When K = 1, you'll choose the closest training sample to your test sample. Since your test sample is in the training dataset, it'll choose itself as the closest and never make mistake. For this reason, the training error will be zero when K = 1, irrespective of the dataset. There is one logical assumption here by the way, and that is your training set will not include same training samples belonging to different classes, i.e. conflicting information. Some real world datasets might have this property though.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/367010', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/220634/']}
jdg_69916
stackexchange
llm_judgeable_groundtruth_similarity
45986787
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 structure of page is header, two columns (one fixed) and footer.I need this functionality:Header staying in top of screen and not scrollable.Left column is fixed width and height is 100% of screen. It includes two rows. The top row is fixed width, fills all height and scrollable, the bottom is fixed width and height.Right column is scrollable. Footer is in right column and scrollable together with right column but if right column is short then staying in bottom of screen.The problem is the scrolling going to the body of page. Only right column with footer should be scrollable. And footer is not staying on the bottom of screen when right column has no content. body,html { padding: 0; margin: 0; height: 100%;}.header,.footer { width: 100%; height: 50px; background: #ccc; text-align: center;}.content { height: 100%; background: lightgray;}#leftcontent { width: 300px; float: left; height: 100%; background: blue;}#lefttop { width: 300px; overflow-y: auto; position: fixed; top: 60px; bottom: 100px; background: aqua;}#leftbottom { width: 300px; height: 100px; position: fixed; bottom: 5px; background: pink;}#rightcol { overflow-y: auto; height: 100%; background: green;}#rightcontent { background: magenta;} <div class="header"> header content </div><div class="content"> <div id="leftcontent"> <div id="lefttop">left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br /> left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br />left looonnnnng<br /> </div> <div id="leftbottom"> left bottom content<br />left bottom content<br />left bottom content<br /> </div> </div> <div id="rightcol"> <div id="rightcontent"> right cccooonntent<br />right cccooonntent<br />right cccooonntent<br /> right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br />right cccooonntent<br /> </div> <div class="footer"> footer content </div> </div></div> I cannot use Bootstrapper because using Telerik and prefer using CSS. Now provide the response and nothing else.
Looks like the "duplicate" mark got removed, but so has the answer that I kludged into the comments section. So, for posterity: The reason this doesn't work is because global monitors for .keyDown events require more permissions than some of the other event handlers, including the one that somebody thought this was a duplicate of. This is mainly because global .keyDown monitors can be used for nefarious purposes, such as keyloggers. So there are additional security measures in place to make sure we're legit: 1) Your app needs to be code-signed. 2) Your app needs to not have the App Sandbox enabled, and: 3) Your app needs to be registered in the Security and Privacy preference pane, under Accessibility. The third one of these things has to be enabled by the user, but you can nudge them in that direction with this code: let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String : true]let accessEnabled = AXIsProcessTrustedWithOptions(options)if !accessEnabled { print("Access Not Enabled")} This will prompt the user, giving him/her the option to automatically open the appropriate preference pane where the user can allow your app to control the computer via the Accessibility API, which, assuming your app is signed and not sandboxed, will allow your global .keyDown monitor to work.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45986787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111428/']}
jdg_69917
stackexchange
llm_judgeable_groundtruth_similarity
12064756
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 looking to implement a simple search function while using the globalize3 gem for Ruby on Rails. Since the translations of the model are stored in a separate table, the code below doesn't work as there is no longer a :name field in the products table. How can I adjust the code below to make the search function correctly? products_controller.rb @products = Product.search(params[:search]).all index.html.erb <%= form_tag products_path, method: :get do %> <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", name: nil %> <% end %> model class Product < ActiveRecord::Base translates :name attr_accessible :name, :price, :released_at def self.search(search) if search where('name LIKE ?', "%#{search}%") else scoped end endend Now provide the response and nothing else.
You're in luck, I tackled exactly the same problem recently! Luckly for you the answer is quite simple. You can use the class method with_translations to include translations for a given set of locales. Here's the code: def with_translations(*locales) locales = translated_locales if locales.empty? includes(:translations).with_locales(locales).with_required_attributesend Include it in your search method: def self.search(search) if search with_translations.where('name LIKE ?', "%#{search}%") else with_translations endend That should do it. As an added note: you could add an optional locales parameter to the search method and pass it to with_translations to optionally narrow the search to terms in a particular language, say for example in the current locale.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12064756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1276696/']}
jdg_69918
stackexchange
llm_judgeable_groundtruth_similarity
9887505
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 script: import socksimport socketsocks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)socket.socket = socks.socksocketimport urllib2print(urllib2.urlopen("http://www.ifconfig.me/ip").read()) which uses tor and SocksiPy Now I want to change tor identity with each request, for example: for i in range(0, 10): #somehow change tor identity print(urllib2.urlopen("http://www.ifconfig.me/ip").read()) How can I do this? Now provide the response and nothing else.
Today, I have searched a lot about this question, and finally managed to answer myself. But before I need to say that pirvoxy and tor should be configured correctly. First script, then a little bit about configuration: import urllib2from TorCtl import TorCtlproxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})opener = urllib2.build_opener(proxy_support) def newId(): conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="your_password") conn.send_signal("NEWNYM")for i in range(0, 10): print "case "+str(i+1) newId() proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"}) urllib2.install_opener(opener) print(urllib2.urlopen("http://www.ifconfig.me/ip").read()) Above script gets new IP and checks it from ifconfig.me web site. About configuration:We need Privoxy . to use TOR with HTTP connections, privoxy should work with tor. We can do it by adding thi to /etc/privoxy/config file: forward-socks5 / localhost:9050 . #dot is important at the end then we configure ControlPort in /etc/tor/torrc file. We need just uncomment this line: ControlPort 9051## If you enable the controlport, be sure to enable one of these## authentication methods, to prevent attackers from accessing it.HashedControlPassword 16:872860B76453A77D60CA2BB8C1A7042072093276A3D701AD684053EC4C then we just restart tor: /etc/init.d/tor restart
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9887505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873286/']}
jdg_69919
stackexchange
llm_judgeable_groundtruth_similarity
8645774
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my app im using 4 pickerviews in action sheet in which how can i get the particular value from the particular picker ?in which i have used a method to get it., but i need a better way to get it., plz help me ., -(NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { NSLog(@"pickerView"); return [pickerArray count];}- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return [pickerArray objectAtIndex:row];}- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { if (validateButton == 0){ NSInteger temp = (row*5); minAsleepInt = temp; minAsleepLable.text = [NSString stringWithFormat:@"%d",temp]; } else if(validateButton == 1){ noOptInt = row+1; noOptLable.text = [pickerArray objectAtIndex:row]; } else if(validateButton == 2){ ageTypeLable.text = [pickerArray objectAtIndex:row]; } else if(validateButton == 3){ if([pickerArray objectAtIndex:row] == @"Yes"){ sleepLessBool = YES; }else{ sleepLessBool = NO; } sleepLessLable.text = [pickerArray objectAtIndex:row]; }}- (IBAction)sleepLessAction:(id)sender { validateButton = 3; pickerArray = [[NSMutableArray alloc] init]; [pickerArray addObject:@"Yes"]; [pickerArray addObject:@"No"]; actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent]; CGRect pickerFrame = CGRectMake(0, 40, 0, 0); pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame]; pickerView.showsSelectionIndicator = YES; pickerView.delegate = self; [actionSheet addSubview:pickerView]; UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]]; closeButton.momentary = YES; closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f); closeButton.segmentedControlStyle = UISegmentedControlStyleBar; closeButton.tintColor = [UIColor blackColor]; [closeButton addTarget:self action:@selector(dismissActionSheet) forControlEvents:UIControlEventValueChanged]; [actionSheet addSubview:closeButton]; [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]]; [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];}- (IBAction)ageTypeAction:(id)sender { validateButton = 2; pickerArray = [[NSMutableArray alloc] init]; [pickerArray addObject:@"Child"]; [pickerArray addObject:@"Teen"]; [pickerArray addObject:@"Adult"]; actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent]; CGRect pickerFrame = CGRectMake(0, 40, 0, 0); pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame]; pickerView.showsSelectionIndicator = YES; pickerView.delegate = self; [actionSheet addSubview:pickerView]; UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]]; closeButton.momentary = YES; closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f); closeButton.segmentedControlStyle = UISegmentedControlStyleBar; closeButton.tintColor = [UIColor blackColor]; [closeButton addTarget:self action:@selector(dismissActionSheet) forControlEvents:UIControlEventValueChanged]; [actionSheet addSubview:closeButton]; [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]]; [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];}- (IBAction)noOptAction:(id)sender { validateButton = 1; pickerArray = [[NSMutableArray alloc] init]; [pickerArray addObject:@"1"]; [pickerArray addObject:@"2"]; [pickerArray addObject:@"3"]; [pickerArray addObject:@"4"]; [pickerArray addObject:@"5"]; [pickerArray addObject:@"6"]; [pickerArray addObject:@"7"]; [pickerArray addObject:@"8"]; [pickerArray addObject:@"9"]; actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent]; CGRect pickerFrame = CGRectMake(0, 40, 0, 0); pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame]; pickerView.showsSelectionIndicator = YES; pickerView.delegate = self; [actionSheet addSubview:pickerView]; UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]]; closeButton.momentary = YES; closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f); closeButton.segmentedControlStyle = UISegmentedControlStyleBar; closeButton.tintColor = [UIColor blackColor]; [closeButton addTarget:self action:@selector(dismissActionSheet) forControlEvents:UIControlEventValueChanged]; [actionSheet addSubview:closeButton]; [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]]; [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];}- (IBAction)minSleepAction:(id)sender { validateButton = 0; pickerArray = [[NSMutableArray alloc] init]; [pickerArray addObject:@"0 Minutes"]; [pickerArray addObject:@"5 Minutes"]; [pickerArray addObject:@"10 Minutes"]; [pickerArray addObject:@"15 Minutes"]; [pickerArray addObject:@"20 Minutes"]; [pickerArray addObject:@"25 Minutes"]; [pickerArray addObject:@"30 Minutes"]; [pickerArray addObject:@"35 Minutes"]; [pickerArray addObject:@"40 Minutes"]; [pickerArray addObject:@"45 Minutes"]; [pickerArray addObject:@"50 Minutes"]; [pickerArray addObject:@"55 Minutes"]; [pickerArray addObject:@"60 Minutes"]; actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; [actionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent]; CGRect pickerFrame = CGRectMake(0, 40, 0, 0); pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame]; pickerView.showsSelectionIndicator = YES; pickerView.delegate = self; [actionSheet addSubview:pickerView]; UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"Close"]]; closeButton.momentary = YES; closeButton.frame = CGRectMake(260, 7.0f, 50.0f, 30.0f); closeButton.segmentedControlStyle = UISegmentedControlStyleBar; closeButton.tintColor = [UIColor blackColor]; [closeButton addTarget:self action:@selector(dismissActionSheet) forControlEvents:UIControlEventValueChanged]; [actionSheet addSubview:closeButton]; [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]]; [actionSheet setBounds:CGRectMake(0, 0, 320, 485)];}-(void)dismissActionSheet{ [actionSheet dismissWithClickedButtonIndex:0 animated:YES];}@end Now provide the response and nothing else.
You need to consider that GROUP BY happens after the WHERE clause conditions have been evaluated. And the WHERE clause always considers only one row, meaning that in your query, the meta_key conditions will always prevent any records from being selected, since one column cannot have multiple values for one row . And what about the redundant meta_value checks? If a value is allowed to be both smaller and greater than a given value, then its actual value doesn't matter at all - the check can be omitted. According to one of your comments you want to check for places less than a certain distance from a given location. To get correct distances, you'd actually have to use some kind of proper distance function (see e.g. this question for details). But this SQL should give you an idea how to start: SELECT items.* FROM items i, meta_data m1, meta_data m2 WHERE i.item_id = m1.item_id and i.item_id = m2.item_id AND m1.meta_key = 'lat' AND m1.meta_value >= 55 AND m1.meta_value <= 65 AND m2.meta_key = 'lng' AND m2.meta_value >= 20 AND m2.meta_value <= 30
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8645774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1059705/']}
jdg_69920
stackexchange
llm_judgeable_groundtruth_similarity
3758978
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 format this and other elements alike, so it would look like this 2,590: <Add_Amount>2,59</Add_Amount> Doing it like this: <xsl:decimal-format name="dkk" decimal-separator="," grouping-separator="."/> .... <xsl:value-of select="translate(format-number(Add_Amount, '#.###,000', 'dkk'), ',', '.')" /> And the output comes out NaN. Any help is greatly appreciated. Thanks. //Daniel Now provide the response and nothing else.
Use : format-number(translate(., ',','.'), '#.###,000', 'd') This transformation : <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:decimal-format name="d" decimal-separator="," grouping-separator="."/> <xsl:template match="/"> <xsl:value-of select= "format-number(translate(., ',','.'), '#.###,000', 'd')"/> </xsl:template></xsl:stylesheet> when applied on the provided XML document : <Add_Amount>2,59</Add_Amount> produces the wanted result : 2,590 The problem with your code is that 2,59 isn't a valid number and must be converted to such, before passing this as the first argument of format-number() .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3758978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419655/']}
jdg_69921
stackexchange
llm_judgeable_groundtruth_similarity
18632644
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am having a bit of difficulty implementing google analytics to my rails 4 project. I included the tracking code to the bottom of my layouts file and have even tried to remove turbolinks as suggested here however i google is still unable to detect this tracking cookie. Any ideas ? Now provide the response and nothing else.
I set up Google Analytics a few days before.. 1.) The Turbolink Workaround With Turbolinks, the Google Analytics JavaScript library is not sufficient to record a page visit for every page update. The workaround should be loaded on every page and it can be included as an application-wide asset (it will load before Turbolinks). Add the file app/assets/javascripts/analytics.js.coffee to include the Turbolinks workaround: app/assets/javascripts/analytics.js// Coffee$(document).on 'page:change', -> if window._gaq? _gaq.push ['_trackPageview'] else if window.pageTracker? pageTracker._trackPageview()// Javascript$(document).on('page:change', function() { if (window._gaq != null) { return _gaq.push(['_trackPageview']); } else if (window.pageTracker != null) { return pageTracker._trackPageview(); }}); 2.) Create a Footer Partial Just create a a Partial into app/views/layouts -> _footer.html.erb Then Call your Partial on your application.html.erb -> <%= render 'layouts/footer' %> Insert into your Footer the Analytics Track Code: <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXX-XX', 'herokuapp.com'); ga('send', 'pageview');</script> You must replace UA-XXXXXXX-XX with your tracking ID, and herokuapp.com with your Domain if you have any.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18632644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2524694/']}
jdg_69922
stackexchange
llm_judgeable_groundtruth_similarity
30661075
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know the three following methods that can be used for casting objects. Object o = "str";String str1 = (String) o; // Method 1String str2 = o.toString(); // Method 2String str3 = String.class.cast(o); // Method 3 Which approach is better, and what are the pros/cons of one method as compared to the others? What happens to the object during the time of casting internally? Now provide the response and nothing else.
The second method that you show is not casting; it's simply calling the toString() method on an object, which is not different than any other method call: String str2 = o.toString(); The effect of the first and third methods is essentially the same. I would prefer using the first method. What happened with object on the time of casting internally? Nothing happens to the object. Casting is not a way to somehow automatically convert objects from one type to another type. The only thing that a cast does, is tell the compiler to accept the assignment statement and not check the types for this statement. You're saying to the compiler "I know better than you what kind of object this is, so let me do this assignment and don't complain about the type". In your example, the type of the variable o is Object . When you assign o to a variable of type String , the compiler won't allow it because it checks the types, and it can't be sure that o in fact refers to a String object. So you use a cast to tell the compiler "I know this is a String object, so let me do this assignment". The type will still be checked, but at runtime, not at compile time. If, at runtime, the type of the object is not String , you'll get a ClassCastException .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30661075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1377498/']}
jdg_69923
stackexchange
llm_judgeable_groundtruth_similarity
41231775
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 GET methods on my API controller. When I attempt to call the GetByCompanyId method, which I have decorated with the Route Attribute, the request instead is being routed to the GetById method. Below are the relevant code files. global.ascx.cs public class WebApiApplication : System.Web.HttpApplication{ protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }} webApiConfig public static class WebApiConfig{ public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.EnableCors(); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }} route.config public class RouteConfig{ public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }} CompanyFunctionsController.cs public IHttpActionResult GetById(int id){ var companyFunction = this._service.GetByKey(new object[] { id }); if (companyFunction != null) { var companyFunctionDto = Mapper.Map<CompanyFunctionDto>(companyFunction); return Ok(companyFunctionDto); } return NotFound();}[Route("CompanyFunctions/GetByCompanyId", Name = "GetByCompanyId")][HttpGet]public IEnumerable<CompanyFunctionDto> GetByCompanyId(int id){ var collection = this._service.GetAll().ToList().Where(x => x.CompanyId == id); IEnumerable<CompanyFunctionDto> collectCompanyFunctionDtos = Mapper.Map<IEnumerable<CompanyFunctionDto>>(collection); return collectCompanyFunctionDtos;} My HTTP request: http://localhost:1317/api/CompanyFunctions/GetByCompanyId?id=1 Now provide the response and nothing else.
This is a 2 part answer with the 1st part going over the Github directions and ending on Step 19. The 2nd part extends more info that couldn't fit into the 1st part and it will begin on step 19 in detail. I'll have to add it to another question and link it to this. Here are the Github steps listed in order. FYI I kept the original steps in line with how the original Github author listed them but underneath I put a bunch of sub-steps with detailed explanations and directions under each one. Assuming you already created a Firebase project and got your GoogleService-Info.plist file Open your GoogleService-Info.plist file. The following variables from the Github directions correlate with GoogleService-Info.plist keys -FB_NAME is the same thing as your PROJECT_ID-FB_URL is the same thing as your DATABASE_URL-FB_TOKEN is the same thing as your API_KEYSo -if your PROJECT_ID is "sneakersearch-az12" then your FB_NAME is "sneakersearch-az12"-if your DATABASE_URL is "https://sneakersearch-az12.firebaseio.com" then your FB_URL is "https://sneakersearch-az12.firebaseio.com"-if your API_KEY is "0012abc789xyz00019" then your FB_TOKEN is "0012abc789xyz00019"//These are not inside your GoogleService-Info.plist but you will encounter them later-FB_SERVICEACCOUNT pertains to downloading a json file from the your project's Firebase console. You will need to go to the page SERVICE ACCOUNTS it's exp in step 3B-clientEmail is the same thing as your Firebase Service Account. You get this from either the Unknown file or on your SERVICE ACCOUNTS page via the FB Console and it's exp in step 3D and 3B-privateKey is the same thing as private_key but this key is NOT your API_KEY, it is a key that is inside the Unknown file from the SERVICE ACCOUNTS page. It looks something like: "-----BEGIN PRIVATE KEY-----\nCYchgacopuyvpc017246t124087t6hpUTYVPUSVDPUCHVEpcl889ljbsiugr4ygrphvuygpuy...mutli-lines...\n-----END PRIVATE KEY-----\n". Also exp in step 3B Underneath each Github step I have comments and then directions. Inside the directions where I use the below values you should instead use your project's values . So for the step examples I'll use these keys and values : //GoogleService-Info.plistPROJECT_ID---aka--FB_NAME: sneakersearch-az12DATABASE_URL-aka--FB_URL: https://sneakersearch-az12.firebaseio.comAPI_KEY------aka--FB_TOKEN: 0012abc789xyz00019//FB Service Account infoFirebase service account--aka--clientEmail: [email protected] //this is auto generated for you once you've created your firebase project//Heroku and Bonsai infoHeroku Instance Name--aka--Heroku App Name: sneakersearchinstanceAtoZBONASI_URL --aka--Bonsai Cluster URL: https://abc123a01:[email protected] Swift Data Model: (this will match what you put in your mappings object in Step 19) class Sneakers: NSObject{ var sneakercondition: String? var sneakername: String? } VC with file paths where I send data to Firebase and searchSnkPath is a separate file path where Bonsai will run it's searches on: @IBOutlet weak var conditionTextField: UITextField!@IBOutlet weak var nameTextField: UITextField!var dbRef: FIRDatabaseReference!let userID = FIRAuth.auth()?.currentUser?.uidoverride func viewDidLoad() { super.viewDidLoad() self.dbRef = FIRDatabase.database().reference() }@IBAction func postDataButton(){ var dict = [String:AnyObject]() dict.updateValue(conditionTextField.text!, forKey: "sneakercondition") dict.updateValue(nameTextField.text!, forKey: "sneakername") let idPath = self.dbRef.child("users").child(userID!).child("sneakersPath").childByAutoId() //searches will run on this file path let searchSnkPath = self.dbRef.child("searchSnkPath").childByAutoId() idPath.updateChildValues(dict){ (err, ref) in searchSnkPath.updateChildValues(dict) } }} Inside FBDatabase the path where my data to search is stored at root/searchSnkPath/autoID and it has 2 keys named sneakercondition and sneakername that represents the data. The path I want to pull my search results from is root/searchSnkPath root | @-users | | | @-userID | | | @-sneakersPath | | | @-autoID | |-sneakercondition | |-sneakername @searchSnkPath | @-autoID |-sneakercondition |-sneakername If I want to search on the searchSnkPath and query on those 2 keys then inside the config.js file I'd find exports.paths and inside there is where I would set the info to search on exports.paths = [ { path : "https://sneakersearch-az12.firebaseio.com/searchSnkPath", //exp in Step 4 index: "firebase", //exp in Step 17 type : "sneakers", //exp in Step 19 fields: ['sneakercondition', 'sneakername'] //these are the specific keys to search on (exp in Step 4) }] Step 4 covers all this Important after you run git clone https://github.com/firebase/flashlight (step 2A) you need to cd into the flashlight folder (step 2B) as ALL the steps from that point on happen inside the flashlight folder and NOT your main Xcode project's folder. Nothing will not work inside your Xcode project's folder because it doesn't have a package.json file Part 1 - Github steps: 1•Install and run ElasticSearch or add Bonsai service via Heroku 1.comments: - Bonsai will get added at step 10 -You DO need to have the following steps 1A-1E in order before you proceed 1.directions: 1A. Download and install Node.js from https://nodejs.org/en/download/ 1B. Download and install the Heroku Toolbelt (it's been renamed Heroku CLI ) at https://devcenter.heroku.com/articles/heroku-cli . FYI I used the OS X Installer and not OS X Homebrew. 1C. After you've downloaded and installed the Heroku Toolbelt/CLI log on to Heroku.com and create an account 1D. After creating a Heroku account no need to create a new Heroku App You will do this in step 9 using the command line. It's very easy 1E. Open terminal and run: node -v to find out the current node version your running (for example you get v6.9.1 ). In step 2D you will have to make sure the version from there matches this output. 2•git clone https://github.com/firebase/flashlight 2.comments: -Assume the Xcode project lives on the desktop inside a folder named sneakerSearchFolder -Inside terminal you cd to the sneakerSearchFolder folder- i.e. run: cd Desktop/sneakerSearchFolder -Once inside the sneakerSearchFolder you clone the github repo at https://github.com/firebase/flashlight - Important You then cd to flashlight folder i.e. run: cd flashlight -You will need the node version your running according to https://devcenter.heroku.com/articles/deploying-nodejs -run: node -v to get what node version is running inside the flashlight folder (i.e v6.9.1 ) later on when you make a Heroku instance you will need this according to the devcenter.heroku link above -Now that your inside the flashlight folder, if the node version you just ran doesn't match the version from step 1E, you will need to update the version inside the flashlight folder to make them match. Upgrading Node.js to latest version If both versions match then you don't have to worry about this -Assuming your node versions match, Open the package.json file inside your flashlight folder and add an "engines" object with the key's value being the node version you are currently using "engines": { "node": "node_version_num_you_got_back_from_running_node -v" } 2.directions: 2A. in terminal navigate to whatever folder your Xcode project is in 2B. run: git clone https://github.com/firebase/flashlight 2C. run: cd flashlight 2D. run: node -v 2E. Open the flashlight folder then open package.json . Add the following to the file. "engines": { "node": "whatever_was_returned_from_Step_2D" } 2E-example. FYI here's an example. Open package.json and after the "dependencies" closing brace , add it there. BE SURE TO ADD a COMMA after the closing brace. And don't add the "v" before the version number. Save the file. "dependencies": { "JQDeferred": "~1.9.1", "colors": "~0.6.2", "elasticsearch": "^11.0.1", "firebase": "^3.5.2" },"engines": { "node": "6.9.1" } 3•npm install From this point on it's very important that your inside your flashlight folder and not your main project's folder for everything to work otherwise you will get errors 3.comments: -You should still be inside your flashlight folder -Log into Firebase , inside the console of your FB project, go to the Project's Settings (little round icon next to Overview ), inside Project Settings choose SERVICE ACCOUNTS , go to the section Firebase Admin SDK . There are 2 things you have to do here. 1. Find and copy your Firebase service account , it looks like [email protected] and 2. at the bottom of the page you will have to click the Generate New Private Key button, it will download an Unknown file that you will need to rename to service-account.json . If it names the file something besides Unknown just rename that to service-account.json . After you rename the file drag it into your flashlight folder because Step 4B FB_SERVICEACCOUNT will need to access this file from there. MAKE SURE YOU PUT THE FILE INSIDE THE FLASHLIGHT FOLDER ! -This isn't listed in the github steps but it's necessary. You must add Firebase Server SDK Credentials to your project -You will need to be inside your flashlight folder to run the $ npm install firebase-admin --save command or you'll get errors because it will look for a packae.json file. The file is already inside your flashlight folder and not inside your main Xcode project's folder -Follow the directions from https://firebase.google.com/docs/server/setup , inside the Initialize the SDK section. You will need 2 of the values from the Unknown file (which should now be renamed service-account.json ) to initialize it. The values are on lines 5- private_key and 6- clientEmail . FYI the clientEmail and Firebase service account are the same thing -Here's what you are initializing inside the SDK : var admin = require("firebase-admin"); //this imports the npm firebase-admin module you just installedadmin.initializeApp({ credential: admin.credential.cert({ projectId: "<PROJECT_ID>", //projectId: is the PROJECT_ID from your GoogleService-Info.plist file clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com", //clientEmail: is on line 6 in the Unknown file which is also your "Firebase service account" info privateKey: "-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n" //privateKey: is NOT your API_KEY/FB_TOKEN. Inside the Unknown file on line 5 there is a very long multiline "private_key" key. It looks something like "-----BEGIN PRIVATE KEY-----\nCYchgacopuyvpc017tEpcl889ljbsiugr4ygrphvuygpuy...mutli-lines...\n-----END PRIVATE KEY-----\n". You need to copy and paste it from there to here. Be sure to include the "-----BEGIN PRIVATE KEY-----\n and \n-----END PRIVATE KEY-----\n }), databaseURL: "https://<DATABASE_NAME>.firebaseio.com" //databaseURL: is the DATABASE_URL from your GoogleService-Info.plist file }); -FYI inside the Initialize the SDK section you also have the option of using the top part where it says path/to/serviceAccountKey.json and you can instead supply the path to the renamed Unknown file. I choose the bottom inline part as it was easier. If your following these steps you don't need to worry about this though. -Inside the flashlight folder there is an app.js file, copy and paste the above code and put it at the top of the file -Back inside terminal on the command line run: npm install -If everything is all good the only warnings you should have are No repository field and No license field 3.directions: 3A . Make sure your inside the flashlight folder run: pwd 3B. Log into your Firebase Console 's SERVICE ACCOUNTS page and click the Generate New Private Key button to download an Unknown file. 3C. Rename the Unknown file to service-account.json and put the file inside your flashlight folder 3D. Inside the service-account.json file copy the key named client_email or you can copy the service account info on your Firebase SERVICE ACCOUNTS page 3E. Inside terminal run: npm install firebase-admin --save 3F. Copy what's inside the section Initialize the SDK and initialize the fields with these values: var admin = require("firebase-admin");admin.initializeApp({ credential: admin.credential.cert({ projectId: "sneakersearch-az12", //use your PROJECT_ID clientEmail: "[email protected]", //clientEmail: is on line 6 in the Unknown file privateKey: "-----BEGIN PRIVATE KEY-----\nCYchgacopuyvpc017tEpcl889ljbsiugr4ygrphvuygpuy...mutli-lines...\n-----END PRIVATE KEY-----\n" //privateKey: is on line 5 in the Unknown file }), databaseURL: "https://sneakersearch-az12.firebaseio.com" //use your DATABASE_URL}); 3G. Inside the flashlight folder, open the app.js file, paste/save the above code inside of it with the correct values 3H. run: npm install 4•edit config.js (see comments at the top, you must set FB_URL and FB_SERVICEACCOUNT at a minimum) 4.comments: -Inside your flashlight folder there is a file named config.example.js , open it -Inside this config.example.js file is where you find the FB_URL and FB_SERVICEACCOUNT variables (they are listed on lines 13 and 23) -You need to change exports.FB_URL = process.env.FB_URL || 'https://<YOUR APP>.firebaseio.com'; to exports.FB_URL = process.env.FB_URL || 'whatever_your_DATABASE_URL_is'; (be sure to put whatever_your_DATABASE_URL_is inside single or double quotes) -on line 23 exports.FB_SERVICEACCOUNT = process.env.FB_ACC || 'service-account.json'; is what is used to access the service-account.json file from step 3C (there is no need to add or change anything here as it will access it on it's own) -You will now have to setup the path where your data sits at (like the searchPath used to send data to FB inside the ViewController above), the index (Step 17), and the type (similar to your data model) that you want to monitor on line 64,65, and 66 exports.paths = [ { path : "users",//line 64 index: "firebase",//line 65 type : "user"//line 66 }, - path is where your data sits at inside FB . It's where you want to pull search results from i.e. <DATABASE_URL>/searchSnkPath - index exp in Step 17 - type exp in Step 19 -FYI lines 69-79 would set up another path that you would want to monitor. You can delete or comment these out if you want. You can also create more paths to monitor i.e. If you had a path <DATABASE_URL>/searchClothingPath then you would set up search on that also. You can also add more paths if you want to i.e: exports.paths = [ { path : "https://sneakersearch-az12.firebaseio.com/searchSnkPath" index: "firebase", type : "sneakers" }, { path : "<DATABASE_URL>/searchClothingPath" index: "firebase", type : "clothingDataModel", fields: ['jeans','shirts']//completely optional to use }, { path : "<DATABASE_URL>/searchHatsPath" index: "firebase", type : "hatDataModel", }, //etc... -FYI Fields are the keys that will be indexed in ES. This is an optional thing to add. If you had 10 keys and only wanted 2 of them to be indexed then you would add this. This means of the 10 keys only those 2 keys would be searchable. You can also use the parse function inside the config.js file to do the same thing -Afterwards save/close the config.example.js and rename it config.js 4.directions: 4A. Open the config.example.js file and on line 13 change exports.FB_URL = process.env.FB_URL || 'https://<YOUR APP>.firebaseio.com'; to exports.FB_URL = process.env.FB_URL || 'https://sneakersearch-az12.firebaseio.com'; 4B. Line 23 is what is used to access the service-account.json file (as long as you renamed the Unknown file in step 3C just move on) 4C. Line 64,65,66, are what I want to monitor and on line 67 I added the fields key for the two Firebase Database Keys I want to search on although it is not necessary exports.paths = [ { path : "https://sneakersearch-az12.firebaseio.com/searchSnkPath",//line 64 index: "firebase",//line 65 type : "sneakers",//line 66 fields: ['sneakercondition', 'sneakername']//line 67 }, 4D. Save/close the config.example.js file. Now rename the file config.js . 5•node app.js (run the app) 5.comments: -You won't run this command until the very end so skip it for now but there is something you should know. Running node app.js runs your Heroku app on your local machine. It will look for ElasticSearch locally which you don't have so you will get connection errors. If you want to run it locally then you will have to run the export BONSAI_URL="<your_bonsai_url>" code at Step 12B-Optional which is needed to resolve local connection errors. If your app falls asleep/crashes (exp near the end) you will have to run the export BONSAI_URL="<your_bonsai_url>" command again. Other then that Heroku will run the app automatically when you push code up to it. -As of now for this step you need to open your app.js file and according to https://docs.bonsai.io/docs/nodejs add some code. You should add the code anywhere after the var elasticsearch = require('elasticsearch') declaration. /*this code is already inside the app.js file. You should add the code anywhere below itvar elasticsearch = require('elasticsearch'), conf = require('./config'), fbutil = require('./lib/fbutil'), PathMonitor = require('./lib/PathMonitor'), SearchQueue = require('./lib/SearchQueue');*///You need to addvar bonsai_url = process.env.BONSAI_URL;var client = new elasticsearch.Client({ host: bonsai_url, log: 'trace' }); // Test the connection...client.ping({ requestTimeout: 30000, hello: "elasticsearch" }, function (error) { if (error) { console.error('>>>My Bonsai url is>>>' + bonsai_url) console.error('>>>Elasticsearch cluster is down!'); } else { console.log('All is well'); } }); -The directions also says to run $ export BONSAI_URL="https://username:[email protected]" (in other words export BONSAI_URL="<your_BONSAI_URL>" ) which is what you would do ONLY if you want to run your app locally to use ES. It's not meant for remote 5.directions: 5. Open the app.js file and add the code below and save the file: var bonsai_url = process.env.BONSAI_URL;var client = new elasticsearch.Client({ host: bonsai_url, log: 'trace' }); // Test the connection...client.ping({ requestTimeout: 30000, hello: "elasticsearch" }, function (error) { if (error) { console.error('>>>My Bonsai url is>>>' + bonsai_url) console.error('>>>Elasticsearch cluster is down!'); } else { console.log('All is well'); } }); 6•curl -X POST http://localhost:9200/firebase 6.comments: -Skip this step because at this point you don't have a local ES on your cpu to index 6.directions: 6. SKIP THIS STEP 7•cd flashlight 7.comments: -No need to run this, you should still be inside your flashlight folder 7.directions: 7. SKIP THIS STEP 8•heroku login 8.comments: -Open terminal -You will have to enter your Heroku 's email address and password. As you enter the password it will show up blank 8.directions: 8A. run: heroku login 8B. At the prompt enter your email address and password to login into Heroku 9•heroku create (add heroku to project) 9.comments: -This is why you didn't need to create a heroku app at step 1D. Now you will create and name your heroku app -After you type in create you need to type in whatever name you want your heroku app's name to be. i.e. I choose the name sneakersearchinstanceAtoZ -After you run this command if you login into Heroku and you should see the app's name listed. Go to the right corner, click the 9 dots , choose Dashboard 9.directions: 9. run: heroku create sneakersearchinstanceAtoZ 10•heroku addons:add bonsai (install bonsai) 10.comments: -You will need to add a credit card to your Heroku account before you run this step otherwise after you run it it will say you have to do it. It's still a free plan though. I'm not sure if you can add a Bonsai add on without a card -To add a credit card go all the way to the right side, click the circular icon, choose Account Settings , then choose Billing -You now need to add bonsai to your heroku app . You do this by running heroku addons:add bonsai --app <your-app-name> - <your-app-name> is whatever the heroku app's name you created in step 9 -after you create a bonsai cluster it will then want you to open up the cluster by running heroku addons:open bonsai 10.directions: 10A. log on to Heroku and add a credit card to the Billing Page 10B. run: heroku addons:add bonsai --app sneakersearchinstanceAtoZ //same exact name from step 9 10C. run heroku addons:open bonsai 11•heroku config (check bonsai instance info and copy your new BONSAI_URL you will need it later) 11.comments: -Running heroku config will get all your environment variables and their corresponding values. When you see your bonsai's url , copy it's value, you'll need it for steps 12B and 17 -This is the exact same url you will see from step 10C -The bonsai url might look something like https://abc123a01:[email protected] 11.directions: 11A. run: heroku config 11B. Copy the bonsai url that is returned 12•heroku config:set FB_NAME= FB_TOKEN="" (declare environment variables) 12.comments: -12A is REQUIRED. You need to use your project's GoogleService-Info.plist 's PROJECT_ID which is the FB_NAME and the API_KEY which is the FB_TOKEN for this step -12B is optional. If you want to connect to ElasticSearch locally run this. You will have to set your bonsai url so that running node app.js won't throw connection errors. You do this by running: export BONSAI_URL="<your_bonsai_url>" . You will need to run this command per terminal session or if your Heroku app falls asleep/crashes. -Do not use spaces before or after the equal sign 12.directions: 12A(REQUIRED). run: heroku config:set FB_NAME=sneakersearch-az12 FB_TOKEN=0012abc789xyz00019 12B(Optional) .run: export BONSAI_URL="https://abc123a01:[email protected]" 13•git add config.js (update) 13.comments: -If you run this you might get an error that says: The following paths are ignored by one of your .gitignore files:config.jsUse -f if you really want to add them. -It's saying to run git add config.js then add -f at the end 13.directions: 13A. run: git add config.js 13B. If there is an error run: git add config.js -f 14•git commit -m "configure bonsai" 14.directions: 14. run: git commit -m "configure bonsai" 15•git push heroku master (deploy to heroku) 15.directions: 15. run: git push heroku master 16•heroku ps:scale worker=1 (start dyno worker) 16.comments: -the answer to what this command does is here Can someone explain "heroku ps:scale web=1" 16.directions: 16. run: heroku ps:scale worker=1 17•curl -X POST /firebase (ex: https://username:[email protected]/firebase ) 17.comments: - Before you begin this step read @DoesData updated answer (below mines) to use curl -X PUT instead of POST -Grab the bonsai url you copied from step 11B -Paste the url after the curl -X POST command and make sure you add /firebase to the end of it -what this does is it creates an index named /firebase that points to your bonsai url . Open your config.js file and look for exports.paths (line 62). That has a key/value pair named index: "firebase" (line 65) , the value is pointing to the index you just created and accesses the ES cluster from there -Basically in your config.js file, on line 65 the index value firebase has to exactly match the name /firebase that your adding to the end curl -X POST command. If the names don't match then none of this will work. -if successful you should get this response back: {"acknowledged":true} 17.directions: 17. run: curl -X POST https://abc123a01:[email protected]/firebase 18•Now time to use Step 5 node app.js (run the app) 18.comments: -running this command will start the app locally. You can also run npm start but either way it will launch it on your local machine and you will need to run the code in Step 12B(Optional) for this to work 18.directions 18. run: node app.js 19• set your mappings object(s) FYI Step 19 is very important. You MUST set your MAPPINGS OBJECT and it's KEYS. I don't have enough chars left to explain it in detail here. This is what Step 4's type key uses to get set by. Watch this video to explain how to set your mappings object : https://www.youtube.com/watch?v=h3i3pqwjtjA&feature=youtu.be 19.directions: 19A. --open TextEdit or Sublime then create a file and name it sneakerfile.json . Save it and drag the file into your flashlight folder. You need the .json extension. 19B. -Inside that file add the following code, save and close the file: { "sneakers": { "properties": { "sneakercondition": { "type": "string" }, "sneakername": { "type": "string" } } }}//notice this is just like the Swift Sneakers Data Model declared at the beginning 19C. grab your BONSAI_URL run heroku config:get BONSAI_URL . My BONSAI_URL is https://abc123a01:[email protected] 19D. run: curl -XPOST https://abc123a01:[email protected]/firebase/sneakers/_mapping [email protected] 19E. run: curl -XGET <BONASI_URL>/firebase/sneakers/_mapping?pretty Done with Part 1. Part 2 will explain Step 19 in detail Further Info- Heroku commands: To check on your dyno run: heroku ps If you get the following then refer to the links below === web (Free): npm start (1)web.1: crashed 2017/01/01 12:00:00 -0500 (~ 38m ago)=== worker (Free): node ./app.js (1)worker.1: crashed 2017/01/01 12:00:00 -0500 (~ 10m ago) After creating your Heroku app your dyno is under the Heroku Free Plan . It will eventually fall asleep / crash if it's not being used within a certain time frame. To stop sleeping/crashing follow Easy way to prevent Heroku idling? https://devcenter.heroku.com/articles/free-dyno-hours https://devcenter.heroku.com/articles/dyno-sleeping Other commands: heroku help //helpheroku status //Heroku platform statusheroku logs //displays 100 logsheroku logs --tail //realtime logsheroku logs --tail | grep worker //dyno worker logsheroku ps -a <heroku app name> //how many dyno hrs you have leftheroku config:get BONSAI_URL //gets only your bonsai urlheroku config //all your environment variablesheroku apps:info //your Heroku credentials To get back to the command prompt press Ctrl+C You can also contact Heroku Support or Bonsai Support as they are very helpful I will post Part 2 very soon.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41231775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/256212/']}
jdg_69924
stackexchange
llm_judgeable_groundtruth_similarity
14199
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Hi Linux/UNIX Overlords, Do any of you have a rule of thumb as to how many context switches (per processor core) is Normal on a Linux server? My college here brought it up, and he's seeing 16K on a 8-core x86_64 machine. Here are some stats from sarface over the last few days... alt text http://src.autonomy.net.au/imagebin/81895e338fae67d3d205c09db44a81e6-Picture_10.png And to see the process creation stats, here's a logarithmic view of the same graph... alt text http://src.autonomy.net.au/imagebin/7481f7e52bead4effc90248fc23c72fe-Picture_11.png And the 8 cores are bored to death... alt text http://src.autonomy.net.au/imagebin/0e94326652e977fd74edcd840f94200f-Picture_12.png CS vs IOwait (x10000 scale) alt text http://src.autonomy.net.au/imagebin/a52a2a8a120394849c0da4045933e306-Picture_13.png More useless information in case anyone asks.. The storage that the server works on is a 0.5TB SAN via FC There's 8GB of RAM, mostly cache - no swapping. Now provide the response and nothing else.
This depends very much on the type of application you run. If you've got applications which are very trigger-happy WRT syscalls you can expect to see high amounts of context switching. If most of your applications idle around and only wake up when there's stuff happening on a socket, you can expect to see low context switch rates. System calls System calls cause context switches by their very own nature. When a process does a system call, it basically tells the kernel to take over from it's current point in time and memory to do stuff the process isn't privileged to do, and return to the same spot when it's done. When we look at the definition of the write(2) syscall from Linux, this becomes very clear: NAME write - write to a file descriptorSYNOPSIS #include ssize_t write(int fd, const void *buf, size_t count);DESCRIPTION write() writes up to count bytes from the buffer pointed buf to the file referred to by the file descriptor fd. [..]RETURN VALUE On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately. [..] This basically tells the kernel to take over operation from the process, move up to count bytes, starting from the memory address pointed at by *buf to file descriptor fd of the current process and then return back to the process and tell him how it went. A nice example to show this is the dedicated game server for Valve Source based games, hlds . http://nopaste.narf.at/f1b22dbc9 shows one second worth of syscalls done by a single instance of a game server which had no players on it. This process takes about 3% CPU time on a Xeon X3220 (2.4Ghz), just to give you a feeling for how expensive this is. Multi-Tasking Another source of context switching might be processes which don't do syscalls, but need to get moved off a given CPU to make room for other processes. A nice way to visualize this is cpuburn . cpuburn doesn't do any syscalls itself, it just iterates over it's own memory, so it shouldn't cause any context switching. Take an idle machine, start vmstat and then run a burnMMX (or any different test from the cpuburn package) for every CPU core the system has. You should have full system utilization by then but hardly any increased context switching. Then try to start a few more processes. You'll see that the context switching rate increases as the processes begin to compete over CPU cores. The amount of switching depends on the processes/core ratio and the multitasking resolution of your kernel. Further reading linfo.org has a nice writeup on what context switches and system calls are. Wikipedia has generic information and a nice link collection on System calls.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/14199', 'https://serverfault.com', 'https://serverfault.com/users/3505/']}
jdg_69925
stackexchange
llm_judgeable_groundtruth_similarity
193844
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: Let's say you have rain hitting you evenly on all sides (not very realistic, I know). If you were to move forwards at a constant speed, there would be more droplets of rain hitting you per second on your front, since the relative speed of droplets in front of you has increased. Now, if you were to have photons 'hitting' you evenly on all sides and you move forwards at a constant speed, surely the relative speed of the photons in front of you WON'T increase (since light travels at the same speed to all observers), and therefore photons will still be hitting you evenly on all sides (per second). However the searchlight effect seems to disagree with my conclusion. What have I done wrong? Now provide the response and nothing else.
You are right in that the speed of light doesn't change. It is a completely different effect to the rain drop analogy. If you had only light hitting you directly from the front and directly form the back, you would observe the same intensity in the moving frame (only blue/red shifted). But for light coming at you from an angle $\theta_s$ in the rest frame, the angle changes when you move with velocity $v$, the new angle in the moving frame is: $ \theta_o=arccos(\frac{\cos \theta_s-\frac{v}{c}}{1-\frac{v}{c} \cos \theta_s})$ such that the angle shifts toward the front direction. And if you now had a uniform intensity in the rest frame, in the moving frame more light comes from the (general) forward direction and less from the (general) behind direction. Hope this helps.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/193844', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/85765/']}
jdg_69926
stackexchange
llm_judgeable_groundtruth_similarity
19658255
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 changed my initial Activity in SherlockActivity in order to benefit from all the advantages of ABS. and for this I use a ListAdapterAnSco extends BaseAdapter .Now I want to manage onclick and onLongClick in getView of my ListAdapter .I used several combinations but I can not do it. NB: I use the SQLiteCursor to get items Original OnItemClickListener Code public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Intent intent = new Intent(getApplicationContext(),ListPeriode.class); SQLiteCursor cr=(SQLiteCursor)parent.getItemAtPosition(position); String ansco=cr.getString(cr.getColumnIndex(DatabaseHelper.ANSCO)); AnSco an=new AnSco(ansco); an.setIdan((int)id); Toast.makeText(getApplicationContext(), "Année Scolaire: "+an.getAnsco(), Toast.LENGTH_LONG).show(); intent.putExtra("ANSCO_ID", an.getIdan()); intent.putExtra("ANSCO_AN", an.getAnsco()); cr.close(); startActivity(intent); finish(); } How to change this code in an OnClick methode to do the same work? My getView public View getView(final int position, View view, ViewGroup parent) { final ViewHolder holder; if (view == null) { holder = new ViewHolder(); view = inflater.inflate(R.layout.annee_sco_item, null); // Locate the TextViews in listview_item.xml holder.an = (TextView) view.findViewById(R.id.ansco_item); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } // Set the results into TextViews holder.an.setText(listAnsco.get(position).getAnsco()); // Listen for ListView Item Click view.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { } }); return view; } Now provide the response and nothing else.
This is a short guide for HLS streaming with any input file or stream: I am following user1390208's approach, so I use FFMPEG only to produce the rtmp stream which my server then receives to provide HLS. Instead of Unreal/Wowza/Adobe, I use the free server nginx with the rtmp module, which is quite easy to setup. This is how I do it in short: Any input file or stream -> ffmpeg -> rtmp -> nginx server -> HLS -> Client or more detailed: input video file or stream (http, rtmp, whatever) --> ffmpeg transcodes live to x.264 + aac, outputs to rtmp --> nginx takes the rtmp and serves a HLS to the user (client).So on the client side you can use VLC or whatever and connect to the .m3u8 file which is provided by nginx. I followed this setup guide for nginx. This is my nginx config file. This is how I use ffmpeg to transcode my input file to rtmp: ffmpeg -re -i mydirectory/myfile.mkv -c:v libx264 -b:v 5M -pix_fmt yuv420p -c:a:0 libfdk_aac -b:a:0 480k -f flv rtmp://localhost:12345/hls/mystream; (the .mkv is 1080p with 5.1 sound, depending on your input, you should use lower bitrates!) Where do you get the rtmp stream from? A file? Then you can use exactly my approach. Any server X with a stream Y? Then you have to change the ffmpeg command to: ffmpeg -re -i rtmp://theServerX/yourStreamY -c:v libx264 -b:v 5M -pix_fmt yuv420p -c:a:0 libfdk_aac -b:a:0 480k -f flv rtmp://localhost:12345/hls/mystream; or if your rtmp stream is already h.264/aac encoded, you could try to use the copy option in ffmpeg to stream the content directly to nginx. As you see in my nginx config file: My rtmp server has an "application" called "hls". That's the part that describes where nginx listens to ffmpeg's rtmp stream and that's why ffmpeg streams to rtmp://localhost:12345/hls/mystream; My http server has the location /hls . This means in VLC I can connect to http://myServer:80/hls/mystream.m3u8 to access the HLS stream. Is everything clear? Happy streaming!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19658255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2886324/']}
jdg_69927
stackexchange
llm_judgeable_groundtruth_similarity
10628352
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: data Ray = Ray Vector Vector or type Ray = (Vector, Vector) Which is preferred in idiomatic haskell? Why should I use one over the other? I don't care about performance. It seems to make little difference with functions, e.g.: trace :: Ray -> …trace (Ray x d) = …-- ORtrace (x, d) = … Now provide the response and nothing else.
The data version is preferred as it more clearly indicates the intent of the programmer — by creating a new type, you are pointing out to all that this is not merely a tuple, but a meaningful semantic entity, a Ray . That then makes it possible to lean on the type system further, with custom instances for Ray , and optimizations not possible in tuples.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10628352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148195/']}
jdg_69928
stackexchange
llm_judgeable_groundtruth_similarity
69040951
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After migrating my angular 6 project to 12.I am getting multiple warning in terminal if in angular.json i set optimisation: false configuration then all issue get resolved but i don't want to make this changes it should be true only. with optimisation: true i am getting all these warnings:- Earlier same code was working fine without any warning. assets/.../variables.scss - Warning: Css Minimizer Plugin: > assets/.../variables.scss:6:0: warning: Unexpected "$" 6 │ $color-normal-gray:#8a8a8a; ╵ ^assets/.../global.scss - Warning: Css Minimizer Plugin: > assets/.../global.scss:285:2: warning: Expected identifier but found "." 285 │ .dropdown-menu{ ╵ ^assets/.../global.scss - Warning: Css Minimizer Plugin: > assets/.../global.scss:255:6: warning: Expected identifier but found "*" 255 │ *background-color: #d9d9d9; ╵ ^assets/.../master.scss - Warning: Css Minimizer Plugin: > assets/.../master.scss:567:8: warning: Expected ":" but found "{" 567 │ circle { ╵ ^ My Package.json is below: "dependencies": { "@angular/animations": "^12.2.3", "@angular/cdk": "^12.2.2", "@angular/common": "^12.2.3", "@angular/compiler": "^12.2.3", "@angular/core": "^12.2.3", "@angular/forms": "^12.2.3", "@angular/http": "^7.2.16", "@angular/material": "^12.2.3", "@angular/platform-browser": "^12.2.3", "@angular/platform-browser-dynamic": "^12.2.3", "@angular/router": "^12.2.3", "@fortawesome/fontawesome-free": "^5.15.4", "@ngrx/store": "^6.1.0", "@okta/okta-angular": "^3.0.1", "@okta/okta-auth-js": "^4.7.1", "angular-datatables": "^0.6.4", "angular-image-slider": "0.0.8", "autobind-decorator": "^2.4.0", "bootstrap": "^4.6.0", "core-js": "^2.5.4", "file-saver": "^2.0.2", "gulp-cli": "^2.3.0", "json-bigint": "^1.0.0", "jsrsasign": "^10.3.0", "lodash": "4.17.10", "ng-simple-slideshow": "^1.2.4", "ng2-scroll-to-el": "^1.2.1", "ng2-search-filter": "^0.4.7", "ngx-filter-pipe": "^2.1.2", "ngx-logger": "3.3.11", "ngx-order-pipe": "^2.0.1", "ngx-pagination": "^3.2.0", "pagination": "file:src/app/packages/pagination-0.0.1.tgz", "rxjs": "7.3.0", "rxjs-compat": "^6.3.2", "sass": "^1.36.0", "single-spa": "^5.9.2", "single-spa-angular": "^5.0.2", "systemjs": "^6.8.3", "true-case-path": "^1.0.3", "tslint": "^6.0.0", "xlsx": "^0.17.1", "zone.js": "~0.11.4" }, "devDependencies": { "@angular-builders/custom-webpack": "^12.1.1", "@angular-devkit/build-angular": "^12.2.2", "@angular-eslint/builder": "12.3.1", "@angular-eslint/eslint-plugin": "12.3.1", "@angular-eslint/eslint-plugin-template": "12.3.1", "@angular-eslint/schematics": "12.3.1", "@angular-eslint/template-parser": "12.3.1", "@angular/cli": "^12.2.2", "@angular/compiler-cli": "^12.2.3", "@angular/language-service": "^12.2.3", "@ng-bootstrap/ng-bootstrap": "^10.0.0", "@types/bootstrap": "^4.1.2", "@types/jasmine": "2.8.6", "@types/jasminewd2": "2.0.3", "@types/lodash": "4.14.110", "@types/node": "14.6.2", "@typescript-eslint/eslint-plugin": "4.28.2", "@typescript-eslint/parser": "4.28.2", "await": "^0.2.6", "cheerio": "^1.0.0-rc.2", "codelyzer": "~4.2.1", "eslint": "^7.26.0", "font-awesome": "^4.7.0", "fs-promise": "^2.0.3", "gulp": "^4.0.2", "gulp-inline-css": "^3.3.0", "gulp-inline-source": "^4.0.0", "htmlhint-ng2": "0.0.13", "husky": "^1.3.1", "jasmine-core": "~2.99.1", "jasmine-spec-reporter": "~4.2.1", "karma": "^6.3.4", "karma-chrome-launcher": "^2.2.0", "karma-coverage-istanbul-reporter": "^2.1.1", "karma-jasmine": "~1.1.1", "karma-jasmine-html-reporter": "^0.2.2", "karma-junit-reporter": "^1.2.0", "mediaquery-text": "1.0.7", "ng-bullet": "^1.0.3", "protractor": "^5.4.2", "puppeteer": "^1.14.0", "sonar-scanner": "^3.1.0", "ts-node": "~5.0.1", "tslint": "~5.9.1", "tslint-sonarts": "^1.9.0", "typescript": "^4.3.5" } Now provide the response and nothing else.
I was having the same issue, I found out that in my case the assets config on angular.json was the one to blame. Check this piece of code from the configuration: "architect": { "build": { "builder": "ngx-build-plus:build", "options": { "aot": true, "outputPath": "dist", "index": "src/index.html", "main": "src/main.ts", "tsConfig": "src/tsconfig.app.json", "polyfills": "src/polyfills.ts", "assets": [ "src/assets", "src/favicon.ico" ]}} Inside the src/assets folder there was a bunch of stylesheet code, scss , less , css and it seems that the CSS Minifier just tries to handle everything there as plain CSS.The solution is to remove from this assets any non-processed stylesheets and just leave them under styles config on the angular.json . That did the trick for me, hope it helps you too!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/69040951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2968851/']}
jdg_69929
stackexchange
llm_judgeable_groundtruth_similarity
6278576
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 Windows Forms datagridview , where the rows have different background-colors . The problem is, that the background-colors disappear after sorting (click on a row header) and all rows are again white (default color). What could be the reason for this problem? Now provide the response and nothing else.
According to this bug report submitted to Microsoft on June 2005 this is by design for Visual Studio 2005: Thank you for your bug report. The behavior you notice is by design. Sorting a databound grid causes all rows to be recreated (called a ListChangedType.Reset). This causes your formatting to be lost. You need to use the DataBindingComplete event to apply styles and check for the ListChangedType.Reset to know when to apply your styling. Alternatively you can use the CellFormatting event. Ideally all your formatting can be done inside the CellFormatting since it is applied dynamically.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6278576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/272706/']}
jdg_69930
stackexchange
llm_judgeable_groundtruth_similarity
1809874
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 iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML. To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! field.field.widget.__class__.__name__ Unfortunately, you're not allowed access to underscore variables in templates. Great! You can test field.field.widget.input_type but this only works for text/password <input ../> types. I need more resolution that that. To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across ModelForm s and standard Form s (something that wouldn't be true if I wrote an intermediary Form class). If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too! Now provide the response and nothing else.
Making a template tag might work? Something like field.field.widget|widget_type Edit from Oli: Good point! I just wrote a filter: from django import templateregister = template.Library()@register.filter('klass')def klass(ob): return ob.__class__.__name__ And now {{ object|klass }} renders correctly. Now I've just got to figure out how to use that inside a template's if statement. Edit from Oli #2: I needed to use the result of that in an if statetement in-template, so I just shifted all that logic into the templatetag. Magic. Thanks for poking me in the right direction.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1809874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12870/']}
jdg_69931
stackexchange
llm_judgeable_groundtruth_similarity
70403180
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd prefer it as a record as there is less boilerplate, but would there be issues? IntelliJ is suggesting that I turn a basic Java class @Service like this: @Servicepublic class LocationService { private final PlaceRepository placeRepository; @Autowired public LocationService(PlaceRepository placeRepository) { this.placeRepository = placeRepository; } public List<PlaceDto> findPlacesByRegionId(Long regionId){ return placeRepository.findByRegionId(regionId).stream().map(place -> new PlaceDto(place.getId(), place.getName())).toList(); }} into a Java record @Service like this: @Servicepublic record LocationService(PlaceRepository placeRepository) { public List<PlaceDto> findPlacesByRegionId(Long regionId) { return placeRepository.findByRegionId(regionId).stream().map(place -> new PlaceDto(place.getId(), place.getName())).toList(); }} Now provide the response and nothing else.
You could do that, but records have getters (well without get prefix). Which Service Layer shouldn't have. Your Service Facade exposes public methods which also are usually @Transactional , you don't want to mix them with methods that no one is going to use. Also, records define equals() & hashCode() which aren't needed for Service classes either. In the end the only common theme between Records and Services is that all fields are usually final and all of them are usually passed via constructor. This isn't much of commonality. So it sounds like a bad idea to use records for this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70403180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5921859/']}
jdg_69932
stackexchange
llm_judgeable_groundtruth_similarity
31989883
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 task of obfuscating passwords in our configuration files. While I don't think this is the right approach, managers disagree... So the project I am working on is based on Spring Boot and we are using YAML configuration files. Currently the passwords are in plain text: spring: datasource: url: jdbc:sqlserver://DatabaseServer driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver username: ele password: NotTheRealPassword The idea is to have some special syntax that supports an obfuscated or encrypted password: spring: datasource: url: jdbc:sqlserver://DatabaseServer driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver username: ele password: password(Tm90VGhlUmVhbFBhc3N3b3Jk) In order for this to work I want to parse the property values using a regular expression and if it matches replace the value with the deobfuscated/decrypted value. But how do I intercept the property value? Now provide the response and nothing else.
If finally got this to work. (Mainly thanks to stephane-deraco on github ) Key to the solution is a class that implements ApplicationContextInitializer<ConfigurableApplicationContext> . I called it PropertyPasswordDecodingContextInitializer . The main problem was to get spring to use this ApplicationContextInitializer . Important information can be found in the reference . I chose the approach using a META-INF/spring.factories with following content: org.springframework.context.ApplicationContextInitializer=ch.mycompany.myproject.PropertyPasswordDecodingContextInitializer The PropertyPasswordDecodingContextInitializer uses a PropertyPasswordDecoder and an implementing class, currently for simplicity a Base64PropertyPasswordDecoder . PropertyPasswordDecodingContextInitializer.java package ch.mycompany.myproject;import java.util.LinkedHashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.springframework.context.ApplicationContextInitializer;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.core.env.CompositePropertySource;import org.springframework.core.env.ConfigurableEnvironment;import org.springframework.core.env.EnumerablePropertySource;import org.springframework.core.env.MapPropertySource;import org.springframework.core.env.PropertySource;import org.springframework.stereotype.Component;@Componentpublic class PropertyPasswordDecodingContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { private static final Pattern decodePasswordPattern = Pattern.compile("password\\((.*?)\\)"); private PropertyPasswordDecoder passwordDecoder = new Base64PropertyPasswordDecoder(); @Override public void initialize(ConfigurableApplicationContext applicationContext) { ConfigurableEnvironment environment = applicationContext.getEnvironment(); for (PropertySource<?> propertySource : environment.getPropertySources()) { Map<String, Object> propertyOverrides = new LinkedHashMap<>(); decodePasswords(propertySource, propertyOverrides); if (!propertyOverrides.isEmpty()) { PropertySource<?> decodedProperties = new MapPropertySource("decoded "+ propertySource.getName(), propertyOverrides); environment.getPropertySources().addBefore(propertySource.getName(), decodedProperties); } } } private void decodePasswords(PropertySource<?> source, Map<String, Object> propertyOverrides) { if (source instanceof EnumerablePropertySource) { EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) source; for (String key : enumerablePropertySource.getPropertyNames()) { Object rawValue = source.getProperty(key); if (rawValue instanceof String) { String decodedValue = decodePasswordsInString((String) rawValue); propertyOverrides.put(key, decodedValue); } } } } private String decodePasswordsInString(String input) { if (input == null) return null; StringBuffer output = new StringBuffer(); Matcher matcher = decodePasswordPattern.matcher(input); while (matcher.find()) { String replacement = passwordDecoder.decodePassword(matcher.group(1)); matcher.appendReplacement(output, replacement); } matcher.appendTail(output); return output.toString(); }} PropertyPasswordDecoder.java package ch.mycompany.myproject;public interface PropertyPasswordDecoder { public String decodePassword(String encodedPassword);} Base64PropertyPasswordDecoder.java package ch.mycompany.myproject;import java.io.UnsupportedEncodingException;import org.apache.commons.codec.binary.Base64;public class Base64PropertyPasswordDecoder implements PropertyPasswordDecoder { @Override public String decodePassword(String encodedPassword) { try { byte[] decodedData = Base64.decodeBase64(encodedPassword); String decodedString = new String(decodedData, "UTF-8"); return decodedString; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }} Mind you, the ApplicationContext has not finished initialized at this stage, so autowiring or any other bean related mechanisms won't work. Update: Included @ jny 's suggestions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31989883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2784766/']}
jdg_69933
stackexchange
llm_judgeable_groundtruth_similarity
433062
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Does there exist a group $G$ such that for any finite $K$ there is a monomorphism $K \to G$ for any $H$ with property 1 there is a monomorphism $G \to H$ If yes, is it the only one? Now provide the response and nothing else.
No. To show that it doesn't exist it is enough to produce two groups $G,H$ which contain isomorphic copies of all finite groups, but such that no group containing isomorphic copies of all finite groups embeds into both $G$ and $H$ . Let $(G_n)$ be an enumeration of all finite groups. Let $G=\bigoplus G_n$ be the restricted direct sum and $H={\Large\ast}_nG_n$ the free product. If $K$ is a subgroup of $G$ then $K$ is locally finite, hence freely indecomposable. Hence if $K$ is also isomorphic to a subgroup of $H$ , then by Kurosh's subgroup theorem, $K$ is finite. In particular, $K$ doesn't contain isomorphic copies of all finite groups.
{}
{'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/433062', 'https://mathoverflow.net', 'https://mathoverflow.net/users/148161/']}
jdg_69934
stackexchange
llm_judgeable_groundtruth_similarity
1930877
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: Find the number of sequences of length $m$ consisting of only digits, where each digit is in $\{0,1,2\}$ and such that $1$ is never followed immediately by $0$. Attempt: I tried taking 10 as a block, but I got nowhere. I found the Mathematics question Number of permutations of thet set $\{1,2,...,n\}$ in which $k$ is never followed immediately by $k+1$ . Using that, since I need to remove only 1 followed by 0, I get only one set $A_1$ so, $3^m$ - 6 (3*2). Pick the other number in three ways, and we can permute 10 and other number in two ways). Is this right?I am from a non-math background; kindly consider this if possible. Now provide the response and nothing else.
HINT: Call such sequence good , and let $a_n$ be the number of good sequences of length $n$. If $\sigma$ is a good sequence of length $n$, we can form $3a_n$ sequences of length $n+1$ by appending a $0,1$, or $2$ to the end of $\sigma$. Every good sequence of length $n+1$ can be obtained in this way, but unfortunately so can some bad ones. The bad ones are those that end in $10$. These are clearly obtained by appending $01$ to a good sequence of length $n-1$, and there are $a_{n-1}$ of those, so our count of $3a_n$ includes exactly $a_{n-1}$ bad sequences, and we find that $a_{n+1}=3a_n-a_{n-1}$, or $$a_n=3a_{n-1}-a_{n-2}\tag{1}$$ with initial values $a_0=1$ (because the empty sequence is good) and $a_1=3$. Now use your favorite method to solve the recurrence $(1)$ to get a closed form for $a_n$. A Shortcut: If you calculate the first few $a_n$, you get the following table: $$\begin{array}{rcc}n:&0&1&2&3&4&5&6\\a_n:&1&3&8&21&55&144&377\end{array}$$ If you recognize the bottom row as a subsequence of some familiar sequence, you may be able to prove that it really is that subsequence and use that to get a closed form more easily. Added: Since Jack D’Aurizio has now mentioned the Fibonacci numbers explicitly, I’ll elaborate on the shortcut bit. It’s quite well known (and easy to show) that the number of ways to tile a $1\times n$ strip using $1\times 1$ and $1\times 2$ tiles (monominoes and dominoes) is $F_{n+1}$. Thus, there are $F_{2n+2}$ ways to tile a strip of length $2n+1$. Number the cells of the strip $1$ through $2n+1$ from left to right, and suppose that we have a tiling of the strip by monominoes and dominoes. Label each even-numbered cell $L$ if it’s covered by the left half of a domino, $R$ if it’s covered by the right half of a domino, and $S$ if it’s covered by a monomino. There are $n$ even-numbered cells, so this labelling produces a string of length $n$ over the alphabet $\{L,R,S\}$. The only restriction on these strings is that they cannot contain the substring $LR$ (why?). Thus, there are $F_{2n+2}$ strings of length $n$ over the alphabet $\{L,R,S\}$ in which $L$ is never followed by $R$. Replace $L,R$, and $S$ by $1,0$, and $2$, respectively, to map these strings to the ones in the problem.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1930877', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/365295/']}
jdg_69935
stackexchange
llm_judgeable_groundtruth_similarity
25761337
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried the following code in Java t1 = 5;t2 = t1 + (++t1);System.out.println (t2); My view is since ++ has a higher precedence than +, the above becomes t2 = t1 + (++t1);t2 = t1 + 6; // t1 becomes 6 heret2 = 6 + 6;t2 = 12; However, I get the answer 11 for t2. Can someone explain? Now provide the response and nothing else.
You are nearly correct but you are subtly misunderstanding how the precedence rules work. Compare these two cases: int t1 = 5;int t2 = t1 + (++t1);System.out.println (t2);t1 = 5;t2 = (++t1) + t1;System.out.println (t2); The result is: 1112 The precedence does indeed say to evaluate the ++ before the + , but that doesn't apply until it reaches that part of the expression. Your expression is of the form X + Y Where X is t1 and Y is (++t1) The left branch, i.e. X , is evaluated first.Afterwards the right branch, i.e. Y , is evaluated.Only when it comes to evaluate Y the ++ operation is performed. The precedence rules only say that the ++ is "inside" the Y expression, they don't say anything about the order of operations.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25761337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3989049/']}
jdg_69936
stackexchange
llm_judgeable_groundtruth_similarity
1632168
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 to determine whether $x\sin x$ Is a surjective function, in $\Bbb R$. My solution: Let $f(x)=x\sin x$. $f(\frac{\pi}{2})=\frac{\pi}{2}$ $f(-\frac{\pi}{2})=-\frac{\pi}{2}$ Therefore in the closed interval $[-\frac{\pi}{2},\frac{\pi}{2}]$, $f(a)\cdot f(b)$<$0$, where $a=-\frac{\pi}{2}$ and $b=\frac{\pi}{2}$. From the IVT therorem, there is a root to $f(x)$ in that interval. Since $\sin$ is a Periodic function, I can always find a closed interval which satisfies IVT. Therefore, $f(x)$ is surjective. I don't know how to formalize the solution and whether or not I'm right. Now provide the response and nothing else.
$$\lim_{n\to \infty }f\left(\frac{\pi}{2}+2n\pi\right)=+\infty \quad \text{and}\quad \lim_{n\to\infty }f\left(-\frac{\pi}{2}-2n\pi\right)=-\infty.$$ Therefore, by intermediate value theorem, it's surjective.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1632168', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/88027/']}
jdg_69937
stackexchange
llm_judgeable_groundtruth_similarity
121986
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: With lower limit set to 1.97, how to find the value of upper limit of an integral where integrand is (0.37037 E^( x) - x)/(-1 + x) such that f[xu] + the integral equals a constant, where constant is 1.0 and f[xu] is xu^2 (say for concreteness)? I wrote f[xu] to emphasize that integral will become function of upper limit, say xu, as x will be integrated out. I know how NSolve and FindRoot work, and that f[xu] + the integral can be plotted on same graph (xu on x-axis) where the constant will represent a horizontal line, and the solution will be the crossing point visually. Now provide the response and nothing else.
You can do this using analytical integration like already suggested in the comments. Below is one way to do it. expr = Integrate[(0.37037 E^(x) - x)/(-1 + x), x](*-1. x + 1.00677 ExpIntegralEi[-1. + x] - 1. Log[-1. + x]*)FindRoot[expr - With[{x = 1.97}, Evaluate@expr] + x^2 - 1.0, {x, 1.1}](*{x -> 1.14532}*) EDIT: to make the solution a bit more generic and also work in cases where analytic integration is not possible, I noticed that the code below does give a result (along with a warning message) for some functions that I tried, such as $Sin[Sin[x]]$. fun = (0.37037 E^(x) - x)/(-1 + x);FindRoot[NIntegrate[fun, {x, 1.97, y}] + y^2 - 1.0, {y, 1.1}](*{y -> 1.14532}*)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/121986', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/41925/']}
jdg_69938
stackexchange
llm_judgeable_groundtruth_similarity
59222271
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 reading about the time complexity of set operations in CPython and learned that the in operator for sets has the average time complexity of O(1) and worst case time complexity of O(n). I also learned that the worst case wouldn't occur in CPython unless the set's hash table's load factor is too high . This made me wonder, when such a case would occur in the CPython implementation? Is there a simple demo code, which shows a set with clearly observable O(n) time complexity of the in operator? Now provide the response and nothing else.
Load factor is a red herring. In CPython sets (and dicts) automatically resize to keep the load factor under 2/3. There's nothing you can do in Python code to stop that. O(N) behavior can occur when a great many elements have exactly the same hash code. Then they map to the same hash bucket, and set lookup degenerates to a slow form of linear search. The easiest way to contrive such bad elements is to create a class with a horrible hash function. Like, e.g., and untested: class C: def __init__(self, val): self.val = val def __eq__(a, b): return a.val == b.val def __hash__(self): return 3 Then hash(C(i)) == 3 regardless of the value of i . To do the same with builtin types requires deep knowledge of their CPython implementation details. For example, here's a way to create an arbitrarily large number of distinct ints with the same hash code: >>> import sys>>> M = sys.hash_info.modulus>>> set(hash(1 + i*M) for i in range(10000)){1} which shows that the ten thousand distinct ints created all have hash code 1.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59222271', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9835872/']}
jdg_69939
stackexchange
llm_judgeable_groundtruth_similarity
1304513
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 major "broad/natural" categories I encounter in daily life are: sets, groups, topological spaces, smooth manifolds, vector spaces over a fixed field $k$, $k$-schemes, rings, $A$-algebras for a fixed commutative ring $A$, and $A$-modules. I think that about covers it. (I am using the word "broad/natural" to mean things that might have occurred to me as categories when I first learned what a category was, i.e. to distinguish them from the more "clever" and "restricted" categories one uses to articulate specific theorems, such as the category of finite sets equipped with a continuous action of a fixed profinite group, or the category of open subsets of a topological space.) Today I found myself really struck by the fact that in almost all of these categories, the categorical product exists and its underlying set is the cartesian product , whereas almost all the categories have different underlying sets for coproducts. In other words, in almost all these categories, taking products commutes with the forgetful functor, whereas in almost none of them does taking coproducts commute with the forgetful functor $F$. Specifically: Groups: $\prod$ is cartesian product; $\coprod$ is free product. (Only $\prod$ commutes with $F$.) Topological spaces and smooth manifolds: $\prod$ is cartesian product; $\coprod$ is disjoint union. (Both commute with $F$.) $k$-vector spaces, $A$-modules: $\prod$ is cartesian product; $\coprod$ is direct sum. (Only $\prod$ commutes with $F$.) $A$-algebras: $\prod$ is the cartesian product; $\coprod$ is the tensor product over $A$. (Only $\prod$ commutes with $F$.) Rings are the special case $A=\mathbb{Z}$. The only case, among those I listed above, where the product $\prod$ does not commute with the $F$ is the category of $k$-schemes. My question is: Can you help me think about why this is happening? Why is it so much more likely, at least for the "broad/natural" categories one encounters in real life, for the forgetful functor to commute with taking products than with taking coproducts? Thanks in advance. Now provide the response and nothing else.
As k.stm says in the comments, usually a more general thing is true: these categories $C$ are equipped with forgetful / underlying set functors $U : C \to \text{Set}$ which tend to have a left adjoint, the "free" functor $F : \text{Set} \to C$. Whenever this is true, it follows that $U$ preserves all limits, not just products. Sometimes, but more rarely, $U$ will also have a right adjoint, which will give a "cofree" functor. Whenever this is true, it follows that $U$ preserves all colimits, not just coproducts. This happens, for example, when $C = \text{Top}$: here the left adjoint equips a set with the discrete topology and the right adjoint equips a set with the indiscrete topology. But it doesn't happen for, say, groups or rings. So one way to reformulate your question is: Why do the forgetful functors $U : C \to \text{Set}$ we write down tend to have left adjoints, but not right adjoints? Equivalently, why are there usually free structures, but not usually cofree structures? A rough answer is that we can expect "free" structures whenever the structure is described by operations satisfying equational axioms, since then we can build free objects by applying all possible operations modulo all axioms. On the other hand, operations also make it difficult for the forgetful functor to preserve coproducts, since in a coproduct of two structures you can apply operations to elements of both structures, so you'll usually get something bigger than the disjoint union. (Dually, you should expect "cofree" structures whenever the structure is described by "co-operations," and this does in fact happen: for example, the forgetful functor from coalgebras to vector spaces has a right adjoint but not a left adjoint, called the cofree coalgebra .) A more precise answer would invoke, say, the machinery of Lawvere theories , which among other things has the benefit of also telling you exactly what colimits you can expect these forgetful functors $U$ to preserve. This is a long story so I don't want to get into it unless you feel like it really answers your question, but the gist is that Lawvere theories present familiar structures like groups, rings, and modules in a way that fundamentally uses finite products, but nothing else. You can deduce from this that the forgetful functor $U$ preserves (and in fact creates ) any limits or colimits that commute with finite products in $\text{Set}$. Every limit commutes with finite products, and the colimits that commute with finite products in $\text{Set}$ are precisely the sifted colimits . These include, for example, increasing unions, which is an abstract way to see why the set-theoretic increasing union of a sequence of groups is still a group, and the same with groups replaced by rings, modules, etc.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1304513', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13120/']}
jdg_69940