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
|
28043
|
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:
so I have the x,y,z value for 3 points to define a plane in 3d space. I need to find the z value of an arbitrary point given the x,y. I can sort of see some ways to calculate this, but they seem like they might be doing a lot of extra steps. I eventually need to encapsulate the process in a algorithm for a computer program, so the fewer steps the better.
Now provide the response and nothing else.
|
The simplest way is to first find the equation of the plane. So, suppose you are given three points,$$ (a_1,b_1,c_1),\quad (a_2,b_2,c_2),\quad (a_3,b_3,c_3).$$ I'm first going to assume everything will work out fine; I'll point out the possible problems later. First, construct two vectors determined by these three points:$$\begin{align*}\mathbf{v}_1 &= (a_1,b_1,c_1) - (a_2,b_2,c_2) = (a_1-a_2, b_1-b_2, c_1-c_2).\\\mathbf{v}_2 &= (a_1,b_1,c_1) - (a_3,b_3,c_3) = (a_1-a_3, b_1-b_3, c_1-c_3).\end{align*}$$ Then, compute their cross product:$$\mathbf{n} = \mathbf{v}_1\times\mathbf{v}_2 = (r,s,t).$$ The plane you want has equation $rx + sy + tz = k$ for some $k$. To find $k$, plug in one of the points you have, say $(a_1,b_1,c_1)$, so you know that$$k = ra_1 + sb_1 + tc_1.$$ Finally, given the $x$ and $y$ coordinate of a point, you can find the value of $z$ by solving:$$z = \frac{1}{t}\left( ra_1 + sb_1 + tc_1 - rx - sy\right).$$ What can go wrong? For three points to determine a unique plane, you need the three points to not be collinear (not lie on the same line). You will find this when you compute the vector $\mathbf{n}$. If $\mathbf{n}=(0,0,0)$, then $\mathbf{v}_1$ and $\mathbf{v}_2$ are parallel, so that means that the three points are collinear and don't determine a unique plane. So you can just test $\mathbf{n}$ to see if it is nonzero before proceedings. It's possible for there to not be a unique value of $z$ that goes with the given $x$ and $y$. This will happen if $\mathbf{n}$ has the form $\mathbf{n}=(r,s,0)$. Then either the given $x$ and $y$ satisfy the equation you get, in which case every value of $z$ works; or else the given $x$ and $y$ do not satisfy the equation you get and no value of $z$ works. Example. Suppose you are given $(1,2,3)$, $(1,0,1)$, and $(-2,1,0)$. Then$$\begin{align*}\mathbf{v}_1 &= (1,2,3) - (1,0,1) = (0,2,2).\\\mathbf{v}_2 &= (1,2,3) - (-2,1,0) = (3,1,3).\end{align*}$$Then$$\begin{align*}\mathbf{n} &= \mathbf{v}_1\times\mathbf{v}_2 = \left|\begin{array}{rrr}\mathbf{i} & \mathbf{j} & \mathbf{k}\\0 & 2 & 2\\3 & 1 & 3\end{array}\right|\\&= ( 6-2, 6- 0, 0-6) \\&= (4,6,-6).\end{align*}$$So the plane has equation $4x + 6y - 6z = k$. To find $k$, we plug in $(1,2,3)$:$$ 4(1) + 6(2) - 6(3) = -2,$$so the plane has equation$$4x + 6y - 6z = -2$$or$$2x + 3y - 3z = -1.$$ Then, given two values of $x$ and $y$, say, $x=7$ and $y=-2$, you plug them in and solve for $z$:$$z = \frac{1}{-3}(-1 -2(7) -3(-2)) = \frac{1 + 14 - 6}{3} = 3,$$so the point is $(7,-2,3)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/28043', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8483/']}
|
jdg_372641
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
375036
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Related: How can I enable domain authentication over wireless in Windows 7/2k8? To test the domain login over wireless connection feature I'm trying to set up in the above question, I need an account that hasn't had its domain credentials cached on the local system. Unfortunately, there's only so many people in my office who might help me test this, and even then I'd rather not bother them for it. So, I'd like to be able to clear my own cached credentials after each login. How can I clear the local cache, while still retaining the ability to cache credentials in the future?
Now provide the response and nothing else.
|
David Yu's answer is pretty much on-target, but there is a way to do this without editing the registry directly. Again though, this will only work if the setting is not configured by GPO. First, I'd like to point out where the cached credential data is stored. This will help demonstrate (and, for troubleshooting purposes, verify) the effect of the configuration changes. WARNING: I found this information in several places on the Internet, most of which recommended against modifying these values manually. The registry key that stores cached domain logins is hidden even from Administrators. It is only accessible by the SYSTEM account. Therefore, to view it you will need a tool like psexec (available from Microsoft, but not installed by default) which will allow you to run regedit as SYSTEM. The command line to do this (assuming it is installed, and in your %PATH% ) is: psexec -d -i -s regedit Once you're in there, navigate to HKLM\SECURITY\Cache\ . Here, you should see several BINARY values. There will be one named NL$Control, and others named NL$## for each slot that you have available for cached credentials. (Default 10) Again, I want to emphasize here that you should not manually modify or delete this key or its values. So, now that we know where the data is cached, and that we should not touch it there , how do we clear it? Again, David Yu's answer will point you to the right registry key. But, if you'd rather not modify the registry directly, there is another way to do this via the Local Security Policy. secpol.msc In the Security Settings tree, navigate to Local Policies\Security Options . Here will be a policy called Interactive logon: Number of previous logons to cache (in case domain controller is not available) . By default this is set to 10 logons . To clear the cache, set it to zero and click OK. On Server 2008, this will take effect immediately. For Server 2003, you will need to reboot. The affect can be seen in HKLM\SECURITY\Cache\ where there will no longer be any NL$## values. To re-enable credential caching, edit the same Policy to reflect your preferred value and hit OK. Again, if you're on Server 2008, this will take effect immediately. Server 2003 will require a reboot. Note that, if you are doing this on Server 2008 and you have not logged off or rebooted yet, you can see that the cache slots have been restored but no actual data is in them. Doing this without logoff or reboot in Server 2008 can be useful if you want to just do a quick, one-time check of whatever function requires temporarily-disabled credential caching. It also helps ensure you don't forget to revert the change after your next login.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/375036', 'https://serverfault.com', 'https://serverfault.com/users/54923/']}
|
jdg_372642
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56505453
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new in react-native and I was trying to create one component and try to pass props on that by using FlatList . But, FlatList show either on Vertical or Horizontal View, i need View in next line when View reaches edges. But i can't found any solution. data={data} //Optional // horizontal={true} // numColumns={4} renderItem={({ item }) => ( <TrendingTopicsDesign image={item.imageuri} title={item.title} /> )} keyExtractor={(item, index) => index.toString()} I expect My view came out with break when it reaches edge
Now provide the response and nothing else.
|
MultiProvider or not doesn't change anything. If two providers share the same type, the deepest one overrides the value. It's not possible to obtain the value from a provider that is not the closest ancestor for a given type. If you need to access all of these values independently, each should have a unique type. For example, instead of: Provider<int>( value: 42, child: Provider<int>( value: 84, child: <something> ),) You can do: class Root { Root(this.value); final int value;}class Leaf { Leaf(this.value); final int value;}Provider<Root>( value: Root(42), child: Provider<Leaf>( value: Leaf(84), child: <something> ),) This allows to obtain each value independently using: Provider.of<Root>(context)Provider.of<Leaf>(context);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56505453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9581492/']}
|
jdg_372643
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2108975
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I m new to Jboss, but I have multiple web applications each using spring-hibernate and other open source libraries and portlets, so basically now each war file includes those jar files. How do I move these jars to a common location so that I don't have to put these in each war file? I guess location is server/default/lib , but I'm not sure. Also, how is it different to have those jars at WEB-INF/lib vs. JBOSS/server/default/lib ? Will I face any classloader issue? Also I have static data stored in static fields like Singleton , will those be shared across all WAR files?
Now provide the response and nothing else.
|
Classloading: You're right, put the .jar s to JBOSS/server/<configuration>/lib , or JBOSS/lib . JBoss AS comes with bundled Hibernate libs which are tested with that AS version. See jboss-6.0.0-SNAPSHOT\server\default\conf\jboss-service.xml : <server> <!-- Load all jars from the JBOSS_HOME/server/<config>/lib directory and the shared JBOSS_HOME/common/lib directory. This can be restricted to specific jars by specifying them in the archives attribute. TODO: Move this configuration elsewhere --> <classpath codebase="${jboss.server.lib.url}" archives="*"/> <classpath codebase="${jboss.common.lib.url}" archives="*"/></server> Also see: http://community.jboss.org/wiki/classloadingconfiguration http://community.jboss.org/wiki/JbossClassLoadingUseCases Difference between WEB-INF/lib and JBOSS/server/default/lib : Libs in WEB/lib come with your WAR and are only visible within that WAR.If you have other module, e.g. EJB JAR, they will not be visible from it and you'll get ClassNotFoundException or (if you have the class in multiple places) ClassCastException . Libs in JBOSS-AS/server/<config>/lib are visible for whole server, thus all deployed apps and their modules. However (IIRC) they don't have precedence, so if you bring that lib e.g. in a WAR, but not in EJB jar, you can end up using two different versions, which is undesirable (will likely lead to aforementioned ClassCastException ). Class loading behavior may be tweaked several ways, see e.g. JBoss wiki . Static data: Don't rely on static fields in Java EE, that brings troubles. For instance,. the same class can be loaded by different classloaders, so there will be multiple instances of these static values. If you want to share data amongst more WARs, use an external storage - a database, a file (with synchronization if you write to it), JBoss Cache, etc.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2108975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255740/']}
|
jdg_372644
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41366955
|
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 quite new to NoSQL and DynamoDB and I used to RDBMS. I’m designing database for a game and we're using DynamoDB and AWS Lambda for our backend. I created a table name “Users” for player profile that contains the user information and resources. Because the game has inventory system I also created a table name “UserItems”. It’s all good until I realized DynamoDB don’t have transaction and any operation that is executed on both table (for example using an item that increase resource) has a chance of failure on one table while success on other and will cause missing data which affect our customers. So I was thinking maybe my multiple tables design is not good since it’s a habit of me to design multiple table when I’m working with RDBMS. Which let me to think of storing the entire “UserItems” as hash in “Users” but I’m not sure this is a good practice because the size of a single row in Users table will be really big (we may have 500 unique items per users) and each time I pull or put data from/to “Users” (most of the time don’t need “UserItems” data) the read/write throughput will be also really large. What should I do, keep the multiple tables design and handle transaction manually or switch to single table design? Or maybe there is a 3rd option? Updated: more information about my use case Currently I have 2 tables Users: UserId (key), Username, Gold UserItems: UserId (partition key), ItemId (sort key), Name, GoldValue Scenarios: User buy an item: Users.Gold will be deduced, new UserItem will be add to UserItems table. User sell an item: Users.Gold will be increased, the Item will be deleted from UserItems table. In both scenarios above I will have to do 2 update operation for 2 tables which without transaction there is a chance one of them failed. To solve that I consider using single table solution which is a single Users table with 4 columns UserId(key), Username, Gold, UserItems. However there are two things I'm worried about: Data in UserItems might be come to big for a single cell because one user could have up to 500 items. To add/delete item I have to pull the UserItems from dynamodb, add/delete item and then put it back into Users. So I have to do 1 read and 1 write operation for 1 action. And because of issue (1) the read/write data size could become really big.
Now provide the response and nothing else.
|
NoSql database is best suited for non-trasactional data. If you bring normalization(splitting your data into multiple tables) into noSQL, then you are beating the whole purpose of it. If performance is what matters most, then you should consider only having a single table for your use case. DynamoDB supports Range Keys, and also supports Secondary Indices. For your usecase, it would be better to redesign your table to use Range Keys.If you can share more details about your current table, maybe i can help you with more inputs.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41366955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7132823/']}
|
jdg_372645
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2469058
|
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:
An infinite sequence of pairwise distinct numbers $a_1, a_2, a_3, ...$ is defined thus: $a_n$ is the smallest positive integer number such that $\sqrt{a_n+\sqrt{a_{n-1}+...+\sqrt{a_1}}}$ is positive integer. Prove that the sequence $ a_1, a_2, a_3, ... $ contains all positive integers numbers. My work: Let $a_1=1$ . Then $\sqrt{a_2+1}$ is positive integer and $a_2$ is the smallest positive integer then $a_2=3$ . Then $\sqrt{a_3+2}$ is positive integer and $a_3$ is the smallest positive integer then $a_3=2$ . Then $\sqrt{a_4+\sqrt{a_3+\sqrt{a_{2}+\sqrt{a_1}}}}=\sqrt{a_4+2}$ is positive integer and $a_4$ is the smallest positive integer and $a_4\not=a_1,a_2,a_3$ then $a_4=7$ .
Now provide the response and nothing else.
|
Consider the sequence of square roots $s_n$, where $s_n=\sqrt{a_n+s_{n-1}}$. This sequence starts out $1,2,2,3,3,4,3,5,3,\ldots$. If we can show that every positive integer occurs at least once in this sequence, then we can conclude that every positive integer occurs (exactly once) in the sequence of $a_n$'s: each integer $k$ must occur among the $a_n$'s no later than the first time $s_{n-1}=k^2-k$. Observe first that the sequence of $s_n$'s cannot recycle a finite set of values infinitely often, since $a_n=s_n^2-s_{n-1}$ must not repeat. So there must be an infinite number of "new" values in the sequence. To show that every positive integer occurs in the sequence of $s_n$'s, it suffices to show that each "new" value in the sequence is precisely one more than the previous "new" value -- e.g., $7$ won't occur as an $s_n$ until after $6$ has occurred. To prove this, note that if $s_1,s_2,\ldots,s_{n-1}\le k$, then $a_1,a_2,\ldots,a_{n-1}\lt k^2$ (since $a_j=s_j^2-s_{j-1}$). Since $(k+1)^2-s_{n-1}\ge k^2+k-1\gt a_j$ for all $j\lt n$ and $a_n$ is the smallest positive integer (not already in the sequence) for which $a_n+s_{n-1}$ is a square, we must have $s_n\le k+1$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2469058', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/309360/']}
|
jdg_372646
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9217799
|
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 currently trying to create a very very simple sandbox . Some class A has a method Execute which is invoked in another AppDomain than the caller. Problem is I've execution permission only and reflection is possible anyway. This is the code sample: [Serializable]public class A : MarshalByRefObject{ public void Execute() { typeof(A).GetConstructor(Type.EmptyTypes).Invoke(null); // Fine - Why? typeof(B).GetConstructor(Type.EmptyTypes).Invoke(null); // Fine - Why? }}public class B{}class Program{ static void Main(string[] args) { PermissionSet set = new PermissionSet(PermissionState.None); SecurityPermission security = new SecurityPermission(SecurityPermissionFlag.Execution); set.AddPermission(security); Evidence evidence = new Evidence(); AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = "C:"; AppDomain domain = AppDomain.CreateDomain ( "hello", evidence, setup, set ); A a = (A)domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(A).FullName); a.Execute(); }} UPDATE Great! Finally I did it. Thanks to your advices I've revised my code and I'd like to share it with you, since I had a hard time understanding how to don't use CAS but use same kind of permissions in the new .NET 4.x and above security model, and the way of sandboxing using an AppDomain . That's it: using System;using System.Reflection;using System.Security;using System.Security.Permissions;using System.Security.Policy;namespace ConsoleApplication1{ [Serializable] public class A : MarshalByRefObject { public void Execute() { B b = new B(); // BOMB! ERROR! Security demand: reflection forbidden! b.GetType() .GetMethod("ExecuteInB", BindingFlags.Instance | BindingFlags.NonPublic) .Invoke(b, null); } } public class B { private void ExecuteInB() { } } class Program { static void Main(string[] args) { PermissionSet set = new PermissionSet(PermissionState.None); SecurityPermission security = new SecurityPermission(PermissionState.None); security.Flags = SecurityPermissionFlag.Execution; set.AddPermission(security); Evidence evidence = new Evidence(); AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = "C:"; AppDomain domain = AppDomain.CreateDomain ( "hola", evidence, setup, set ); A a = (A)domain.CreateInstanceAndUnwrap("ConsoleApplication1", "ConsoleApplication1.A"); a.Execute(); } }}
Now provide the response and nothing else.
|
Reflection permission is demanded when invoking an inaccessible member. A and B are public types with public constructors, and so are accessible. You could invoke those constructors without reflection, so there is no demand when you attempt to do so with reflection. Moreover, using reflection for discovery is always legal; you can interrogate an object and ask it for a list of its private members, even without reflection permission being granted. It is only when you attempt to cause an invocation of the private member that the permission is demanded.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9217799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/411632/']}
|
jdg_372647
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18938788
|
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 lines: [Run]Filename: "{app}\MyApp.exe"; Flags: postinstall nowait I would like my app to get started without showing a checkbox (which would disallow the user to do so). Can somebody show me how, please?Thank you.
Now provide the response and nothing else.
|
There are few options I can think of. The first one is to run your application from the [Code] section of your script, the second one is to disable that check box for your [Run] section entry and the third one is to hide the RunList . 1. How to manually run an application when the wizard is finished ? I would personally prefer this way, because it's more straightforward than adding a check box and hiding it later on. You will remove your current [Run] section entry and call one of the following functions from the NextButtonClick event method when its CurPageID parameter equals to wpFinished , which indicates the Finish button click: Exec - executes the specified executable or batch file, using the same credentials as Setup/Uninstall. ExecAsOriginalUser - executes the specified executable or batch file, using the (normally non-elevated) credentials of the user that started Setup initially ShellExec - opens the specified file or performs another action specified by Verb, using the same credentials as Setup/Uninstall. ShellExecAsOriginalUser - opens the specified file or performs another action specified by Verb, using the (normally non-elevated) credentials of the user that started Setup initially. Because you haven't used the runascurrentuser nor shellexec flags, the setup internally calls a function similar to this: function NextButtonClick(CurPageID: Integer): Boolean;var ResultCode: Integer;begin Result := True; if CurPageID = wpFinished then ExecAsOriginalUser(ExpandConstant('{app}\MyApp.exe'), '', '', SW_SHOWNORMAL, ewNoWait, ResultCode);end; One weakness of this solution is that the program would be executed even if the restart is requested by the setup. To workaround a missing possibility to determine this request we can check if the YesRadio is visible (it is the Yes, restart the computer now radio button) and selected, which means that the user was asked to restart the computer and confirmed it. Here is the version considering the restart request: function NextButtonClick(CurPageID: Integer): Boolean;var ResultCode: Integer;begin Result := True; // if the "Finish" button was clicked and "Yes, restart the computer now" // radio button was either not visible or not selected that time, then... if (CurPageID = wpFinished) and ((not WizardForm.YesRadio.Visible) or (not WizardForm.YesRadio.Checked)) then ExecAsOriginalUser(ExpandConstant('{app}\MyApp.exe'), '', '', SW_SHOWNORMAL, ewNoWait, ResultCode);end; 2. How to disable the post install check box on the final page ? Another option is to disable the check box. The user will see that the application is going to be executed, but won't be able to do anything against it (except killing the setup from Task Manager, of course). This time you will keep your [Run] section entry as it, but modify the RunList from the [Code] section: [Setup]AppName=My ProgramAppVersion=1.5DefaultDirName=My Program[Files]Source: "MyApp.exe"; DestDir: "{app}"[Run]Filename: "{app}\MyApp.exe"; Flags: postinstall nowait[Code]procedure CurPageChanged(CurPageID: Integer);begin // you must do this as late as possible, because the RunList is being modified // after installation; so this will check if there's at least one item in the // RunList and then set to the first item (indexing starts at 0) Enabled state // to False if (CurPageID = wpFinished) and (WizardForm.RunList.Items.Count > 0) then WizardForm.RunList.ItemEnabled[0] := False;end; 3. How to completely hide the RunList ? This will, contrary to the second option, do what you asked for. It will keep the check box hidden, or to be more precise, it will hide the whole RunList , so if you were having more than one entry in the [Run] section with the postinstall flag specified, it won't be seen as well: [Setup]AppName=My ProgramAppVersion=1.5DefaultDirName=My Program[Files]Source: "MyApp.exe"; DestDir: "{app}"[Run]Filename: "{app}\MyApp.exe"; Flags: postinstall nowait[Code]procedure CurPageChanged(CurPageID: Integer);begin if CurPageID = wpFinished then WizardForm.RunList.Visible := False;end;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18938788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1390192/']}
|
jdg_372648
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4066601
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to develop a URL shortener application for practice with Django. I do not understand how can I create unique strings for each long URL to use as a short URL. Something like other popular URL shorteners do. How can I do this? Is it possible to make all short urls of the same length?
Now provide the response and nothing else.
|
I do not understand how can I create unique strings for each long URL to use as a short URL. Something like other popular URL shorteners do. As sugerman has said, this is simple, you just create a hash table. How can I do this? There are dynamic ways to do this, but the simplest and most effective is to have a 2 field table in a database, which holds the hashkey and full url. Then your server, like Apache, would have the ability to redirect to the correct page. Is it possible to make all short urls of the same length? Yes, to a certain extent, however once you reach the maximum amount of keys, you would have to reuse/replace the short url IDs. When you set a fixed-length, then you're limiting the amount of possibilities. My question to you: I'm under the assumption that by URL shortener you are referring to something like jsFiddle or a pastebin in that they have something like http://jsfiddle.net/sdfj2/ . Otherwise, we'd need some more clarification.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4066601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/345145/']}
|
jdg_372649
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3370078
|
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 .Net service that connects to an Oracle database on every request. It works fine at the beginning, but after some number of requests I start getting: Oracle.DataAccess.Client.OracleException ORA-03135: connection lost contact at Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, String procedure) at Oracle.DataAccess.Client.OracleException.HandleError(Int32 errCode, OracleConnection conn, String procedure, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src) at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery, Boolean fillRequest, CommandBehavior behavior) at Oracle.DataAccess.Client.OracleCommand.ExecuteReader() at MyApp.Services.OracleConnectionWithRetry.ExecuteReader(OracleCommand command) ... Any idea what might be the problem? I dispose all the connections, results and parameters. The load on this service is, well, very low.
Now provide the response and nothing else.
|
It happens because your code requests a connection from the Oracle Connection Pool and the connection pool returns a disconnected / stale connection to the Oracle DB. ODP.NET does not itself test the connection status of the connection sent to client. So to be safe, either you check the connection status == Open for the connection received from the pool when you do a Connection.Open() OR let ODP.NET do the checking for you by setting Validate Connection = true in your connection string in web.config. Both this methods have a impact on performance as they test the connection status each time you need to connect to the database. A third option which I use is use of exceptions. First be optimistic and use whateven connection is returned from the connection pool. If you get a ORA - 3135 then request a new connection and execute your query again like a while loop. In best case, you can get your 1st connection as valid and your query will execute. In worst case, all the connections in your pool are stale in which case the code will be executed N time (where N is the connection pool size).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3370078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5363/']}
|
jdg_372650
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2432909
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Googling is only coming up with the keyword, but I stumbled across some code that says MyVariable = default(MyObject); and I am wondering what it means.
Now provide the response and nothing else.
|
For a reference-type, it returns null For a value-type other than Nullable<T> it returns a zero-initialized value For Nullable<T> it returns the empty (pseudo-null) value (actually, this is a re-statement of the second bullet, but it is worth making it explicit) The biggest use of default(T) is in generics, and things like the Try... pattern: bool TryGetValue(out T value) { if(NoDataIsAvailable) { value = default(T); // because I have to set it to *something* return false; } value = GetData(); return true;} As it happens, I also use it in some code-generation, where it is a pain to initialize fields / variables - but if you know the type: bool someField = default(bool);int someOtherField = default(int)global::My.Namespace.SomeType another = default(global::My.Namespace.SomeType);
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2432909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174375/']}
|
jdg_372651
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11397983
|
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 VB.NET, a lambda expression can be declared and invoked on the same line: 'Output 3Console.WriteLine((Function(num As Integer) num + 1)(2)) Is this possible in C#?
Now provide the response and nothing else.
|
You have to tell the compiler a specific delegate type. For example, you could cast the lambda expression: Console.WriteLine(((Func<int, int>)(x => x + 1))(2)); EDIT: Or yes, you can use a delegate creation expression as per Servy's answer: Console.WriteLine(new Func<int, int>(i => i + 1)(2)); Note that this isn't really a normal constructor call - it's special syntax for delegate creation which looks like a regular constructor call. Still clever though :) You can make it slightly cleaner with a helper class: public static class Functions{ public static Func<T> Of<T>(Func<T> input) { return input; } public static Func<T1, TResult> Of<T1, TResult> (Func<T1, TResult> input) { return input; } public static Func<T1, T2, TResult> Of<T1, T2, TResult> (Func<T1, T2, TResult> input) { return input; }} ... then: Console.WriteLine(Functions.Of<int, int>(x => x + 1)(2)); Or: Console.WriteLine(Functions.Of((int x) => x + 1)(2));
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11397983', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244104/']}
|
jdg_372652
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2666315
|
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 man has 3 friends. The number of ways in which he can invite one friend everyday for dinner on six successive nights so that no friend is invited more than three times is? I am trying to use Principle of Inclusion and Exclusion to solve this problem. Attempt: $N(\bar{c_1}\bar{c_2}\bar{c_3})= N - (N(c_1)+N(c_2)+N(c_3)) + (N(c_1c_2)+N(c_1c_3)+N(c_2c_3)) - (N(c_1c_2c_3))$ $c_i$= condition that i$^{th}$ friend is invited more than thrice. $c_ic_j$ = $i^{th}$ AND $j^{th}$ friend are invited more than thrice... $\implies \left(\dbinom{3}{1}\right)^6- 3\times(\dbinom{6}{4}\dbinom{2}{2}\times 2! + \dbinom{6}{5}\dbinom{1}{1}\times 2!+1)+0-0= 630$ Because:$N(c_1)= N(c_2)= N(c_3)$ and, explanation of the rest of the part (the part in brackets that is multiplied by $3$): There are only three possibilities, one of the friends is invited either for $5$ days or for $6$ days or for $4$ days. So I chose any $4$ days out of $6$ days, gave them to the friend who is being invited extra times and then $2$ days out of remaining two days and arranged them between two friends. then, I chose $5$ days out of $6$ days, gave them to the friend who is getting extra dinners and arranged the remaining one day among the remaining two friends. Lastly, when a friend is invited for all 6 days, the remaining friends have $0$ choices. But answer given is $510$. Where have I gone wrong?
Now provide the response and nothing else.
|
Say $\lambda$ is an eigenvalue of $ST$; there exists $x\ne0$ such that $$STx=\lambda x.$$ If you let $y=Tx$ then it follows that $$TSy=\lambda y.$$ No, that's not a proof. Because $TSy=\lambda y$ does not show that $\lambda$ is an eigenvalue of $TS$. Exercise, that you should do before reading on: Why not? Why not is because we need to know that $y=Tx\ne0$ to conclude that $\lambda$ is an eigenvalue. The actual proof splits into two cases. First assume $\lambda\ne0$. Then the argument above is ok: $STx=\lambda x\ne0$, hence $y=Tx\ne0$. Now assume $0$ is an eigenvalue of $ST$. This says precisely that $ST$ is not invertible. Hence $S$ and $T$ cannot both be invertible, hence (at least in the finite-dimensional case) $TS$ is not invertible, so $0$ is an eigenvalue of $TS$. (If $TS$ is invertible then $T$ must be surjective and $S$ must be injective; hence in the finite-dimensional case they are both invertible.) Note We need to assume $V$ has finite dimension or the result is false. Let $V$ be the space of all one-sided sequences $v=(v_1,\dots)$; let $Sv=(v_2,v_3,\dots)$ and $Tv=(0,v_1,v_2,\dots)$. Then $ST$ is the identity but $TS$ has $0$ for an eigenvalue.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2666315', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/476145/']}
|
jdg_372653
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8215008
|
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 bits of code: <h:panelGroup rendered="#{userTypeController.permissionItemsUserType.contains(item)}"> <h:selectBooleanCheckbox valueChangeListener="#{userTypeController.permissionChanged(this)}" value="#{true}"/> <h:outputText value="#{item.getAction()}" /> </h:panelGroup> <h:panelGroup rendered="#{!userTypeController.permissionItemsUserType.contains(item)}"> <h:selectBooleanCheckbox value="#{false}"/> <h:outputText value="#{item.getAction()}" /> </h:panelGroup> But for some reason the permissionChanged method is never called. Any ideas of what might be going wrong? My permissionChanged method: public void PermissionChanged(ValueChangeEvent event) { System.out.println("test");}
Now provide the response and nothing else.
|
There are three problems: Your listener method call in EL is wrong. You should not pass the current component along it. Replace valueChangeListener="#{userTypeController.permissionChanged(this)}" by valueChangeListener="#{userTypeController.permissionChanged}" Your method signature in backing bean is wrong. It should conform the Java naming conventions . Replace public void PermissionChanged(ValueChangeEvent event) { by public void permissionChanged(ValueChangeEvent event) { You seem to be expecting that it fires immediately when you click the checkbox (otherwise you'd have seen an ELException ). This expectation is not true. It will only be fired when you submit the form. Using onclick="submit()" is a common hack/workaround for this. That said, there are likely better ways for this. As the functional requirement is unclear, it is not possible to propose the right solution. I think that the <f:ajax> is what you're looking for if all you want is immediate and asynchronous feedback and re-render. Although the JSF 2.0 tag is missing from your question, based on your question history you're using JSF 2.0, so <f:ajax> should work for you.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8215008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1054268/']}
|
jdg_372654
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
107196
|
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 do a clean build my C# project, the produced dll is different then the previously built one (which I saved separately). No code changes were made, just clean and rebuild. Diff shows some bytes in the DLL have changes -- few near the beginning and few near the end, but I can't figure out what these represent. Does anybody have insights on why this is happening and how to prevent it? This is using Visual Studio 2005 / WinForms. Update: Not using automatic version incrementing, or signing the assembly. If it's a timestamp of some sort, how to I prevent VS from writing it? Update: After looking in Ildasm/diff, it seems like the following items are different: Two bytes in PE header at the start of the file. <PrivateImplementationDetails>{ guid } section Cryptic part of the string table near the end (wonder why, I did not change the strings) Parts of assembly info at the end of file. No idea how to eliminate any of these, if at all possible...
Now provide the response and nothing else.
|
My best guess would be the changed bytes you're seeing are the internally-used metadata columns that are automatically generated at build-time. Some of the Ecma-335 Partition II (CLI Specification Metadata Definition) columns that can change per-build, even if the source code doesn't change at all: Module.Mvid: A build-time-generated GUID. Always changes, every build. AssemblyRef.HashValue: Could change if you're referencing another assembly that has also been rebuilt since the old build. If this really, really bothers you, my best tip on finding out exactly what is changing would be to diff the actual metadata tables. The way to get these is to use the ildasm MetaInfo window: View > MetaInfo > Raw:Header,Schema,Rows // important, otherwise you get very basic info from the next stepView > MetaInfo > Show!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/107196', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838/']}
|
jdg_372655
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1298636
|
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 putting around 4 million different keys into a Python dictionary.Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast. I suspect that dictionary creation is so resource consuming because the dictionary is very often rehashed (as it grows enormously).Is is possible to create a dictionary in Python with some initial size or bucket number? My dictionary points from a number to an object. class MyObject: def __init__(self): # some fields...d = {}d[i] = MyObject() # 4M times on different key...
Now provide the response and nothing else.
|
With performance issues it's always best to measure. Here are some timings: d = {} for i in xrange(4000000): d[i] = None # 722ms d = dict(itertools.izip(xrange(4000000), itertools.repeat(None))) # 634ms dict.fromkeys(xrange(4000000)) # 558ms s = set(xrange(4000000)) dict.fromkeys(s) # Not including set construction 353ms The last option doesn't do any resizing, it just copies the hashes from the set and increments references. As you can see, the resizing isn't taking a lot of time. It's probably your object creation that is slow.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1298636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42201/']}
|
jdg_372656
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
74634
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
We know that principal congruence subgroups are characteristic in $SL(n,\mathbb Z)$. Suppose $\Gamma$ is a finite index subgroup of $SL(n,\mathbb Z)$ and $\Gamma_m$ is a principal congruence subgroup of level m contained in $\Gamma$. Will it be characteristic in $\Gamma$?
Now provide the response and nothing else.
|
This is false. Consider the case $n=2$, and let $p$ be a prime. Let $A=\left[\begin{array}{cc}0 & -1 \\\ p & 0\end{array}\right]$ be an Atkin-Lehner involution (considered as an element of $PGL_2(\mathbb{Q})$), and consider the subgroup$\Gamma_0(p) = \{ \left[\begin{array}{cc}a & b \\\ c & d\end{array}\right]\in SL_2(\mathbb{Z}) | c\equiv 0(\mod p) \}$. Then one may check that for $B\in \Gamma_0(p)$, $A^{-1} B A = \left[\begin{array}{cc}d & -c/p \\\ -pb & a\end{array}\right]\in \Gamma_0(p)$, so $A\in Aut(\Gamma_0(p))$. Also, the principal congruence subgroup $\Gamma(p) \leq \Gamma_0(p)$. However, consider the matrix $C=\left[\begin{array}{cc}1 & 0 \\\ p & 1\end{array}\right] \in \Gamma(p)$. Then one has $A^{-1} C A = \left[\begin{array}{cc}1 & -1 \\\ 0 & 1\end{array}\right] \notin \Gamma(p)$. Thus, the subgroup $\Gamma(p)\leq \Gamma_0(p)$ is not characteristic. This extends to all $n$, taking the appropriate congruence subgroup by extending trivially $\mod p$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/74634', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13835/']}
|
jdg_372657
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17018010
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do you get current culture or browser locale on MVC 4. I find some samples which gets it from HttpContext and HttpRequest but this doesnt work on MVC 4. How do you do it on MVC 4?
Now provide the response and nothing else.
|
I find some samples which gets it from HttpContext and HttpRequest but this doesnt work on MVC 4. I just love the it doesn't work problem description!!! It's like saying to a mechanic whom you don't want to pay for the job: my car doesn't work, tell me what is wrong with it so that I can fix it myself , without showing him your car of course. Anyway, you still got the HttpRequest in your controller action. Look at the UserLanguages property: public ActionResult SomeAction(){ string[] userLanguages = Request.UserLanguages; ...} Remark: the value of this property will be null if the user agent didn't send the Accept-Languages request header. So make sure you check whether it is not null before accessing its value to avoid getting NREs.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17018010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177883/']}
|
jdg_372658
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10242306
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there any possible way to open a .doc extension file?
Now provide the response and nothing else.
|
Unlike iOS, Android itself does not support rendering .doc or .ppt files. You are looking for a public intent that allows your app to reuse other apps' activities to display these document types. But this will only work for a phone that has an app installed that supports this Intent. http://developer.android.com/guide/topics/intents/intents-filters.html or if you have installed some app then use this Intent: //Uri uri = Uri.parse("file://"+file.getAbsolutePath());Intent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(Intent.ACTION_VIEW);String type = "application/msword";intent.setDataAndType(Uri.fromFile(file), type);startActivity(intent);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10242306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737540/']}
|
jdg_372659
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10032950
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I created a DLL project and successfully built it. I then tried to use the DLL in another Project, TEST, and I am getting the following error. Error 1 error LNK2001: unresolved external symbol "public: void __thiscall SnoMessage::setRawMessageName(class ATL::CStringT<wchar_t,class StrTraitMFC_DLL<wchar_t,class ATL::ChTraitsCRT<wchar_t> > >)" (?setRawMessageName@SnoMessage@@QAEXV?$CStringT@_WV?$StrTraitMFC_DLL@_WV?$ChTraitsCRT@_W@ATL@@@@@ATL@@@Z) I added the required lib in the linker properties, and I also added the header files in the TEST include directory. So the function is being recognized, but it keeps giving those errors. The DLL is comprised of the following files SnoMessage.h #pragma once#include "StdAfx.h"class SnoMessage{public: __declspec(dllexport) SnoMessage(void); __declspec(dllexport) ~SnoMessage(void); __declspec(dllexport) void setRawMessageName(CString messageName); __declspec(dllexport) void setRawMessageType(CString messageType); __declspec(dllexport) void setRawMessageAttributes(std::map<CString,CString> attributes); __declspec(dllexport) CString getRawMessageName(); __declspec(dllexport) CString getRawMessageType(); __declspec(dllexport) std::map<CString,CString> getRawMessageAttributes();private: CString messageName; CString messageType; std::map<CString,CString> attributes;}; SnoMessage.cpp #include "stdafx.h"#include "SnoMessage.h"SnoMessage::SnoMessage(void){}SnoMessage::~SnoMessage(void){}void SnoMessage::setRawMessageName(CString messageName){ this->messageName = messageName;}void SnoMessage::setRawMessageType(CString messageType){ this->messageType = messageType;}void SnoMessage::setRawMessageAttributes(std::map<CString,CString> attributes){ this->attributes = attributes;}CString SnoMessage::getRawMessageName(){ return messageName;}CString SnoMessage::getRawMessageType(){ return messageType;}std::map<CString,CString> SnoMessage::getRawMessageAttributes(){ return attributes;} And in test I am doing the following: test.cpp // test.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "SnoMessage.h"int _tmain(int argc, _TCHAR* argv[]){ SnoMessage *msg = new SnoMessage(); msg->setRawMessageName("TEST"); return 0;} Let me know if you need more info, thanks.
Now provide the response and nothing else.
|
In your dll define this in some header you want to use for your export defs... MyExports.h #ifdef SNOMESSAGE_EXPORTS#define SNOMESSAGE_API __declspec(dllexport)#else#define SNOMESSAGE_API __declspec(dllimport)#endif Now in your dll you just define SNOMESSAGE_EXPORTS, then when your dll is compiled your class and methods will be visible to the exe. But when you include those same headers in the exe the Macro will import them instead of export. //In the DLL this is == to export, in the executable this is import. Problem solved.class SNOMESSAGE_API SnoMessage{public://...}; You no longer need to export each member, just the class.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10032950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/655696/']}
|
jdg_372660
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4371706
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Essentially, I'm trying to achieve the affect of "text-align:justify" but with floating block elements. I have many blocks that I want to justify-align. Ie. each line is horizontally-spaced differently to make sure lengths of each line are the same. (Non-ragged right edge). Is there a way to do this with CSS? If not, is there a suitable JS library to achieve this? Or is this just infeasible?
Now provide the response and nothing else.
|
If the items are not actually float ing, you can use position:absolute; left:1em; right:1em to have CSS calculate the widths of the items for you based on offsets from some positioned parent. If you are only using float because you have some block-level items you are trying to make flow, use display:inline-block on the items instead of floating them. If the parent element has text-align:justify this should give you the effect (I imagine that) you want. Here is a simple test showing you the result of inline-block with text-align:justify . Edit : I've updated the simple test to more clearly show that the left and right edges are always aligned except for the last line.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4371706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/180057/']}
|
jdg_372661
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24063194
|
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 .NET solution in Visual Studio 2010 with a bunch of projects. Up until recently, when I would run the startup project from within the IDE, projects would only build if changes had been made to the code in either the startup project or one of the dependency projects. About two weeks ago I noticed that every time I run the startup project, Visual Studio builds all projects, which takes about seven minutes. Needless to say this is taking a large amount of time out of my day, and I've tried my best to look online for solutions, but have yet to find any solutions that address my specific problem. A few additional pieces of information - the same problem began happening to everyone else on my team around the same time that I began experiencing this issue. We are also using a source code repository. Since we didn't change any settings in Visual Studio, my suspicion is that someone inadvertently changed something in the source code for some project that now requires all projects to build every time. Any suggestions would be greatly appreciated.
Now provide the response and nothing else.
|
The cause could be many things, so without having your solution + projects, we can only guess. The typical way I handle this problem is by narrowing it down with a binary search. That is, I build everything. Next I find something in the middle of the build order and build that project. If something that that project depends on is the culprit, you'll experience the issue. If something that it doesn't depend on has the problem you won't (i.e. it will say all projects skipped). Now you repeat this process until you narrow it down to (hopefully) the project that has started causing the problem. This (of course) only works if there is a single project that introduced the new problem (which is likely). One of the culprits in my specific situation was having an x64 project reference an x86 project that wasn't selected to be built in the x64 configuration.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24063194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1959348/']}
|
jdg_372662
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1456438
|
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:
Consider that $ABC=I_n \implies (ABC)^{-1}=(I_n)^{-1} \implies C^{-1}B^{-1}A^{-1}=I_n^{-1}=I_n$. Since $ABCI_n=ABC=I_n \implies ABCC^{-1}B^{-1}A^{-1}=I_n \implies A ,\ B,$ and $C$ are invertible $n\times n$ matrices. Q.E.D. Is this the proper approach to showing the desired result?
Now provide the response and nothing else.
|
Be careful, you can't write $(ABC)^{-1}=C^{-1}B^{-1}A^{-1}$ until you have proved that $A$, $B$ and $C$ are invertible. It's in fact what you want to prove ! i.e. that if $ABC=I_n$ then $(ABC)^{-1}=C^{-1}B^{-1}A^{-1}$. Since $$ABC=A(BC)=(AB)C=I_n,$$ the matrix $A$ and $C$ are invertible. Rest to prove that $B$ is also invertible. Hint Use the fact that since $A(BC)=I_n$ and $(AB)C=I_n$ then $A(BC)=(BC)A$ and $(AB)C=C(AB)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1456438', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/119306/']}
|
jdg_372663
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15241300
|
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 asked in interview following question. I could not figure out how to approach this question. Please guide me. Question: How to know whether a string can be segmented into two strings - like breadbanana is segmentable into bread and banana, while breadbanan is not. You will be given a dictionary which contains all the valid words.
Now provide the response and nothing else.
|
Build a trie of the words you have in the dictionary, which will make searching faster.Search the tree according to the following letters of your input string. When you've found a word, which is in the tree, recursively start from the position after that word in the input string. If you get to the end of the input string, you've found one possible fragmentation. If you got stuck, come back and recursively try another words. EDIT: sorry, missed the fact, that there must be just two words.In this case, limit the recursion depth to 2. The pseudocode for 2 words would be: T = trie of words in the dictionaryfor every word in T, which can be found going down the tree by choosing the next letter of the input string each time we move to the child: p <- length(word) if T contains input_string[p:length(intput_string)]: return truereturn false Assuming you can go down to a child node in the trie in O(1) (ascii indexes of children), you can find all prefixes of the input string in O(n+p) , where p is the number of prefixes, and n the length of the input. Upper bound on this is O(n+m) , where m is the number of words in dictionary. Checking for containing will take O(w) where w is the length of word, for which the upper bound would be m , so the time complexity of the algorithm is O(nm) , since O(n) is distributed in the first phase between all found words. But because we can't find more than n words in the first phase, the complexity is also limited to O(n^2) .So the search complexity would be O(n*min(n, m)) Before that you need to build the trie which will take O(s) , where s is the sum of lengths of words in the dictionary. The upper bound on this is O(n*m) , since the maximum length of every word is n .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15241300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2131106/']}
|
jdg_372664
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54984035
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have written a GraphQL query which like the one below: { posts { author { comments } comments }} I want to know how can I get the details about the requested child fields inside the posts resolver. I want to do it to avoid nested calls of resolvers. I am using ApolloServer's DataSource API. I can change the API server to get all the data at once. I am using ApolloServer 2.0 and any other ways of avoiding nested calls are also welcome.
Now provide the response and nothing else.
|
You'll need to parse the info object that's passed to the resolver as its fourth parameter. This is the type for the object: type GraphQLResolveInfo = { fieldName: string, fieldNodes: Array<Field>, returnType: GraphQLOutputType, parentType: GraphQLCompositeType, schema: GraphQLSchema, fragments: { [fragmentName: string]: FragmentDefinition }, rootValue: any, operation: OperationDefinition, variableValues: { [variableName: string]: any },} You could transverse the AST of the field yourself, but you're probably better off using an existing library. I'd recommend graphql-parse-resolve-info . There's a number of other libraries out there, but graphql-parse-resolve-info is a pretty complete solution and is actually used under the hood by postgraphile . Example usage: posts: (parent, args, context, info) => { const parsedResolveInfo = parseResolveInfo(info) console.log(parsedResolveInfo)} This will log an object along these lines: { alias: 'posts', name: 'posts', args: {}, fieldsByTypeName: { Post: { author: { alias: 'author', name: 'author', args: {}, fieldsByTypeName: ... } comments: { alias: 'comments', name: 'comments', args: {}, fieldsByTypeName: ... } } }} You can walk through the resulting object and construct your SQL query (or set of API requests, or whatever) accordingly.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54984035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1745409/']}
|
jdg_372665
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4417072
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Please take a look at my source files, they're a bit too long to post them here: X11Painter.cpp: http://pastebin.com/gu4SrHUr X11Painter.h: http://pastebin.com/3ktp1Fvn The behaviour of this class is in my opinion very strange . I'm having the following test case: #include "X11Painter.h"int main(){ X11Painter p ; p.show();} Compiling it with the line g++ -O0 -g -o test2 test2.cpp X11Painter.cpp -lX11 -lXfixes -lXinerama and simply running it does the following: this->some_test=1234this->screen:01:: this->display='0x8b73008'; this->window='77594625'width: 32000xbff91bdcthis->some_test=1234this->some_test=3682292Segmentation fault I'm trying to map the X11 window in X11Painter::show() When I started investigating why X11Painter.cpp:83 is segfaulting, I found out that most of the variables are overwritten and completely different in show() than they were in the constructor. I put the int some_test to see what's happening. Why the hell is the value changing? If I do printf("%p\n", this) , the pointer also changes. I suspect that somewhere, the this-pointer is overwritten. But why is this happening? Debugging with ddd told me that this->some_value is modified right while exiting the constructor. Doing a short test with a testclass (class with a public constructor, one public method and one private variable) works without any problem. Does anybody have an idea why this strange thing is happening?I know what happens to variables lieing on the stack, but we're still in main there... Might it be related to the X11-libraries?
Now provide the response and nothing else.
|
In your parameterless constructor, you do this X11Painter::X11Painter(){ X11Painter(-1);} This is not doing what you think it is doing, since there is no constructor chaining in C++. What the code above is doing is constructing a temporary X11Painter object, calling the other constructor for that temporary object, but not actually initializing anything in the object you want to construct. To fix this but retain the same behavior, remove your parameterless constructor and in your .h file declare the other constructor as X11Painter(int screenno = -1); This will default the screenno argument to -1 if you do not supply one.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4417072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146003/']}
|
jdg_372666
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42084161
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an .rdl file that I need to open in Visual Studio. When I try to open this file, I got an XML file. However, I am unable to see the designer format. I don't know which version of Visual Studio is used to create this .rdl file. Is it possible to open a random .rdl file in Visual Studio and see the designer format and, if so, how can I do that?
Now provide the response and nothing else.
|
Correct, the Report Definition Language is just XML. And, as with any other file, you can just open it (File/Open/File...) in Visual Studio, just like in a text editor. In order to see a designer you need to give Visual Studio a bit of context about what sort of file it is by making it part of a Report Server Project. Install SSDT for Visual Studio if you haven't already done so Create a new project using the 'Report Server Project' template Copy/move the .rdl file(s) you have into the folder for the newly created project (eg ..\Visual Studio 2015\Projects\My Report Project\My Report Project) Use the "Add Existing Item..." context menu option in Solution Explorer to add the .rdl to the project Open report designer by double-clicking the newly added report project item(s)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42084161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6624493/']}
|
jdg_372667
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42604261
|
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 training data for NN along with expected outputs. Each input is 10 dimensional vector and has 1 expected output.I have normalised the training data using Gaussian but I don't know how to normalise the outputs since it only has single dimension. Any ideas? Example: Raw Input Vector: -128.91, 71.076, -100.75,4.2475, -98.811, 77.219, 4.4096, -15.382, -6.1477, -361.18 Normalised Input Vector: -0.6049, 1.0412, -0.3731, 0.4912, -0.3571, 1.0918, 0.4925, 0.3296, 0.4056, -2.5168 The raw expected output for the above input is 1183.6 but I don't know how to normalise that. Should I normalise the expected output as part of the input vector?
Now provide the response and nothing else.
|
From the looks of your problem, you are trying to implement some sort of regression algorithm. For regression problems you don't normally normalize the outputs. For the training data you provide for a regression system, the expected output should be within the range you're expecting, or simply whatever data you have for the expected outputs. Therefore, you can normalize the training inputs to allow the training to go faster, but you typically don't normalize the target outputs. When it comes to testing time or providing new inputs, make sure you normalize the data in the same way that you did during training. Specifically, use exactly the same parameters for normalization during training for any test inputs into the network.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42604261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4820880/']}
|
jdg_372668
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5473580
|
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 view which contains one sub-view; this sub-view itself contains another sub-view, which is meant to be slightly smaller than its superview. I am creating the first subview full-screen size then shrinking it to a very small size on the screen. When the subview is tapped, I animate it from its small size to full-screen. The problem is that my second subview never resizes itself during this animation - it is always rendered full-size and overflows the bounds of its superview. Is there a simple way to get a subview to keep itself sized proportionally as its superview changes size?
Now provide the response and nothing else.
|
you could add the autoresizing-behavior programmatically Objective-C subview.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; Swift 3.x subview.autoresizingMask = [.flexibleWidth, .flexibleHeight] Swift 2.x subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] In Interface-Builder navigate to tab 3 and click on the arrows in the middle ;D Another workaround could be to implement the setFrame-method and always adapt it to the size of the superview (not the given frame.size). Don't forget to set up the origin as you need it. - (void) setFrame:(CGRect)frame{ CGRect rect = self.superview.frame; rect.origin.x = 0; rect.origin.y = 0; [super setFrame:rect];}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5473580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14606/']}
|
jdg_372669
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
463014
|
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:
Can a magnetic field be induced without an electric field?Because, as far as I know, a time varying electric field induces a magnetic field an vice versa. But in the case of conductors carrying currennt, it doesn't seem that electric field varies with time, then how is a magnetic field induced?
Now provide the response and nothing else.
|
One of Maxwell’s four equations for electromagnetism in a vacuum shows how magnetic fields are produced: $$\nabla\times\mathbf{B}=\frac{1}{c}\left(4\pi\mathbf{J}+\frac{\partial\mathbf{E}}{\partial t}\right).$$ (I’ve written it in Gaussian units.) From this equation you can see that there are two different sources for magnetic fields: the first is a current density, and the second is a changing electric field. So to have a magnetic field you do not need to have a time-varying electric field. You can just have moving charge. But when a magnetic field is produced by moving charge, physicists don’t call it “induced”.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/463014', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/192694/']}
|
jdg_372670
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
162985
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I have a question, but not sure how to prove this. We are given $n$ points in the Euclidean plane such that there exists no disk of radius $a$ which contains all of the points. Conjecture: There must exist three of these points which are not contained in a disk of radius $a$. Any idea about how to prove this? Thanks.
Now provide the response and nothing else.
|
There is a classical result of convex geometry, called Helly's theorem ( http://en.wikipedia.org/wiki/Helly%27s_theorem ). It states that if you have $n$ convex subsets of $R^d$ and any $d+1$ of these convex subsets have nontrivial intersection, then all of them have nontrivial intersection. For your question you just apply this theorem to the balls of radius $a$ around your points.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/162985', 'https://mathoverflow.net', 'https://mathoverflow.net/users/49425/']}
|
jdg_372671
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9364
|
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So...lugging the engine obviously isn't something that is good. But why? For example when you feather a clutch to get the car moving, it lugs for a quick moment when you hit the catch point (When giving it no gas). Or at least it does in my car (2014 VW GTI). Is this a really bad habit, I only feather it when im moving slowly in say....traffic jams, or drive throughs and such. Thanks!
Now provide the response and nothing else.
|
Lugging an engine is like hammering the engine parts with every explosion in a cylinder. It racks on the rod bearing/journals, makes the pistons slap the side of the cylinders hard, and if is done enough, could probably break piston rings. It also creates a hammer effect all the way through the drivetrain. There are springs in the friction disk (of the clutch) which takes up some of this hammering, but they will only take so much before they wear out as well. This causes premature wear all the way around. It's not like it will wear out tomorrow, but it will cause wear over time. If you want your car to last a while, you don't want to be doing this. I think the major problem with what you are doing is, you aren't doing it right. It sounds like you are just trying to take off from a stop (or slow roll) without revving the engine at all. You should bring the engine up in rpm to around 1500 to 2000 rpm when starting to slip the clutch. You should get used to slipping the clutch in either situation (stopped or slow roll) no matter where you are at. To get it down, you should press on the pedals like you would a bicycle. Basically, as you press on one, you should allow the other to come up, so: gas pedal down slightly while allowing the clutch pedal to come out; and visa-versa - clutch pedal down while allowing the gas pedal to come out. Over time and experience, this becomes second nature. You will figure out (mainly by feel) where the engine needs to be at in speed in order to get the car moving. This will keep you from lugging the engine at all. EDIT: Here is an Engineering Explained video about lugging your engine and why it's bad. He gets a lot more technical than I did above, adds to what I've said, but it definitely concurs with it (I believe).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/9364', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/-1/']}
|
jdg_372672
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24539551
|
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 query a nested properties with multiple values. Here is an example that will be clearer. Create an index with a nested field curl -X DELETE "http://localhost:9200/testing_nested_query/" curl -X POST "http://localhost:9200/testing_nested_query/" -d '{ "mappings": { "class": { properties: { title: {"type": "string"}, "students": { "type": "nested", "properties": { "name": {"type": "string"} } } } } } }' Add some values curl -XPUT 'http://localhost:9200/testing_nested_query/class/1' -d '{ "title": "class1", "students": [{"name": "john"},{"name": "jack"},{"name": "jim"}] }' curl -XPUT 'http://localhost:9200/testing_nested_query/class/2' -d '{ "title": "class2", "students": [{"name": "john"},{"name": "chris"},{"name": "alex"}] }' Query for all classes where john is (2 hits as expected) curl -XGET 'http://localhost:9200/testing_nested_query/class/_search' -d '{ "query": { "nested": { "path":"students", "query": { "bool": { "must": [ {"match": {"students.name": "john"}} ] } } } }}' Query for classes where both john and jack are attending ( 0 results instead of 1) curl -XGET 'http://localhost:9200/testing_nested_query/class/_search' -d '{ "query": { "nested": { "path":"students", "query": { "bool": { "must": [ {"match": {"students.name": "john"}}, {"match": {"students.name": "jack"}} ] } } } }}' I've tried with match and filter but I can never get the query to return the expected values.
Now provide the response and nothing else.
|
It just needs a bit change: { "query": { "bool": { "must": [ { "nested": { "path":"students", "query": { "bool": { "must": [ {"match": {"name": "john"}} ] } } } }, { "nested": { "path":"students", "query": { "bool": { "must": [ {"match": {"name": "jack"}} ] } } } } ] } }} Why? Basically, in a nested query, the query and the filter are collectively executed on a single nested document - in your case one name. So your query would pick up every nested document and try to find every document that has name equal to john and jack at the same time - which is impossible. My query tries to find an indexed document that has one nested document with name equal to john and another nested document with name equal to jack . So basically one nested query tries to match one nested document completely. To prove what I am suggesting, try this: Create the same index with same mapping as you did ** Then index the following documents ** curl -XPUT 'http://localhost:9200/testing_nested_query/class/1' -d '{ "title": "class1", "students": [{"name": "john", "age": 4},{"name": "jack", "age": 1},{"name": "jim", "age": 9}] }'curl -XPUT 'http://localhost:9200/testing_nested_query/class/2' -d '{ "title": "class1", "students": [{"name": "john", "age": 5},{"name": "jack", "age": 4},{"name": "jim", "age": 9}] }' Now execute the following queries: { "query": { "nested": { "path":"students", "query": { "bool": { "must": [ {"match": {"name": "john"}}, {"match": {"age": 4}} ] } } } }} According to your expectations, this should match 2 documents but it actually matches just only one. Because there is only one nested document that has both name equal to john and age equal to 4 . Hope that helps.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24539551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/474321/']}
|
jdg_372673
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56474
|
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 have been doing hobby electronics for more than 10 years, and some of my electrolytic capacitors are easily that age. They seem to work just fine and do not show corrosion or other visible defects, but they are usually used in prototyping rather than production. Knowing that these have a limited shelf life , I'm curious if I should just discard what I have and purchase new inventory, and rotate it. How best can I tell that my old caps have failed, are out of spec, or perhaps are going to fail?
Now provide the response and nothing else.
|
The best way to tell that an electrolytic cap is bad or about to go bad is to use an ESR meter . An ESR meter directly measures one of the biggest reasons electrolytic caps fail: when ESR gets high, P=I²R tells us that power dissipation goes up, so heat gets produced, which boils off more of the electrolyte, which causes ESR to go up, which... Eventually, poof-bang, it isn't a cap any more. Read the cap's datasheet to find out the expected value of ESR. It varies considerably among capacitor types and capacitance values. As a rule, the cheaper and smaller the cap, the higher the expected ESR. I've seen values ranging from 30 mΩ to 3 Ω. The only reason I even give numbers is to show this 100:1 ratio, not to set your expectations so you can go measuring without having read the cap's datasheet, however. You can re-form the dielectric of electrolytic caps. There are two major methods. Re-forming the Dielectric Using a Bench Supply One school of thought is to charge the cap up over many minutes via some current-limiting scheme to its rated voltage, then leave it there for many more minutes. There are several methods for doing this, all with the major goal of limiting the currents to levels that prevent the capacitor from blowing up in your face if the capacitor simply cannot be restored. The Resistor Method The simplest way to achieve this is to put a large resistor in series between the capacitor and the voltage supply. Use the RC time constant formula (τ = RC) to calculate the proper resistor value. The rule of thumb I was given is based on the fact that a capacitor is nearly fully charged after five time constants, so we set τ = 1500 in the above formula: 5 minutes in seconds × 5 time constants. We can then rearrange that to R = 1500÷C. Now simply substitute your capacitor's value into the formula to get the minimum required resistor. For example, to re-form a 220 μF cap, you'd want to charge it through a resistor no smaller than 6.8 MΩ. Set the power supply's voltage to the normal working voltage for the capacitor. If it's a 35 V capacitor, it probably has about 30 V across it in normal operation, so you'd use that as your voltage set point. I can't see a good reason to push the capacitor beyond its normal working voltage; the dielectric strength will increase over time to some physical limit and stop there. This method is nonlinear, charging fastest at the start, then slowing asymptotically as you approach the power supply's voltage set point. The Constant-Current Method A more sophisticated method would be to use a current-limited bench power supply , achieving the same end. The formula for that is I = CV÷τ. If we always want to charge over 30 minutes, τ=1800. To re-work our 220 µF example, we also need to know the ending voltage, which we'd select the same way as above. Let's use 30 V as our target again. Substituting that and our charge time into the above formula gives the necessary charging current, which in this case is 3.7 µA. If your power supply can only go down to 1 mA for the current limit setting, you then need to decide whether you want to risk recharging over only 6.6 seconds, which we get by a simple rearrangement of the formula. This method is linear, increasing the voltage across the capacitor a fixed amount per unit time until it hits the voltage set point. The main consequence of this is that the ending charge current will be higher for a given total charge time than with the resistor method, but the starting charge current will be lower. Since the danger of damaging the capacitor increases as you approach the voltage set point, that makes the resistor method safer, with the charge time being equal. Combined Method That brings us to the combined method, which was used in the link above: a constant current power supply charging the capacitor through a resistor. The resistor slows the charge current as the voltage rises, and the current-limited power supply can limit the charge rate at low voltages below what the resistor would do alone. Leakage Current If you do this with a good bench supply, once you hit the charging voltage limit, if the power supply continues to show any current flow, that is your capacitor's leakage current, which you can compare to the spec in the cap's datasheet. An ideal capacitor has a leakage current of zero, but only the best capacitors approach that ideal. Electrolytic caps are far from ideal. If you leave the capacitor in the charging setup, you may find that the leakage current drops for some time after hitting the voltage limit, then stabilizes. It is that point that you know that the dielectric is now as strong as it's going to get. Re-forming the Dielectric In-Circuit The second method also raises the capacitor voltage slowly over a long period, but it does so in-circuit. It only works for AC-powered equipment, and it is best used to re-form the dielectrics in linear power supplies, whether regulated or unregulated. You pull this trick off using a variac , which allows you to raise the AC supply voltage to the circuit slowly. I would start off at a volt or two, then tweak it upward a volt or three at a time, with many seconds between changes. As with the methods above, expect to spend at least half an hour on this. We're dealing with wet chemistry here, not semiconductor gates; it takes time. The more "linear" the circuit you do this with, the more likely it is to work well. Switching power supplies and digital circuitry are likely to be annoyed by the slowly rising rail voltage produced by this method. Some circuits can even self-destruct under such conditions, because they're designed with the assumption that the supply voltage will always rise rapidly from zero to its normal operating value. If you have a digital circuit powered by a linear-regulated power supply, you might want to re-form the power supply separate from the powered circuit. You might want to put a resistive load across the output of the power supply while you do this.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/56474', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/2028/']}
|
jdg_372674
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
246534
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know output to the console is a costly operation. In the interest of code readability sometimes it is nice to call a function to output text twice, rather than having a long string of text as an argument. For example how much less efficient is it to have System.out.println("Good morning.");System.out.println("Please enter your name"); vs. System.out.println("Good morning.\nPlease enter your name"); In the example the difference is only one call to println() but what if it's more? On a related note, statements involving printing text can look strange while viewing the source code if the text to print is long. Assuming the text itself can't be made shorter, what can be done? Should this be a case where multiple println() calls be made? Someone once told me a line of code shouldn't be more than 80 characters (IIRC) so what would you do with System.out.println("Good morning everyone. I am here today to present you with a very, very lengthy sentence in order to prove a point about how it looks strange amongst other code."); Is the same true for languages such as C/C++ since each time data is written to an output stream a system call must be made and the process must go to kernel mode (which is very costly)?
Now provide the response and nothing else.
|
There are two 'forces' here, in tension: Performance vs. Readability. Let's tackle the third problem first though, long lines: System.out.println("Good morning everyone. I am here today to present you with a very, very lengthy sentence in order to prove a point about how it looks strange amongst other code."); The best way to implement this and keep readibility, is to use string concatenation: System.out.println("Good morning everyone. I am here today to present you " + "with a very, very lengthy sentence in order to prove a " + "point about how it looks strange amongst other code."); The String-constant concatenation will happen at compile time, and will have no effect on performance at all. The lines are readable, and you can just move on. Now, about the: System.out.println("Good morning.");System.out.println("Please enter your name"); vs. System.out.println("Good morning.\nPlease enter your name"); The second option is significantly faster. I will suggest about 2X as fast.... why? Because 90% (with a wide margin of error) of the work is not related to dumping the characters to the output, but is overhead needed to secure the output to write to it. Synchronization System.out is a PrintStream . All Java implementations that I know of, internally synchronize the PrintStream: See the code on GrepCode! . What does this mean for your code? It means that each time you call System.out.println(...) you are synchronizing your memory model, you are checking and waiting for a lock. Any other threads calling System.out will also be locked. In single-threaded applications the impact of System.out.println() is often limited by the IO performance of your system, how fast can you write out to file. In multithreaded applications, the locking can be more of an issue than the IO. Flushing Each println is flushed . This causes the buffers to be cleared and triggers a Console-level write to the buffers. The amount of effort done here is implementation dependant, but, it is generally understood that the performance of the flush is only in small part related to the size of the buffer being flushed. There is a significant overhead related to the flush, where memory buffers are marked as dirty, the Virtual machine is performing IO, and so on. Incurring that overhead once, instead of twice, is an obvious optimization. Some numbers I put together the following little test: public class ConsolePerf { public static void main(String[] args) { for (int i = 0; i < 100; i++) { benchmark("Warm " + i); } benchmark("real"); } private static void benchmark(String string) { benchString(string + "short", "This is a short String"); benchString(string + "long", "This is a long String with a number of newlines\n" + "in it, that should simulate\n" + "printing some long sentences and log\n" + "messages."); } private static final int REPS = 1000; private static void benchString(String name, String value) { long time = System.nanoTime(); for (int i = 0; i < REPS; i++) { System.out.println(value); } double ms = (System.nanoTime() - time) / 1000000.0; System.err.printf("%s run in%n %12.3fms%n %12.3f lines per ms%n %12.3f chars per ms%n", name, ms, REPS/ms, REPS * (value.length() + 1) / ms); } } The code is relatively simple, it repeatedly prints either a short, or a long string to output. The long String has multiple newlines in it. It measures how long it takes to print 1000 iterations of each. If I run it at the unix (Linux) command-prompt, and redirect the STDOUT to /dev/null , and print the actual results to STDERR , I can do the following: java -cp . ConsolePerf > /dev/null 2> ../errlog The output (in errlog) looks like: Warm 0short run in 7.264ms 137.667 lines per ms 3166.345 chars per msWarm 0long run in 1.661ms 602.051 lines per ms 74654.317 chars per msWarm 1short run in 1.615ms 619.327 lines per ms 14244.511 chars per msWarm 1long run in 2.524ms 396.238 lines per ms 49133.487 chars per ms.......Warm 99short run in 1.159ms 862.569 lines per ms 19839.079 chars per msWarm 99long run in 1.213ms 824.393 lines per ms 102224.706 chars per msrealshort run in 1.204ms 830.520 lines per ms 19101.959 chars per msreallong run in 1.215ms 823.160 lines per ms 102071.811 chars per ms What does this mean? Let me repeat the last 'stanza': realshort run in 1.204ms 830.520 lines per ms 19101.959 chars per msreallong run in 1.215ms 823.160 lines per ms 102071.811 chars per ms It means that, for all intents and purposes, even though the 'long' line is about 5-times longer, and contains multiple newlines, it takes just about as long to output as the short line. The number of characters-per-second for the long run is 5 times as much, and the elapsed time is about the same..... In other words, your performance scales relative to the number of printlns you have, not what they print. Update: What happens if you redirect to a file, instead of to /dev/null? realshort run in 2.592ms 385.815 lines per ms 8873.755 chars per msreallong run in 2.686ms 372.306 lines per ms 46165.955 chars per ms It is a whole lot slower, but the proportions are about the same....
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/246534', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/221185/']}
|
jdg_372675
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35194
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Have you guys had any experiences (positive or negative) by placing your source code/solution on a network drive for Visual Studio 2005 or 2008? Please note I am not referring to placing your actual source control system on that drive, but rather your working folder. Thanks
Now provide the response and nothing else.
|
Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it. Look at the stack trace ... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places. If the exception appears when calling a method on objects instantiated by classes you made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/35194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2343/']}
|
jdg_372676
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4219260
|
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 target the first and last anchor within a list-item of an unordered list: <ul> <li><a href="#">HOME</a></li> <li><a href="#">LINK</a></li> <li><a href="#">LINK</a></li> <li><a href="#">LINK</a></li> <li><a href="#">LINK</a></li></ul> I have tried: .menu ul .last a {}.menu ul.last a {}.menu ul li .last a {}.menu ul li.last a {} I need to target the anchor as I need to remove the border of the first and last anchor. I can't use (or at least I don't think I can) border on the <li> , as it needs some vertical padding so the separator border is not vertically flush.
Now provide the response and nothing else.
|
If you don't need to worry about old browsers, use the :first-child and :last-child pseudo-classes on the list items, like so: /* Because we are looking at the <li> children of your <ul> */.menu ul li:first-child a {}.menu ul li:last-child a {} However, support for CSS3 :last-child is pretty poor right now, so a more browser-compatible alternative is to manually give the last list item a last class, like so (and doing the same for first): <ul> <li class="first"><a href="#">HOME</a></li> <li><a href="#">LINK</a></li> <li><a href="#">LINK</a></li> <li><a href="#">LINK</a></li> <li class="last"><a href="#">LINK</a></li></ul> Then, you can use these selectors: .menu ul li.first a {}.menu ul li.last a {}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4219260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/208754/']}
|
jdg_372677
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48080336
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am building a VoIP app.During a VoIP call when user switches between WiFi to mobile data i have a problem handling the scenario. In my call screen activity I have registered for receiver which helps me get notified about the network change scenarios. This is the code which I am using for detecting change in networks in the onRecieve Method. conn_name is private class level variable holding previous connection name. ConnectivityManager connectivity_mgr = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));NetworkInfo net_info = connectivity_mgr.getActiveNetworkInfo();if (net_info != null && net_info.isConnectedOrConnecting() && !conn_name.equalsIgnoreCase("")) { new_con = net_info.getExtraInfo(); if (new_con != null && !new_con.equalsIgnoreCase(conn_name)) network_changed = true; conn_name = (new_con == null) ? "" : new_con; connectionStatus ="connected";} else { if (net_info != null && conn_name.equalsIgnoreCase("")) { conn_name = net_info.getExtraInfo(); connectionStatus ="connected"; network_changed = true; } else if(!new_con.equals(conn_name)) { conn_name = ""; connectionStatus ="disconnected"; network_changed = true; }} So using above method I able detect network changes. But one peculiar thing happens when I am connected with WiFi. When my app starts initially it is connected with mobile data.when user enters into his known WiFi area,he gets connected to his known WiFi. Since WiFi is always chosen as default route,android switches to WiFi and I receive the network notification that WiFi has been turned on. So I update my apps IP address to WiFi IP address, so no issues here. But still mobile data is still connected at the same time but getActiveNetworkInfo() tells me that I'm connected with WiFi clearly even if I was early connected to mobile data. So the problem is when user switches off the WiFi button,and mobile data is still connected but I still receive the notification for WiFi turn off.It indicates me that network is disconnected even when my phone is still connected to mobile data. But after a second I receive a notification that mobile data is connected.But once I receive the network disconnected, I have closed my VoIP call.So when I receive a notification for WiFi switched off how can I make sure whether mobile data is still connected. I tried getActiveNetworkInfo() but it happens to be null when I receive notification for WiFi turned off. I have followed this links: Android API call to determine user setting "Data Enabled" How to tell if 'Mobile Network Data' is enabled or disabled (even when connected by WiFi)? Using the above link I am able detect that mobile data button has been enabled when user has connected with mobiledata.it gives me true.But the problem happens when this particular case happens. Now when wifi is disabled I get notification but it shows that mobile data is disabled even when my mobile data is enabled. I am not able to handle this situation as I disconnect my calls when I receive my disconnected notification.
Now provide the response and nothing else.
|
You can utilize APIs of ConnectivityManager : particularly in your use case you are interested in registerDefaultNetworkCallback() : public class TestActivity extends AppCompatActivity { private ConnectivityManager manager; private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { super.onAvailable(network); // this ternary operation is not quite true, because non-metered doesn't yet mean, that it's wifi // nevertheless, for simplicity let's assume that's true Log.i("vvv", "connected to " + (manager.isActiveNetworkMetered() ? "LTE" : "WIFI")); } @Override public void onLost(Network network) { super.onLost(network); Log.i("vvv", "losing active connection"); } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); manager.registerDefaultNetworkCallback(networkCallback); } @Override protected void onDestroy() { super.onDestroy(); manager.unregisterNetworkCallback(networkCallback); } } My device connects to LTE in about half second. This means, that you cannot know beforehand, whether device will eventually connect to LTE or no at the time, when WIFI gets disconnected. Thus, you can adopt following approach: post an action on a handler to happen in a second and within this action cancel the call. If connection appears anytime soon - unschedule previously posted action. If you end up being in Runnable code, then connection wasn't established quickly, which means, that you should end the call. public class TestActivity extends AppCompatActivity { private ConnectivityManager manager; private final Handler handler = new Handler(); private final ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { super.onAvailable(network); Log.i("vvv", "connected to " + (manager.isActiveNetworkMetered() ? "LTE" : "WIFI")); // we've got a connection, remove callbacks (if we have posted any) handler.removeCallbacks(endCall); } @Override public void onLost(Network network) { super.onLost(network); Log.i("vvv", "losing active connection"); // Schedule an event to take place in a second handler.postDelayed(endCall, 1000); } }; private final Runnable endCall = new Runnable() { @Override public void run() { // if execution has reached here - feel free to cancel the call // because no connection was established in a second } }; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); manager.registerDefaultNetworkCallback(networkCallback); } @Override protected void onDestroy() { super.onDestroy(); manager.unregisterNetworkCallback(networkCallback); handler.removeCallbacks(endCall); } } The downside of the approach is, that registerDefaultNetworkCallback() is available starting from API 24. There does not exist an alternative in ConnectivityManagerCompat either. Instead, you can use registerNetworkCallback() which is available from API 21.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48080336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6059583/']}
|
jdg_372678
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
193154
|
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 getting the following error when I try to call a stored procedure that contains a SELECT Statement: The operation is not valid for the state of the transaction Here is the structure of my calls: public void MyAddUpdateMethod(){ using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { using(SQLServer Sql = new SQLServer(this.m_connstring)) { //do my first add update statement //do my call to the select statement sp bool DoesRecordExist = this.SelectStatementCall(id) } }}public bool SelectStatementCall(System.Guid id){ using(SQLServer Sql = new SQLServer(this.m_connstring)) //breaks on this line { //create parameters // }} Is the problem with me creating another connection to the same database within the transaction?
Now provide the response and nothing else.
|
After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this: public void MyAddUpdateMethod(){ using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { using(SQLServer Sql = new SQLServer(this.m_connstring)) { //do my first add update statement } //removed the method call from the first sql server using statement bool DoesRecordExist = this.SelectStatementCall(id) }}public bool SelectStatementCall(System.Guid id){ using(SQLServer Sql = new SQLServer(this.m_connstring)) { //create parameters }}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/193154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26327/']}
|
jdg_372679
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6416065
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am currently looking for a regex that can help validate a file path e.g.: C:\test\test2\test.exe
Now provide the response and nothing else.
|
I decided to post this answer which does use a regular expression. ^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$ Works for these: \\test\test$\TEST.xls\\server\share\folder\myfile.txt\\server\share\myfile.txt\\123.123.123.123\share\folder\myfile.txtc:\folder\myfile.txtc:\folder\myfileWithoutExtension Edit: Added example usage: if (Regex.IsMatch (text, @"^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$")){ // Valid} *Edit: * This is an approximation of the paths you could see. If possible, it is probably better to use the Path class or FileInfo class to see if a file or folder exists.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6416065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/807051/']}
|
jdg_372680
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
923706
|
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's the best way to check if a Nib or Xib file exists before trying to load it using initWithNibName:bundle: or similar?
Now provide the response and nothing else.
|
Macro #define AssertFileExists(path) NSAssert([[NSFileManager defaultManager] fileExistsAtPath:path], @"Cannot find the file: %@", path)#define AssertNibExists(file_name_string) AssertFileExists([[NSBundle mainBundle] pathForResource:file_name_string ofType:@"nib"]) Here are a set of macros that you can call before you try an load a .xib or .nib , they will help identify missing files and spit out useful message about what exactly is missing. Solutions Objective-C : if([[NSBundle mainBundle] pathForResource:fileName ofType:@"nib"] != nil) { //file found ...} Please note, the documentation states that ofType: should be the extension of the file. However even if you are using .xib you need to pass `@"nib" or you will get a false-negative. Swift : guard Bundle.main.path(forResource: "FileName", ofType: "nib") != nil else { ... } (See: touti 's original answer: https://stackoverflow.com/a/55919888/89035 )
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/923706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89035/']}
|
jdg_372681
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
433797
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a code that reads a YAML file that consists of several parameters whose values are used throughout the code.For clarity, the YAML file has the following structure: PARAM_1: value_1PARAM_2: value_2PARAM_N: value_N These values are never changed after the YAML file is loaded into the program. When the YAML file is loaded, it is directly converted to a dictionary params and then I access the values using the common notation params['PARAM_N'] . The conversion is performed using the safe_load method in the yaml library. I have discovered namedtuples after writing the code described above. Namedtuples have several interesting features like the possibility to access the values using the dot notation and they are an immutable data structure as pointed out in other answers about this topic. So, given the immutability of these parameters, should I convert the dictionary to a namedtuple (also to be more pythonic)? Or would it be useless? Or maybe do you see any drawback in the long run because of this conversion? I think it would be a good idea, because the code would be safer (I cannot change a value by accident).
Now provide the response and nothing else.
|
Defining a namedtuple or other type to represent the Yaml file can be a good idea compared to using a dict. But not because of immutability. Python doesn't really support immutability the way C++ or Haskell does. It does support preventing further modifications to an existing object. E.g. fields of the built-in tuple cannot be reassigned. By extension, the same holds for namedtuple types. Dataclasses can be declared as frozen . But all of this is mostly just a runtime check. Do consider preventing reassignment of fields if that is a concern to you, but for many programs it's not actually relevant. The bigger reason why you should consider introducing a type for the configuration data is that it makes the available fields explicit. With a dict, the user of this dict doesn't know which entries it is supposed to have or what types those entries have. With a class that represents this data, this information can be made explicit. And as an added benefit, you can get type-checking, autocomplete, and will get an error when you edit the config file but you mistype the name of a field by accident. So instead of config = parse_file()do_something(config['foo'], config['bar']) it would be nice to have: config = Configuration(**parse_file())do_something(config.foo, config.bar) Different ways to declare convenient types include the classic namedtuple() function, the new NamedTuple class notation, and dataclasses. With the classic namedtuple function, you just list the fields: from collections import namedtupleConfiguration = namedtuple('Configuration', ['foo', 'bar']) Or equivalently with the newer typed syntax: from typing import NamedTupleclass Configuration(NamedTuple): foo: int bar: str Drawback: you can't directly validate that the configuration fields contain appropriate values. This could be alleviated by subclassing the namedtuple, except that because tuples are immutable their construction is special: you'd have to implement __new__ instead of __init__ . Dataclasses are typically more appropriate if you don't actually need the configuration to behave like an (ordered) tuple, though you can optionally have Python implement the corresponding methods as well. The class-based notation does expect you to provide either a field type or a default value though: from dataclasses import dataclass@dataclass(frozen=True) # can prevent reassignment if requiredclass Configuration: foo: int bar = "" Validation could be done with a __post_init__ magic method. In any case, it's probably better to do validation outside of the class: import yamldef get_config() -> Configuration: with open('config.yaml') as config_file: raw_config = yaml.load(config_file) if not isinstance(raw_config, dict): raise TypeError('config file must be a mapping') foo = raw_config.pop('foo') if not isinstance(foo, int) and int >= 0: raise TypeError(f'entry `foo` must be a nonnegative int but was {foo!r}') bar = raw_config.pop('bar', "") if not isinstance(bar, str): raise TypeError(f'entry `bar` must be a string but was {bar!r}') if raw_config: raise TypeError(f'config file contains unknown entries: {list(raw_config)}') return Configuration(foo=foo, bar=bar)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/433797', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/397719/']}
|
jdg_372682
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41231290
|
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 find out how to output the current year in a Flask template. I know in Django you can use {% now "Y" %}. , but is there a Flask equivalent? I have been unable to find anything during my research thus far.
Now provide the response and nothing else.
|
Use a template context processor to pass the current date to every template, then render its year attribute. from datetime import datetime@app.context_processordef inject_now(): return {'now': datetime.utcnow()} {{ now.year }} Or pass the object with render if you don't need it in most templates. return render_template('show.html', now=datetime.utcnow())
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41231290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6460943/']}
|
jdg_372683
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24223623
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I am developing a little forum and I ran into a little design problem. The sidebar in each post is supposed to match the height of the content (the text written) but the sidebar only goes to the height necessary to display everything and then stops. JSFiddle: http://jsfiddle.net/9stPU/5/ CSS: .forumContent {list-style-type: none;background: #34495e;letter-spacing: 1px;width: 1170px;margin: 0;color: white;}.forumContent li {padding: 0 0 0 10px; /* 5px 0 5px 10px */margin-left: -40px;min-height: 41px;overflow: auto;border-bottom: 1px solid #000;}.forumContent li:last-child {border-bottom: none;}.forumContent li h3 {margin: 0;padding: 0;font-size: 14px;}.forumContent li small {font-size: 9px;}.forumContent a {color: white;text-decoration: none;width: 100%;height: 100%;}.forumContent li:hover {background: #3E5368;}.forumContent a li {float: left;width: 366px;}.forumContent a li:first-child {width: 100px;}.forumContent li .new b {font-size: 12px;}.forumContent li .new {float: right;margin-right: 8px;margin-top: -2px;font-size: 9px;background: #2c3e50;padding: 4px;border-radius: 6px;}.topicUser {width: 150px;float: left;background: #000;margin-left: -10px;min-height: 100%;height: 100%;}.topicUser h3 {margin-left: 2 .5px !important;}.topicUser small {position: absolute;margin-top: -15px;margin-left: 7 .5px;}.topicUser p {margin-top: 2px;margin-left: 3px;}.topicContent {width: 1060px;float: right;height: 100%;}.topicContent p {padding: 5px;}
Now provide the response and nothing else.
|
Let's take a closer look at your last line, and explode it to see what's happening: let temporaryAnyObject = test()let temporaryString = temporaryAnyObject as Stringdict["test"] = temporaryString The error is on the second line, where you are telling the compiler to enforce that temporaryAnyObject is definitely a String . The code will still compile (assuming you don't treat warnings as errors), but will crash if temporaryAnyObject is not actually a String . The way as works, with no ? , is basically saying "from now on, treat the result of this expression as that type IF the result is actually of that type, otherwise we've become inconsistent and can no longer run. The way as? works (with the ? ) is saying "from now on, treat the result of this expression as that type IF the result is actually of that type, otherwise the result of this expression is nil . So in my exploded example above, if test() does return a String , then the as downcast succeeds, and temporaryString is now a String . If test() doesn't return a String , but say an Int or anything else not subclassed from String, then the as fails and the code can no longer continue to run. This is because, as the developer in complete control, you told the system to behave this way by not putting the optional ? indicator. The as command specifically means that you do not tolerate optional behavior and you require that downcast to work. If you had put the ? , then temporaryString would be nil , and the third line would simple remove the "test" key/value pair from the dictionary. This might seem strange, but that's only because this is the opposite default behavior of many languages, like Obj-C, which treat everything as optional by default, and rely on you to place your own checks and asserts. Edit - Swift 2 Update Since Swift 2, the forced, failable downcast operator as has been removed, and is replaced with as! , which is much Swiftier. The behavior is the same.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24223623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3740791/']}
|
jdg_372684
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
57259
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a training set with about 3000 positive instances and 3000 negative instances. But my test data set is pretty much un-balanced. The positive set only has 50 instances and negative has 1500 instances.This causes the precision very low. Are there any approaches to solve this problem? I use SVM to build classifier.
Now provide the response and nothing else.
|
This is called Dataset Shift setting. This pdf [1] should help you understand several of the underlying issues involved. For the moment however, you can use least squares importance fitting to obtain importance estimates for your training data using your test set (you don't need the test set labels, just the feature vectors) [2]. Once you gain the importance estimates, you can use them as instance weights in libSVM [3]. That should enable you to get a better classifier. [1] http://www.acad.bg/ebook/ml/The.MIT.Press.Dataset.Shift.in.Machine.Learning.Feb.2009.eBook-DDU.pdf [2] http://www.ms.k.u-tokyo.ac.jp/software.html#uLSIF [3] http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/#weights_for_data_instances
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/57259', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/6720/']}
|
jdg_372685
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54252352
|
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 reading a lot on the subject it looks like a good approach is to create a context once per request. To achive this, in in Startup.cs I have declared two statics objects public class Startup{ public static DbContextOptionsBuilder<MCContext> optionsBuilder = new DbContextOptionsBuilder<MCContext>(); public static MCContext db = null; then init optionsBuilder when the app starts (so only once): public Startup(IConfiguration configuration){ optionsBuilder.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]);} while db at each request: app.Use(async (context, next) =>{ db = db ?? new MCContext(optionsBuilder.Options); await next.Invoke(); }); Then when I need the context in a controller or in a razor page cs I can get it using Startup.db: User cur = await Startup.db.User.Where(x => x.Id == uid).FirstOrDefaultAsync(); I do not Dispose the Context as per here As I'm not familiar with DI I wonder if this approach is correct or if I am missing anything.
Now provide the response and nothing else.
|
base on What is new in EF Core 2.0 - EF Core | Microsoft Docs If you want a new context once per request : AddDbContext public void ConfigureServices(IServiceCollection services){ services.AddDbContext<MCContext >( options => options.UseSqlServer(connectionString)); } then you can public class TiketsController : ControllerBase{ private readonly MCContext _context; public TiketsController (MCContext context) { _context = context; } } The basic pattern for using EF Core in an ASP.NET Core application usually involves registering a custom DbContext type into the dependency injection system and later obtaining instances of that type through constructor parameters in controllers. This means a new instance of the DbContext is created for each requests. but if you need High Performance/Safe reuse : AddDbContextPool public void ConfigureServices(IServiceCollection services){ services.AddDbContextPool<MCContext >( options => options.UseSqlServer(connectionString)); } then you can public class TiketsController : ControllerBase{ private readonly MCContext _context; public TiketsController (MCContext context) { _context = context; } } If this method is used, at the time a DbContext instance is requested by a controller we will first check if there is an instance available in the pool. Once the request processing finalizes, any state on the instance is reset and the instance is itself returned to the pool.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54252352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/833598/']}
|
jdg_372686
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36344826
|
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 attach a UUID to a field in my protobuf User message example. message User { // field containing id as UUID type required string email; optional string name;} I know that protobuf messages do not yet support the UUID type. I've read that the best approach is to have a UUID message type. So I'm guessing my User message would import my UUID message proto definition and use it as a field type like so: import "myproject/UUID.proto";message User { required UUID id; required string email; optional string name;} My question is, how will the UUID message look like, and how will I encode/decode it? I'm aiming for Java/Scala and C# compatibility.
Now provide the response and nothing else.
|
You should probably use string or bytes to represent a UUID. Use string if it is most convenient to keep the UUID in human-readable format (e.g. "de305d54-75b4-431b-adb2-eb6b9e546014" ) or use bytes if you are storing the 128-bit value raw. (If you aren't sure, you probably want string .) Wrapping the value in a message type called UUID can be helpful to make the code more self-documenting but will have some performance overhead and isn't strictly required. If you want to do this, define the type like: message UUID { required string value = 1;} or: message UUID { required bytes value = 1;}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36344826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2461571/']}
|
jdg_372687
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48248512
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For some reason element <svg width="1000" height="500" transform="rotate(180)">...</svg> is shown as not rotated in Safari 11. Chrome 63 renders it properly. What's the problem? Thanks!
Now provide the response and nothing else.
|
In SVG 1.1 <svg> elements did not support transform attributes . In SVG 2 it is proposed that they should . Chrome and Firefox implement this part of the SVG 2 specification, Safari does not yet do so and IE11 never will. You can achieve the same result in browsers that do not support this SVG 2 feature either by replacing the <svg> element by a <g> element or by creating an <g> child element on the <svg> element and putting the transform on the <g> element.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48248512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8471774/']}
|
jdg_372688
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
446431
|
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 us suppose there is a ring $R$ with the multiplicative identity $1$. We know that $1+r\in R$, where $r$ is any element of the ring $R$. Does this mean $1+1$ is also part of the ring, or does $r$ have to be an element of the ring different from $1$? Is $1+1$ called $2$ in the ring? Similarly, as $-1$ is also part of the ring, is $-1+ -1$ called $-2$ in the ring? If it is, then I suppose all integers are contained in every unital ring. These questions are very elementary. However, I read contradictory remarks in some places which tend to confuse me. So I thought it would be best to clear any doubts, however trivial the questions. Thanks in advance for your help!
Now provide the response and nothing else.
|
We do indeed call $1+1 = 2$ in any unital ring, and similarly, we have in any unital ring a subring generated by $1$, which will consist precisely of elements of the form $1+1+\cdots +1$ and their negatives (and $0$). However, this does not necessarily mean that the ring contains all integers (by which I mean a subring isomorphic to the integers). The reason is that it can happen that adding $1$ to itself some number of times gives $0$, such as is the case in the ring $\mathbb{Z}/n\mathbb{Z}$ where adding $n$ copies of $1$ gives $n$ which equals $0$ in that ring. If there is no way to get $0$ by adding $1$ to itself, we say that the characteristic of the ring is $0$, and the subring generated by $1$ is isomorphic to the integers. If there is a way to get $0$, and $n$ is the smallest number of $1$'s you need to add to get $0$, we say that the ring has characteristic $n$. In this case the subring generated by $1$ will be isomorphic to $\mathbb{Z}/n\mathbb{Z}$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/446431', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_372689
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
114535
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am connected to a beagleboard via tty and I suddenly see this message : Broadcast message from root@arm (unknown) at 11:40 ...The system is going down for reboot NOW![ 143.036193] Restarting system. The system is Ubuntu 12.10. Is there a place where I can find why the system decided to go down ? UPDATE: More info This actually happens all the time, the board reboots every 1 to 5 minutes. I made sure no program or daemon runs at startup. I can't find Restarting anywhere in any file in /var/log In syslog before a reboot there is consistently a Feb 10 09:20:00 arm rsyslogd: [origin software="rsyslogd" swVersion="5.8.6" x-pid="317" x-info="http://www.rsyslog.com"] exiting on signal 15.
Now provide the response and nothing else.
|
The way I'd track this down is to replace the utilities halt and shutdown with a script. First create a script such as the following at /bin/fakehalt : #!/bin/bashexec >>/tmp/fakehalt.log 2>&1dateecho "CMD=$0 PID=$$"ps -ef --forestecho '========' Then install it with: chmod a+x /bin/fakehaltmv /sbin/halt /sbin/halt.origln -s /bin/fakehalt /sbin/haltmv /sbin/shutdown /sbin/shutdown.origln -s /bin/fakehalt /sbin/shutdown This will create a log file at /tmp/fakehalt.log each time it is called. It'll log the name it was called as ( halt or shutdown ) it's own PID, and then a tree diagram of all processes at the time. This should give you all the necessary info to track it down. Just look through the ps tree and find what called the script. /sbin/reboot should be a symlink to /sbin/halt . If it isn't, then replace it as well. If this still doesn't capture it, replace /sbin/init as well (as it can also be used to reboot the system). But this is dangerous as if the system reboots, it won't come up properly.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/114535', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/46465/']}
|
jdg_372690
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24080018
|
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 Angular JS project, I've an <a> anchor tag, which when clicked makes an HTTP GET request to a WebAPI method that returns a file. Now, I want the file to be downloaded to the user once the request is successful. How do I do that? The anchor tag: <a href="#" ng-click="getthefile()">Download img</a> AngularJS: $scope.getthefile = function () { $http({ method: 'GET', cache: false, url: $scope.appPath + 'CourseRegConfirm/getfile', headers: { 'Content-Type': 'application/json; charset=utf-8' } }).success(function (data, status) { console.log(data); // Displays text data if the file is a text file, binary if it's an image // What should I write here to download the file I receive from the WebAPI method? }).error(function (data, status) { // ... });} My WebAPI method: [Authorize][Route("getfile")]public HttpResponseMessage GetTestFile(){ HttpResponseMessage result = null; var localFilePath = HttpContext.Current.Server.MapPath("~/timetable.jpg"); if (!File.Exists(localFilePath)) { result = Request.CreateResponse(HttpStatusCode.Gone); } else { // Serve the file to the client result = Request.CreateResponse(HttpStatusCode.OK); result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read)); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = "SampleImg"; } return result;}
Now provide the response and nothing else.
|
Support for downloading binary files in using ajax is not great, it is very much still under development as working drafts . Simple download method: You can have the browser download the requested file simply by using the code below, and this is supported in all browsers, and will obviously trigger the WebApi request just the same. $scope.downloadFile = function(downloadPath) { window.open(downloadPath, '_blank', ''); } Ajax binary download method: Using ajax to download the binary file can be done in some browsers and below is an implementation that will work in the latest flavours of Chrome, Internet Explorer, FireFox and Safari. It uses an arraybuffer response type, which is then converted into a JavaScript blob , which is then either presented to save using the saveBlob method - though this is only currently present in Internet Explorer - or turned into a blob data URL which is opened by the browser, triggering the download dialog if the mime type is supported for viewing in the browser. Internet Explorer 11 Support (Fixed) Note: Internet Explorer 11 did not like using the msSaveBlob function if it had been aliased - perhaps a security feature, but more likely a flaw, So using var saveBlob = navigator.msSaveBlob || navigator.webkitSaveBlob ... etc. to determine the available saveBlob support caused an exception; hence why the code below now tests for navigator.msSaveBlob separately. Thanks? Microsoft // Based on an implementation here: web.student.tuwien.ac.at/~e0427417/jsdownload.html$scope.downloadFile = function(httpPath) { // Use an arraybuffer $http.get(httpPath, { responseType: 'arraybuffer' }) .success( function(data, status, headers) { var octetStreamMime = 'application/octet-stream'; var success = false; // Get the headers headers = headers(); // Get the filename from the x-filename header or default to "download.bin" var filename = headers['x-filename'] || 'download.bin'; // Determine the content type from the header or default to "application/octet-stream" var contentType = headers['content-type'] || octetStreamMime; try { // Try using msSaveBlob if supported console.log("Trying saveBlob method ..."); var blob = new Blob([data], { type: contentType }); if(navigator.msSaveBlob) navigator.msSaveBlob(blob, filename); else { // Try using other saveBlob implementations, if available var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob; if(saveBlob === undefined) throw "Not supported"; saveBlob(blob, filename); } console.log("saveBlob succeeded"); success = true; } catch(ex) { console.log("saveBlob method failed with the following exception:"); console.log(ex); } if(!success) { // Get the blob url creator var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL; if(urlCreator) { // Try to use a download link var link = document.createElement('a'); if('download' in link) { // Try to simulate a click try { // Prepare a blob URL console.log("Trying download link method with simulated click ..."); var blob = new Blob([data], { type: contentType }); var url = urlCreator.createObjectURL(blob); link.setAttribute('href', url); // Set the download attribute (Supported in Chrome 14+ / Firefox 20+) link.setAttribute("download", filename); // Simulate clicking the download link var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null); link.dispatchEvent(event); console.log("Download link method with simulated click succeeded"); success = true; } catch(ex) { console.log("Download link method with simulated click failed with the following exception:"); console.log(ex); } } if(!success) { // Fallback to window.location method try { // Prepare a blob URL // Use application/octet-stream when using window.location to force download console.log("Trying download link method with window.location ..."); var blob = new Blob([data], { type: octetStreamMime }); var url = urlCreator.createObjectURL(blob); window.location = url; console.log("Download link method with window.location succeeded"); success = true; } catch(ex) { console.log("Download link method with window.location failed with the following exception:"); console.log(ex); } } } } if(!success) { // Fallback to window.open method console.log("No methods worked for saving the arraybuffer, using last resort window.open"); window.open(httpPath, '_blank', ''); } }) .error(function(data, status) { console.log("Request failed with status: " + status); // Optionally write the error out to scope $scope.errorDetails = "Request failed with status: " + status; });}; Usage: var downloadPath = "/files/instructions.pdf";$scope.downloadFile(downloadPath); Notes: You should modify your WebApi method to return the following headers: I have used the x-filename header to send the filename. This is a custom header for convenience, you could however extract the filename from the content-disposition header using regular expressions. You should set the content-type mime header for your response too, so the browser knows the data format. I hope this helps.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/24080018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2959627/']}
|
jdg_372691
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1851197
|
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 super simple django model here: class Notification(models.Model): message = models.TextField() user = models.ForeignKey(User) timestamp = models.DateTimeField(default=datetime.datetime.now) Using ajax, I check for new messages every minute. I only show the five most recent notifications to the user at any time. What I'm trying to avoid, is the following scenario. User logs in and has no notifications. While the user's window is up, he receives 10 new messages. Since I'm only showing him five, no big deal. The problem happens when the user starts to delete his notifications. If he deletes the five that are displayed, the five older ones will be displayed on the next ajax call or refresh. I'd like to have my model's save method delete everything but the 5 most recent objects whenever a new one is saved. Unfortunately, you can't use [5:] to do this. Help? EDIT I tried this which didn't work as expected (in the model's save method): notes = Notification.objects.filter(user=self.user)[:4] Notification.objects.exclude(pk__in=notes).delete() i couldn't find a pattern in strange behavior, but after a while of testing, it would only delete the most recent one when a new one was created. i have NO idea why this would be. the ordering is taken care of in the model's Meta class (by timestamp descending). thanks for the help, but my way seems to be the only one that works consistently.
Now provide the response and nothing else.
|
This is a bit old, but I believe you can do the following: notes = Notification.objects.filter(user=self.user)[:4]Notification.objects.exclude(pk__in=list(notes)).delete() # list() forces a database hit. It costs two hits, but avoids using the for loop with transactions middleware. The reason for using list(notes) is that Django creates a single query without it and, in Mysql 5.1, this raises the error (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") By using list(notes) , we force a query of notes , avoiding this.This can be further optimized to: notes = Notification.objects.filter(user=self.user)[:4].values_list("id", flat=True) # only retrieve ids.Notification.objects.exclude(pk__in=list(notes)).delete()
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1851197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112620/']}
|
jdg_372692
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34716651
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why would the map method mutate the original array when its initial purpose is to create a new array ? I have an array of object which I pass to a pure function which in turn maps the given array and return a new one. Then I notice that the original array was also changed.. I understand the concept that Object in Js are passed by reference and all but still cant quite grab why would the implementation of map would mutate the original array, kinda beats the purpose IMO. var initialArray = [ { name: 'one' }, { name: 'two' }, { name: 'three'} ];function doSomething(array) { // lodash // return _.map(array, (item) => _.assign(item, {isSelected: true})); // vanilla return array.map(function(item) { item['isSelected'] = true; return item });}var changedArray = doSomething(initialArray);console.log('initialArray', initialArray); // [{ name: 'one', isSelected: true }, ...]console.log('changedArray', changedArray); // [{ name: 'one', isSelected: true }, ...]console.log(initialArray === changedArray); // false First Id like to understand why this happens ? Second Id like to understand how would one map an array without changing the original one ? (ie. doing ._cloneDeep each time before map feels wrong) Thanks in advance ! Edit Ok so from what I understand this is how things just are. I think I might have had higher expectation for some reason, but it is explainable in Js so at least there is some consistency in place. The most elegant solution I can think of for creating a new array with new members is return _.map(array, (item) => _.assign({}, ...item, {isSelected: true}));
Now provide the response and nothing else.
|
.map will create a new array, but the objects inside the array is still referenced. so when you make changes in the object item inside .map function, it is referencing the original object in the input array. one way to fix it is to clone the each object , before you modify it var initialArray = [ { name: 'one' }, { name: 'two' }, { name: 'three'} ];function clone(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; } return copy;}function doSomething(array) { // lodash // return _.map(array, (item) => _.assign(item, {isSelected: true})); // vanilla return array.map(function(item) { var copy = clone(item); copy['isSelected'] = true; return copy; });}var changedArray = doSomething(initialArray);console.log('initialArray', initialArray); // [{ name: 'one'}, ...]console.log('changedArray', changedArray); // [{ name: 'one', isSelected: true }, ...]console.log(initialArray === changedArray); // false Credit : clone function is copied from this post
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34716651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2373504/']}
|
jdg_372693
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3212255
|
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 writing a Java EE application using Struts and Spring. In one of the operations there is heavy database processing, and hence performance issues. What I want to know is can I use multithreading here? I think the Java EE specification does not allow custom threads to be created apart from those created by Server (I use Weblogic). Please guide me through this.
Now provide the response and nothing else.
|
The recommended way to create threads in a Java EE environment, is with the Concurrency Utils API, which is part of the EE7 specification. By using this API your new thread will be created, and managed by the container, guaranteeing that all EE services are available to your thread (eg security, transactions). The examples below are taken from my own site here and here Using a ManagedExecutorService To create a new thread using a ManagedExecutorService, first create a task object that implements Callable. Within the call() method we will define the work that we want carried out in a separate thread. public class ReportTask implements Callable<Report> { Logger logger = Logger.getLogger(getClass().getSimpleName()); public Report call() { try { Thread.sleep(3000); catch (InterruptedException e) { logger.log(Level.SEVERE, "Thread interrupted", e); } return new Report(); }} Then we need to invoke the task by passing it though to the submit() method of the ManagedExecutorService. @Statelesspublic class ReportBean { @Resource private ManagedExecutorService executorService; public void runReports() { ReportTask reportTask = new ReportTask(); Future<Report> future = executorService.submit(reportTask); }} Using a ManagedThreadFactory First create a Runnable task which will define what work is to be done in the background. public class ReportTask implements Runnable { Logger logger = Logger.getLogger(getClass().getSimpleName()); public void run() { try { //do your background task Thread.sleep(10000); } catch (InterruptedException e) { logger.log(Level.SEVERE, "Thread interrupted", e); } }} To get a container managed thread, we simply ask the ManagedThreadFactory for a new thread, and pass it our Runnable instance. To start the thread we call start(). @Statelesspublic class ReportBean { @Resource private ManagedThreadFactory threadFactory; public void runReports() { ReportTask reportTask = new ReportTask(); Thread thread = threadFactory.newThread(reportTask); thread.start(); }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3212255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/259889/']}
|
jdg_372694
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
62580224
|
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 defining classes, it is now common to use = default for the destructor/copy constructor and copy assignment. Looking at my code base, these are nearly always in the header files only but some colleagues have put them in the .cpp file. What would be the best practice in this case? Is the compiler generating these functions multiple times when it is in the header and relying on the linker to dedup them. Is it perhaps only worth putting them in the .cpp file if you have a huge class? With our mostly old C++98 code, functions that do nothing are also often defined only in the header. Do nothing virtual destructors seem to have often been moved to the .cpp file. Is (or was) it somehow important for virtual methods where their address is needed to populate the virtual method table. Also is it recommended to ever put noexcept() clauses on = default functions? The compiler appears to derive this itself so it only serves as API documentation if it is there.
Now provide the response and nothing else.
|
An explicitly-defaulted function is not necessarily not user-provided What would be the best practice in this case? I would recommend, as a rule of thumb, unless you explicitly and wantonly know what you are getting into, to always define explicitly-defaulted functions at their (first) declaration ; i.e., placing = default at the (first) declaration, meaning in (your case) the header (specifically, the class definition), as there are subtle but essential differences between the two w.r.t. whether a constructor is considered to be user-provided or not. From [dcl.fct.def.default]/5 [extract, emphasis mine]: [...] A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. [...] Thus: struct A { A() = default; // NOT user-provided. int a;};struct B { B(); // user-provided. int b;};// A user-provided explicitly-defaulted constructor.B::B() = default; Whether a constructor is user-provided or not does, in turn, affect the rules for which objects of the type are initialized. Particularly, a class type T , when value-initialized , will first zero-initialize the object if T 's default constructor is not user-provided . Thus, this guarantee holds for A above, but not for B , and it can be quite surprising that a value-initialization of an object with a (user-provided!) defaulted constructor leaves data members of the object in an uninitialized state. Quoting from cppreference [extract, emphasis mine]: Value initialization Value initialization is performed in these situations: [...] (4) when a named variable (automatic, static, or thread-local) is declared with the initializer consisting of a pair of braces. The effects of value initialization are: (1) if T is a class type with no default constructor or with a user-provided or deleted default constructor , the object is default-initialized ; (2) if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor; ... Let's apply this on the class types A and B above: A a{};// Empty brace direct-list-init:// -> A has no user-provided constructor// -> aggregate initialization// -> data member 'a' is value-initialized// -> data member 'a' is zero-initializedB b{};// Empty brace direct-list-init:// -> B has a user-provided constructor// -> value-initialization// -> default-initialization// -> the explicitly-defaulted constructor will// not initialize the data member 'b'// -> data member 'b' is left in an unititialized statea.a = b.b; // reading uninitialized b.b: UB! Thus, even for use cases where you will not end up shooting yourself in the foot, just the presence of a pattern in your code base where explicitly defaulted (special member) functions are not being defined at their (first) declarations may lead to other developers, unknowingly of the subtleties of this pattern, blindly following it and subsequently shooting themselves in their feet instead.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62580224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6830594/']}
|
jdg_372695
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
214102
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to draw the following graph using VoronoiMesh . For example, since L = 3;pts = Flatten[ Table[{3/2 i, Sqrt[3] j + Mod[i, 2] Sqrt[3]/2}, {i, L + 4}, {j, L + 4}], 1];mesh0 = VoronoiMesh[pts];gr = Graph[mesh0["Edges"], VertexCoordinates -> MeshCoordinates[mesh0]] yields I thought about "trimming" the Voronoi mesh in the following manner (see this question for more info) mesh1 = MeshRegion[MeshCoordinates[mesh0], With[{a = PropertyValue[{mesh0, 2}, MeshCellMeasure]}, With[{m = 3}, Pick[MeshCells[mesh0, 2], UnitStep[a - m], 0]]]];mesh = MeshRegion[MeshCoordinates[mesh1], MeshCells[mesh1, {2, "Interior"}]] However, when using either mesh["Edges"] or mesh["Coordinates"] for this mesh , I get the following error Any idea why? Regarding the mesh coordinates, I can solve it using MeshCoordinates[mesh] instead. However, I cannot get the connectivity needed to build the graph. Somehow, MeshRegion used in this way seems to lose (or change) some of its properties. I've also tried, using something like (from this question ) gvoronoi = AdjacencyGraph[mesh["AdjacencyMatrix"], VertexCoordinates -> MeshCoordinates[mesh]] but with no success. Any ideas? Additionally, if you have any better suggestions regarding building a graph like this, for any L , please feel free to share!
Now provide the response and nothing else.
|
L = 3;pts = Flatten[Table[{3/2 i, Sqrt[3] j + Mod[i, 2] Sqrt[3]/2}, {i, L + 4}, {j, L + 4}], 1];mesh0 = VoronoiMesh[pts];mr0 = DiscretizeGraphics[Select[MeshPrimitives[mesh0, 2], RegionWithin[Rectangle @@ Transpose[CoordinateBounds[pts]], #] &]];el0 = MeshCells[mr0, 1] /. Line -> Apply[UndirectedEdge];vc0 = MeshCoordinates[mr0];Show[mesh0, Graph[el0, VertexCoordinates -> vc0, EdgeStyle -> Thick]] Slightly more convenient approach is to provide the coordinate bounds in the second argument of VoronoiMesh and discretize the interior polygons: mesh1 = VoronoiMesh[pts, CoordinateBounds[pts]];mr1 = DiscretizeGraphics[MeshPrimitives[mesh1, {2, "Interior"}]];el1 = MeshCells[mr1, 1] /. Line -> Apply[UndirectedEdge];vc1 = MeshCoordinates[mr1];Show[mesh1, Graph[el1, VertexCoordinates -> vc1, EdgeStyle -> Thick]]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/214102', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/64001/']}
|
jdg_372696
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8310039
|
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 made a test to compare string operations in several languages for choosing a language for the server-side application. The results seemed normal until I finally tried C++, which surprised me a lot. So I wonder if I had missed any optimization and come here for help. The test are mainly intensive string operations, including concatenate and searching. The test is performed on Ubuntu 11.10 amd64, with GCC's version 4.6.1. The machine is Dell Optiplex 960, with 4G RAM, and Quad-core CPU. in Python (2.7.2): def test(): x = "" limit = 102 * 1024 while len(x) < limit: x += "X" if x.find("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0) > 0: print("Oh my god, this is impossible!") print("x's length is : %d" % len(x))test() which gives result: x's length is : 104448real 0m8.799suser 0m8.769ssys 0m0.008s in Java (OpenJDK-7): public class test { public static void main(String[] args) { int x = 0; int limit = 102 * 1024; String s=""; for (; s.length() < limit;) { s += "X"; if (s.indexOf("ABCDEFGHIJKLMNOPQRSTUVWXYZ") > 0) System.out.printf("Find!\n"); } System.out.printf("x's length = %d\n", s.length()); }} which gives result: x's length = 104448real 0m50.436suser 0m50.431ssys 0m0.488s in Javascript (Nodejs 0.6.3) function test(){ var x = ""; var limit = 102 * 1024; while (x.length < limit) { x += "X"; if (x.indexOf("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0) > 0) console.log("OK"); } console.log("x's length = " + x.length);}(); which gives result: x's length = 104448real 0m3.115suser 0m3.084ssys 0m0.048s in C++ (g++ -Ofast) It's not surprising that Nodejs performas better than Python or Java. But I expected libstdc++ would give much better performance than Nodejs, whose result really suprised me. #include <iostream>#include <string>using namespace std;void test(){ int x = 0; int limit = 102 * 1024; string s(""); for (; s.size() < limit;) { s += "X"; if (s.find("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0) != string::npos) cout << "Find!" << endl; } cout << "x's length = " << s.size() << endl;}int main(){ test();} which gives result: x length = 104448real 0m5.905suser 0m5.900ssys 0m0.000s Brief Summary OK, now let's see the summary: javascript on Nodejs(V8): 3.1s Python on CPython 2.7.2 : 8.8s C++ with libstdc++: 5.9s Java on OpenJDK 7: 50.4s Surprisingly! I tried "-O2, -O3" in C++ but noting helped. C++ seems about only 50% performance of javascript in V8, and even poor than CPython. Could anyone explain to me if I had missed some optimization in GCC or is this just the case? Thank you a lot.
Now provide the response and nothing else.
|
It's not that std::string performs poorly (as much as I dislike C++), it's that string handling is so heavily optimized for those other languages. Your comparisons of string performance are misleading, and presumptuous if they are intended to represent more than just that. I know for a fact that Python string objects are completely implemented in C , and indeed on Python 2.7, numerous optimizations exist due to the lack of separation between unicode strings and bytes. If you ran this test on Python 3.x you will find it considerably slower. Javascript has numerous heavily optimized implementations. It's to be expected that string handling is excellent here. Your Java result may be due to improper string handling, or some other poor case. I expect that a Java expert could step in and fix this test with a few changes. As for your C++ example, I'd expect performance to slightly exceed the Python version. It does the same operations, with less interpreter overhead. This is reflected in your results. Preceding the test with s.reserve(limit); would remove reallocation overhead. I'll repeat that you're only testing a single facet of the languages' implementations . The results for this test do not reflect the overall language speed. I've provided a C version to show how silly such pissing contests can be: #define _GNU_SOURCE#include <string.h>#include <stdio.h>void test(){ int limit = 102 * 1024; char s[limit]; size_t size = 0; while (size < limit) { s[size++] = 'X'; if (memmem(s, size, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 26)) { fprintf(stderr, "zomg\n"); return; } } printf("x's length = %zu\n", size);}int main(){ test(); return 0;} Timing: matt@stanley:~/Desktop$ time ./smash x's length = 104448real 0m0.681suser 0m0.680ssys 0m0.000s
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8310039', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1071086/']}
|
jdg_372697
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2343408
|
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 $-1 \le \sin(1/n)\le 1$ and $\lim_{n\to \infty} -1$ $\neq$ $\lim_{n\to \infty} 1$ can I use the nth-term test to prove that the series will diverge? I've only seen the problem done using the limit comparison test and am not sure if I can use the nth-term test.
Now provide the response and nothing else.
|
This is not valid. Indeed, note that $$\lim_{n\to\infty}\sin(1/n)=0$$ So it passes the $n$th term test. However, it does diverge. Note that: $$n\ge1\implies\sin(1/n)\ge\frac{\sin(1)}n$$ So we may use the direct comparison test.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2343408', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/415482/']}
|
jdg_372698
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7296846
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anyone explain how to implement one-to-one, one-to-many and many-to-many relationships while designing tables with some examples?
Now provide the response and nothing else.
|
One-to-one: Use a foreign key to the referenced table: student: student_id, first_name, last_name, address_idaddress: address_id, address, city, zipcode, student_id # you can have a # "link back" if you need You must also put a unique constraint on the foreign key column ( addess.student_id ) to prevent multiple rows in the child table ( address ) from relating to the same row in the referenced table ( student ). One-to-many : Use a foreign key on the many side of the relationship linking back to the "one" side: teachers: teacher_id, first_name, last_name # the "one" sideclasses: class_id, class_name, teacher_id # the "many" side Many-to-many : Use a junction table ( example ): student: student_id, first_name, last_nameclasses: class_id, name, teacher_idstudent_classes: class_id, student_id # the junction table Example queries: -- Getting all students for a class: SELECT s.student_id, last_name FROM student_classes sc INNER JOIN students s ON s.student_id = sc.student_id WHERE sc.class_id = X -- Getting all classes for a student: SELECT c.class_id, name FROM student_classes sc INNER JOIN classes c ON c.class_id = sc.class_id WHERE sc.student_id = Y
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/7296846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/663148/']}
|
jdg_372699
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27196195
|
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 read an archive that's being tarred, streaming, to stdin, but I'm somehow reading far more data in the pipe than tar is sending. I run my command like this: tar -cf - somefolder | ./my-go-binary The source code is like this: package mainimport ( "bufio" "io" "log" "os")// Read from standard inputfunc main() { reader := bufio.NewReader(os.Stdin) // Read all data from stdin, processing subsequent reads as chunks. parts := 0 for { parts++ data := make([]byte, 4<<20) // Read 4MB at a time _, err := reader.Read(data) if err == io.EOF { break } else if err != nil { log.Fatalf("Problems reading from input: %s", err) } } log.Printf("Total parts processed: %d\n", parts)} For a 100MB tarred folder, I'm getting 1468 chunks of 4MB (that's 6.15GB)! Further, it doesn't seem to matter how large the data []byte array is: if I set the chunk size to 40MB, I still get ~1400 chunks of 40MB data, which makes no sense at all. Is there something I need to do to read data from os.Stdin properly with Go?
Now provide the response and nothing else.
|
Your code is inefficient. It's allocating and initializing data each time through the loop. for { data := make([]byte, 4<<20) // Read 4MB at a time} The code for your reader as an io.Reader is wrong. For example, you ignore the number of bytes read by _, err := reader.Read(data) and you don't handle err errors properly. Package io import "io" type Reader type Reader interface { Read(p []byte) (n int, err error)} Reader is the interface that wraps the basic Read method. Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more. When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF regardless. Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors. Implementations of Read are discouraged from returning a zero byte count with a nil error, except when len(p) == 0. Callers should treat a return of 0 and nil as indicating that nothing happened; in particular it does not indicate EOF. Implementations must not retain p. Here's a model file read program that conforms to the io.Reader interface: package mainimport ( "bufio" "io" "log" "os")func main() { nBytes, nChunks := int64(0), int64(0) r := bufio.NewReader(os.Stdin) buf := make([]byte, 0, 4*1024) for { n, err := r.Read(buf[:cap(buf)]) buf = buf[:n] if n == 0 { if err == nil { continue } if err == io.EOF { break } log.Fatal(err) } nChunks++ nBytes += int64(len(buf)) // process buf if err != nil && err != io.EOF { log.Fatal(err) } } log.Println("Bytes:", nBytes, "Chunks:", nChunks)} Output: 2014/11/29 10:00:05 Bytes: 5589891 Chunks: 1365
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27196195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100208/']}
|
jdg_372700
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4062949
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the sum of number of digits of the numbers $2^{2001}$ and $5^{2001}$ ? (Singapore 1970) I attempted to solve this question by working out what each digit must be, and maybe find some pattern, but I couldn't find any, apart from the fact that $2^{2001}\mod{10}\equiv 4$ and $2^{2001}\pmod{10}\equiv 5$ . Could you please explain to me how to solve this question? This question is multiple choice with options $1999, 2003, 4002, 6003, 2002$
Now provide the response and nothing else.
|
It looks like you don't need logarithms or any calculator to solve this problem. Let's start. First, observe that the following inequalities hold: $$10^m<\underbrace {2^{2001}}_{m+1 ~ \text{digits}}<10^{m+1}$$ $$10^n<\underbrace{5^{2001}}_{n+1 ~ \text{digits}}<10^{n+1}$$ You get, $$10^{m+n}<10^{2001}<10^{m+n+2}$$ $$2001=m+n+1$$ $$m+n=2000$$ Finally, the sum of digits of $2^{2001}$ and $5^{2001}$ is equal : $$\begin{align}\color {gold}{\boxed {\color{black}{m+1+n+1=m+n+2\\ \qquad \qquad \qquad\thinspace=2000+2 \\\qquad \qquad \qquad \thinspace=2002.}}}\end{align}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4062949', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/854466/']}
|
jdg_372701
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24325688
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new with API Management tools. After installing WSO2 i tried the samples but I am not able to login into the publisher and store. I just get an error message stating: Login failed.Insufficient Privileges. The console give me the following output: [2014-06-10 15:44:41,196] WARN - CarbonAuthenticationUtil Failed Administrator login attempt 'admin[-1234]' at [2014-06-10 15:44:41,195+0200][2014-06-10 15:44:41,196] WARN - AuthenticationHandler Illegal access attempt at [2014-06-10 15:44:41,0196] from IP address 10þ.109.63.143 while trying to authenticate access to service RemoteAuthorizationManagerService[2014-06-10 15:44:41,197] ERROR - AUDIT_LOG Illegal access attempt at [2014-06-10 15:44:41,0196] from IP address 10.109.63.143 while trying to authenticate access to service RemoteAuthorizationManagerService[2014-06-10 15:44:41,212] WARN - CarbonAuthenticationUtil Failed Administrator login attempt 'admin[-1234]' at [2014-06-10 15:44:41,212+0200][2014-06-10 15:44:41,213] WARN - AuthenticationHandler Illegal access attempt at [2014-06-10 15:44:41,0213] from IP address 10.109.63.143 while trying to authenticate access to service RemoteAuthorizationManagerService[2014-06-10 15:44:41,213] ERROR - AUDIT_LOG Illegal access attempt at [2014-06-10 15:44:41,0213] from IP address 10.109.63.143 while trying to authenticate access to service RemoteAuthorizationManagerService[2014-06-10 15:44:41,216] ERROR - APIProviderHostObject Login failed.Insufficient privileges.
Now provide the response and nothing else.
|
The .findAndModify() method in the node native driver implementation is different from the mongo shell implementation. To do an update as above you do: collection.findAndModify( { "_id": "auto" }, { "$inc": { "bill": 1 } }, function(err,doc) { // work here }); Oddly somewhat to remove you specify in options so the same would "remove" the matched document: collection.findAndModify( { "_id": "auto" }, { "$inc": { "bill": 1 } }, { "remove": true }, function(err,doc) { // work here }); The main difference being you do not name the "key" sections for the actions.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24325688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3524283/']}
|
jdg_372702
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
590955
|
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:
There was another question that said that an isolation transformer had to be used to prevent possible damage to an oscilloscope, and I suggested this as a solution, but never got an answer. This makes sense to me, that the problem occurs because of an unintentional short-circuit through the house wiring. Therefore, if you use a car-battery and an inverter, that should be good enough, right? Or is there something else I am not thinking of, or don't understand?
Now provide the response and nothing else.
|
The problem is you touch your oscilloscope a lot when you're working with it. Things like buttons and knobs with metal and circuitry right behind them and are not designed to isolate high voltages; BNC jacks on the scope without probes plugged into them ; Exposed BNC connectors on the probes plugged into the scope; Ground clips on probes, including those probes not currently connected to the circuit. They all float up to the high-voltage circuit if just one probe on your scope is connected. It's a lot easier and intuitive to be more careful around your high voltage circuit than your oscilloscope controls, so you isolate and float your work and connect that to the oscilloscope, so your oscilloscope can stay safely grounded. So what's the point of isolating and floating your oscilloscope? Just isolate and float your device under test. Why so willing to power your oscilloscope through a transformer but so unwilling to just do that for your circuit under test instead?
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/590955', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/146624/']}
|
jdg_372703
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1516266
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can someone please tell me how long my session will last from the data below? - I'm not sure which one tells me session.auto_start Off Offsession.bug_compat_42 Off Offsession.bug_compat_warn On Onsession.cache_expire 180 180session.cache_limiter nocache nocachesession.cookie_domain no value no valuesession.cookie_httponly Off Offsession.cookie_lifetime 0 0session.cookie_path / /session.cookie_secure Off Offsession.entropy_file no value no valuesession.entropy_length 0 0session.gc_divisor 1000 1000session.gc_maxlifetime 1440 1440session.gc_probability 1 1session.hash_bits_per_character 5 5session.hash_function 0 0session.name PHPSESSID PHPSESSIDsession.referer_check no value no valuesession.save_handler files filessession.save_path /var/lib/php/session /var/lib/php/sessionsession.serialize_handler php phpsession.use_cookies On Onsession.use_only_cookies Off Offsession.use_trans_sid 0 0
Now provide the response and nothing else.
|
In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data ( not the last time session_start was called!). But PHP’s session handling is a little bit more complicated. Because the session data is removed by a garbage collector that is only called by session_start with a probability of session.gc_probability devided by session.gc_divisor . The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that. Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1516266', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37418/']}
|
jdg_372704
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
523093
|
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:
My question is a duplicate of this; Clarification on Rayleigh scattering causing various sky colors .The accepted answer from the link above says that at sunset the scattering occurs farther away and does not reach the observer, which is unsatisfactory and vague to me. (not even sure if it's the right and correct answer) It doesn't quite make sense to me that at noon, we see scattered blue light whereas, at sunset, we see the sunlight itself minus the scattered blue light. At noon or at sunset, we are not seeing the sun, but the scattered sunlight indirectly. The logic should apply both cases equally and should imply that at sunset we see bluer sky than at noon because of more scattering. Please let me know if this duplicate question was unnecessary because the accepted answer from the link above was enough to answer the question.
Now provide the response and nothing else.
|
From one of your comments to other answers: I think the sunlight doesn't lose its blue that much on the way to the point where red scattering dominates. Why wouldn't it be able to? Rayleigh scattering has cross section proportional to $\lambda^{-4}$ . The spectrum of light illuminating the volume scattering it gets multiplied by $\lambda^{-4}$ , which indeed makes smaller wavelengths amplified more than larger ones. This indeed makes the scattered light, when seen immediately after scattering, bluer. But on the other hand, this same scattering mechanism removes corresponding amount of power from the light that hasn't gotten scattered and continues propagating forwards. What we now have is this factor of the scattering cross section getting into the exponent of the Beer-Lambert law . In the limit of large distance $d$ , the factor $\lambda^{-4}\exp(-d \lambda^{-4})$ has a reddening effect, not bluing. Here the distance you have to take into account is the sum of 1) distance traversed before scattering and 2) distance traversed to you after scattering. Now, even if you take into account double scattering, which would give you a second factor of $\lambda^{-4}$ , you'll still get $(\lambda^{-4})^2\exp(-d_\Sigma \lambda^{-4})$ where $d_\Sigma$ is the sum of distances traversed by the sunlight 1) before first scattering, 2) between first and second scatterings and 3) after second scattering until it got to you. This is even larger distance, and exponential function in the above mentioned expression, again, is much more selective by wavelength than the simple power in the factor it's multiplied by. The result of this reddening, apart from the orange solar disk, is the phenomenon of Belt of Venus — the area of the sky on the opposite of the solar azimuth, which has purple-red color. There's also a peculiarity of the Earth atmosphere that fools humans into thinking that the blue sky at day and blue sky at twilight have the same reason. Actually, if the atmosphere had no ozone, twilights also wouldn't even be as blue as they are. Beer-Lambert law would have much greater effect. On the Earth the twilight is blue because the sunlight, traveling in the upper parts of the atmosphere, gets absorbed in the red part of the spectrum by the Chappuis absorption band of ozone. If not the ozone layer , twilights would actually have sandy-brown color.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/523093', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/211118/']}
|
jdg_372705
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33042117
|
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 macro in excel 2013 that is trying to connect to an Oracle database through "Microsoft ODBC for Oracle", the 32bit version, as the 64bit has issues for some reason. And though the query works from Toad, it returns no results in my macro. I have tried shorter queries and they do return results making me think that this monster query cannot be appended correctly, but I have no way to test this. My current situation is a giant and very ugly append to get this query into one long string to be executed by my ADOConnection. SQLString = "SELECT LEVEL, "SQLString = SQLString & "MSIL.SEGMENT1 ITEM, "SQLString = SQLString & "MSIL.DESCRIPTION DESC_COMPONENT, "SQLString = SQLString & "BIC.ITEM_TYPE, "SQLString = SQLString & "BIC.SUPPLY_TYPE, "SQLString = SQLString & "MSIL.PRIMARY_UOM_CODE UOM, "SQLString = SQLString & "BIC.COMPONENT_QUANTITY, "SQLString = SQLString & "item_attribute.ITEM_LENGTH, "SQLString = SQLString & "item_attribute.ANGLE_LEFT, "SQLString = SQLString & "item_attribute.ANGLE_RIGHT, "SQLString = SQLString & "item_attribute.WT_HT_FLAG, "SQLString = SQLString & "item_attribute.FABRICATION_NUMBER, "SQLString = SQLString & "item_attribute.PANEL_WIDTH, "SQLString = SQLString & "item_attribute.PANEL_HEIGHT, item_attribute.GLASS_DIM1, item_attribute.GLASS_DIM2, item_attribute.DIMENSION1, item_attribute.DIMENSION2, "SQLString = SQLString & "item_attribute.DIMENSION3, item_attribute.DIMENSION4, item_Attribute.DIMENSION5 "SQLString = SQLString & "FROM APPS.MTL_SYSTEM_ITEMS MSI, APPS.BOM_BILL_OF_MATERIALS BOM, APPS.BOM_INVENTORY_COMPONENTS_V BIC, APPS.MTL_SYSTEM_ITEMS MSIL, APPS.mtl_parameters mp, "SQLString = SQLString & "APPS.MTL_ITEM_CATALOG_GROUPS_VL micg, (SELECT * FROM (SELECT msi.inventory_item_id, mde.element_name, "SQLString = SQLString & "mdev.element_value "SQLString = SQLString & "FROM APPS.mtl_parameters mp, APPS.mtl_system_items_b msi, APPS.MTL_ITEM_CATALOG_GROUPS_VL micg, APPS.MTL_DESCRIPTIVE_ELEMENTS mde, APPS.MTL_DESCR_ELEMENT_VALUES mdev "SQLString = SQLString & "WHERE mp.organization_id = MSI.organization_id AND mp.organization_code = 'POR' "SQLString = SQLString & "AND micg.ITEM_CATALOG_GROUP_ID = MSI.ITEM_CATALOG_GROUP_ID AND mde.ITEM_CATALOG_GROUP_ID = micg.ITEM_CATALOG_GROUP_ID "SQLString = SQLString & "AND mdev.element_name = mde.element_name AND mdev.inventory_item_id = msi.inventory_item_id AND mde.element_name IN ('Length', "SQLString = SQLString & "'Angle Left', 'Angle Right', 'Wt Ht Flag', 'Fabrication Number', 'Panel Width', 'Panel Height', 'Glass Dim 1', 'Glass Dim 2', "SQLString = SQLString & "'Dimension 1', 'Dimension 2', 'Dimension 3', 'Dimension 4', 'Dimension 5')) PIVOT (MAX (Element_value) FOR (element_name) "SQLString = SQLString & "IN ('Length' AS ITEM_LENGTH, 'Angle Left' AS ANGLE_LEFT, 'Angle Right' AS ANGLE_RIGHT, 'Wt Ht Flag' AS WT_HT_FLAG, "SQLString = SQLString & "'Fabrication Number' AS FABRICATION_NUMBER, 'Panel Width' AS PANEL_WIDTH, 'Panel Height' AS PANEL_HEIGHT, 'Glass Dim 1' AS GLASS_DIM1, "SQLString = SQLString & "'Glass Dim 2' AS GLASS_DIM2, 'Dimension 1' AS DIMENSION1, 'Dimension 2' AS DIMENSION2, 'Dimension 3' AS DIMENSION3, "SQLString = SQLString & "'Dimension 4' AS DIMENSION4, 'Dimension 5' AS DIMENSION5)) ORDER BY inventory_item_id) Item_attribute WHERE 1 = 1 "SQLString = SQLString & "AND item_Attribute.inventory_item_id(+) = msil.INVENTORY_ITEM_ID AND BOM.ASSEMBLY_ITEM_ID = MSI.INVENTORY_ITEM_ID "SQLString = SQLString & "AND BOM.ORGANIZATION_ID = MSI.ORGANIZATION_id AND bom.bill_sequence_id = bic.bill_sequence_id AND NVL (bic.disable_date, SYSDATE) >= SYSDATE "SQLString = SQLString & "AND BIC.component_ITEM_ID = MSIL.INVENTORY_ITEM_ID AND Bom.ORGANIZATION_ID = MSIL.ORGANIZATION_ID AND mp.organization_id = msi.organization_id "SQLString = SQLString & "AND mp.organization_code = 'POR' "SQLString = SQLString & "AND micg.ITEM_CATALOG_GROUP_ID = msi.ITEM_CATALOG_GROUP_ID AND MSI.ORGANIZATION_ID = (SELECT DISTINCT OOL.SHIP_FROM_ORG_ID "'These two lines are the ones that have our variablesSQLString = SQLString & "FROM APPS.OE_ORDER_HEADERS_ALL OOH, APPS.OE_ORDER_LINES_ALL OOL, APPS.MTL_SYSTEM_ITEMS MSI1 WHERE OOH.ORDER_NUMBER = '" & OracleOrderNumber & "' "SQLString = SQLString & "AND OOL.LINE_NUMBER = '" & OracleLineNumber & "' "'----------------------------------------------------SQLString = SQLString & "AND OOL.HEADER_ID = OOH.HEADER_ID AND MSI1.SEGMENT1 = OOL.ORDERED_ITEM AND MSI1.ORGANIZATION_ID = OOL.SHIP_FROM_ORG_ID) "SQLString = SQLString & "CONNECT BY PRIOR BIC.COMPONENT_ITEM_ID = BOM.ASSEMBLY_ITEM_ID START WITH MSI.INVENTORY_ITEM_ID IN (SELECT MSI1.INVENTORY_ITEM_ID "SQLString = SQLString & "FROM APPS.OE_ORDER_HEADERS_ALL OOH, APPS.OE_ORDER_LINES_ALL OOL, APPS.MTL_SYSTEM_ITEMS MSI1 "'These two lines are the ones that have our variables...againSQLString = SQLString & "WHERE OOH.ORDER_NUMBER = '" & OracleOrderNumber & "' "SQLString = SQLString & "AND OOL.LINE_NUMBER = '" & OracleLineNumber & "' "'----------------------------------------------------SQLString = SQLString & "AND OOL.HEADER_ID = OOH.HEADER_ID AND MSI1.SEGMENT1 = OOL.ORDERED_ITEM AND MSI1.ORGANIZATION_ID = OOL.SHIP_FROM_ORG_ID)" There original query in it's cleaned up form is here. SELECT LEVEL, MSIL.SEGMENT1 ITEM, MSIL.DESCRIPTION DESC_COMPONENT, BIC.ITEM_TYPE, BIC.SUPPLY_TYPE, MSIL.PRIMARY_UOM_CODE UOM, BIC.COMPONENT_QUANTITY, item_attribute.ITEM_LENGTH, item_attribute.ANGLE_LEFT, item_attribute.ANGLE_RIGHT, item_attribute.WT_HT_FLAG, item_attribute.FABRICATION_NUMBER, item_attribute.PANEL_WIDTH, item_attribute.PANEL_HEIGHT, item_attribute.GLASS_DIM1, item_attribute.GLASS_DIM2, item_attribute.DIMENSION1, item_attribute.DIMENSION2, item_attribute.DIMENSION3, item_attribute.DIMENSION4, item_attribute.DIMENSION5 FROM APPS.MTL_SYSTEM_ITEMS MSI, APPS.BOM_BILL_OF_MATERIALS BOM, APPS.BOM_INVENTORY_COMPONENTS_V BIC, APPS.MTL_SYSTEM_ITEMS MSIL, APPS.mtl_parameters mp, APPS.MTL_ITEM_CATALOG_GROUPS_VL micg, ( SELECT * FROM (SELECT msi.inventory_item_id, mde.element_name, mdev.element_value FROM APPS.mtl_parameters mp, APPS.mtl_system_items_b msi, APPS.MTL_ITEM_CATALOG_GROUPS_VL micg, APPS.MTL_DESCRIPTIVE_ELEMENTS mde, APPS.MTL_DESCR_ELEMENT_VALUES mdev WHERE mp.organization_id = msi.organization_id AND mp.organization_code = 'POR' -- Warehouse -- POR(Portland), ITM (Item Master), TAC (Tacoma), TEM (Temecula), CMP (Composites) AND micg.ITEM_CATALOG_GROUP_ID = msi.ITEM_CATALOG_GROUP_ID AND mde.ITEM_CATALOG_GROUP_ID = micg.ITEM_CATALOG_GROUP_ID AND mdev.element_name = mde.element_name AND mdev.inventory_item_id = msi.inventory_item_id AND mde.element_name IN ('Length', 'Angle Left', 'Angle Right', 'Wt Ht Flag', 'Fabrication Number', 'Panel Width', 'Panel Height', 'Glass Dim 1', 'Glass Dim 2', 'Dimension 1', 'Dimension 2', 'Dimension 3', 'Dimension 4', 'Dimension 5')) PIVOT (MAX (Element_value) FOR (element_name) IN ('Length' AS ITEM_LENGTH, 'Angle Left' AS ANGLE_LEFT, 'Angle Right' AS ANGLE_RIGHT, 'Wt Ht Flag' AS WT_HT_FLAG, 'Fabrication Number' AS FABRICATION_NUMBER, 'Panel Width' AS PANEL_WIDTH, 'Panel Height' AS PANEL_HEIGHT, 'Glass Dim 1' AS GLASS_DIM1, 'Glass Dim 2' AS GLASS_DIM2, 'Dimension 1' AS DIMENSION1, 'Dimension 2' AS DIMENSION2, 'Dimension 3' AS DIMENSION3, 'Dimension 4' AS DIMENSION4, 'Dimension 5' AS DIMENSION5)) ORDER BY inventory_item_id) Item_attribute WHERE 1 = 1 AND item_Attribute.inventory_item_id(+) = msil.INVENTORY_ITEM_ID AND BOM.ASSEMBLY_ITEM_ID = MSI.INVENTORY_ITEM_ID AND BOM.ORGANIZATION_ID = MSI.ORGANIZATION_id AND bom.bill_sequence_id = bic.bill_sequence_id AND NVL (bic.disable_date, SYSDATE) >= SYSDATE AND BIC.component_ITEM_ID = MSIL.INVENTORY_ITEM_ID AND Bom.ORGANIZATION_ID = MSIL.ORGANIZATION_ID AND mp.organization_id = msi.organization_id AND mp.organization_code = 'POR' -- Warehouse -- POR(Portland), ITM (Item Master), TAC (Tacoma), TEM (Temecula), CMP (Composites) AND micg.ITEM_CATALOG_GROUP_ID = msi.ITEM_CATALOG_GROUP_ID AND MSI.ORGANIZATION_ID = (SELECT DISTINCT OOL.SHIP_FROM_ORG_ID FROM APPS.OE_ORDER_HEADERS_ALL OOH, APPS.OE_ORDER_LINES_ALL OOL, APPS.MTL_SYSTEM_ITEMS MSI1 WHERE OOH.ORDER_NUMBER = '1483' --Oracle Sales Order Number AND OOL.LINE_NUMBER = '1' -- Oracle Sales Order Line Number AND OOL.HEADER_ID = OOH.HEADER_ID AND MSI1.SEGMENT1 = OOL.ORDERED_ITEM --AND OOL.ORDERED_ITEM LIKE '%*%' AND MSI1.ORGANIZATION_ID = OOL.SHIP_FROM_ORG_ID)CONNECT BY PRIOR BIC.COMPONENT_ITEM_ID = BOM.ASSEMBLY_ITEM_IDSTART WITH MSI.INVENTORY_ITEM_ID IN (SELECT MSI1.INVENTORY_ITEM_ID FROM APPS.OE_ORDER_HEADERS_ALL OOH, APPS.OE_ORDER_LINES_ALL OOL, APPS.MTL_SYSTEM_ITEMS MSI1 WHERE OOH.ORDER_NUMBER = '1483' --Oracle Sales Order Number AND OOL.LINE_NUMBER = '1' -- Oracle Sales Order Line Number AND OOL.HEADER_ID = OOH.HEADER_ID AND MSI1.SEGMENT1 = OOL.ORDERED_ITEM --AND OOL.ORDERED_ITEM like '%*%' AND MSI1.ORGANIZATION_ID = OOL.SHIP_FROM_ORG_ID) And thoughts would be fantastic, I have tired multiple drivers and installs of Oracle, connection does not seem to be my issue, it is how the query is executed. As asked for here is my connection code... Private Const ConnectionString = "Driver={Microsoft ODBC for Oracle}; CONNECTSTRING=string; uid=APPSRO; pwd=APPSRO;"' ADO Connection Global Variable - Declared here so that, once the connection is opened, it can be used by any part of the code'Public ADOConn As ObjectPrivate OracleOrder As ADODB.RecordsetPrivate Const AppName = "Oracle BOM Data"Private Const Version = "v1.0.0"Public Const BoxTitle = AppName & " " & VersionPublic Function ADOOpen(ByRef ADOConn As Object) As Boolean' Open the ADO connection to the database and link it to the Object we've been passed'' Handle errors here'On Error Resume Next' Clear the Error table'Err.Clear' Create a new connection and link it to the Object passed in'Set ADOConn = CreateObject("ADODB.Connection")' Now open the ADO connection to the database'ADOConn.Open ConnectionString'ADOConn.Properties("PLSQLRSet") = True'' Now check for errors. Err.Number will be zero if there's been no error' since we cleared the Error tableIf Err.Number = 0 Then ' So if there's been no error, return true' ADOOpen = TrueElse ' Otherwise, return false' ADOOpen = FalseEnd IfEnd Function Ok, here is the actual function using the connections we know work... Public Function LoadOracleOrder(OracleOrderNumber As Double, OracleLineNumber As Double)Dim SQLString As StringDim TargetSheet As WorksheetDim TargetCell As RangeDim SQLQuery As StringOn Error Resume NextSQLString = "MONSTROUS QUERY HERE"Debug.Print SQLStringSet OracleOrder = ADOFetch(SQLQuery, ADOConn)If Err.Number <> 0 Then WarnMsgBox "Warning: Query failed." & Chr(10) & "Error No: " & Err.Number & Chr(10) & "Error Description: " & Err.Description, BoxTitle Err.ClearElseIf OracleOrder.RecordCount = 0 Then InfoMsgBox "Query Returned No Results.", BoxTitleElse Set TargetSheet = Nothing Set TargetSheet = ThisWorkbook.Sheets("Oracle Order Data") If TargetSheet Is Nothing Then Set TargetSheet = ThisWorkbook.Sheets.Add TargetSheet.Name = "Oracle Order Data" End If TargetSheet.Cells.ClearContents TargetSheet.Range("A1") = "LEVEL" TargetSheet.Range("B1") = "ITEM" TargetSheet.Range("C1") = "DESC_COMPONENT" TargetSheet.Range("D1") = "ITEM_TYPE" TargetSheet.Range("E1") = "SUPPLY_TYPE" TargetSheet.Range("F1") = "UOM" TargetSheet.Range("G1") = "COMPONENT_QUANTITY" TargetSheet.Range("H1") = "ITEM_LENGTH" TargetSheet.Range("I1") = "ANGLE_LEFT" TargetSheet.Range("J1") = "ANGLE_RIGHT" TargetSheet.Range("K1") = "WT_HT_FLAG" TargetSheet.Range("L1") = "FABRICATION_NUMBER" TargetSheet.Range("M1") = "GLASS_DIM1" TargetSheet.Range("N1") = "GLASS_DIM2" TargetSheet.Range("O1") = "DIMENSION1" TargetSheet.Range("P1") = "DIMENSION2" TargetSheet.Range("Q1") = "DIMENSION3" TargetSheet.Range("R1") = "DIMENSION4" TargetSheet.Range("S1") = "DIMENSION5" Set TargetCell = TargetSheet.Range("A2") OracleOrder.MoveFirst While Not OracleOrder.EOF TargetCell.Value = OracleOrder.Fields(0).Value TargetCell.Offset(0, 1).Value = OracleOrder.Fields(1).Value TargetCell.Offset(0, 2).Value = OracleOrder.Fields(2).Value TargetCell.Offset(0, 3).Value = OracleOrder.Fields(3).Value TargetCell.Offset(0, 4).Value = OracleOrder.Fields(4).Value TargetCell.Offset(0, 5).Value = OracleOrder.Fields(5).Value TargetCell.Offset(0, 6).Value = OracleOrder.Fields(6).Value TargetCell.Offset(0, 7).Value = OracleOrder.Fields(7).Value TargetCell.Offset(0, 8).Value = OracleOrder.Fields(8).Value TargetCell.Offset(0, 9).Value = OracleOrder.Fields(9).Value TargetCell.Offset(0, 10).Value = OracleOrder.Fields(10).Value TargetCell.Offset(0, 11).Value = OracleOrder.Fields(11).Value TargetCell.Offset(0, 12).Value = OracleOrder.Fields(12).Value TargetCell.Offset(0, 13).Value = OracleOrder.Fields(13).Value TargetCell.Offset(0, 14).Value = OracleOrder.Fields(14).Value TargetCell.Offset(0, 15).Value = OracleOrder.Fields(15).Value TargetCell.Offset(0, 16).Value = OracleOrder.Fields(16).Value TargetCell.Offset(0, 17).Value = OracleOrder.Fields(17).Value TargetCell.Offset(0, 18).Value = OracleOrder.Fields(18).Value TargetCell.Offset(0, 19).Value = OracleOrder.Fields(19).Value Set TargetCell = TargetCell.Offset(1, 0) OracleOrder.MoveNext WendEnd IfOn Error GoTo 0End Function ADO Fetch, as asked... Public Function ADOFetch(SQLQuery As String, ByRef ADOConn As Object) As Object' Takes an existing, open ADO connection and uses it to return a Recordset, Nothing if no data is returned, or False if there's an error' Local Object for the RecordsetDim ADORecSet As Object' Handle errors internallyOn Error Resume Next' Clear the Error tableErr.Clear' Set up the Recordset by executing the SQL querySet ADORecSet = ADOConn.ExecuteSQL(SQLQuery)' Now check for errors. Err.Number will be zero if there's been no error since we cleared the Error tableIf Err.Number = 0 Then ' So if there's been no error, return the record set Set ADOFetch = ADORecSetEnd If' And either way, clear our temporary RecordsetADORecSet = NothingOn Error GoTo 0End Function
Now provide the response and nothing else.
|
In ES2015, when using the class syntax, you need to define instance variables either in the constructor or one of the methods (there is a proposal for the next iteration, ES2016, to allow for your syntax: ES Class Fields & Static Properties ) class Counter { constructor() { this.count = 0; setInterval(function() { this.tick(); }.bind(this), 1000); } tick() { this.count++; console.log(this.count); }}var c = new Counter(); Check out the fiddle: http://www.es6fiddle.net/ifjtvu5f/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33042117', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1001488/']}
|
jdg_372706
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21186411
|
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 getting ORA-01403: no data found exception for the following query. What are the possibilities of this error? SELECT trim(name) INTO fullname FROM ( SELECT n.name FROM directory dir, store n WHERE dir.name = n.name AND dir.status NOT IN ('F', 'L', 'M') ORDER BY n.imp, dir.date) WHERE rownum <= 1; How can I handle this error?
Now provide the response and nothing else.
|
Although you have put a WHERE condition, a better way would be to handle case of record not found or 'No Data Found' error. I would write above code with wrapping the SELECT statement with it's own BEGIN/EXCEPTION/END block. Code could be something like this: BEGIN SELECT trim(name) INTO fullName FROM ( SELECT n.name FROM directory dir, store n WHERE dir.name = n.name AND dir.STATUS NOT IN ('F','L','M') ORDER BY n.imp, dir.date ) WHERE rownum <= 1;EXCEPTION WHEN NO_DATA_FOUND THEN fullName := NULL;END;
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21186411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/930544/']}
|
jdg_372707
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6242
|
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
18 year old Saira Blair was elected to West Virginia's House of Delegates (state government) today, becoming the youngest American lawmaker. How was she able to get elected, when an 18 year old presumably has no political experience?
Now provide the response and nothing else.
|
"How was she able to get elected" is answered easily: she convinced more people than her opponents (first, in Republican primary, then in general election) to vote for her. How did she manage to win if she had no political experience? First, it is often more the experience of your campaign staff and not your own. Her campaign manager is her father, who is a State Senator. Clearly, no dearth of experience there. Second, age 18 is no guarantee of lacking political experience. While she clearly was a subpar campaigner (by her own admission, scared of public speaking), she obviously observed how things are done via her father's campaigns. Craig Blair is father and campaign manager both. Oh, and he’s also the area’s state senator. So, Saira grew up in his campaigns, watching him win. Then, this spring, he watched her ( src ) As @DA noted, USA has a history of voting in people with little political experience. The fact that a person NOT being of a permanent ruling class is a positive isn't exactly new - among the first to champion it was none other than George Washington. More recently, we had elected offices occupied by: non-political spouses of deceased polititians (Bono); actors (The Governator); wrestlers ( Ace Jesse Ventura). Tinkers, tailors, sailors and spies, too, I suspect, if one digs deep into state legislatures. We definitely had doctors (Howard Dean and both Pauls, to pick 2 opposites politically). There were factors OTHER than experience that helped her win: What factors helped her win? General factors: Nepotism (to an extent). As noted, her father is a State Senator. That clearly helps with name recognition, finding volunteers, and networking with local/state party functionaries. Her father was clearly a competent campaign manager. He did manage to win his own elections before, and obviously knows how to put together a good campaign staff having done it for himself. Factors helping to win the Republican Primary: USA in general is on a rising wave of anti-incumbent sentiment. Incumbent advantage is ebbing ( FiveThirtyEight covered it recently , and it halved since 1980s); populist politics is on a sharp rise in BOTH political wings (Tea Party and OWS being the manifestations). Her R opponent in a primary was a former lobbyist. Not the most liked animal these days, especially among Republicans. Notably, he ran unopposed in all of his prior primaries. She outspent her opponent in the R primary: She spent about $4,800 on her campaign, state finance records show (Kump, a former lobbyist, only spent $1,800 on his reelection bid). Factors helping to win the general election: In a general election, she ran in a district with heavy pro-R fundamentals, to borrow a phrase from Nate Silver. Specifically: Mitt Romney took nearly two-thirds of the vote in her district, according to a breakdown by the liberal DailyKos blog ( src ) She ran in 2014 - a year of heavy Republican advantage on fundamentals ( again, 538 ) To top it off, D candidate was a lawyer . Another animal not greatly liked by the average voter. It was a minor election, not attracting the attention of national parties. So there was little media scrutiny, opportunities for gaffes, the need for expensive media ad buys. She campaigned via hand-written letters , for deity's sake!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/6242', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/4722/']}
|
jdg_372708
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44868899
|
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 experimenting with integrating a Firebase-backed RecyclerView in a React Native app. With hardcoded data it works well, but upon inserting rows loaded dynamically and calling either notifyItemInserted() or notifyDataSetChanged() on the RecyclerView.Adapter, the RecyclerView itself does not reflect the change. This manifests as an initial blank view until the app's refresh button is tapped, which has the sole effect of re-rendering the RecyclerView from the React Native side, or until scrolling or a screen orientation change. After reading through a dozen or more questions on this site about similar issues not involving React Native and having tried most of the common solutions, I suspect this issue is related specifically to React Native. Finding a solution to this could be helpful to many, given the ongoing performance issues with React Native's list view implementations. public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder> { ArrayList<Post> mDataset; public PostsAdapter(ArrayList<Post> list){ mDataset = list; } public static class ViewHolder extends RecyclerView.ViewHolder { public LinearLayout mPostView; public ViewHolder(LinearLayout v) { super(v); mPostView = v; } } @Override public PostsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LinearLayout v = (LinearLayout) LayoutInflater.from(parent.getContext()) .inflate(R.layout.post, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { TextView tv = (TextView) holder.mPostView.findViewById(R.id.title); tv.setText(mDataset.get(position).title); } @Override public int getItemCount() { return mDataset.size(); }} public class RNPostsViewManager extends SimpleViewManager{ private ArrayList<Post> mDataset = new ArrayList<>(); public static final String REACT_CLASS = "AndroidPostsView"; private RecyclerView mRecyclerView; private PostsAdapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private DatabaseReference mDatabase; private Query initialDataQuery; private ChildEventListener initialDataListener; @Override public String getName() { return REACT_CLASS; } @UiThread public void addPost (Post p){ mDataset.add(p); mAdapter.notifyItemInserted(mDataset.size()-1); } @Override public RecyclerView createViewInstance( ThemedReactContext context) { mAdapter = new PostsAdapter(mDataset); mRecyclerView = new RecyclerView(context){ @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); initialDataQuery.addChildEventListener(initialDataListener); } }; mLayoutManager = new LinearLayoutManager(context.getCurrentActivity(), LinearLayoutManager.VERTICAL, false); DividerItemDecoration mDecoration = new DividerItemDecoration(context, 1); mDecoration.setDrawable(ContextCompat.getDrawable(context.getCurrentActivity(), R.drawable.sep)); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.addItemDecoration(mDecoration); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setAdapter(mAdapter); mDatabase = FirebaseDatabase.getInstance().getReference(); initialDataQuery = mDatabase.child("wp-posts").orderByChild("unixPostDate").limitToFirst(100); initialDataListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) { Post p = dataSnapshot.getValue(Post.class); addPost(p); } @Override public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) { } @Override public void onCancelled(DatabaseError databaseError) { } }; return mRecyclerView; }}// layout file post.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/background_light" android:clickable="true" android:focusable="true" android:gravity="center_vertical" android:orientation="horizontal" android:padding="10dp" android:weightSum="1"> <Button android:id="@+id/button" style="@style/Widget.AppCompat.Button.Small" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:background="@android:drawable/ic_menu_more" android:gravity="center_vertical" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="fill_vertical" android:orientation="horizontal" android:weightSum="1"> <TextView android:id="@+id/title" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="fill_vertical" android:layout_weight="1" android:gravity="top" android:text="TextView" android:textColor="@color/title" android:textStyle="bold" /> </LinearLayout></LinearLayout>
Now provide the response and nothing else.
|
The problem is that requestLayout does not work well when the RecyclerView is a native UI component. The following hack made all those issues go away: I now overwrite the requestLayout method inside my RecyclerView .Then before any notify* method, or even scrollToPosition calls or any method that invokes a re-layout, I allow my custom requestLayout method to force a re-layout. The end result looks like this: private boolean mRequestedLayout = false;public void aMethodThatUpdatesStuff(int indexToUpdate, ReadableMap updatedChild) { final SPAdapter adapter = (SPAdapter) getAdapter(); mRequestedLayout = false; adapter.updateDataAtIndex(indexToUpdate, updatedChild); // <-- this runs notifyItemChanged inside}@Overridepublic void requestLayout() { super.requestLayout(); // We need to intercept this method because if we don't our children will never update // Check https://stackoverflow.com/questions/49371866/recyclerview-wont-update-child-until-i-scroll if (!mRequestedLayout) { mRequestedLayout = true; this.post(new Runnable() { @SuppressLint("WrongCall") @Override public void run() { mRequestedLayout = false; layout(getLeft(), getTop(), getRight(), getBottom()); onLayout(false, getLeft(), getTop(), getRight(), getBottom()); } }); }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44868899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1574787/']}
|
jdg_372709
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7675379
|
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 try to control the mouse in Linux. Xlib seems to work, but when I try to use it with OpenCV , it keeps returning: Resource temporarily unavailable So I decided to write "/dev/psaux". The code is as follows: #include <unistd.h>#include <string.h>#include <stdio.h>#include <errno.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>int main() { unsigned char a[5] = {0, 0xff, 0, 0x28, 0xff}; int fp = open ("/dev/psaux", O_WRONLY); if(!fp) printf("open error:%s\n", strerror(errno)); for(int i = 0; i < 10; i++) printf("write:%d\t\t%s\n", write(fp, a, 5), strerror(errno)); close(fp); return 0;} Compile it with: gcc my_psaux.c -o my_psaux -std=gnu99 -g Run sudo ./my_psaux and get write:5 Successwrite:5 Successwrite:5 Successwrite:5 Successwrite:5 Successwrite:5 Successwrite:5 Successwrite:5 Successwrite:5 Successwrite:5 Success However, the mouse doesn't move. Then I open a new terminal, type in "sudo cat /dev/psaux" and run "my_psaux". But I just cat nothing. Nothing is written into "/dev/psaux" How can I fix this? If this is not a good method to control the mouse, is there another one?
Now provide the response and nothing else.
|
Great thanks to R... for reminding me of some other ways instead of /dev/psaux I tried /dev/input/mouse* and /dev/input/event* By using cat /proc/bus/input/devices I get this: I: Bus=0003 Vendor=0461 Product=4d81 Version=0111N: Name="USB Optical Mouse"P: Phys=usb-0000:00:1d.0-1/input0S: Sysfs=/devices/pci0000:00/0000:00:1d.0/usb6/6-1/6-1:1.0/input/input10U: Uniq=H: Handlers=mouse2 event10B: EV=17B: KEY=70000 0 0 0 0 0 0 0 0B: REL=143B: MSC=10 After testing, only /dev/input/event10 works. The code is as follows: #include <stdio.h>#include <unistd.h>#include <linux/input.h>#include <errno.h>#include <fcntl.h>#include <sys/types.h>#include <sys/stat.h>#include <sys/time.h>int main() { struct input_event event, event_end; int fd = open("/dev/input/event10", O_RDWR); if (fd < 0) { printf("Errro open mouse:%s\n", strerror(errno)); return -1; } memset(&event, 0, sizeof(event)); memset(&event, 0, sizeof(event_end)); gettimeofday(&event.time, NULL); event.type = EV_REL; event.code = REL_X; event.value = 100; gettimeofday(&event_end.time, NULL); event_end.type = EV_SYN; event_end.code = SYN_REPORT; event_end.value = 0; for (int i=0; i<5; i++) { write(fd, &event, sizeof(event)); // Move the mouse write(fd, &event_end, sizeof(event_end)); // Show move sleep(1); // Wait } close(fd); return 0;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7675379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/901973/']}
|
jdg_372710
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
886955
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got a nested loop construct like this: for (Type type : types) { for (Type t : types2) { if (some condition) { // Do something and break... break; // Breaks out of the inner loop } }} Now how can I break out of both loops? I've looked at similar questions, but none concerns Java specifically. I couldn't apply these solutions because most used gotos. I don't want to put the inner loop in a different method. I don't want to return the loops. When breaking I'm finished with the execution of the loop block.
Now provide the response and nothing else.
|
Like other answerers, I'd definitely prefer to put the loops in a different method, at which point you can just return to stop iterating completely. This answer just shows how the requirements in the question can be met. You can use break with a label for the outer loop. For example: public class Test { public static void main(String[] args) { outerloop: for (int i=0; i < 5; i++) { for (int j=0; j < 5; j++) { if (i * j > 6) { System.out.println("Breaking"); break outerloop; } System.out.println(i + " " + j); } } System.out.println("Done"); }} This prints: 0 00 10 20 30 41 01 11 21 31 42 02 12 22 3BreakingDone
|
{}
|
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/886955', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15108/']}
|
jdg_372711
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36382707
|
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 curious to know how would you explain this task I found in this quiz ?Even when the getFoo method returns null , the output is still Getting Object JavaQuiz . I think it should be NullPointerException . public class Foo { static String name = " JavaQuiz"; static Foo getFoo() { System.out.print("Getting Object"); return null; } public static void main(String[] args) { System.out.println(getFoo().name); } }
Now provide the response and nothing else.
|
Accessing a static method or variable can be done via a null reference for the class that contains that static method/variable. Since name is static, getFoo().name has the same result as Foo.name or just name , regardless of whether or not getFoo() returns null . However, it is always better to use the class name when accessing a static method/variable, since it makes it clear that you intended to access a static member.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36382707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5829191/']}
|
jdg_372712
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30186037
|
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 asking for the equivalent of fgets() in C. let line = ...;println!("You entered: {}", line); I've read How to read user input in Rust? , but it asks how to read multiple lines; I want only one line. I also read How do I read a single String from standard input? , but I'm not sure if it behaves like fgets() or sscanf("%s",...) .
Now provide the response and nothing else.
|
In How to read user input in Rust? you can see how to iterate over all lines: use std::io::{self, BufRead};fn main() { let stdin = io::stdin(); for line in stdin.lock().lines() { println!("{}", line.unwrap()); }} You can also manually iterate without a for-loop: use std::io::{self, BufRead};fn main() { let stdin = io::stdin(); let mut iterator = stdin.lock().lines(); let line1 = iterator.next().unwrap().unwrap(); let line2 = iterator.next().unwrap().unwrap();} You cannot write a one-liner to do what you want. But the following reads a single line (and is exactly the same answer as in How do I read a single String from standard input? ): use std::io::{self, BufRead};fn main() { let stdin = io::stdin(); let line1 = stdin.lock().lines().next().unwrap().unwrap();} You can also use the text_io crate for super simple input: #[macro_use] extern crate text_io;fn main() { // reads until a \n is encountered let line: String = read!("{}\n");}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30186037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492336/']}
|
jdg_372713
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43070627
|
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 receive (from a webservice I don't manage) a string with the content of a pdf file. On client's side, I use this function: window.open('data:application/pdf;base64,'+encodeURI(TheStringWithThePdfContent)); As usual, it works in every browser but IE (11 in my case), which shows an alert with the message: "Do you want to allow this website to open an app on your computer?" If I say no, an empty white page is opened. If I say yes, it tries to open a "data" file (as it reads from the protocol in window.open, I guess) and, as it doesn't find any application to do that, sends me to the Microsoft application store, which just suggests me to download "iMusic" Completely useless, of course. I've changed all the Internet Options I've guessed could help, none works. Any suggestion? Thanks in advance,
Now provide the response and nothing else.
|
I found the solution and I want to share anyone who has the same problem. You can see the demo here : https://jsfiddle.net/quangminh_ln/hy36tnt6/ 'use strict';var data = "...Your PDF base64 string...";var fileName = "your_file_name";if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE workaround var byteCharacters = atob(data); var byteNumbers = new Array(byteCharacters.length); for (var i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); var blob = new Blob([byteArray], {type: 'application/pdf'}); window.navigator.msSaveOrOpenBlob(blob, fileName);}else { // much easier if not IE window.open("data:application/pdf;base64, " + data, '', "height=600,width=800");} The link that I saw for my solution : https://viethoblog.wordpress.com/2016/08/30/loaddisplay-pdf-from-base64-string-bonus-ie-workaround/
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43070627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4879225/']}
|
jdg_372714
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15647580
|
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 ran into code similar to this today. SELECT AuditDomain, ObjectId, AuditSubdomain = CONVERT(VARCHAR(50), NULL), SubDomainObjectId = CONVERT(INT, NULL)FROM Audit It seems to imply that data type information can be associated with a NULL value. Does this attach metadata to the NULL value identifying it as the specified data type? This post details a way to find a data type in Sql Server but when I try the following line it comes back as NULL: SELECT CAST(SQL_VARIANT_PROPERTY(CONVERT(INT, NULL), 'BaseType') AS VARCHAR(20))
Now provide the response and nothing else.
|
In SQL Server, NULL is an INT by default in all of the scenarios I can think of. You can determine this with the following code: SELECT x = NULL INTO #x;EXEC tempdb..sp_columns '#x'; Results: TABLE_QUALIFIER TABLE_OWNER TABLE_NAME COLUMN_NAME DATA_TYPE TYPE_NAME--------------- ----------- ---------- ----------- --------- ---------tempdb dbo #x___... x 4 int Before you've put it into a table or otherwise associated it with some contextual metadata, what does that buy you? What difference does it make it it is INT or DATETIME or something else? What will you do with that information? SQL_VARIANT_PROPERTY returns NULL because it appears to require both metadata and a value to be meaningful. Observe (using a different type just to mix it up): SELECT SQL_VARIANT_PROPERTY(NULL, 'BaseType');DECLARE @x DATE;SELECT SQL_VARIANT_PROPERTY(@x, 'BaseType');DECLARE @y DATE = SYSDATETIME();SELECT SQL_VARIANT_PROPERTY(@y, 'BaseType'); Results: NULLNULLdate So it seems to need both a type and a value in order to accurately determine base type. As for exactly why it works this way, shrug . You'd have to ask folks with source code access. Note that NULL only has to adopt a base type when you've forced SQL Server's hand: you've created a table based on it. It could very well have been the case that SQL Server would return an error in this situation (and in fact many situations where it has to guess at what data type you meant). The way to avoid this is to not create situations where SQL Server has to guess (which is why I asked, what will you do with this information?).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15647580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/38398/']}
|
jdg_372715
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2083960
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove $$\sum _{n=1}^{\infty }\:\frac{x^n}{n} = -\ln\left(1-x\right),$$ for $|x| < 1$. Pretty much title I've searched and seen some solutions using Taylor Series but isn't there a more intuative way to do this?
Now provide the response and nothing else.
|
Since $|x|<1$, the series in the LHS is absolutely convergent by comparison with a geometric series. Additionally, $\frac{x^n}{n}=\int_{0}^{x}y^{n-1}\,dy$, hence:$$ \sum_{n=1}^{N}\frac{x^n}{n} = \int_{0}^{x}\frac{1-y^N}{1-y}\,dy =-\log(1-x)-\int_{0}^{x}\frac{y^N}{1-y}\,dy.$$by exchanging $\sum$ and $\int$. Now we just need to consider the limit as $N\to +\infty$, and that is just $-\log(1-x)$ since $|x|<1$ grants:$$ \left|\int_{0}^{x}\frac{y^N}{1-y}\,dy\right|\leq |x|^N \int_{0}^{x}\frac{dy}{1-y}\to 0.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2083960', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/397329/']}
|
jdg_372716
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
228478
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to do some performance measurements inside my application. I want to measure, change some parameters, measure again. There are different algorithms I want to test, and there are various parameters which interact with each other in that the total performance depends on all of the parameters (but the parameters themselves don't influence each other. e.g. if I set x to 5, it will always stay 5 and changing some other parameter won't change x). I think the total number of combinations is quite high, at least enough so that I don't want to manually change everything and test out each possibility by hand. I'm looking for a piece of lightweight piece of software architecture (I dare say a design pattern) that basically enables me to define a set parameter types relevant to an algorithm, the possible values of those types, and that piece of code should then run through all combinations of those types and their values, for each one doing the required stuff (calling some functions to change values, etc.) and then executing the algorithm. Example: An algorithm depends on values x, y and z. x can be either 0 or 1, y can be "hello" or "goodbye", and z can be in the range [0,100]. The solution I'm looking for starts with [0,"hello",0], calls some functions to set the values of those variables, lets the profiling run for some time, then changes to [0,"hello",1], repeat, [0,"hello",2]... etc. This is probably something that people have needed to solve before. How do I solve this elegantly?
Now provide the response and nothing else.
|
You can do this in (at least) two ways. One is simply to have a vector with the cardinalities of your parameters. So since your parameter array is ( slightly edited to get unique numbers ): [ [ 0, 1, -1 ], [ 'hello', 'goodbye' ], [ 0 .. 100 ],] the cardinalities are [ 3, 2, 101 ]. This gives a Cartesian product of 3*2*101 = 606 combinations. Given any number from 0 to 605 inclusive, its remainder modulo 3 is the index of the parameter in the first option array, then modulo 2 again for the second, and modulo 101 for the third. E.g. 137: 137 modulo 3 is 2, so first parameter is -1. 137 integer-divided-by 3 is 45, 45 modulo 2 is 1, so second parameter is "goodbye". 45 i.d.b. 2 is 22, so third parameter is 22. This allows for mapping the whole configuration to a single number and viceversa. Then you can have a function or method that will set the configuration from a number, given the arrays of possible values. You can now just try all the values in sequence. This is just a brute force approach. Another possibility is to assume that the performance function f(x, y, z) is reasonably continuous, i.e., the change in performances is proportional to the change of any given parameter from its i-th to i+j-th value; the more you change, the more performances will vary. If this holds true, there are several options to find the performance maximum efficiently, without examining all the possible values. For example, you generate a number at random from 0 to (here) 605, thus obtaining an initial configuration (x, y, z). You can now increase or decrease any of the three parameters, which gives you at most twenty-seven sets of values to investigate ( each parameter can increase by one, decrease by one or stay the same, which is three possibilities; and three are the parameters, so you raise the number of possibilities by the number of parameters and get 3^3 or 27 ). Run the performance test for each of these sets. The best combination will be your new starting point. Repeat (you will want to cache results for the last runs, since several sets would otherwise be examined repeatedly). When you have many possible values for each parameter, this method allows for examining comparatively very few of them. If f() is "reasonably" well-behaved, this method will "walk" the parameter space following the line of steepest ascent, rapidly converging towards the best combination. You may want to use techniques such as annealing or restarting from a very different initial position to ensure that you do not get "stuck" in a local maximum.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/228478', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/52770/']}
|
jdg_372717
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42843305
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I understand this is a very common problem in RN and I am still trying to understand the very possible advantage of returning a promise when loading data from a property file instead of just returning the value, which makes chaining requests very cumbersome...but anyway. Here is what I have right now, which is a wrapper from the AsyncStorage RN implementation: multiGet = async (key) => { var value = null; try { value = await AsyncStorage.multiGet(key).then( (values) => { value = values; console.log('Then: ',values); }); } catch (error) { console.log('Error: ',error); } console.log('Final: ',value); return value; } At this point, value gets undefined. In my main code I have this: var filter = this._getFilter();console.log('returned filter:',filter); The _getFilter function is the one using the AsyncStorage wrapper but the 'returned filter' is logging before the first function so it is not waiting for the returned values before continue, so I get an undefined value. At first, I thought that just by using the async/await the AsyncStorage wold return a value instead of a promise but after testing, the value I get from: value = await AsyncStorage.getItem('key') is STILL a promise, so I have to use then() to read the value. Basically the order that I am seeing in the logs is: _getFilterreturned value: undefinedThen: value: here I get the correct value from the keys but the code already passed and I don't have the correct value in the variable I have no clue what is going on or how to handle this correctly. This is supposed to be very simple and common use case. I would love to solve this without using a third party module. Thanks SOLUTION Edit: After understanding a little more about the concepts of async/await and callbacks, I finally have a code that works. I don't like it, because it makes the code very hard to read. I might need to refactor it to use promises but for now, it works. Here are some snippets in case someone finds the same issue: this._getFilter(body,this._filterSearchCallback,callback); Note: I am sending the body through the chain because I am "completing" the information as I pass the functions. The second parameter is the first callback that actually makes a fetch query and the third callback is the return of the fetch function. _getFilter(body,callback,returnCallback){ {...} this._sh.multiGet(keysBanks).then( (banks) => { filter.banks = banks; console.log(banks); this._sh.multiGet(keysCards).then( (cards) => { console.log(cards); filter.credit_cards = cards; callback(body,filter,returnCallback); }); } ); } Here basically I am chaining a couple of gets because I need several values from the store. This is the part I dont really like. _sh is my StorageHelper which is a wrapper to the AsyncStorage, nothing fancy. multiGet = async (key) => { const value = await AsyncStorage.multiGet(key); return value; } Then my very last callback that actually makes the fetch and send the JSON response to the main screen in react native: _filterSearchCallback(body,filter,callback){ body.filter = filter; return fetch(apiUrl, {method: 'post', body: JSON.stringify(body)}) .then((response) => response.json()) .then((responseJson) => { callback(responseJson); }) .catch((error) => { console.error(error); callback(responseJson); }); } I will improve this and make it cleaner but for now, it works. Hope it helps others too.
Now provide the response and nothing else.
|
Once upon a time, i was having the same problem so what I did I will share with you here. Basically, your execution is moving forward without taking any value i.e undefined what you are getting right now so there are 3-4 ways to get out of this: 1) async await2) callback 1) We will start with the callback which is use by most of the people. We will use your code to implement this: _getFilter(key,callback){ multiGet = (key) => { var collect; try { var value = AsyncStorage.multiGet(key).then( (values) => { // value = values; console.log('Then: ',values); callback(values) }); } catch (error) { console.log('Error: ',error); } console.log('Final: ',value); }} this._getFilter(key,function(filter){ console.log('returned filter:',filter); }); 2)async/await If you are using await alone then you would get an error, to use await inside a function you have to declare the async function by setting async keyword before the function name. async _getFilter(key){multiGet = async (key) => { var value,collect; try { value = await AsyncStorage.multiGet(key).then( (values) => { collect= values; console.log('Then: ',values); }); } catch (error) { console.log('Error: ',error); } console.log('Final: ',value); return collect; }//calling the async functionthis._getFilter(key).then((filter)=>{if(filter!=null)console.log('returned filter:',filter)elseconsole.log('error')}) Hope this would clear your concepts and help you with other react native developers.I have seen lots of people struggling with this thing so today I got the chance to clear your doubts. Cheers :)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42843305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/580552/']}
|
jdg_372718
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54430119
|
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 https://material-ui.com/ components inside shadow dom, and need a way to inject those styles inside shadow dom. by default material-ui , which uses jss under the hood injects styles in the head of the page. Is that even possible? Can anyone come with an example?
Now provide the response and nothing else.
|
This is what my web component looks like, it is a web component that renders a react app that contains material-ui styles. import * as React from 'react';import { render } from 'react-dom';import { StylesProvider, jssPreset } from '@material-ui/styles';import { create } from 'jss';import { App } from '@myApp/core';class MyWebComponent extends HTMLElement { connectedCallback() { const shadowRoot = this.attachShadow({ mode: 'open' }); const mountPoint = document.createElement('span'); const reactRoot = shadowRoot.appendChild(mountPoint); const jss = create({ ...jssPreset(), insertionPoint: reactRoot }); render( <StylesProvider jss={jss}> <App /> </StylesProvider>, mountPoint ); }}customElements.define('my-web-commponent', MyWebComponent); Setting the insertionPoint on jss to the actual react root inside the shadow root will tell jss to insert those styles inside that shadow root.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54430119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1597360/']}
|
jdg_372719
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31098255
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anyone help me how exactly this code works.how IEnumarable gets saved in memory what exactly var does in this context? why they used concat in this code what exactly is it concatenating public IEnumerable<Control> GetAll(Control control,Type type){ var controls = control.Controls.Cast<Control>(); return controls.SelectMany(ctrl => GetAll(ctrl,type)).Concat(controls) .Where(c => c.GetType() == type);}
Now provide the response and nothing else.
|
Per the docs , linalg.solve is used to compute the "exact" solution, x , of the well-determined, i.e., full rank, linear matrix equation ax = b . Beinglinear, there can be at most one solution. If the solution you found does notsum up to 1, then adding the extra constraint would yield no solution. However, you could use scipy.optimize.minimize to find the point on the constraint plane which minimizes the quantity ||Ax-b||^2 : def f(x): y = np.dot(A, x) - b return np.dot(y, y)cons = ({'type': 'eq', 'fun': lambda x: x.sum() - 1})res = optimize.minimize(f, [0, 0, 0], method='SLSQP', constraints=cons, options={'disp': False}) For example, given this system of equations import numpy as npimport numpy.linalg as LAimport scipy.optimize as optimizeA = np.array([[1, 3, 4], [5, 6, 9], [1, 2, 3]])b = np.array([1, 2, 1])x = LA.solve(A, b) The solution does not add up to 1: print(x)# [-0.5 -1.5 1.5] But you could try to minimize f : def f(x): y = np.dot(A, x) - b return np.dot(y, y) subject to the constraint cons : cons = ({'type': 'eq', 'fun': lambda x: x.sum() - 1})res = optimize.minimize(f, [0, 0, 0], method='SLSQP', constraints=cons, options={'disp': False})xbest = res['x']# array([ 0.30000717, 1.89998823, -1.1999954 ]) xbest sums to 1: print(xbest.sum())1 The difference A·xbest - b is: print(np.dot(A, xbest) - b)# [ 0.19999026 0.10000663 -0.50000257] and the sum of the squares of the difference, (also computable as f(xbest) ) is : print(res['fun'])0.30000000014542572 No other value of x minimizes this quantity more while satisfying the constraint.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31098255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5055886/']}
|
jdg_372720
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13532084
|
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 GridLayout with 5 columns and 3 rows. Now I can insert arbitrary child views, which is great. Even better is, that I can assign columnSpan=2 to some item in order to span it to 2 columns (the same with rowSpan). The problem now is, that I cannot assign rowSpan or columnSpan programmatically (i.e. at runtime). Some search suggested something like this: layoutParams.columnSpec = GridLayout.spec(0, columnSpan); But I don't quite understand what the parameters of spec mean (start and size). The documentation is also quite poor at this point. Any help is highly appreciated!
Now provide the response and nothing else.
|
GridLayout gridLayout = (GridLayout)findViewById(R.id.tableGrid); gridLayout.removeAllViews(); int total = 12; int column = 5; int row = total / column; gridLayout.setColumnCount(column); gridLayout.setRowCount(row + 1); for(int i =0, c = 0, r = 0; i < total; i++, c++) { if(c == column) { c = 0; r++; } ImageView oImageView = new ImageView(this); oImageView.setImageResource(R.drawable.ic_launcher); GridLayout.LayoutParams param =new GridLayout.LayoutParams(); param.height = LayoutParams.WRAP_CONTENT; param.width = LayoutParams.WRAP_CONTENT; param.rightMargin = 5; param.topMargin = 5; param.setGravity(Gravity.CENTER); param.columnSpec = GridLayout.spec(c); param.rowSpec = GridLayout.spec(r); oImageView.setLayoutParams (param); gridLayout.addView(oImageView); }
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13532084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1463757/']}
|
jdg_372721
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9749
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What are some interesting applications of the Mean Value Theorem for derivatives? Both the 'extended' or 'non-extended' versions as seen here are of interest. So far I've seen some trivial applications like finding the number of roots of a polynomial equation. What are some more interesting applications of it? I'm asking this as I'm not exactly sure why MVT is so important - so examples which focus on explaining that would be appreciated.
Now provide the response and nothing else.
|
There are several applications of the Mean Value Theorem. It is one of the most important theorems in analysis and is used all the time. I've listed $5$ important results below. I'll provide some motivation to their importance if you request. $1)$ If $f: (a,b) \rightarrow \mathbb{R}$ is differentiable and $f'(x) = 0$ for all $x \in (a,b)$, then $f$ is constant. $2)$ Leibniz's rule: Suppose $ f : [a,b] \times [c,d] \rightarrow \mathbb{R}$ is a continuous function with $\partial f/ \partial x$ continuous. Then the function $F(x) = \int_{c}^d f(x,y)dy$ is derivable with derivative $$ F'(x) = \int_{c}^d \frac{\partial f}{\partial x} (x,y)dy.$$ $3)$ L'Hospital's rule $4)$ If $A$ is an open set in $\mathbb{R}^n$ and $f:A \rightarrow \mathbb{R}^m$ is a function with continuous partial derivatives, then $f$ is differentiable. $5)$ Symmetry of second derivatives: If $A$ is an open set in $\mathbb{R}^n$ and $f:A \rightarrow \mathbb{R}$ is a function of class $C^2$, then for each $a \in A$, $$\frac{\partial^2 f}{\partial x_i \partial x_j} (a) = \frac{\partial^2 f}{\partial x_j \partial x_i} (a)$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/9749', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/181/']}
|
jdg_372722
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15189949
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to make a comparator that can take any type of an element to compare. I'm unsure about how to create the class. I just want it to compare two elements of the same type (But whatever type the client gives it, ex: Integer, String, Double, etc...) to see which one is greater then the other. public class InsertionComparator implements Comparator<T>{/** * Compares two elements. * * @param f1 The first element you want to compare. * @param f2 The second element you want to compare. * @return -1,0,1 Whether or not one is greater than, less than, * or equal to one another. */public int compare(<T> element1,<T> element2){ if(element1 < element2) { return -1; } else { if(element1 > element2) { return 1; } else { return 0; } } }} Please help, thank you!
Now provide the response and nothing else.
|
The closest thing you can do to this is a Comparator that can compare any objects that implement the Comparable interface: class NaturalComparator<T extends Comparable<T>> implements Comparator<T> { public int compare(T a, T b) { return a.compareTo(b); }} That's really the closest you can do: only Comparable objects have the "natural ordering" you're trying to model here. But generally, once you have Comparable objects, you don't necessarily need a Comparator : for example, Collections.sort can take either a List with a Comparator , or a List with Comparable elements.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15189949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1759727/']}
|
jdg_372723
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52028310
|
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 ASP.NET Core 2.1 Project runs fine on my Mac OS. However it throws this exception when I run it from Windows PC. I tried to run this from two Windows machines using the same version of .NET Core SDK. I tried reinstalling .NET Core SDK 2.1.302 , also tried upgrading to 2.1.401 . Appreciate any help. The error is System.IO.FileLoadException: Could not load file or assembly 'Microsoft.AspNetCore.Connections.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) Used Nuget Packages in .csproj file <PackageReference Include="HangFire" Version="1.6.19" /><PackageReference Include="Hangfire.LiteDB" Version="0.1.0" /><PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.3.0" /><PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.1" /><PackageReference Include="Microsoft.AspNetCore.WebSockets" Version="2.1.1" /><PackageReference Include="LiteDB" Version="4.1.4" /><PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" /> Full stack trace > dotnet runUsing launch settings from C:\Source\repos\src\Properties\launchSettings.json...Application startup exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileLoadException: Could not load file or assembly 'Microsoft.AspNetCore.Connections.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions..ctor() --- End of inner exception stack trace --- at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache) at System.Activator.CreateInstance[T]() at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name) at Microsoft.Extensions.Options.OptionsManager`1.<>c__DisplayClass5_0.<Get>b__0() at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy`1.CreateValue() at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions) at Microsoft.Extensions.Options.OptionsManager`1.Get(String name) at Microsoft.Extensions.Options.OptionsManager`1.get_Value() at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.CreateServiceContext(IOptions`1 options, ILoggerFactory loggerFactory) at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer..ctor(IOptions`1 options, ITransportFactory transportFactory, ILoggerFactory loggerFactory)--- End of stack trace from previous location where exception was thrown --- at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureServer() at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()crit: Microsoft.AspNetCore.Hosting.Internal.WebHost[6] Application startup exceptionSystem.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileLoadException: Could not load file or assembly 'Microsoft.AspNetCore.Connections.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions..ctor() --- End of inner exception stack trace --- at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache) at System.Activator.CreateInstance[T]() at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name) at Microsoft.Extensions.Options.OptionsManager`1.<>c__DisplayClass5_0.<Get>b__0() at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy`1.CreateValue() at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions) at Microsoft.Extensions.Options.OptionsManager`1.Get(String name) at Microsoft.Extensions.Options.OptionsManager`1.get_Value() at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.CreateServiceContext(IOptions`1 options, ILoggerFactory loggerFactory) at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer..ctor(IOptions`1 options, ITransportFactory transportFactory, ILoggerFactory loggerFactory)--- End of stack trace from previous location where exception was thrown --- at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureServer() at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileLoadException: Could not load file or assembly 'Microsoft.AspNetCore.Connections.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions..ctor() --- End of inner exception stack trace --- at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache) at System.Activator.CreateInstance[T]() at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name) at Microsoft.Extensions.Options.OptionsManager`1.<>c__DisplayClass5_0.<Get>b__0() at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy`1.CreateValue() at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions) at Microsoft.Extensions.Options.OptionsManager`1.Get(String name) at Microsoft.Extensions.Options.OptionsManager`1.get_Value() at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.CreateServiceContext(IOptions`1 options, ILoggerFactory loggerFactory) at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer..ctor(IOptions`1 options, ITransportFactory transportFactory, ILoggerFactory loggerFactory)--- End of stack trace from previous location where exception was thrown --- at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureServer() at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken) at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String shutdownMessage) at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token) at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host) at JustALink.Program.Main(String[] args) in C:\Source\repos\src\Program.cs:line 10
Now provide the response and nothing else.
|
This problem is a known issue in .NET Core 2.1.x that was fixed in .NET Core 2.1.5 and newer. See https://github.com/dotnet/core-setup/issues/4512 . If you are getting failures due to "System.IO.FileLoadException" after updating the .NET Core SDK, you are probably running into https://github.com/dotnet/core-setup/issues/4376 . The best fix is to upgrade to .NET Core 2.1.5 or newer. If you can't upgrade, another workaround is to update the project to <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.3" /> The cause of this issue, as described in https://github.com/dotnet/core-setup/issues/4376 , is unintentionally upgrading out of the shared framework. For example: <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" /><PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.1" /> Microsoft.AspNetCore.All 2.1.0 depends on Microsoft.AspNetCore.SignalR 1.0.0 , but your project has upgrade to Microsoft.AspNetCore.SignalR 1.0.1 . When you dotnet publish , you get Microsoft.AspNetCore.SignalR 1.0.1 AND ⚠️ its transitive dependencies in your publish folder. This is the publish trimming pitfall described in https://natemcmaster.com/blog/2018/08/29/netcore-primitives-2/ . This results in the following +=================+===============================+================================+============================+| AspNetCore.All | M.A.Connections.Abstractions | M.A.Connections.Abstractions | Which M.A.C.Abstractions || | (in shared framework) | (in publish dir) | should load |+=================+===============================+================================+============================+| 2.1.0 | 2.1.0 | 2.1.1 | publish dir |+-----------------+-------------------------------+--------------------------------+----------------------------+| 2.1.3 | 2.1.3 | 2.1.1 | shared framework* |+-----------------+-------------------------------+--------------------------------+----------------------------+ * This is bug, and https://github.com/dotnet/core-setup/issues/4512 tracks getting a fix in a future 2.1.x update.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52028310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1256550/']}
|
jdg_372724
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10085945
|
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 want to debug some code running on Linux and I need a debug build ( -O0 -ggdb ). So I added these things to my CMakeLists.txt : set(CMAKE_BUILD_TYPE DEBUG)set(CMAKE_C_FLAGS "-O0 -ggdb")set(CMAKE_C_FLAGS_DEBUG "-O0 -ggdb")set(CMAKE_C_FLAGS_RELEASE "-O0 -ggdb")set(CMAKE_CXX_FLAGS "-O0 -ggdb")set(CMAKE_CXX_FLAGS_DEBUG "-O0 -ggdb")set(CMAKE_CXX_FLAGS_RELEASE "-O0 -ggdb") When I tried to compile I turned verbose on using make VERBOSE=1 And I observed the output, like this ... /usr/bin/c++ -D_BSD_SOURCE **-O0 -ggdb** -Wnon-virtual-dtor -Wno-long-long -ansi -Wundef -Wcast-align -Wchar-subscripts -Wall -W -Wpointer-arith -Wformat-security -fno-exceptions -DQT_NO_EXCEPTIONS -fno-check-new -fno-common -Woverloaded-virtual -fno-threadsafe-statics -fvisibility=hidden -fvisibility-inlines-hidden **-g -O2** -fno-reorder-blocks -fno-schedule-insns -fno-inline ... Apparently the code is compiled with "-g -O2" and this is not what I want. How can I force it to use "-O0 -ggdb" only?
Now provide the response and nothing else.
|
You need to set the flags after the project command in your CMakeLists.txt. Also, if you're calling include(${QT_USE_FILE}) or add_definitions(${QT_DEFINITIONS}) , you should include these set commands after the Qt ones since these would append further flags. If that is the case, you maybe just want to append your flags to the Qt ones, so change to e.g. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0 -ggdb")
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10085945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/871359/']}
|
jdg_372725
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
276465
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the example below. Any change to the ColorChoice enum affects all IWindowColor subclasses. Do enums tend to cause brittle interfaces? Is there something better than an enum to allow for more polymorphic flexibility? enum class ColorChoice{ Blue = 0, Red = 1};class IWindowColor{public: ColorChoice getColor() const=0; void setColor( const ColorChoice value )=0;}; Edit: sorry for using color as my example, that's not what the question is about. Here is a different example that avoids the red herring and provides more info about what I mean by flexibility. enum class CharacterType{ orc = 0, elf = 1};class ISomethingThatNeedsToKnowWhatTypeOfCharacter{public: CharacterType getCharacterType() const; void setCharacterType( const CharacterType value );}; Further, imagine that handles to the appropriate ISomethingThatNeedsToKnowWhatTypeOfCharacter subclass are handed out by a factory design pattern. Now I have an API that cannot be extended in the future for a different application where the allowable character types are { human, dwarf }. Edit: Just to be more concrete about what I'm working on. I am designing a strong binding of this ( MusicXML ) specification and I am using enum classes to represent those types in the specification which are declared with xs:enumeration. I am trying to think about what happens when the next version (4.0) comes out. Could my class library work in a 3.0 mode and in a 4.0 mode? If the next version is 100% backward compatible, then maybe. But if enumeration values were removed from the specification then I'm dead in the water.
Now provide the response and nothing else.
|
When used properly, enums are far more readable and robust than the "magic numbers" they replace. I don't normally see them making code more brittle. For instance: setColor() doesn't have to waste time checking if value is a valid color value or not. The compiler has already done that. You can write setColor(Color::Red) instead of setColor(0). I believe the enum class feature in modern C++ even lets you force people to always write the former instead of the latter. Usually not important, but most enums can be implemented with any size integral type, so the compiler can choose whatever size is most convenient without forcing you to think about such things. However, using an enum for color is questionable because in many (most?) situations there's no reason to limit the user to such a small set of colors; you might as well let them pass in any arbitrary RGB values. On the projects I work with, a small list of colors like this would only ever come up as part of a set of "themes" or "styles" that's supposed to act as a thin abstraction over concrete colors. I'm not sure what your "polymorphic flexibility" question is getting at. Enums don't have any executable code, so there's nothing to make polymorphic. Perhaps you're looking for the command pattern ? Edit: Post-edit, I'm still not clear on what kind of extendability you're looking for, but I still think the command pattern is the closest thing you'll get to a "polymorphic enum".
|
{}
|
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/276465', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/130255/']}
|
jdg_372726
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9086017
|
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 playing a bit with the MSIL decompiler - ILDASM and I tried to decompile a simple .NET method. The opcodes looked somehow like this: .method private hidebysig static int32 Add(int32 a, int32 b) cil managed{ // Code size 18 (0x12) .maxstack 2 .locals init ([0] int32 c, [1] int32 d, [2] int32 CS$1$0000) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.5 IL_0003: add IL_0004: stloc.0 IL_0005: ldarg.1 IL_0006: ldc.i4.s 10 IL_0008: add IL_0009: stloc.1 IL_000a: ldloc.0 IL_000b: ldloc.1 IL_000c: add IL_000d: stloc.2 IL_000e: br.s IL_0010 IL_0010: ldloc.2 IL_0011: ret} What I'm wondering is - are these opcodes atomic? i.e In a preemptive scheduling kernel, is it possible for a single opcode to be preempted before it finishes execution? The opcode in here could be easily mapped to asm instructions pretty much 1:1, as they have separate opcodes for loads, stores, add, etc. But what in case of a more complex opcodes? like "call", when the operand is a method-reference token that should first be followed to resolve the method and then called? is that atomic too?
Now provide the response and nothing else.
|
No, not all opcodes are atomic. For example, if you use stloc or ldloc for value types which are larger than the native pointer size, that's not guaranteed to be atomic. Section 12.6.6 of ECMA 335 guarantees this much: A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size (the size of type native int) is atomic (see §12.6.2) when all the write accesses to a location are the same size. Atomic writes shall alter no bits other than those written. ... but then there's a note: [Note: There is no guaranteed atomic access to 8-byte data when the size of a native int is 32 bits even though some implementations might perform atomic operations when the data is aligned on an 8-byte boundary. end note] So that means any op code storing or reading an Int64 isn't guaranteed to be atomic on x86, for example...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9086017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2753/']}
|
jdg_372727
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38666283
|
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: >>> myString = "has spaces">>> first, second = myString.split()>>> myString = "doesNotHaveSpaces">>> first, second = myString.split()Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: need more than 1 value to unpack I would like to have second default to None if the string does not have any white space. I currently have the following, but am wondering if it can be done in one line: splitted = myString.split(maxsplit=1)first = splitted[0]second = splitted[1:] or None
Now provide the response and nothing else.
|
May I suggest you to consider using a different method, i.e. partition instead of split : >>> myString = "has spaces">>> left, separator, right = myString.partition(' ')>>> left'has'>>> myString = "doesNotHaveSpaces">>> left, separator, right = myString.partition(' ')>>> left'doesNotHaveSpaces' If you are on python3, you have this option available: >>> myString = "doesNotHaveSpaces">>> first, *rest = myString.split()>>> first'doesNotHaveSpaces'>>> rest[]
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38666283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2687324/']}
|
jdg_372728
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6273551
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So the scenario is this: a user does some action (like earn a badge or unlock something) and an email notification gets sent out. One to the user (with a message like "You've unlocked XYZ...") and then a different message to each of their friends like ("You're friend has unlocked XYZ..."). public interface INotify{ void Notify(User user, User friend);}public class NotificationService{ private IEnumerable<INotify> _notifiers; public NotificationService(IEnumerable<INotify> notifiers) { _notifiers = notifiers; } public SendNotifications() { User user = GetUser(); IEnumerable<User> friends = GetFriends(); foreach(var notifier in _notifiers) { //Send notification to user notifier.Notify(user, null); //send notification to users friends foreach(var friend in friends) notifier.Notify(user, friend); } }} I'm trying to use moq to test that each notifier is called 2x. Once passing null as the second parameter and the second time passing in a value to both parameters. [Test]public void MakeSureEveryoneIsNotified(){ var notifierMock = new Mock<INotifier>(); var svc = new NotificationService(new List<INotifier>{ notifierMock.Object }); svc.SendNotifications(); notifierMock.Verify(x => x.Notify(It.Is<User>(user => user.UserId == 1), null), Times.Once()); notifierMock.Verify(x => x.Notify(It.Is<User>(user => user.UserId == 1), It.Is<User>(user => user.UserId == 2)), Times.Once());} The problem is that the second verify call throws an ArgumentNullException for the second parameter. Is there away to say "Check the first call has these parameters, and then the second call has other parameters". I know I can get it around it simply by calling: notifierMock.Verify(x => x.Notify(It.IsAny<User>(), It.IsAny<User>()), Times.Exactly(2)); But I was wanting to be a little more specific. Anyway to do this?
Now provide the response and nothing else.
|
You can achieve this by recording what happens on each call to Notify . Then you can compare the recording to what's expected: [TestMethod]public void TestMoqInvocations(){ var notifierMock = new Mock<INotifier>(); var svc = new NotificationService(new List<INotifier>{ notifierMock.Object }); svc.SendNotifications(); var invocations = new List<NotifyParams>(); notifierMock .Setup(f => f.Notify(It.IsAny<User>(), It.IsAny<User>())) .Callback<string, string>((user, friend) => invocations.Add(new NotifyParams{user = user, friend = friend})); Assert.AreEqual(1, invocations[0].user.UserId); Assert.IsNull(invocations[0].friend); Assert.AreEqual(1, invocations[1].user.UserId); Assert.AreEqual(2, invocations[1].user.UserId);}public struct NotifyParams { public User user {get;set;} public User friend { get; set; }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6273551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17744/']}
|
jdg_372729
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
352942
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Is logrotate hiding somewhere on OSX, or is there an equivalent? It's not in /usr/sbin .
Now provide the response and nothing else.
|
Based on Brian Armstrong's answer, here's something with a little more explanation and a correction. This handles the log created by postgres on OSX installed by Homebrew. Located at /etc/newsyslog.d/postgresql.conf : # logfilename [owner:group] mode count size(KB) when flags [/pid_file] [sig_num]/usr/local/var/postgres/postgresql.log : 600 2 2048 * J /usr/local/var/postgres/postmaster.pid This will rotate the log file when it reaches 2MB in size, keep 2 archives (for a total of 6MB storage used), and bzip2-compress the archives. It will notify the postgres process to reopen the log files once rotated, which is necessary to get new log entries and to actually free the disk space without restarting the machine. Important to note that size is in KB, not bytes. You can test the config file (without affecting any files) using sudo newsyslog -nvv . newsyslog documentation is located here: http://www.freebsd.org/cgi/man.cgi?newsyslog.conf(5) .Also used: http://www.redelijkheid.com/blog/2011/3/28/adding-custom-logfile-to-os-x-server-log-rotation.html
|
{}
|
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/352942', 'https://serverfault.com', 'https://serverfault.com/users/68259/']}
|
jdg_372730
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37499307
|
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 really new to Spring and Spring Security. I was reading about Spring Security and it came out the concept of principal , which should be the current logged user. But what if we have more than one current logged user? So, my question is, what exactly is then the principal in spring security? I've read for example this tutorial: http://www.mkyong.com/spring-security/get-current-logged-in-username-in-spring-security/ and they seem to take into account that there's just one current logged user, which isn't often the case. How do I retrieve a specific user? And how do I differentiate between users that are doing requests?
Now provide the response and nothing else.
|
The principal is the currently logged in user. However, you retrieve it through the security context which is bound to the current thread and as such it's also bound to the current request and its session. SecurityContextHolder.getContext() internally obtains the current SecurityContext implementation through a ThreadLocal variable. Because a request is bound to a single thread this will get you the context of the current request. To simplify you could say that the security context is in the session and contains user/principal and roles/authorities. How do I retrieve a specific user? You don't. All APIs are designed to allow access to the user & session of the current request. Let user A be one of 100 currently authenticated users. If A issues a request against your server it will allocate one thread to process that request. If you then do SecurityContextHolder.getContext().getAuthentication() you do so in the context of this thread. By default from within that thread you don't have access to the context of user B which is processed by a different thread. And how do I differentiate between users that are doing requests? You don't have to, that's what the Servlet container does for you.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/37499307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3924118/']}
|
jdg_372731
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4081783
|
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 question requires some hypothetical background. Let's consider an employee table that has columns name , date_of_birth , title , salary , using MySQL as the RDBMS. Since if any given person has the same name and birth date as another person, they are, by definition, the same person (barring amazing coincidences where we have two people named Abraham Lincoln born on February 12, 1809), we'll put a unique key on name and date_of_birth that means "don't store the same person twice." Now consider this data: id name date_of_birth title salary 1 John Smith 1960-10-02 President 500,000 2 Jane Doe 1982-05-05 Accountant 80,000 3 Jim Johnson NULL Office Manager 40,000 4 Tim Smith 1899-04-11 Janitor 95,000 If I now try to run the following statement, it should and will fail: INSERT INTO employee (name, date_of_birth, title, salary)VALUES ('Tim Smith', '1899-04-11', 'Janitor', '95,000') If I try this one, it will succeed: INSERT INTO employee (name, title, salary)VALUES ('Jim Johnson', 'Office Manager', '40,000') And now my data will look like this: id name date_of_birth title salary 1 John Smith 1960-10-02 President 500,000 2 Jane Doe 1982-05-05 Accountant 80,000 3 Jim Johnson NULL Office Manager 40,000 4 Tim Smith 1899-04-11 Janitor 95,000 5 Jim Johnson NULL Office Manager 40,000 This is not what I want but I can't say I entirely disagree with what happened. If we talk in terms of mathematical sets, {'Tim Smith', '1899-04-11'} = {'Tim Smith', '1899-04-11'} <-- TRUE{'Tim Smith', '1899-04-11'} = {'Jane Doe', '1982-05-05'} <-- FALSE{'Tim Smith', '1899-04-11'} = {'Jim Johnson', NULL} <-- UNKNOWN{'Jim Johnson', NULL} = {'Jim Johnson', NULL} <-- UNKNOWN My guess is that MySQL says, "Since I don't know that Jim Johnson with a NULL birth date isn't already in this table, I'll add him." My question is: How can I prevent duplicates even though date_of_birth is not always known? The best I've come up with so far is to move date_of_birth to a different table. The problem with that, however, is that I might end up with, say, two cashiers with the same name, title and salary, different birth dates and no way to store them both without having duplicates.
Now provide the response and nothing else.
|
A fundamental property of a unique key is thatit must be unique. Making part of that key Nullable destroys this property. There are two possible solutions to your problem: One way, the wrong way, would be to use some magic date to represent unknown. This just gets you pastthe DBMS "problem" but does not solve the problem in a logical sense.Expect problems with two "John Smith" entries having unknown datesof birth. Are these guys one and the same or are they unique individuals?If you know they are different then you are back to the same old problem -your Unique Key just isn't unique. Don't even think about assigning a whole range of magic datesto represent "unknown" - this is truly the road to hell. A better way is to create an EmployeeId attribute as a surrogate key. This is just anarbitrary identifier that you assign to individuals that you know are unique. Thisidentifier is often just an integer value.Then create an Employee table to relate the EmployeeId (unique, non-nullablekey) to what you believe are the dependant attributers, in this caseName and Date of Birth (any of which may be nullable). Use the EmployeeId surrogate key everywhere that youpreviously used the Name/Date-of-Birth. This adds a new table to your system butsolves the problem of unknown values in a robust manner.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4081783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/199712/']}
|
jdg_372732
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1311228
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the most unusual proof you know that $\sqrt{2}$ is irrational? Here is my favorite: Theorem: $\sqrt{2}$ is irrational. Proof: $3^2-2\cdot 2^2 = 1$. (That's it) That is a corollary ofthis result: Theorem: If $n$ is a positive integer and there are positive integers $x$ and $y$ such that $x^2-ny^2 = 1$, then $\sqrt{n}$ is irrational. The proof is in two parts,each of whichhas a one line proof. Part 1: Lemma: If $x^2-ny^2 = 1$, then there are arbitrarily large integers $u$ and $v$ such that $u^2-nv^2 = 1$. Proof of part 1: Apply the identity $(x^2+ny^2)^2-n(2xy)^2=(x^2-ny^2)^2$ as many times as needed. Part 2: Lemma: If $x^2-ny^2 = 1$ and $\sqrt{n} = \frac{a}{b}$ then $x < b$. Proof of part 2: $1= x^2-ny^2= x^2-\frac{a^2}{b^2}y^2= \frac{x^2b^2-y^2a^2}{b^2}$ or $b^2= x^2b^2-y^2a^2= (xb-ya)(xb+ya)\ge xb+ya> xb$ so $x < b$. These two partsare contradictory,so$\sqrt{n}$must be irrational. Two things to note aboutthis proof. First,this does not needLagrange's theoremthat for everynon-square positive integer $n$there arepositive integers $x$ and $y$such that$x^2-ny^2 = 1$. Second,the key property ofpositive integers needed is thatif $n > 0$then$n \ge 1$.
Now provide the response and nothing else.
|
Suppose that $\sqrt{2} = a/b$, with $a,b$ positive integers. Meaning $a = b\sqrt{2}$. Consider $$A = \{ m \in \Bbb Z \mid m > 0 \text{ and }m\sqrt{2} \in \Bbb Z \}.$$ Well, $A \neq \varnothing$, because $b \in A$. By the well-ordering principle , $A$ has a least element, $s$. And $s,s\sqrt{2} \in \Bbb Z_{>0}$. Then consider the integer: $$r= s\sqrt{2}-s.$$We have $r =s(\sqrt{2}-1) < s$, and $r > 0$. But $r\sqrt{2} = 2s-s\sqrt{2}$ is again an integer. Hence $r \in A$ and $r < s$, contradiction.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1311228', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13079/']}
|
jdg_372733
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13500852
|
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 created an application for Android, in which there is a NumberPicker. And I need to change the value of this NumberPicker but with a smooth animation like when you touch it and change its value. For example, assume the current value is 1 and it's going to be 5, I want the NumberPicker to spin from 1 to 2 then to 3 and so on. But I want it to spin not just instantly change the values! If I use the following code: numberPicker.setValue(5); its value will instantly change to 5, but I want it to roll up from 1 to 5 like when you manually touch it and make it spin.
Now provide the response and nothing else.
|
I solved it via refelction /** * using reflection to change the value because * changeValueByOne is a private function and setValue * doesn't call the onValueChange listener. * * @param higherPicker * the higher picker * @param increment * the increment */ private void changeValueByOne(final NumberPicker higherPicker, final boolean increment) { Method method; try { // refelction call for // higherPicker.changeValueByOne(true); method = higherPicker.getClass().getDeclaredMethod("changeValueByOne", boolean.class); method.setAccessible(true); method.invoke(higherPicker, increment); } catch (final NoSuchMethodException e) { e.printStackTrace(); } catch (final IllegalArgumentException e) { e.printStackTrace(); } catch (final IllegalAccessException e) { e.printStackTrace(); } catch (final InvocationTargetException e) { e.printStackTrace(); } } works perfect. I don't know why this method is private
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13500852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/401084/']}
|
jdg_372734
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3600960
|
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 mysql, i tried changing an existing table like this: ALTER TABLE `etexts` CHANGE `etext` `etext` VARCHAR( 100 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT NULL I got the response: #1067 - Invalid default value for 'etext' Why?
Now provide the response and nothing else.
|
It's contradictive... NOT NULL , but make it default NULL ... Remove DEFAULT NULL and change NOT NULL to NULL : ALTER TABLE `etexts` CHANGE `etext` `etext` VARCHAR( 100 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3600960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/428479/']}
|
jdg_372735
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1574168
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
UPDATE Feb 10 2012: zOompf has completed some very thorough research on this very topic here . It trumps any findings below. UPDATE Sept 11 2010: A testing platform has been created for this here HTTP 1.1 definitions of GZIP and DEFLATE (zlib) for some background information: " 'Gzip' is the gzip format, and 'deflate' is the zlib format . Theyshould probably have called the second one 'zlib' instead to avoidconfusion with the raw deflate compressed data format. While the HTTP1.1 RFC 2616 correctly points to the zlib specification in RFC 1950for the 'deflate' transfer encoding, there have been reports ofservers and browsers that incorrectly produce or expect raw deflatedata per the deflate specification in RFC 1951, most notablyMicrosoft products . So even though the 'deflate' transfer encoding using thezlib format would be the more efficient approach ( and in fact exactly what the zlib format was designed for ), using the 'gzip' transferencoding is probably more reliable due to an unfortunate choice ofname on the part of the HTTP 1.1 authors." (source: http://www.gzip.org/zlib/zlib_faq.html ) So, my question: if I send RAW deflate data with NO zlib wrapper (or gzip,for that matter) are there any modern browsers (e.g., IE6 and up, FF,Chrome, Safari, etc) that can NOT understand the raw deflatecompressed data (assuming HTTP request header "Accept-Encoding" contains "deflate")? Deflate data will ALWAYS be a few bytes smaller than GZIP. If all these browsers can successfully decode the data, whatdownsides are there to sending RAW deflate instead of zlib? UPDATE Sept 11 2010: A testing platform has been created for this here
Now provide the response and nothing else.
|
UPDATE: Browsers have been dropping support for raw deflate. zOompf has completed some very thorough research on this very topic here . Unfortunately, it appears that raw deflate is NOT safe to use. Check http://www.vervestudios.co/projects/compression-tests/results for more results. Here are the browsers that have been tested: /* Browser DEFLATE ZLIB */ XP Internet Explorer 6 PASS FAIL XP Internet Explorer 7 PASS FAIL XP Internet Explorer 8 PASS FAIL Vista Internet Explorer 8 PASS FAIL XP Firefox 3.6.* PASS PASS XP Firefox 3.5.3 PASS PASS XP Firefox 3.0.14 PASS PASS Win 7 Firefox 3.6.* PASS PASS Vista Firefox 3.6.* PASS PASS Vista Firefox 3.5.3 PASS PASS XP Safari 3 PASS PASS XP Safari 4 PASS PASS XP Chrome 3.0.195.27 PASS PASS XP Opera 9 PASS PASS XP Opera 10 PASS PASS XP Sea Monkey 1.1.8 PASS PASS Android 1.6 Browser (v4)* N/A N/A OS-X Safari 4 PASS PASS OS X Chrome 7.0.517.44 PASS PASS OS X Opera 10.63 PASS PASS iPhone 3.1 Safari PASS PASS * Android Sends HTTP request header "Accept-Encoding: gzip". Deflate is not permitted. I conclude that we can always send raw DEFLATE (when the HTTP request header "Accept-Encoding" contains "deflate") and the browser will be able to correctly interpret the encoded data. Can someone prove this wrong? note: .NET's native implementation of DEFLATE (System.IO.Compression.DeflateStream) is raw DEFLATE. It also sucks. Please use zlib.net for all of your .NET deflating needs.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1574168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/160173/']}
|
jdg_372736
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28139377
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between daemon and service ? (In windows or Linux).
Now provide the response and nothing else.
|
A daemon is a background, non-interactive program. It is detached from the keyboard and display of any interactive user. The word daemon for denoting a background program is from the Unix culture; it is not universal. A service is a program which responds to requests from other programs over some inter-process communication mechanism (usually over a network). A service is what a server provides. For example, the NFS port mapping service is provided as a separate portmap service, which is implemented as the portmapd daemon. A service doesn't have to be a daemon, but usually is. A user application with a GUI could have a service built into it: for instance, a file-sharing application. For more details: https://askubuntu.com/questions/192058/what-is-technical-difference-between-daemon-service-and-process
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28139377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/601310/']}
|
jdg_372737
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51784903
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to convert SQL inner join query into PostgreSQL inner join query. In this inner join query which tables are using that all tables are not present in one database. we separated tables into two databases i.e. application db and security db users and permission table are present in security db userrolemapping and department are present in application db I tried like below but I am getting following error Error ERROR: cross-database references are not implemented: "Rockefeller_ApplicationDb.public.userrolemapping"LINE 4: INNER JOIN "Rockefeller_ApplicationDb".public.userro.. SQL Stored Function SELECT Department.nDeptID FROM Users INNER JOIN Permission ON Users.nUserID = Permission.nUserID INNER JOIN UserRoleMapping ON Users.nUserID = UserRoleMapping.nUserID INNER JOIN Department ON Permission.nDeptInst = Department.nInstID AND Department.nInstID = 60 WHERE Users.nUserID = 3; PostgreSQL Stored Function SELECT dep.ndept_id FROM "Rockefeller_SecurityDb".public.users as u INNER JOIN "Rockefeller_SecurityDb".public.permissions p ON u.nuser_id = p.nuser_id INNER JOIN "Rockefeller_ApplicationDb".public.userrolemapping as urm ON u.nuser_id = urm.nuser_id INNER JOIN "Rockefeller_ApplicationDb".public.department dep ON p.ndept_inst = dep.ninst_id AND dep.ninst_id = 60 WHERE u.nuser_id = 3;
Now provide the response and nothing else.
|
You cannot join tables from different databases. Databases are logically separated in PostgreSQL by design. If you want to join the tables, you should put them into different schemas in one database rather than into different databases. Note that what is called “database” in MySQL is called a “schema” in standard SQL. If you really need to join tables from different databases, you need to use a foreign data wrapper.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51784903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9240234/']}
|
jdg_372738
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1593620
|
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 this Git repository which contains two folders: binary-search and poker . For example: https://github.com/soulnafein/code-katas I would like to turn these folders into submodules and keep their change history. How can I do that?
Now provide the response and nothing else.
|
The general idea is to use ' git filter-branch' and the following steps: 1) Create a submodule using --subdirectory-filter of filter-branch (after cloning your repo). $ git filter-branch --subdirectory-filter ABC HEAD -- --all See this SO question for more on this step. 2) Create a superproject using an index filter of filter-branch to delete the submodule. $ git filter-branch --index-filter "git rm -r -f --cached --ignore-unmatch ABC" --prune-empty HEAD 3) Commit the submodule to the latest version of the superproject. See Detach subdirectory into separate git repository for a practical example. Each submodule will keep its history. But as said in this patch proposal , it would: lose all the historical connections between the superproject and the submodule, breaking tools like ' git bisect ', and making it difficult to recover old releases. Ideally, each version of the newly created superproject would be linked to the correct version of the submodule (and all the .gitmodules entries would be set up correctly, too, throughout the project's history) If you do not need to have previous history linked to the new submodules, you can follow the steps mentioned above. But if you do need to branch from an older point while have references to your submodules (which are currently simple sub-directories), the you could consider trying the script mentioned in the patch I refer to. It is discussed in this thread , but integrated to Git yet, as Junio C Hamano says: Unfortunately, I do not think we have designed fully (nor implemented at all) behaviour to check out different points of history that has the same submodule moved around in the superproject tree.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1593620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144345/']}
|
jdg_372739
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
494760
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried xtricman⚓ArchVirtual⏺️~ls /proc/self/fd/ -lTotal 0lrwx------ 1 xtricman users 64 1月 16 16:34 0 -> /dev/pts/0lrwx------ 1 xtricman users 64 1月 16 16:34 1 -> /dev/pts/0lrwx------ 1 xtricman users 64 1月 16 16:34 2 -> /dev/pts/0lrwx------ 1 xtricman users 64 1月 16 16:34 3 -> '/home/xtricman/a (deleted)'lr-x------ 1 xtricman users 64 1月 16 16:34 4 -> /proc/1273/fdxtricman⚓ArchVirtual⏺️~ln /proc/self/fd/3 bln: failed to create hard link 'b' => '/proc/self/fd/3': Invalid cross-device link Since the inode is still on the disk, how can I re-create a name for it? What if there's no open file description pointing to that inode but that inode is mmaped? How can I restore it in that case?
Now provide the response and nothing else.
|
You're not supposed to be able to do that (but read below for an interesting exception). If the kernel was to let it happen, then a call like: fd = open(filename, O_CREAT|O_RDWR, 0666);unlink(filename);linkat(fd, "", 0, "/new/path", AT_EMPTY_PATH); would succeed even when the inode referenced by fd has a link count of 0, when done by a process with CAP_DAC_READ_SEARCH caps. But the kernel is actively preventing it from happening, without regard to the capabilities or privileges of the process doing it. int vfs_link(struct dentry *old_dentry, ...{ ... /* Make sure we don't allow creating hardlink to an unlinked file */ if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE)) error = -ENOENT; This is also documented in the manpage: AT_EMPTY_PATH (since Linux 2.6.39) If oldpath is an empty string, create a link to the file referenced by olddirfd (which may have been obtained using the open(2) O_PATH flag). In this case, olddirfd can refer to any type of file except a directory. This will generally not work if the file has a link count of zero (files created with O_TMPFILE and without O_EXCL are an exception) . The caller must have the CAP_DAC_READ_SEARCH capability in order to use this flag. This flag is Linux-specific; define _GNU_SOURCE to obtain its definition. based on the kernel source, there seems to be no other exception besides O_TMPFILE . O_TMPFILE is documented in the open(2) manpage; below is a small example based on that: #define _GNU_SOURCE 1#include <fcntl.h>#include <unistd.h>#include <stdio.h>#include <err.h>int main(int ac, char **av){ char path[64]; int fd; if(ac < 3) errx(1, "usage: %s dir newpath", av[0]); if((fd = open(av[1], O_TMPFILE|O_RDWR, 0666)) == -1) err(1, "open"); /* * ... * write stuff to fd and only "realize" the file at the end if * everything has succeeded */ /* the following line only works with CAP_DAC_READ_SEARCH */ /* if(linkat(fd, "", 0, av[2], AT_EMPTY_PATH)) err(1, "linkat"); */ snprintf(path, sizeof path, "/proc/self/fd/%d", fd); if(linkat(AT_FDCWD, path, AT_FDCWD, av[2], AT_SYMLINK_FOLLOW)) err(1, "linkat"); return 0;}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/494760', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/301641/']}
|
jdg_372740
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.