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
45217166
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hello I have more than one project connecting to a certain DB that is CodeFirst Entity Framework. All Projects are able to connect successfully except for one stubborn one. The error I am getting is: Keyword not supported: 'port' I have looked through countless stackoverflow questions, mysql forums, entity framework forums etc. including: MappingException Edm.String not compatible with SqlServer.varbinary Keyword not supported in MySQL's connection string Keyword not supported: 'metadata' + MySQL My connection string looks like: server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123 My db.cs file looks like: public partial class MyDB : DbContext{ public MyDB () : base("server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123") { Logger.Trace("test123"); } public virtual DbSet<MyItem> MyItems { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<MyItem>() .Property(e => e.Content) .IsUnicode(false); }} When I remove the port:3306 from the connection string I get this: System.Data.Entity.Core.MappingException: Schema specified is not valid. Errors: (8,12) : error 2019: Member Mapping specified is not valid. The type 'Edm.DateTime[Nullable=False,DefaultValue=,Precision=]' of member 'Time' in type 'something.Model.MyItem' is not compatible with 'SqlServer.timestamp[Nullable=False,DefaultValue=,MaxLength=8,FixedLength=True,StoreGeneratedPattern=Identity]' of member 'time' in type 'CodeFirstDatabaseSchema.MyItem'. at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.Init(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders, IList`1 filePaths, Boolean throwOnError) at System.Data.Entity.Core.Mapping.StorageMappingItemCollection..ctor(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders) at System.Data.Entity.ModelConfiguration.Edm.DbDatabaseMappingExtensions.ToStorageMappingItemCollection(DbDatabaseMapping databaseMapping, EdmItemCollection itemCollection, StoreItemCollection storeItemCollection) at System.Data.Entity.ModelConfiguration.Edm.DbDatabaseMappingExtensions.ToMetadataWorkspace(DbDatabaseMapping databaseMapping) at System.Data.Entity.Internal.CodeFirstCachedMetadataWorkspace..ctor(DbDatabaseMapping databaseMapping) at System.Data.Entity.Infrastructure.DbCompiledModel..ctor(DbModel model) at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity) at System.Data.Entity.DbSet`1.Add(TEntity entity) at MyFunction(Int32 userId, String id, String type, String contentJsonString) in I am using MySql Connector and not Sql Server... I am completely stumped by this as well as the rest of my team. Edit:Here is my Web.Config <?xml version="1.0"?> <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/> </configSections> <appSettings file="config-sources\app-settings.config"/> <system.web> <compilation debug="true" targetFramework="4.5.2"> <assemblies> <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> </assemblies> </compilation> <httpRuntime targetFramework="4.5.1"/> </system.web> <connectionStrings configSource="config-sources\ef-connection-strings.config"/> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="MySql.Data" publicKeyToken="C5687FC88969C44D" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-6.8.3.0" newVersion="6.8.3.0" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-3.3.0.0" newVersion="3.3.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-4.2.29.0" newVersion="4.2.29.0"/> </dependentAssembly> </assemblyBinding> </runtime> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" /> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> <system.webServer> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0"/> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="POST,HEAD,GET" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> <security> <requestFiltering> <verbs> <add verb="POST" allowed="true"/> </verbs> </requestFiltering> </security> <defaultDocument> <files> <add value="webhook.ashx"/> </files> </defaultDocument> </system.webServer> </configuration> Now provide the response and nothing else.
The argument of the used base DbContext constructor is called nameOrConnectionString . Hence it supports a name of a connection string from the configuration file, or like in your case an actual connection string. The problem with the later is that it doesn't allow specifying the provider name as with the former coming from the configuration, in which case EF uses the one specified in the defaultConnectionFactory configuration element, which in your case is System.Data.Entity.Infrastructure.SqlConnectionFactory , in other words - Sql Server , hence the port not supported exception. There are several ways to fix the issue. (A) Change the defaultConnectionFactory configuration: <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6"></defaultConnectionFactory> (B) Use named configuration connection string and specify explicitly the provider: <connectionStrings> <add name="MyDB" providerName="MySql.Data.MySqlClient" connectionString="server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123" /></connectionStrings> and change the constructor to public MyDB(){ // ...} or if the name is different than your DbContext derived class name: public MyDB() : base(connection_string_name){ // ...} (C) Use DbConfigurationTypeAttribute : [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]public class MyDB : DbContext{ // ...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45217166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5695863/']}
jdg_79841
stackexchange
llm_judgeable_groundtruth_similarity
551416
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: Suppose I estimate the following model, $$ y = \hat{\beta_0} + \hat{\beta_1} X_1 + \hat{\beta_2} X_2\ ,$$ and am additionally interested in the quantity $$ \gamma = \sqrt{\beta_0^2 - 4\beta_1\beta_2}\ .$$ An estimate of the above, $\hat{\gamma}$ , is clearly given by inserting the estimated $\hat\beta_i$ 's in the above formula. But how does one go about computing the confidence interval around such a "compound" quantity that is not directly estimated? My attempt. My "empirical" approach is as follows. I generate a multivariate normal distribution of size $n$ using the estimated means $\hat\beta_i$ 's and the covariance matrix of the fit. I consequently have a distribution of size $n$ for the $\gamma$ . The mean of this distribution $\bar\gamma$ is naturally then close to the $\hat\gamma$ computed above, and I now additionally have a standard deviation of this distribution $\sigma$ . Using $\sigma$ to generate a confidence interval. If I use the standard definition $\bar\gamma \pm t(\alpha, n-1) \sigma / \sqrt{n}$ , where $t$ is the PPF of the $t$ -distribution, I run into the following quandary: since I pick $n$ myself, I can in fact make the standard error as small as I like. This is not what I want: I am looking for a "natural" confidence interval which depends solely on the uncertainty in my estimates of the $\beta$ 's. Therefore, my idea is the following: $\sigma$ stays positive, and seems to "converge" to its true value for large $n$ : hence, 95% of the values in my $\gamma$ distribution lie within the interval $\bar\gamma \pm 2\sigma$ . Is this approach valid? Now provide the response and nothing else.
Two common approaches for this problem are to calculate the non-linear combination of the coefficients directly from the regression or to bootstrap it. The variance in the former is based on the "delta method", an approximation appropriate in large samples. This was suggested in the other answer, but statistics software can make the calculation a whole lot easier. The variance for the latter comes from resampling the data in memory with replacement, fitting the model, calculating the coefficient combination, and then using the sampled distribution to get the confidence interval. Here's an example of both using Stata: . sysuse auto, clear(1978 automobile data). set seed 11082021. regress price mpg foreign Source | SS df MS Number of obs = 74-------------+---------------------------------- F(2, 71) = 14.07 Model | 180261702 2 90130850.8 Prob > F = 0.0000 Residual | 454803695 71 6405685.84 R-squared = 0.2838-------------+---------------------------------- Adj R-squared = 0.2637 Total | 635065396 73 8699525.97 Root MSE = 2530.9------------------------------------------------------------------------------ price | Coefficient Std. err. t P>|t| [95% conf. interval]-------------+---------------------------------------------------------------- mpg | -294.1955 55.69172 -5.28 0.000 -405.2417 -183.1494 foreign | 1767.292 700.158 2.52 0.014 371.2169 3163.368 _cons | 11905.42 1158.634 10.28 0.000 9595.164 14215.67------------------------------------------------------------------------------. nlcom (gamma_dm:sqrt(_b[_cons] - 4*_b[mpg]*_b[foreign])) gamma_dm: sqrt(_b[_cons] - 4*_b[mpg]*_b[foreign])------------------------------------------------------------------------------ price | Coefficient Std. err. z P>|z| [95% conf. interval]-------------+---------------------------------------------------------------- gamma_dm | 1446.245 361.0078 4.01 0.000 738.6823 2153.807------------------------------------------------------------------------------ The 95% CI using the delta method is [738.6823, 2153.807]. Boostrapping yields [740.5149, 2151.974], which is fairly similar: . bootstrap (gamma_bs:sqrt(_b[_cons] - 4*_b[mpg]*_b[foreign])), reps(500) nodots: regress price mpg foreignLinear regression Number of obs = 74 Replications = 499 Command: regress price mpg foreign[gamma_bs]_bs_1: sqrt(_b[_cons] - 4*_b[mpg]*_b[foreign])------------------------------------------------------------------------------ | Observed Bootstrap Normal-based | coefficient std. err. z P>|z| [95% conf. interval]-------------+----------------------------------------------------------------gamma_bs | _bs_1 | 1446.245 360.0728 4.02 0.000 740.5149 2151.974------------------------------------------------------------------------------Note: One or more parameters could not be estimated in 1 bootstrap replicate; standard-error estimates include only complete replications. Your Solution Your proposed solution would work if you have lots of data, but here it does not do so well with only 74 observations: . quietly regress price mpg foreign. corr2data b_mpg b_foreign b_cons, n(500) means(e(b)) cov(e(V)) clear(obs 500). gen gamma_sim = sqrt(b_cons - 4*b_mpg*b_foreign)(3 missing values generated). sum gamma_sim Variable | Obs Mean Std. dev. Min Max-------------+--------------------------------------------------------- gamma_sim | 497 1426.183 366.6408 197.5594 2397.263. display "[" %-9.4f r(mean) + invttail(r(N)-1,.975)*r(sd) ", " r(mean) + invttail(r(N)-1,.025)*r(sd) "]"[705.8224 , 2146.5434] The CI here is [705.8224 , 2146.5434], which is noticeably different from the two CIs above. My thought is that if you are going to simulate, you might as well bootstrap and not rely on the normal approximation that is only valid asymptotically. If you have lots of data, the difference between bootstrapping and sampling from MVN parameterized by estimated coefficients and variance should not be noticeable.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/551416', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/277115/']}
jdg_79842
stackexchange
llm_judgeable_groundtruth_similarity
4977
Below is a question asked on the forum bioinformatics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I do not understand how to specify correctly the parameters on a SLURM cluster for snakemake to use them. I tried submitting the following SLURM file, but it does not work this way and the number of cores used is only 1 , not 20 : #!/bin/bash#SBATCH -p standard#SBATCH -A overall #SBATCH --time=12:00:00#SBATCH --output=snakemake%A.out#SBATCH --error=snakemake%A.err#SBATCH --nodes=1#SBATCH --ntasks=1#SBATCH --cpus-per-task=20#SBATCH --mem=120000snakemake Then, I tried following snakemake tutorial . And created cluster.json based on the SLURM parameters that I need: { "__default__" : { "A" : "overall", "time" : "24:00:00", "nodes": 1, "ntasks": 1, "cpus" : 20, "p" : "standard", "mem": 120000, "output": "snakemake%A.out", "error": "snakemake%A.err" }} And ran snakemake inside a newly created snakemake.sh script: #!/bin/bashsnakemake -j 999 --cluster-config cluster.json --cluster "sbatch -A {cluster.A} -p {cluster.p} \ -t {cluster.time} --output {cluster.output} --error {cluster.error} -- nodes {cluster.nodes} \--ntasks {cluster.ntasks} --cpus-per-task {cluster.cpus} --mem {cluster.mem}" And it is giving me an error now: sbatch: error: Unable to open file /bin/sh: line 1: -t: command not found Error submitting jobscript (exit code 127): I am now completely lost at what I shoould actually do. I would prefer plain regular .slurm file submission, but how to make snakemake use them? Any suggestions would be greatly appreciated. I removed \ - line separators in the snakemake.sh script: #!/bin/bashsnakemake -j 10 --cluster-config cluster.json --cluster "sbatch -A {cluster.A} -p {cluster.p} -t {cluster.time} --output {cluster.output} --error {cluster.error} --nodes {cluster.nodes} --ntasks {cluster.ntasks} --cpus-per-task {cluster.cpus} --mem {cluster.mem}" And it started to run. It is not convenient though for me. I would rather prefer submitting just one job using .slurm file passing all of the parameters from #SBATCH . Is it possible? Now provide the response and nothing else.
You can omit --nodes , you need the following: #!/bin/bash#SBATCH --ntasks-per-node=1#SBATCH -c threads_from_snakemake#SBATCH -p some_partitionCommands go here For slurm, you may want to modify my SlurmEasy script . We use that with snakemake all the time, usually of the form: snakemake -c "SlurmEasy -t {threads} -n {rule} --mem-per-cpu {cluster.memory}" ... You'll also want units with your memory requests, like 12G . Also, in general it's best not to submit snakemake itself to the cluster, rather run it on an interactive node and have it submit jobs on your behalf (if the admins complain point out that snakemake is barely using any resources on the head node).
{}
{'log_upvote_score': 4, 'links': ['https://bioinformatics.stackexchange.com/questions/4977', 'https://bioinformatics.stackexchange.com', 'https://bioinformatics.stackexchange.com/users/2005/']}
jdg_79843
stackexchange
llm_judgeable_groundtruth_similarity
41744368
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 still learning and in response to one of my questions: here , I was told to that it might be due because the element in question is not in view. I looked through the documentation and SO, here was the most relevant answer: here You can use the "org.openqa.selenium.interactions.Actions" class to move to an element: WebElement element = driver.findElement(By.id("my-id"));Actions actions = new Actions(driver);actions.moveToElement(element);## actions.click();actions.perform(); When I try to use the above to scroll to the element:It says WebElement not defined. I think this is because I have not imported the relevant module. Can someone point out what I am supposed to import? Edit:As pointed out by alecxe, this was java code. But in the meantime right after trying to figure it out for some time. I have found out the import method for WebElement: from selenium.webdriver.remote.webelement import WebElement Might help someone like me. The how of it is also a good lesson, IMO: Went to: Documentation The class selenium.webdriver.remote.webelement.WebElement(parent, id_, w3c=False) Need to be separated into the command form mentioned above. Now provide the response and nothing else.
You are trying to run Java code with Python. In Python/Selenium, the org.openqa.selenium.interactions.Actions are reflected in ActionChains class : from selenium.webdriver.common.action_chains import ActionChainselement = driver.find_element_by_id("my-id")actions = ActionChains(driver)actions.move_to_element(element).perform() Or, you can also "scroll into view" via scrollIntoView() : driver.execute_script("arguments[0].scrollIntoView();", element) If you are interested in the differences: scrollIntoView vs moveToElement
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/41744368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6387095/']}
jdg_79844
stackexchange
llm_judgeable_groundtruth_similarity
42060
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the linux kernel is there a file that I can start to add my code, ex. load libraries? thanks Now provide the response and nothing else.
If you're trying to accomplish a user-space task by directly modifying the operating system's kernel, you're doing something wrong 99.999% of the times. For cases where a direct interaction with kernel's subsystems and data structures is required, people invented the loadable kernel modules. I think you have a misunderstood the terms kernel and shell . To answer your question: in order to play an mp3 file at system startup, you should probably get mpg123 or some other command-line music player, and launch it via an init script , after your sound system is initialized, as Mat already pointed out in an earlier comment. For more information on init scripts usage, refer to your distribution's documentation and man-pages.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/42060', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/15813/']}
jdg_79845
stackexchange
llm_judgeable_groundtruth_similarity
49038464
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 calibrate a fisheye lens following these instructions https://medium.com/@kennethjiang/calibrate-fisheye-lens-using-opencv-333b05afa0b0 where you can find the full code I'm using for the calibration part. I arrive at this point where: N_OK = len(objpoints)K = np.zeros((3, 3))D = np.zeros((4, 1))rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)] rms, _, _, _, _ = \ cv2.fisheye.calibrate( objpoints, imgpoints, gray.shape[::-1], K, D, rvecs, tvecs, calibration_flags, (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-3) )print("Found " + str(N_OK) + " valid images for calibration")print("DIM=" + str(_img_shape[::-1]))print("K=np.array(" + str(K.tolist()) + ")")print("D=np.array(" + str(D.tolist()) + ")") I get this error: Traceback (most recent call last)<ipython-input-10-deaca9981fe4> in <module>() 13 tvecs, 14 calibration_flags,---> 15 (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-3) 16 ) 17 print("Found " + str(N_OK) + " valid images for calibration")error: C:\ci\opencv_1512688052760\work\modules\calib3d\src\fisheye.cpp:1414: error: (-3) CALIB_CHECK_COND - Ill-conditioned matrix for input array 0 in function cv::internal::CalibrateExtrinsics I don't understand what's going on and I could only find so little information around the internet, does anyone have experienced something similar and know how to solve this? Thanks These are the images of the checkerboard I'm using: https://i.stack.imgur.com/goHIg.jpg https://i.stack.imgur.com/kja3O.jpg https://i.stack.imgur.com/XbIzh.jpg https://i.stack.imgur.com/uQ9Gr.jpg https://i.stack.imgur.com/N8aLJ.jpg https://i.stack.imgur.com/JMmmZ.jpg https://i.stack.imgur.com/QJ8wn.jpg https://i.stack.imgur.com/NmiFQ.jpg https://i.stack.imgur.com/sQHdd.jpg https://i.stack.imgur.com/DNBuD.jpg https://i.stack.imgur.com/vFtOo.jpg https://i.stack.imgur.com/lhkF5.jpg Now provide the response and nothing else.
I think it is because your variable calibration_flags has CALIB_CHECK_COND set.Try disabling this flag. Without it I was able to undistort your images (see links below). I am not sure what this check is for (the documentation is not very explicit). This flag reject some images¹ of my gopro hero 3 even when the chessboard is visible and detected. In my case one image among 20 is not passing this test. This image has the chessboard close to the left border. https://i.stack.imgur.com/m2WF6.jpg https://i.stack.imgur.com/KiTRz.jpg https://i.stack.imgur.com/MhHyN.jpg https://i.stack.imgur.com/pSiyG.jpg https://i.stack.imgur.com/drXSL.jpg https://i.stack.imgur.com/DDze1.jpg https://i.stack.imgur.com/b6l8f.jpg https://i.stack.imgur.com/9MrAk.jpg https://i.stack.imgur.com/WYmg5.jpg https://i.stack.imgur.com/rmJ5Q.jpg https://i.stack.imgur.com/K8k8Y.jpg https://i.stack.imgur.com/MiBER.jpg ¹ in OpenCV versions >= 3.4.1 the error message tells you which image is not passing the test
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49038464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2779432/']}
jdg_79846
stackexchange
llm_judgeable_groundtruth_similarity
9544370
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is an actual name of instance variable, say, topSpeed, as from lectures of Stanford University about the Objective-C and iOS development? Here is the code: @property (nonatomic) double topSpeed; Looking at this code I will think that I have defined a variable topSpeed in the class.I can't understand why it will declare automatically the getter method with the name the same as the variable name - topSpeed? Another question is when we use @synthesize topSpeed = _topSpeed And if we look at what the @synthesize will generate: - (double) setTopSpeed:(double)speed{ _topSpeed = speed;}- (double) topSpeed{ return _topSpeed;} What is _topSpeed here and what is topSpeed? I have declared a variable topSpeed, not the _topSpeed. What if I don't use property what would the variable name be? Now provide the response and nothing else.
In the earlier days of Obj-C and still today you declared variables in your class's header file like so: @interface MySubclass : NSObject { int varName;} Then you would have to manually create setter and getter methods to access the variable outside your class. In order to help deal with memory management (useful for objects), Apple introduced properties in Obj-C 2.0 and it allowed you to define the accessors for a given variable. You could say that a variable would have certain attributes (such as retaining or copying a value, having alternate setter or getter name, etc) and you defined this like: @property (someAttributes) int varName; then in your @implementation you could @synthesize these properties with the given attributes and the compiler would generate setter and getter methods for your variable. @synthesize varName; // Generates -setVarName: and -varName for you Now, today the idea is that you can move away from implementing the instance variables in the {} section and just declare a property and a synthesize. What we get if we just say @property (nonatomic) double topSpeed;@synthesize topSpeed; is a setter and a getter called setTopSpeed: and topSpeed with an instance variable called topSpeed (created by the compiler) to store the value. The idea behind @synthesize topSpeed = _topSpeed; is that the instance variable name will be _topSpeed but the accessor names will still be -setTopSpeed: and -topSpeed . This helps for code readability because there can be confusion between when you say self.topSpeed or topSpeed in your code (the first calls the accessor the second is the ivar). The _topSpeed differentiates itself from normal variables and also makes it explicit when you're calling self.topSpeed (the accessor) vs _topSpeed (the ivar). Apple is moving to this underscore syntax as well so don't think that it's going extinct, because it's quite the opposite. Update: (See Tommy's comment) It also helps with variable naming collisions. If you had to implement setTopSpeed: yourself it would look something like this: - (void)setTopSpeed:(double)topSpeed { _topSpeed = topSpeed; // _topSpeed makes it obvious it's an ivar}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9544370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/242388/']}
jdg_79847
stackexchange
llm_judgeable_groundtruth_similarity
43264
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: Given two numbers, month and year, how can I compute the first and the last day of that month ? My goal is to output these three lines: month / year (month in textual form but that is trivial) for each day of the month: name of the day of the week for the current day: Fri. & Sat. & Sun. [...] day number within the month: 1 & 2 & 3 [...] & 28 & .. ? I'm looking for a solution using GNU date or BSD date (on OS X). Now provide the response and nothing else.
# Last month:l_first_date=$(date -d "`date +%Y%m01` -1 month" +%Y-%m-%d)l_last_date=$(date -d "`date +%Y%m01` -1 day" +%Y-%m-%d)# This month:t_first_date=$(date +%Y-%m-01)t_last_date=$(date -d "`date +%Y%m01` +1 month -1 day" +%Y-%m-%d)# Next month:n_first_date=$(date -d "`date +%Y%m01` +1 month" +%Y-%m-%d)n_last_date=$(date -d "`date +%Y%m01` +2 month -1 day" +%Y-%m-%d)# Print everythingecho "Last month: $l_first_date to $l_last_date"echo "This month: $t_first_date to $t_last_date"echo "Next month: $n_first_date to $n_last_date"
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/43264', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/20687/']}
jdg_79848
stackexchange
llm_judgeable_groundtruth_similarity
43386277
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 following AudioContext() sound object in JavaScript. Its volume is 100%. I want to play its volume in 10% (where volume = 0.1). How can I reduce its volume to 10%? const aCtx = new AudioContext();let source = aCtx.createBufferSource();let buf;fetch('https://dl.dropboxusercontent.com/s/knpo4d2yooe2u4h/tank_driven.wav') // can be XHR as well .then(resp => resp.arrayBuffer()) .then(buf => aCtx.decodeAudioData(buf)) // can be callback as well .then(decoded => { source.buffer = buf = decoded; source.loop = true; source.connect(aCtx.destination); check.disabled = false; });check.onchange = e => { if (check.checked) { source.start(0); // start our bufferSource } else { source.stop(0); // this destroys the buffer source source = aCtx.createBufferSource(); // so we need to create a new one source.buffer = buf; source.loop = true; source.connect(aCtx.destination); }}; <label>Start Playing</label><input type="checkbox" id="check" disabled><br><br>Its volume is 100%. Please help me to reduce it to 10%. Now provide the response and nothing else.
We use GainNodes to control the volume. var gainNode = aCtx.createGain()gainNode.gain.value = 0.1 // 10 %gainNode.connect(aCtx.destination)// now instead of connecting to aCtx.destination, connect to the gainNodesource.connect(gainNode) solution const aCtx = new AudioContext();const gainNode = aCtx.createGain();gainNode.gain.value = 0.1; // setting it to 10%gainNode.connect(aCtx.destination);let source = aCtx.createBufferSource();let buf;fetch('https://dl.dropboxusercontent.com/s/knpo4d2yooe2u4h/tank_driven.wav') // can be XHR as well .then(resp => resp.arrayBuffer()) .then(buf => aCtx.decodeAudioData(buf)) // can be callback as well .then(decoded => { source.buffer = buf = decoded; source.loop = true; source.connect(gainNode); check.disabled = false; });check.onchange = e => { if (check.checked) { source.start(0); // start our bufferSource } else { source.stop(0); // this destroys the buffer source source = aCtx.createBufferSource(); // so we need to create a new one source.buffer = buf; source.loop = true; source.connect(gainNode); }}; <label>Start Playing</label><input type="checkbox" id="check" disabled><br><br>Its volume is 100%. Please help me to reduce it to 10%.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43386277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2037411/']}
jdg_79849
stackexchange
llm_judgeable_groundtruth_similarity
87674
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: As how I understand it, there are two ways of converting DC. One is by using a voltage regulator (zener diode, feedback combination etc), and the other is by using a buck boost converter . Firstly, if there are other methods, please tell me! How do lab bench power supplies work? I've heard that buck-boost supplies are noisy (for precise lab requirements) and I know that voltage regulators basically drop the remaining voltage as wasted energy . Now to my question: I have only seen a single transformer in any lab supply, so obviously the output voltage of it is fixed . If say the bench supply's max voltage output is 24V, then I'm assuming the output of the transformer would be ~24+V. If this is going (after AC-DC conversion) to a voltage regulator, and say I pick 1V fixed o/p voltage and connect the bench supply to a load that draws 1A current. If I understand it correctly) the lab supply will waste at least (P=VI=[24-1]*1) 23W and have an efficiency of just 4% . Is this true? If so, the heat output would increase dramatically as selected output voltage is lowered (and current increased). So much energy would be wasted? Not to mention heat sinking etc. What am I missing? Is there a better way? Or is this a necessary sacrifice for getting a precise power supply? Now provide the response and nothing else.
Many supplies nowadays use both a switching regulator and a linear regulator together. The two are set up to track each other, so the voltage dropped by the linear regulator is never excessive. So for example, say you set the supply to 5V, you might have a 24V input which the switching regulator drops down to 6-7V, then the linear regulator drops that down to the desired 5V. This way you get the benefit of the switchers efficiency with the quiet output of the linear regulator. However, as mentioned by Passerby, efficiency and weight is not always so much of a concern compared to reliability and quietness, so many simply use a purely linear supply and deal with the losses involved. To keep from being ridiculously inefficient however, generally many linear supplies will have more than one tap on the transformer which are switched between at appropriate points in the range (e.g. instead of dropping from 24V to 1V, it would switch to, say, a 5V tap so a lot less power is dissipated) You can usually hear the clicks of the relays at certain points in the voltage range.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/87674', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/24404/']}
jdg_79850
stackexchange
llm_judgeable_groundtruth_similarity
2589653
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: Say I want to evaluate this sum:$$\sum_{x=2}^\infty \ln(x^3+1)-\ln(x^3-1)$$We can rewrite the sum as$$\ln\left(\prod_{x=2}^\infty \frac{x^3+1}{x^3-1}\right)$$We can split the product into two products:$$\ln\left(\prod_{x=2}^\infty \frac{x+1}{x-1}\right)+\ln\left(\prod_{x=2}^\infty \frac{x^2-x+1}{x^2+x+1}\right)$$These are both telescopic products! We can rewrite them as $$\ln\left(\prod_{x=2}^\infty \frac{(x+2)-1}{x-1}\right)+\ln\left(\prod_{x=2}^\infty \frac{(x-1)^2+(x-1)+1}{x^2+x+1}\right)$$Plugging in numbers makes this pattern more obvious;$$\ln\left(\prod_{x=2}^\infty \frac{\color{green}{3}}{1}\frac {\color{red}{4}}{2} \frac{\color{blue}{5}}{\color{green}{3}} \frac{\color{bluedark}{6}}{\color{red}{4}} \right) +\ln\left(\prod_{x=2}^\infty \frac{3}{\color{green}{7}} \frac{\color{green}{7}}{\color{red}{13}} \frac{\color{red}{13}}{\color{blue}{21}} \right)$$Simplifying, we get that the sum is equal to$$\ln(1/2)+\ln(3)=\ln\left(\frac 32 \right) \approx 0.405465108108164381978013115464349136571990423462494197614$$However, when I put the sum in Wolfram Alpha directly, I get the following number: $$0.4054588737136331726677370820628648457601892466568342890929$$ Why are these two numbers different? It's not a small difference either; it's on the 5th number after the decimal point! How can Wolfram make such an error? Now provide the response and nothing else.
In Mathematica , the input FullSimplify[Sum[Log[x^3+1]-Log[x^3-1],{x,2,Infinity}]] gives Log[3/2] , exactly. In WolframAlpha, the issue is that when you request more digits of accuracy, it converts your input into the command NSum[Log[x^3 + 1] - Log[x^3 - 1], {x, 2, Infinity}, WorkingPrecision -> 104] which of course is insufficient working precision for the number of decimal digits that it displays due to the very slow convergence of the sum. Somewhat ironically, if you enter Product[(x^3+1)/(x^3-1),{x,2,n}] into WolframAlpha, you get exact output: $$\frac{3n(n+1)}{2(n^2+n+1)},$$ which is correct, furthermore upon taking Limit[3n(n+1)/(2(n^2+n+1)), n -> Infinity] , you get the correct answer $3/2$. So it isn't as if WolframAlpha cannot compute the original sum symbolically as Mathematica did. It just needs a little extra help, it seems. Users of WolframAlpha don't always realize that although it is using the same underlying algorithms as Mathematica , it is not the same thing. There are things that one does that the other does not. Precise control of processing of input, for example, is something that the former does not do. Update. I believe the above response is not entirely sufficient to explain the behavior of WolframAlpha. When I changed the summand to $$\log \left(1 + \frac{2}{x^3-1}\right),$$ WolframAlpha still gives the wrong result when more digits are requested, despite the fact that the generated code NSum[Log[1 + 2/(x^3 - 1)], {x, 2, Infinity}, WorkingPrecision -> 104] yields the correct result. So this points to an internal inconsistency with WolframAlpha that cannot be solely explained by the insufficient precision used in NSum . To confirm, in Mathematica I input both variants with NSum , namely NSum[Log[x^3 + 1] - Log[x^3 - 1], {x, 2, Infinity}, WorkingPrecision -> 104] as well as NSum[Log[1 + 2/(x^3 - 1)], {x, 2, Infinity}, WorkingPrecision -> 104] The first input, as expected, generates a warning NIntegrate::ncvb . Also as expected, the second one does not. But if this is the case, then WolframAlpha should not still present the wrong result in the second case when more digits are requested, given that this is the exact code that it generated. When you open up the computable notebook (click the orange cloud) and evaluate the expression, you are basically running a cloud version of Mathematica . Doing this gets the right answer. So I suspect that there is some kind of bug in WolframAlpha that fails to present the correct output.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/2589653', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/405572/']}
jdg_79851
stackexchange
llm_judgeable_groundtruth_similarity
10833836
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I handle the paste selected through right click in javascript?I tried with "onpaste" event and all other html events available but nothing works. Now provide the response and nothing else.
The onpaste event should work in all modern browsers ( UPD Including Opera >= 12.10 1 ). Bind it in jQuery like this: $('#txt').on('paste', function() {console.log('text pasted!')}) Here's a live example: http://jsfiddle.net/7N6Xq/ In pure JavaScript it would look something like this for modern browsers elem.addEventListener ("paste", handler, false); // all browsers and IE9+ and for old IE versions: elem.attachEvent ("onpaste", handler); // IE<9 You can also combine it with oninput and other events ( change , propertychange , dragdrop , etc.) to create a relatively bulletproof tracking of content change. Footnotes: 1 Opera supports Clipboard API starting from Presto/2.10.286 which corresponds to 12.10 as suggested here . Blink versions of Opera (starting from 15) should also support it but I am unable to test it as there is still no Linux version.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10833836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1016413/']}
jdg_79852
stackexchange
llm_judgeable_groundtruth_similarity
31858
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following expression from which I want to extract data for a contour plot. a = (r^2/2 + (r BesselI[1, 2 r])/( 2 BesselI[0, 2 (1 + 0.24` z + 0.2` Sin[6.2834` z])])) (1.386371389484812` + 0.4367320268554276` (2.289733608959785` - 0.7936052912509126` (1 + 0.24` z + 0.2` Sin[6.2834` z])^2) + (-45.44` BesselI[0, 2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] - 4 (1.386371389484812` + 0.4367320268554276` (2.289733608959785` - 0.7936052912509126` (1 + 0.24` z + 0.2` Sin[6.2834` z])^2) + 0.346592847371203` (1 + 0.24` z + 0.2` Sin[6.2834` z])^2) (4 BesselI[1, 2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] (1 + 0.24` z + 0.2` Sin[6.2834` z]) - 4 BesselI[0, 2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] (1 + 0.24` z + 0.2` Sin[6.2834` z])^2))/(4 (BesselI[1, 2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] - 4 BesselI[0, 2 (1 + 0.24` z + 0.2` Sin[6.2834` z])] (1 + 0.24` z + 0.2` Sin[6.2834` z])^2)) + 0.346592847371203` (1 + 0.24` z + 0.2` Sin[6.2834` z])^2); ContourPlot[a, {z, 0, 1.5}, {r, 3, 5.5}, PlotPoints -> 180, Frame -> True, FrameStyle -> {Thickness[0.0005]}, Axes -> False, FrameStyle -> {Thickness[0.0005]}, ContourShading -> False] The output should be a text file. Now provide the response and nothing else.
Original answer For getting points of individual lines one can use Normal : points = Cases[Normal@plot, Line[pts_, ___] :> pts, Infinity]; (I assumed here that each Line primitive contains exactly one line, as it is true for the current ContourPlot implementation. Generally, a Line primitive can contain several lines and for this case this code should be rewritten, for example: points = Cases[Normal@plot, Line[pts_, ___] :> Flatten[pts, Depth[pts] - 3], Infinity]; ) To convert this list of lists of points into multicolumn table one can use: multicolumnTable = Flatten /@ Flatten[PadRight[points, Automatic, ""], {2}]; Here is how it looks: TableForm[multicolumnTable[[;; 10, ;; 6]], TableHeadings -> {None, Flatten@Array[{x@#, y@#} &, Length[points]]}] Exporting the multicolumn table: Export["table.tsv", multicolumnTable] Extracting the values of the objective function (per request in comments) The 2D Graphics object generated by ContourPlot does not necessarily contain information on the values of the objective function (Z-coordinate). The only source of this information are contour labels which are generated according to the ContourLabels option. With the default value ContourLabels->Automatic each contour is wrapped by Tooltip with second argument being the contour label providing information on the value of the objective function. In the current ContourPlot implementation the label is simply a number and the contour is one or more Line primitives each containing exactly one actual line. Assuming that the plot does not contain any other Tooltip s, it is straightforward to extract the data: points = Flatten[ Cases[Normal@plot, Tooltip[contour_, label_] :> Cases[contour, l_Line :> ArrayPad[First@l, {{0}, {0, 1}}, label]], Infinity], 1];multicolumnTable = Flatten /@ Flatten[PadRight[points, Automatic, ""], {2}];TableForm[multicolumnTable[[;; 10, ;; 6]], TableHeadings -> {None, Flatten@Array[{x@#, y@#, z@#} &, Length[points]]}]Export["table.tsv", multicolumnTable]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/31858', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/8538/']}
jdg_79853
stackexchange
llm_judgeable_groundtruth_similarity
12134231
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like serialize an object such that one of the fields will be named differently based on the type of the field. For example: public class Response { private Status status; private String error; private Object data; [ getters, setters ] } Here, I would like the field data to be serialized to something like data.getClass.getName() instead of always having a field called data which contains a different type depending on the situation. How might I achieve such a trick using Jackson? Now provide the response and nothing else.
Using a custom JsonSerializer . public class Response { private String status; private String error; @JsonProperty("p") @JsonSerialize(using = CustomSerializer.class) private Object data; // ...}public class CustomSerializer extends JsonSerializer<Object> { public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeObjectField(value.getClass().getName(), value); jgen.writeEndObject(); }} And then, suppose you want to serialize the following two objects: public static void main(String... args) throws Exception { ObjectMapper mapper = new ObjectMapper(); Response r1 = new Response("Error", "Some error", 20); System.out.println(mapper.writeValueAsString(r1)); Response r2 = new Response("Error", "Some error", "some string"); System.out.println(mapper.writeValueAsString(r2));} The first one will print: {"status":"Error","error":"Some error","p":{"java.lang.Integer":20}} And the second one: {"status":"Error","error":"Some error","p":{"java.lang.String":"some string"}} I have used the name p for the wrapper object since it will merely serve as a p laceholder. If you want to remove it, you'd have to write a custom serializer for the entire class, i.e., a JsonSerializer<Response> .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12134231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/862193/']}
jdg_79854
stackexchange
llm_judgeable_groundtruth_similarity
7341835
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 searched the entire internet (maybe I am exaggerating a little) for a tutorial on how to put a DatePicker into a UIPopover and display that in an iPad application. I have tried creating a viewcontroller, placing the datepicker in the view controller and then: self.popover = [[UIPopoverController alloc] initWithContentViewController:sa]; (sa is the name of the viewcontroller i created), but this doesn't work, and the app crashes. Can anyone help? Now provide the response and nothing else.
Try with below code. It will work fine: Objective-C - (IBAction)showDatePicker:(UIButton *)sender { UIDatePicker *datePicker = [[UIDatePicker alloc]init];//Date picker datePicker.frame = CGRectMake(0, 0, 320, 216); datePicker.datePickerMode = UIDatePickerModeDateAndTime; [datePicker setMinuteInterval:5]; [datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];//need to implement this method in same class UIView *popoverView = [[UIView alloc] init]; //view popoverView.backgroundColor = [UIColor clearColor]; [popoverView addSubview:datePicker]; // here you can add tool bar with done and cancel buttons if required UIViewController *popoverViewController = [[UIViewController alloc] init]; popoverViewController.view = datePicker; popoverViewController.view.frame = CGRectMake(0, 0, 320, 216); popoverViewController.modalPresentationStyle = UIModalPresentationPopover; popoverViewController.preferredContentSize = CGSizeMake(320, 216); popoverViewController.popoverPresentationController.sourceView = sender; // source button popoverViewController.popoverPresentationController.sourceRect = sender.bounds; // source button bounds //popoverViewController.popoverPresentationController.delegate = self; [self presentViewController:popoverViewController animated:YES completion:nil];}- (void)dateChanged:(UIDatePicker *)datePicker { NSLog(@"DATE :: %@", datePicker.date);} Swift 4.2 @IBAction func showDatePicker(_ sender: UIButton) { let datePicker = UIDatePicker()//Date picker let datePickerSize = CGSize(width: 320, height: 216) //Date picker size datePicker.frame = CGRect(x: 0, y: 0, width: datePickerSize.width, height: datePickerSize.height) datePicker.datePickerMode = .dateAndTime datePicker.minuteInterval = 5 datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged) let popoverView = UIView() popoverView.backgroundColor = UIColor.clear popoverView.addSubview(datePicker) // here you can add tool bar with done and cancel buttons if required let popoverViewController = UIViewController() popoverViewController.view = popoverView popoverViewController.view.frame = CGRect(x: 0, y: 0, width: datePickerSize.width, height: datePickerSize.height) popoverViewController.modalPresentationStyle = .popover popoverViewController.preferredContentSize = datePickerSize popoverViewController.popoverPresentationController?.sourceView = sender // source button popoverViewController.popoverPresentationController?.sourceRect = sender.bounds // source button bounds popoverViewController.popoverPresentationController?.delegate = self // to handle popover delegate methods self.present(popoverViewController, animated: true, completion: nil) } @objc func dateChanged(_ datePicker: UIDatePicker) { print("DATE :: \(datePicker.date)") } Same code will work iPhone also if you implement below delegate respective in view controller extension YourViewController : UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { // Force popover style return UIModalPresentationStyle.none }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7341835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/901421/']}
jdg_79855
stackexchange
llm_judgeable_groundtruth_similarity
54979168
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using asp.net core 2.1 and I have a problem on redirect.My URL is like: HTTP://localhost:60695/ShowProduct/2/شال-آبی the last parameter is in Persian.and it throws below error: InvalidOperationException: Invalid non-ASCII or control character in header: 0x0634 but when I change the last parameter in English like: HTTP://localhost:60695/ShowProduct/2/scarf-blue it works and everything is OK.I'm using below codes for redirecting: [HttpPost][Route("Login")]public IActionResult Login(LoginViewModel login, string returnUrl){ if (!ModelState.IsValid) { ViewBag.ReturnUrl = returnUrl; return View(login); } //SignIn Codes is hidden if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } if (permissionService.CheckUserIsInRole(user.UserId, "Admin")) { return Redirect("/Admin/Dashboard"); } ViewBag.IsSuccess = true; return View();} how can I fix the problem? Now provide the response and nothing else.
General speaking, it is caused by the Redirect(returnUrl) . This method will return a RedirectResult(url) and finally set the Response.Headers["Location"] as below : Response.Headers[HeaderNames.Location] = returnUrl; But the Headers of HTTP doesn't accept non-ASCII characters. There're already some issues( #2678 , #4919 ) suggesting to encode the URL by default. But there's no such a out-of-box function yet. A quick fix to your issue: var host= "http://localhost:60695";var path = "/ShowProduct/2/شال-آبی";path=String.Join( "/", path.Split("/").Select(s => System.Net.WebUtility.UrlEncode(s)));return Redirect(host+path);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54979168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7390462/']}
jdg_79856
stackexchange
llm_judgeable_groundtruth_similarity
363307
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: Whenever I need division, for example, condition checking, I would like to refactor the expression of division into multiplication, for example: Original version: if(newValue / oldValue >= SOME_CONSTANT) New version: if(newValue >= oldValue * SOME_CONSTANT) Because I think it can avoid: Division by zero Overflow when oldValue is very small Is that right? Is there a problem for this habit? Now provide the response and nothing else.
Two common cases to consider: Integer arithmetic Obviously if you are using integer arithmetic (which truncates) you will get a different result. Here's a small example in C#: public static void TestIntegerArithmetic(){ int newValue = 101; int oldValue = 10; int SOME_CONSTANT = 10; if(newValue / oldValue > SOME_CONSTANT) { Console.WriteLine("First comparison says it's bigger."); } else { Console.WriteLine("First comparison says it's not bigger."); } if(newValue > oldValue * SOME_CONSTANT) { Console.WriteLine("Second comparison says it's bigger."); } else { Console.WriteLine("Second comparison says it's not bigger."); }} Output: First comparison says it's not bigger.Second comparison says it's bigger. Floating point arithmetic Aside from the fact that division can yield a different result when it divides by zero (it generates an exception, whereas multiplication does not), it can also result in slightly different rounding errors and a different outcome. Simple example in C#: public static void TestFloatingPoint(){ double newValue = 1; double oldValue = 3; double SOME_CONSTANT = 0.33333333333333335; if(newValue / oldValue >= SOME_CONSTANT) { Console.WriteLine("First comparison says it's bigger."); } else { Console.WriteLine("First comparison says it's not bigger."); } if(newValue >= oldValue * SOME_CONSTANT) { Console.WriteLine("Second comparison says it's bigger."); } else { Console.WriteLine("Second comparison says it's not bigger."); }} Output: First comparison says it's not bigger.Second comparison says it's bigger. In case you don't believe me, here is a Fiddle which you can execute and see for yourself. Other languages may be different; bear in mind, however, that C#, like many languages, implements an IEEE standard (IEEE 754) floating point library, so you should get the same results in other standardized run times. Conclusion If you are working greenfield , you are probably OK. If you are working on legacy code, and the application is a financial or other sensitive application that performs arithmetic and is required to provide consistent results, be very cautious when changing around operations. If you must, be sure that you have unit tests that will detect any subtle changes in the arithmetic. If you are just doing things like counting elements in an array or other general computational functions, you will probably be OK. I am not sure the multiplication method makes your code any clearer, though. If you are implementing an algorithm to a specification, I would not change anything at all, not just because of the problem of rounding errors, but so that developers can review the code and map each expression back to the specification to ensure there are no implementation flaws.
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/363307', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/248528/']}
jdg_79857
stackexchange
llm_judgeable_groundtruth_similarity
9873674
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 ist possible to tell String.split("(") function that it has to split only by the first found string "("? Example: String test = "A*B(A+B)+A*(A+B)";test.split("(") should result to ["A*B" ,"A+B)+A*(A+B)"]test.split(")") should result to ["A*B(A+B" ,"+A*(A+B)"] Now provide the response and nothing else.
Yes, absolutely: test.split("\\(", 2); As the documentation for String.split(String,int) explains: The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n , and the array's last entry will contain all input beyond the last matched delimiter.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9873674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1148626/']}
jdg_79858
stackexchange
llm_judgeable_groundtruth_similarity
12122369
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 evaluating existing resources for script loading optimization, but I readed in some articles like this , refers to the older browsers block other downloads until this sequential script loading phase is completed. I check Modernizr(yepnope.js), headjs and ControlJs as candidates. But, is it necesary use this tools for parallel script loading in modern browsers? Now provide the response and nothing else.
I believe by default most browsers today will actually load the scripts in parallel; but the browser will not by default execute the scripts in parallel. For example, in the following code the scripts will be loaded in parallel. In the image we can see that Fast1.js and Fast2.js loads extremely fast, but based on the time in the browser console, Fast2.js executes 3 seconds after Fast1.js executes. Also, something else to keep in mind is that the order of the files can make a difference. The Backbone.js file depends on the underscore.js file. If we changed the order of these files, where bacbone.js is before underscore.js, an error will be raised. <html ><head> <title></title> <script src="scripts/fast1.js" type="text/javascript"></script> <script src="scripts/libs/jquery-1.8.3.js" type="text/javascript"></script> <script src="scripts/libs/underscore.js" type="text/javascript"></script> <script src="scripts/libs/backbone.js" type="text/javascript"></script> <script src="scripts/fast2.js" type="text/javascript"></script></head><body> Hello <script type="text/javascript"> console.log("html: " + Date()); </script> <img src="imgs/bImg.png" /></body></html> Here's the code for the JavaScript file Fast1.js and Fast2.js console.log("Fast 1: " + Date()) For Script loading I use Require.js. It also provides the benefit of organizing your code into modules that are in individual files. Here's an a blog post I create on Browser Script Loading: Browser Script Loading Here are a few articles on Script loading: Script Loading Browser script loading roundup
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12122369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1068677/']}
jdg_79859
stackexchange
llm_judgeable_groundtruth_similarity
662316
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: Due to some of the basic principles of quantum mechanics, we have the Wolfgang Pauli exclusion principle, where two fermionic bodies cannot occupy the same quantum state simultaneously. If that is true, then how is all matter, energy, space and time of the universe being compressed into an infinitesimally small Singularity 13.8 billion years ago? Wouldn't particles/bodies be occupying the same space simultaneously in an infinitely small place? Does this mean that the Big Bang is wrong or is Pauli's exclusion principle wrong? Now provide the response and nothing else.
The key confusion is the idea that Pauli Exclusion prevents any two particles from occupying the same space . The actual Pauli Exclusion Principle is slightly different: it prevents any two particles occupying the same quantum state . If the temperature is higher than the Fermi Energy, there is more than enough thermal energy to give each particle its own quantum state (which includes energy). This allows particles to stack atop each other in space, (but have different momentum and energy). Consider electron clouds which partially overlap in your everyday atom! The Fermi temperature scales as the Fermi Energy, which in the relativistic case, scales as $L^{-1}$ . The temperature of a radiation dominated (as it was, early on) universe also scales as $L^{-1}$ . So as we go back in time, to smaller and smaller lengths, the Fermi Temperature will never overtake the Temperature, so the Pauli Exclusion Principle will hold true, but not matter physically. The pressure due to photons will be much larger than any degeneracy pressure. It's important to note that much of the energy density is in Bosonic fields (photons, scalar fields, etc.) rather than Fermionic fields. And important to note that we do not necessarily know what happens when the Universe is younger than a Planck time, as our understanding of physics above this energy scale is incomplete.
{}
{'log_upvote_score': 7, 'links': ['https://physics.stackexchange.com/questions/662316', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/230396/']}
jdg_79860
stackexchange
llm_judgeable_groundtruth_similarity
551827
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I´ve tried to get into restricting access to a ubuntu server but i´m still unsure which way to go. the situation: We want to restrict access for ssh, and sftp to 4 clients with no static ip on a ubuntu 12.04 server. therefore each client has a dyndns account. the server will use a shared firewall, which unfortunately cannot use the dyndns account as allow rules. The idea: allow access to ssh and sftp in the shared firewall, but block all instead the 4 dyndns accounts on server side. but what´s the easiest way to achive this? First solution would be the use of iptabels with this script : Run by a cronjob it checks for dyndns ips and updates iptable rules with something like: # All connectsion from address 1.2.3.4 to SSH (port 22)iptables -A INPUT -p tcp -m state --state NEW --source DYNDNS_IP --dport 22 -j ACCEPT# Deny all other SSH connectionsiptables -A INPUT -p tcp --dport 22 -j DROP Second solution would be a restricion through denyhosts, f.e.: # /etc/hosts.allowsshd: client.dyndns.org# /etc/hosts.denysshd: ALL But I am unsure if denyhosts is also able to restrict ftp access. if so, this solution would look a bit easier to manage. thankful for every idea, with kind regards, toni Now provide the response and nothing else.
Unless the author gave more supporting evidence, maybe he was just full of hot air. You've run the test and got the result and proven him wrong. Edit: From Jeffrey Snover's blog: A filter is a function that just has a process scriptblock That alone isn't enough to convince me that a filter is going to have a speed advantage over a function, given both have identical process blocks. Also what sort of 1950's equipment is that guy on where it takes 4.6 seconds to add one to a number? PS C:\Users\Ryan> Measure-Command { Filter AddOne { $_ + 1 }; AddOne 1 }TotalMilliseconds : 7.7266PS C:\Users\Ryan> Measure-Command { Function AddOne { $_ + 1 }; AddOne 1 } TotalMilliseconds : 0.4108 4.6 seconds is whack. Maybe the author was using some sort of CTP version of Powershell before the binaries were ngen'ed. :P Finally, try your test in a new Powershell session, but in reverse order. Try the Function first and the Filter second, or vice versa: PS C:\Users\Ryan> Measure-Command { Function AddOne { $_ + 1 }; AddOne 1 } TotalMilliseconds : 6.597 PS C:\Users\Ryan> Measure-Command { Filter AddOne { $_ + 1 }; AddOne 1 }TotalMilliseconds : 0.4055 See? The first one you run will always be slower. It was just about the .NET internals of having already loaded stuff into memory that makes the second operation faster, regardless of whether it's a function or a filter. I will admit though that the Function still seems to be consistently faster than the Filter, regardless of how many times it's run. Measure-Command { Function AddOne($Num) { Return $Num += 1 }; 1..50000 | AddOne $_ }TotalMilliseconds : 13.9813Measure-Command { Filter AddOne($Num) { Return $Num += 1 }; 1..50000 | AddOne $_ }TotalMilliseconds : 69.5301 So the author was wrong... and now I don't feel bad for never having ever used a Filter instead of a Function before.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/551827', 'https://serverfault.com', 'https://serverfault.com/users/197808/']}
jdg_79861
stackexchange
llm_judgeable_groundtruth_similarity
38812
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm still waiting to sort getting a Pi Zero, but a thought has just occured to me. The Pi Zero has 4 pins which are AFAIK something to do with video: So I have two questions: What is the pinout for this? Does it include an audio output? The reason I am guessing this functions the same way as the RCA jack on the B+/2B, which I think includes stereo audio and a composite video connection (2 pins for audio, 1 pin for video, and 1 ground). In which case if I was to get a Zero, could I use this as a audio (and video) output via connection to a RCA or similar cable? N.B. This question is similar in the audio respect but more specific than this one Now provide the response and nothing else.
No, those pins have nothing to do with audio. The upper two pins are to reset the Pi and are labeled "Run". While we have no schematics of the Pi Zero available yet, we can deduce this from former models of the Pi. According to this article it's a two pin header. The circuit with two clamp diodes, a pull-up resistor, and capacitor connected (at least that's what we know about the model B, Rev 2.1 ). The lower two pins are dedicated to composite video out. Note that in both cases the circular pads are ground and the rectangular pads are the respective signals - reset, and composite video out.
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/38812', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/10590/']}
jdg_79862
stackexchange
llm_judgeable_groundtruth_similarity
4186118
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing a clone of inetd in which I must run a server that prints the IP and port of the client connecting to it. As I overwrite STDIN and STDOUT with the socket descriptor, my initial solution to do this was to recover the sockaddr_in structure, which contains the needed information. Doing this with getsockname() , however, is returning an empty structure, with all bits set to 0. Any idea of what is wrong with my approach? Are there any other approaches I can use to recover the IP/Port? Thanks Now provide the response and nothing else.
As R.. pointed out, you should use getpeername . Both that function and getsockname take a file descriptor as its first argument, not a stream pointer ( FILE * ). Use fileno(stdin) to get the file descriptor for standard input (or hard-code it to STDIN_FILENO , as it's constant). Also, the last argument to getsockname and getpeername should be a pointer to socklen_t , not a constant, and you should use a sockaddr_in for TCP/IP: struct sockaddr_in peeraddr;socklen_t peeraddrlen = sizeof(peeraddr);getpeername(STDIN_FILENO, &peeraddr, &peeraddrlen); See a complete example here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4186118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1130121/']}
jdg_79863
stackexchange
llm_judgeable_groundtruth_similarity
32581986
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: how can I specify in podspec a local path for an dependency ? like : s.dependency 'MyLibrary', :path => '../MyLibrary' thanks Now provide the response and nothing else.
You should use the :path keyword in your Podfile : pod 'AFNetworking', :path => '~/Documents/AFNetworking/AFNetworking.podspec' Tips: If you don't know the path, you can drag & drop the file in your Podfile and it will display it. EDIT I did not understand correctly what the OP was asking for, here is the correct answer: Put the local dependency inside your pod's folder root directory, In your Podspec file, just add s.ios.dependency 'YourPodName/YourPodDependencyFolder' After that, create a subspace like so: s.subspec 'YourPodName' do |ss|ss.source_files = 'YourPodName/**/*.{h,m}'end
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32581986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4069848/']}
jdg_79864
stackexchange
llm_judgeable_groundtruth_similarity
8369718
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Having some problem getting my program to sleepWhat im trying to do is when the btnStart is pressed firs randomly set pictures to 12 ImageButtonsThen i want it to pause for 5 secs and then change the first ImageButton to another picture My code looks like this, right now it pauses straight away when the button is pressed... btnStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Collections.shuffle(pic); int time=1; press=true; pic.get(0).setImageDrawable(getResources().getDrawable(R.drawable.memgreen)); pic.get(1).setImageDrawable(getResources().getDrawable(R.drawable.memgreen)); pic.get(2).setImageDrawable(getResources().getDrawable(R.drawable.memred)); pic.get(3).setImageDrawable(getResources().getDrawable(R.drawable.memred)); pic.get(4).setImageDrawable(getResources().getDrawable(R.drawable.memblue)); pic.get(5).setImageDrawable(getResources().getDrawable(R.drawable.memblue)); pic.get(6).setImageDrawable(getResources().getDrawable(R.drawable.memwhite)); pic.get(7).setImageDrawable(getResources().getDrawable(R.drawable.memwhite)); pic.get(8).setImageDrawable(getResources().getDrawable(R.drawable.mempurple)); pic.get(9).setImageDrawable(getResources().getDrawable(R.drawable.mempurple)); pic.get(10).setImageDrawable(getResources().getDrawable(R.drawable.memyellow)); pic.get(11).setImageDrawable(getResources().getDrawable(R.drawable.memyellow)); try { Thread.sleep(5000); pic.get(0).setImageDrawable(getResources().getDrawable(R.drawable.coin)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); Now provide the response and nothing else.
Well, if you want the UI to remain responsive you can't block the UI thread with Thread.sleep there. Create a new thread, then sleep it. After the sleep, run the method for changing the view drawable on the UI thread new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } runOnUiThread(new Runnable() { @Override public void run() { pic.get(0).setImageDrawable(getResources().getDrawable(R.drawable.coin)); } }); }}).start();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8369718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1079218/']}
jdg_79865
stackexchange
llm_judgeable_groundtruth_similarity
2900758
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know how to prove that $$\cos^2x=\frac{1}{2}+\frac{1}{2}\cos(2x)$$ by substituting $\cos(2x)$ with $2\cos^2x-1$ according to the double angle identity$$\cos(2x)=2\cos^2x-1$$ However, how do I do that for $\cos^4x$? Do I do it by writing $\cos^4x$ as $$\cos^2(x)\cdot \cos^2(x)$$ and thus get it by squaring the LHS of $$\cos^2x=\frac{1}{2}+\frac{1}{2}\cos(2x)$$ Im not sure how to proceed. Any ideas? Now provide the response and nothing else.
Since$$\cos^2x=\frac{1}{2}+\frac{1}{2}\cos(2x)$$ we have$$\cos^2(2x)=\frac{1}{2}+\frac{1}{2}\cos(4x)$$ and thus, if we square first equation we get $$\cos^4x=\frac{1}{4}+{1\over 2}\cos(2x)+{1\over 4}\cos ^2(2x)=$$ $$ =\frac{1}{4}+{1\over 2}\cos(2x)+{1\over 4}\Big{(}\frac{1}{2}+\frac{1}{2}\cos(4x)\Big{)}$$$$ =\frac{3}{8}+{1\over 2}\cos(2x)+\frac{1}{8}\cos(4x)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2900758', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/574266/']}
jdg_79866
stackexchange
llm_judgeable_groundtruth_similarity
14626636
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 Node.js application that contains an http(s) server. In a specific case, I need to shutdown this server programmatically. What I am currently doing is calling its close() function, but this does not help, as it waits for any kept alive connections to finish first. So, basically, this shutdowns the server, but only after a minimum wait time of 120 seconds. But I want the server to shutdown immediately - even if this means breaking up with currently handled requests. What I can not do is a simple process.exit(); as the server is only part of the application, and the rest of the application should remain running. What I am looking for is conceptually something such as server.destroy(); or something like that. How could I achieve this? PS: The keep-alive timeout for connections is usually required, hence it is not a viable option to decrease this time. Now provide the response and nothing else.
The trick is that you need to subscribe to the server's connection event which gives you the socket of the new connection. You need to remember this socket and later on, directly after having called server.close() , destroy that socket using socket.destroy() . Additionally, you need to listen to the socket's close event to remove it from the array if it leaves naturally because its keep-alive timeout does run out. I have written a small sample application you can use to demonstrate this behavior: // Create a new server on port 4000var http = require('http');var server = http.createServer(function (req, res) { res.end('Hello world!');}).listen(4000);// Maintain a hash of all connected socketsvar sockets = {}, nextSocketId = 0;server.on('connection', function (socket) { // Add a newly connected socket var socketId = nextSocketId++; sockets[socketId] = socket; console.log('socket', socketId, 'opened'); // Remove the socket when it closes socket.on('close', function () { console.log('socket', socketId, 'closed'); delete sockets[socketId]; }); // Extend socket lifetime for demo purposes socket.setTimeout(4000);});// Count down from 10 seconds(function countDown (counter) { console.log(counter); if (counter > 0) return setTimeout(countDown, 1000, counter - 1); // Close the server server.close(function () { console.log('Server closed!'); }); // Destroy all open sockets for (var socketId in sockets) { console.log('socket', socketId, 'destroyed'); sockets[socketId].destroy(); }})(10); Basically, what it does is to start a new HTTP server, count from 10 to 0, and close the server after 10 seconds. If no connection has been established, the server shuts down immediately. If a connection has been established and it is still open, it is destroyed.If it had already died naturally, only a message is printed out at that point in time.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14626636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1333873/']}
jdg_79867
stackexchange
llm_judgeable_groundtruth_similarity
40463
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: If a rectangle is formed from rigid bars for edges and jointsat vertices, then it is flexible in the plane: it can flexto a parallelogram.On any smooth surface with a metric, one can define a linkage(e.g., a rectangle) whose edges are geodesics of fixed length,and whose vertices are joints, and again ask if it is rigidor flexible on the surface.This leads to my first, specific question: Q1 .Is a rhombus, or a rectangle,always flexible on a sphere? It seems the answer should be Yes but I am a bit uncertainif there must be a restriction on the edge lengths.(In the above figure, the four arcs are each $49^\circ$ in length, comfortably short.) Q2 .The same question for other surfaces: Arbitrary convex surfaces? A torus? I am especially interested to learn if there are situations where a linkage that is flexiblein the plane is rendered rigid when embedded on some surface.It seems this should be possible...? Q3 .More generally, Laman's theorem provides a combinatorial characterization of the rigid linkages in the plane.The $n{=}4$ rectangle is not rigid because it has fewer than $2n-3 = 5$ bars:it needs a 5th diagonal bar to rigidify.Has Laman's theorem been extended to arbitary (closed, smooth) surfacesembedded in $\mathbb{R}^3$ ?Perhaps at least to spheres, or to all convex surfaces? Thanks for any ideas or pointers to relevant literature! Addendum .I found one paper related to my question:"Rigidity of Frameworks Supported on Surfaces"by A. Nixon, J.C. Owen, S.C. Power. arXiv:1009.3772v1 math.CO In it they prove an analog of Laman's theorem forthe circular cylinder in $\mathbb{R}^3$ .If one phrases Laman's theorem as requiring forrigidity that the number of edges $E \ge 2 V - 3$ in both the graph and in all its subgraphs,then their result (Thm. 5.3) is that, on the cylinder, rigidity requires $E \ge 2 V -2$ in the graph and in all its subgraphs.This is not the precise statement of their theorem.They must also insist that the graph be regular in a sense that depends on the rigidity matrix achieving maximal rank(Def. 3.3).They give as examples of irregular linkages on a sphereone thatcontains an edge with antipodal endpoints, or one that includesa triangle all three of whose vertices lie on a great circle.But modulo excluding irregular graphs and other minor technicaldetails, they essentially replace the constant 3 in Laman'stheorem for the plane with 2 for the cylinder. Theirs is a very recent paper but contains few citations to relatedwork on surfaces, suggesting that perhaps the areaof linkages embedded on surfaces isnot yet well explored.In light of this apparent paucity of information, it seems appropriate that I 'accept'one of the excellent answers received. Thanks! Addendum [31Jan11]. I just learned of a 2010 paper by Justin Malestein and Louis Theran,"Generic combinatorial rigidity of periodic frameworks" arXiv:1008.1837v2 (math.CO) ,which pretty much completely solves the problem of linkages on a flat 2-torus,generalizing to flat orbifolds. They obtain a combinatorial characterization for generic minimalrigidity for "planar periodic frameworks," which encompass these surfaces. Now provide the response and nothing else.
Q3: Laman's theorem is the same on the sphere. Indeed, a configuration with $n$ vertices and $m$ edges is defined by a system of $m$ equations in $2n-3$ variables (there are $2n$ coordinates of points, but we may assume that the first point is fixed and the direction of one of the edges from the first point is fixed too). The the left-hand sides are analytic functions of our variables and the right-hand sides are the squares of the lengths of the bars (on the sphere, cosines rather than squares). Consider this system as a map $f:\mathbb R^{2n-3}\to\mathbb R^m$. The rigidity means that a generic point $x\in\mathbb R^{2n-3}$ cannot be moved within the pre-image of $f(x)$. This implies that $rank(df)=2n-3$ on an open dense set. Choose a configuration from this set and project it to the sphere of radius $R\to\infty$. The equations on the sphere converge to those in the plane, hence the rank of the linearization on the sphere will be maximal ($=2n-3$) for all large $R$. So we get an open set of configuration on the sphere where the linearization has the maximal rank (and this implies rigidity). Since all functions involved are analytic and the rank is maximal on an open set, it is maximal generically. So our linkage is generically rigid on the sphere. Conversely, consider a flexible linkage on the plane. If $m<2n-3$, it will be flexible on the sphere by a dimension counting argument. Otherwise, by Laman's theorem, there is a subgraph with $r$ vertices and more than $2r-3$ edges. Consider such a subgraph for which $r$ is minimal. Then, by Laman's theorem, we can remove some edges so that this subgraph remains rigid. And, by the above argument, it is rigid on the sphere too. So the edges that we removed were redundant both in the plane and in the sphere. Let's forget about them and repeat the procedure. Eventually we will get a linkage with fewer than $2n-3$ edges.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/40463', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6094/']}
jdg_79868
stackexchange
llm_judgeable_groundtruth_similarity
618295
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have these 2 languages: $$L_1 = \left\{a^ib^jc^k: k\ge i+j\right\}\\L_2 = \left\{w_1cw_2 : w_1,w_2\in\{a,b\}^\ast\land |w_1|_a = |w_2|_a\right\}$$ How can I determine that they are context free languages by using the closure properties of context-free languages?Thanks a lot ( Original screenshot of formulas ) Now provide the response and nothing else.
To prove: $\sum_{n\geq 1} \frac{1+(-1)^n}{n}$ diverges. Proof: \begin{align*} \sum _{n\geq 1} \frac{1+(-1)^n}{n} &= \sum _{k\geq 1} \frac{1+(-1)^{2k}}{2k} + \sum _{k\geq 1} \frac{1+(-1)^{2k-1}}{2k-1} \\&= \sum _{k\geq 1} \frac{2}{2k} + \sum _{k\geq 1} \frac{0}{2k-1} \\\&= \sum _{k\geq 1} \frac{1}{k} \end{align*} Because $\sum _{k\geq 1} \frac{1}{k}$ diverges, $\sum_{n\geq 1} \frac{1+(-1)^n}{n}$ diverges as well. \qed Improved answer (with partial sums): For each $m\in \mathbb{N}$ we have \begin{align*}\sum _{n=1} ^m \frac{1 + (-1)^n}{n} & = \sum _{k=1} ^{\lfloor m/2 \rfloor} \frac{1 + (-1)^{2k}}{2k} + \sum _{k=1} ^{\lfloor \frac{m+1}{2}\rfloor} \frac{1 + (-1)^{2k-1}}{2k-1} \\& = \sum _{k=1} ^{\lfloor m/2 \rfloor} \frac{2}{2k} + \sum _{k=1} ^{\lfloor \frac{m+1}{2}\rfloor} \frac{0}{2k-1} = \sum _{k=1} ^{\lfloor m/2 \rfloor} \frac{1}{k}\end{align*} Because $\sum _k 1/k $ diverges, $\sum _n \frac{1 + (-1)^n}{n}$ diverges as well. QED
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/618295', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114441/']}
jdg_79869
stackexchange
llm_judgeable_groundtruth_similarity
26892957
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 execute this code. What puzzles me is why doesn't this comparison return any value when false. Is this the default behavior of these comparison operators? my $output = (2 <= 1); print "value=$output"; Will a comparison operator return undef when its logical check fails? Now provide the response and nothing else.
The relational operators return 1 for true and a special version of the defined empty string, "" , which counts as a zero but is exempt from warnings about improper numeric conversions, just as "0 but true" is. The value you get back is actually a dualvar. It has separate numeric and string values (not a special version of the empty string, really). The numeric value is 0 and the string value is the empty string. You used the string portion, which is empty, but the 0 is still there. You can look inside the variable records with Devel::Peek : use Devel::Peek;my $result = ( 1 == 2 );Dump( $result ); In the SV (scalar value) thing behind the scenes, you see the string value in the PV and the numeric value in the IV And NV (the integer and numeric values): SV = PVNV(0x7fe602802750) at 0x7fe603002e70 REFCNT = 1 FLAGS = (PADMY,IOK,NOK,POK,pIOK,pNOK,pPOK) IV = 0 NV = 0 PV = 0x7fe6026016b0 ""\0 CUR = 0 LEN = 16 There are other sorts of dualvars too. The $! error variable has the error number and the error text, for instance (and I talk about that in Mastering Perl ). This isn't something you normally have to worry about because Perl does the right thing for the context. If you always want a numeric value, use it in a numeric context: my $numeric = 0 + $result; # 0 You can create your own dualvars with Scalar::Util 's dualvar , and you can check if a scalar is a dualvar with isdual . use Scalar::Util qw(isdual);my $result = ( 1 == 2 );print isdual($result) ? "dualvar" : "Not dualvar"; If you wanted to check that the value you got back was defined (you said it wasn't), you can check with defined . An empty string is defined, though. If you want to check that it's not the empty string, you can use length . These help when the value you have isn't printable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26892957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1878947/']}
jdg_79870
stackexchange
llm_judgeable_groundtruth_similarity
2084503
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I recently came across this expression - but reading up on Wikipedia did not clarify it much for me - I still don't get it: What's the point of it How is it used in practice (i.e. how does it benefit a coder in their day to day work/building systems)? [Edit] The Wikipedia article C++ example is overly long, and conflates the discussion of a fluent interface with an example of a simple Glut app. Can someone provide a SUCCINCT C++ example of a class that illustrates a fluent interface (how does such an influence differ from an ordinary C++ interface for example)? Now provide the response and nothing else.
It benefits the coder by reducing the amount he has to type (and read). To use the C++ example on Wikipedia: Before: int main(int argc, char **argv) { GlutApp app(argc, argv); app.setDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_ALPHA|GLUT_DEPTH); // Set framebuffer params app.setWindowSize(500, 500); // Set window params app.setWindowPosition(200, 200); app.setTitle("My OpenGL/GLUT App"); app.create();} After: int main(int argc, char **argv) { FluentGlutApp app(argc, argv); app.withDoubleBuffer().withRGBA().withAlpha().withDepth() .at(200, 200).across(500, 500) .named("My OpenGL/GLUT App"); app.create(); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2084503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/205040/']}
jdg_79871
stackexchange
llm_judgeable_groundtruth_similarity
10816986
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 got a break point on the first line of Application_Start() , but Visual Studio wont break on it. Visual Studio have attached itself to the IIS working process: Auto-attach to process '[2092] w3wp.exe' on machine 'SRD00510' succeeded. My breakpoint in the home controller do work. update I've tried: iisreset restarted visual studio Rebooted. Tried to reinstall aspnet ( aspnet_regiis -i ) Now provide the response and nothing else.
Reading your question, I assume you are using IIS for debugging, not Visual Studio Development Server. In this case, debugging application start is tricky, because it is only called once when the application pool is started or recycled. When Visual Studio attaches to the process, Application_Start has already been running. The trick is to make the application pool recycle without killing the process you are attached to. Do the following: In Visual Studio (must be run as Administrator) set your breakpoint inglobal.asax.cs and start debugging as usual (F5). The page opens inyour web browser, but the breakpoint isn't hit. Now the trick: With a text editor, open web.config from where it isserved by IIS, change it (e.g. enter a blank line somewhere) andsave it. In contrast to recycling the application pool in IIS, thislets the application pool recycle (and thus running throughApplication_Start in global.asax.cs the next time the web site iscalled) without killing the process you are attached to. In your web browser, reload the page. The breakpoint should be hit now! That works for me (IIS 7.5, VS2015).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10816986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/70386/']}
jdg_79872
stackexchange
llm_judgeable_groundtruth_similarity
7981316
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 starting a new project from scratch and have written User Stores to describe how a given user will interact with the system. But, I'm having trouble understanding how to break the first user story in to tasks without the first one becoming an epic. For example, if I were building a car and the first user story said something like "As a driver, I would like to be able to change the direction of motion so that I don't hit things.", that would imply a user interface (steering wheel), but also motion (wheels) and everything necessary to link those together (axle, frame, linkage, etc...). In the end, that first user story always seems to represent about 40% of the project because it implies so much about the underlying architecture. How do you break user stories down for a new project such that the first one doesn't become an epic representing your entire underlying architecture? Now provide the response and nothing else.
You might want to think of your story as a vertical slice of the system. A story may (and often will) touch components in all of the architectural layers of the system. You might therefore want to think of your tasks as the work needed to be done on each of the components that your story touches . For example, Let's say you have a story like In order to easily be able to follow my friends' tweets, as a registered user, I want to automatically follow all of my gmail contacts that have twitter accounts. In order to accomplish this, you will have to pass through the UI layer, service layer, persist some data in the data layer, and make an API call to twitter and gmail. Your tasks might be: Add an option to the menu Add a new gmail authentication screen Add a twitter authentication screen Add a contact selection screen Add a controller that calls into your service layer Write a new service that does the work Save contacts to the database Modify your existing gmail API calling service to get contacts Add a twitter API calling service to follow selected contacts There: That's 9 possible tasks right there. Now, as a rule, you want your tasks to take roughly 1/2 a day to 2 days, with a bias towards one day (best practice, for sizing). Depending on the difficulty, you might break down these tasks further, or combine some if they are two easy (perhaps the two API calling services are so simple, you'd just have a modify external API services ). At any rate, this is a raw sketch of how to break the stories down. EDIT: In response to more question that I got on the subject of breaking stories into tasks, I wrote a blog post about it, and would like to share it here. I've elaborated on the steps needed to break the story. The link is here .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7981316', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57185/']}
jdg_79873
stackexchange
llm_judgeable_groundtruth_similarity
11273773
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My application is Swing-based. I would like to introduce JavaFX and configure it to render a Scene on a secondary display.I could use a JFrame to hold a JFXPanel which could hold a JFXPanel but I would like to achieve this with JavaFX API. Subclassing com.sun.glass.ui.Application and using Application.launch(this) is not an option because the invoking thread would be blocked. When instantiating a Stage from Swing EDT, the error I get is: java.lang.IllegalStateException: Toolkit not initialized Any pointers? EDIT: Conclusions Problem : Non-trivial Swing GUI application needs to run JavaFX components. Application's startup process initializes the GUI after starting up a dependent service layer. Solutions Subclass JavaFX Application class and run it in a separate thread e.g.: public class JavaFXInitializer extends Application { @Override public void start(Stage stage) throws Exception { // JavaFX should be initialized someGlobalVar.setInitialized(true); }} Sidenote: Because Application.launch() method takes a Class<? extends Application> as an argument, one has to use a global variable to signal JavaFX environment has been initialized. Alternative approach: instantiate JFXPanel in Swing Event Dispatcher Thread : final CountDownLatch latch = new CountDownLatch(1);SwingUtilities.invokeLater(new Runnable() { public void run() { new JFXPanel(); // initializes JavaFX environment latch.countDown(); }});latch.await(); By using this approach the calling thread will wait until JavaFX environment is set up. Pick any solution you see fit. I went with the second one because it doesn't need a global variable to signal the initialization of JavaFX environment and also doesn't waste a thread. Now provide the response and nothing else.
Found a solution. If I just create a JFXPanel from Swing EDT before invoking JavaFX Platform.runLater it works.I don't know how reliable this solution is, I might choose JFXPanel and JFrame if turns out to be unstable. public class BootJavaFX { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new JFXPanel(); // this will prepare JavaFX toolkit and environment Platform.runLater(new Runnable() { @Override public void run() { StageBuilder.create() .scene(SceneBuilder.create() .width(320) .height(240) .root(LabelBuilder.create() .font(Font.font("Arial", 54)) .text("JavaFX") .build()) .build()) .onCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent windowEvent) { System.exit(0); } }) .build() .show(); } }); } }); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11273773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/439533/']}
jdg_79874
stackexchange
llm_judgeable_groundtruth_similarity
4485399
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know how to bump the last digit in a version number using bash. e.g. VERSION=1.9.0.9NEXT_VERSION=1.9.0.10 EDIT: The version number will only contain natural numbers. Can the solution be generic to handle any number of parts in a version number. e.g. 1.21.2.31.2.3.41.2.3.4.5 Now provide the response and nothing else.
TL;DR: VERSION=1.9.0.9echo $VERSION | awk -F. '/[0-9]+\./{$NF++;print}' OFS=.# will print 1.9.0.10 For a detailed explanation, read on. Let's start with the basic answer by froogz3301 : VERSIONS="1.2.3.4.41.2.3.4.5.6.7.71.9.91.9.0.9"for VERSION in $VERSIONS; do echo $VERSION | awk -F. '{$NF = $NF + 1;} 1' | sed 's/ /./g'done How can we improve on this? Here are a bunch of ideas extracted from the copious set of comments. The trailing '1' in the program is crucial to its operation, but it is not the most explicit way of doing things. The odd '1' at the end is a boolean value that is true, and therefore matches every line and triggers the default action (since there is no action inside braces after it) which is to print $0, the line read, as amended by the previous command. Hence, why not this awk command, which obviates the sed command? awk -F. '{$NF+=1; OFS="."; print $0}' Of course, we could refine things further — in several stages. You could use the bash '<<<' string redirection operator to avoid the pipe: awk -F. '...' <<< $VERSION The next observation would be that given a series of lines, a single execution of awk could handle them all: echo "$VERSIONS" | awk -F. '/[0-9]+\./{$NF+=1;OFS=".";print}' without the for loop. The double quotes around "$VERSION" preserve the newlines in the string. The pipe is still unnecessary, leading to: awk -F. '/[0-9]+\./{$NF+=1;OFS=".";print}' <<< "$VERSIONS" The regex ignores the blank lines in $VERSION by only processing lines that contain a digit followed by a dot. Of course, setting OFS in each line is a tad clumsy, and ' +=1 ' can be abbreviated ' ++ ', so you could use: awk -F. '/[0-9]+\./{$NF++;print}' OFS=. <<< "$VERSIONS" (or you could include ' BEGIN{OFS="."} ' in the program, but that is rather verbose. The ' <<< ' notation is only supported by Bash and not by Korn, Bourne or other POSIX shells (except as a non-standard extension parallelling the Bash notation). The AWK program is going to be supported by any version of awk you are likely to be able to lay hands on (but the variable assignment on the command line was not supported by old UNIX 7th Edition AWK).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4485399', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83416/']}
jdg_79875
stackexchange
llm_judgeable_groundtruth_similarity
1849802
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been developing an iphone application using a domain model, and have put off the persistence aspect of the app until now. Core Data looks like a really good solution since I already have a well defined model but I am running into a snag with my existing unit tests. Here is simple example of what I have now: - (void)test_full_name_returns_correct_string { Patient *patient = [[Patient alloc] init]; patient.firstName = @"charlie"; patient.lastName = @"chaplin"; STAssertTrue([[patient fullName] isEqualToString:@"charlie chaplin"], @"should have matched full name");} How can I make this work once my Patient object extends from NSManagedObject and uses @dynamic for the firstName and lastName properties? Has anyone else run into this type of this with Core Data? Thanks. Now provide the response and nothing else.
You need to build a Core Data stack, either within each method or in -setUp and then tear it down. Using an NSInMemoryPersistentStore will keep things fast and in-memory for your unit tests. Add a @property (nonatomic,retain) NSManagedObjectContext *moc to your TestCase subclass. Then: - (void)setUp { NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:bundleContainingXCDataModel]]; NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom]; STAssertTrue([psc addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:NULL] ? YES : NO, @"Should be able to add in-memory store"); self.moc = [[NSManagedObjectContext alloc] init]; self.moc.persistentStoreCoordinator = psc; [mom release]; [psc release];}- (void)tearDown { self.moc = nil;} Your test method then looks like: - (void)test_full_name_returns_correct_string { Patient *patient = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.moc]; patient.firstName = @"charlie"; patient.lastName = @"chaplin"; STAssertTrue([[patient fullName] isEqualToString:@"charlie chaplin"], @"should have matched full name");} assuming your entity is named Person . There was a memory leak in your version of the method, by the way; patient should be -release 'd in the non-Core Data version ( insertNewObjectForEntityForName:managedObjectContext: returns an autoreleased instance).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1849802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8517/']}
jdg_79876
stackexchange
llm_judgeable_groundtruth_similarity
4067068
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 DataGridView. I set its .DataSource prop to be an BindingList of my own objects: a BindingList<IChessItem> I then created some columns for it.. DataGridViewTextBoxColumn descColumn = new DataGridViewTextBoxColumn(); descColumn.DataPropertyName = "Description"; descColumn.HeaderText = "Description"; descColumn.Width = 300; DataGridViewTextBoxColumn gameIDColumn = new DataGridViewTextBoxColumn(); gameIDColumn.DataPropertyName = "GameID"; gameIDColumn.HeaderText = "Game ID"; gameIDColumn.Width = 60; dataGrid.Columns.Add(descColumn); dataGrid.Columns.Add(gameIDColumn); My question is.. I want to color one of the columns GREEN based upon data in another field of my BindingList). How can I do this? I don't really have to show this field, I just want to act upon the data in it.. in my case, one of the fields of IChessItem shows whether the record is new, and I want to color the other fields in the datagridview to reflect that. Now provide the response and nothing else.
You can use the 'CellFormatting' event of the DataGridView. The DataGridViewCellFormattingEventArgs contains indexes of the row and the column of the current cell as it is being bound. I hope my code example makes some sense to you: private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e){ // Compare the column to the column you want to format if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ColumnName") { //get the IChessitem you are currently binding, using the index of the current row to access the datasource IChessItem item = sourceList[e.RowIndex]; //check the condition if (item == condition) { e.CellStyle.BackColor = Color.Green; } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4067068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/129565/']}
jdg_79877
stackexchange
llm_judgeable_groundtruth_similarity
2630159
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can i strip <h1>including this content</h1> I know you can use strip tags to remove the tags, but i want everything in between gone as well. Any help would be appreciated. Now provide the response and nothing else.
As you’re dealing with HTML, you should use an HTML parser to process it correctly. You can use PHP’s DOMDocument and query the elements with DOMXPath , e.g.: $doc = new DOMDocument();$doc->loadHTML($html);$xpath = new DOMXPath($doc);foreach ($xpath->query('//h1') as $node) { $node->parentNode->removeChild($node);}$html = $doc->saveHTML();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2630159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/202926/']}
jdg_79878
stackexchange
llm_judgeable_groundtruth_similarity
24963718
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wrote this simple class in java just for testing some of its features. public class class1 { public static Integer value=0; public class1() { da(); } public int da() { class1.value=class1.value+1; return 5; } public static void main(String[] args) { class1 h = new class1(); class1 h2 = new class1(); System.out.println(class1.value); }} The output is: 2 But in this code: public class class1 { public static Integer value=0; public void class1() { da(); } public int da() { class1.value=class1.value+1; return 5; } public static void main(String[] args) { class1 h = new class1(); class1 h2 = new class1(); System.out.println(class1.value); }} The output of this code is: 0 So why doesn't, when I use void in the constructor method declaration, the static field of the class doesn't change any more? Now provide the response and nothing else.
In Java, the constructor is not a method. It only has the name of the class and a specific visibility. If it declares that returns something, then it is not a constructor , not even if it declares that returns a void . Note the difference here: public class SomeClass { public SomeClass() { //constructor } public void SomeClass() { //a method, NOT a constructor }} Also, if a class doesn't define a constructor, then the compiler will automatically add a default constructor for you.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24963718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3878321/']}
jdg_79879
stackexchange
llm_judgeable_groundtruth_similarity
15106690
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 this piece of code, why f() is declared as "double & f(..."? What does it mean and how does it work? I don't even know what to google to find the answer to my question. Please help. double a = 1, b = 2;double & f (double & d) { d = 4; return b;} I know ampersand sign means the address of a variable or a function, but I don't see why it would make sense to write it when you are declaring a function. Now provide the response and nothing else.
When the & operator is used in a declaration form, preceded by a type it doesn't mean "the address of" but a "reference to" which is essentially an automatically dereferenced pointer with disabled pointer arithmetic. There are no references in C, so if you want to pass or return by reference, you had to pass a const pointer and dereference it to access the pointed to value. C++ added references to make this concept easier, to prevent accidental walking off the address with pointer arithmetic, and to save the need to dereference the pointer. This makes working with it much easier and resulting in cleaner and more readable syntax.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15106690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/228632/']}
jdg_79880
stackexchange
llm_judgeable_groundtruth_similarity
4523023
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using fitBounds() to set the zoom level on my map too include all the markers currently displayed. However, when I have only one marker visible, the zoom level is 100% (... which zoom level 20 I think...). However, I don't want it to be that far zoomed in so the user can adjust the position of the marker without having to zoom out. I have the following code: var marker = this.map.createMarker(view.latlng, this.markerNumber);this.map.bounds.extend(view.latlng);this.map.map.setCenter(this.map.bounds.getCenter());this.map.map.fitBounds(this.map.bounds);if (this.markerNumber === 1) { this.map.map.setZoom(16);}this.markerNumber++; where this.map.bounds was previously defined as: this.map.bounds = new google.maps.LatLngBounds(); However, the problem I am having is that the line this.map.map.setZoom(16); doesn't work if I use this.map.map.fitBounds(this.map.bounds); , however, I know that line of code is correct because when I comment out the fitBound() line, the setZoom() magically starts functioning. Any ideas how I resolve this? I'm thinking of setting a maxZoom level as an alternative if I can't get this working. Now provide the response and nothing else.
Alright, I've figured it out. Apparently, the fitbounds() happens asynchronously, so you have to wait for a bounds_changed event before setting zoom works. map = this.map.map;map.fitBounds(this.map.bounds);zoomChangeBoundsListener = google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) { if (this.getZoom()){ this.setZoom(16); }});setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000); Update : See @Nequin's answer using addListenerOnce for a better solution that doesn't require a timeout.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4523023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461146/']}
jdg_79881
stackexchange
llm_judgeable_groundtruth_similarity
1554222
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 often have the case that I want to work on a SVN repository right away. But an ordinary git svn clone [url] also clones the entire history. So I want to speed things up. The first part is to fetch only the last revision into your Git repository. I do it like so: URL=http://google-web-toolkit.googlecode.com/svn/trunk/REV=`svn info $URL |grep Revision: | awk '{print $2}'`PROJECT_FOLDER=google-web-toolkit-readonlygit svn clone -r$REV:HEAD $URL $PROJECT_FOLDER (more info in the StackOverflow article: "How to git-svn clone last n revisions from svn" This way I'm up and running and can work immediately. But without local copy of the history. The question is, how do I afterwards fetch history from the svn repository? And preferably, can this be done in chunks of, say 1000 revisions (in reverse order). Any help here would be greatly appreciated :) Now provide the response and nothing else.
I found out how it can be done. The trick is not to use git svn clone . Instead, use git svn init and git svn fetch individually. Modified the example: URL=http://google-web-toolkit.googlecode.com/svn/trunk/REV=`svn info $URL |grep Revision: | awk '{print $2}'`PROJECT_FOLDER=google-web-toolkit-readonlymkdir $PROJECT_FOLDERcd !$ #goes into dir named $PROJECT_FOLDERgit svn init -s $URL #-s implies --stdlayout with /trunk /tags /branchesgit svn fetch -r $REV# hack, hack, hack# or update history (fetch 50 revisions back each loopfor (( r=$REV; r>0; r-=50 )); do git svn fetch -r $r:HEADdone
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1554222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109305/']}
jdg_79882
stackexchange
llm_judgeable_groundtruth_similarity
2770630
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just a quick question. Is there any performance difference between using PDO::fetchAll() and PDO::fetch() in a loop (for large result sets)? I'm fetching into objects of a user-defined class, if that makes any difference. My initial uneducated assumption was that fetchAll might be faster because PDO can perform multiple operations in one statement while mysql_query can only execute one. However I have little knowledge of PDO's inner workings and the documentation doesn't say anything about this, and whether or not fetchAll() is simply a PHP-side loop dumped into an array. Any help? Now provide the response and nothing else.
Little benchmark with 200k random records. As expected, the fetchAll method is faster but require more memory. Result :fetchAll : 0.35965991020203s, 100249408bfetch : 0.39197015762329s, 440b The benchmark code used : <?php// First benchmark : speed$dbh = new PDO('mysql:dbname=testage;dbhost=localhost', 'root', '');$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);$sql = 'SELECT * FROM test_table WHERE 1';$stmt = $dbh->query($sql);$data = array();$start_all = microtime(true);$data = $stmt->fetchAll();$end_all = microtime(true);$stmt = $dbh->query($sql);$data = array();$start_one = microtime(true);while($data = $stmt->fetch()){}$end_one = microtime(true);// Second benchmark : memory usage$stmt = $dbh->query($sql);$data = array();$memory_start_all = memory_get_usage();$data = $stmt->fetchAll();$memory_end_all = memory_get_usage();$stmt = $dbh->query($sql);$data = array();$memory_end_one = 0;$memory_start_one = memory_get_usage();while($data = $stmt->fetch()){ $memory_end_one = max($memory_end_one, memory_get_usage());}echo 'Result : <br/>fetchAll : ' . ($end_all - $start_all) . 's, ' . ($memory_end_all - $memory_start_all) . 'b<br/>fetch : ' . ($end_one - $start_one) . 's, ' . ($memory_end_one - $memory_start_one) . 'b<br/>';
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2770630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/296308/']}
jdg_79883
stackexchange
llm_judgeable_groundtruth_similarity
15388892
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 table in SQL Server 2012 as the snapshot shows: Then I'm using Last_Value() and First Value to get AverageAmount of each EmpID for different YearMonth. The script is as follows: SELECT A.EmpID, First_Value(A.AverageAmount) OVER (PARTITION BY A.EmpID Order by A.DimYearMonthKey asc) AS '200901AvgAmount', Last_Value(A.AverageAmount) OVER (PARTITION BY A.EmpID Order by A.DimYearMonthKey asc) AS '201112AvgAmount'FROM Emp_Amt AS A However, the result for this query is: In column of "201112AvgAmount", it shows different values for each EmpID while "200901AvgAmount" has correct values. Is there anything wrong with my SQL script? I did a lot research online but still cannot find the answer.... Now provide the response and nothing else.
There is nothing wrong with your script, this is a way how partitioning works in SQL server :/. If you change LAST_VALUE to MAX result will be the same. Solution would be: SELECT A.EmpID, First_Value(A.AverageAmount) OVER (PARTITION BY A.EmpID Order by A.DimYearMonthKey asc) AS '200901AvgAmount', Last_Value(A.AverageAmount) OVER (PARTITION BY A.EmpID Order by A.DimYearMonthKey ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS '201112AvgAmount' FROM Emp_Amt AS A There is a great post about it, link . GL!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15388892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1317602/']}
jdg_79884
stackexchange
llm_judgeable_groundtruth_similarity
29223071
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I require() / import modules from the console? For example, say I've installed the ImmutableJS npm, I'd like to be able to use functions from the module while I'm working in the console. Now provide the response and nothing else.
Here's another more generic way of doing this. Requiring a module by ID The current version of WebPack exposes webpackJsonp(...) , which can be used to require a module by ID: function _requireById(id) { return webpackJsonp([], null, [id]);} or in TypeScript window['_requireById'] = (id: number): any => window['webpackJsonp'];([], null, [id]); The ID is visible at the top of the module in the bundled file or in the footer of the original source file served via source maps. Requiring a module by name Requiring a module by name is much trickier, as WebPack doesn't appear to keep any reference to the module path once it has processed all the sources. But the following code seems to do the trick in lot of the cases: /** * Returns a promise that resolves to the result of a case-sensitive search * for a module or one of its exports. `makeGlobal` can be set to true * or to the name of the window property it should be saved as. * Example usage: * _requireByName('jQuery', '$'); * _requireByName('Observable', true)´; */window['_requireByName'] = (name: string, makeGlobal?: (string|boolean)): Promise<any> => getAllModules() .then((modules) => { let returnMember; let module = _.find<any, any>(modules, (module) => { if (_.isObject(module.exports) && name in module.exports) { returnMember = true; return true; } else if (_.isFunction(module.exports) && module.exports.name === name) { return true; } }); if (module) { module = returnMember ? module.exports[name] : module.exports; if (makeGlobal) { const moduleName = makeGlobal === true ? name : makeGlobal as string; window[moduleName] = module; console.log(`Module or module export saved as 'window.${moduleName}':`, module); } else { console.log(`Module or module export 'name' found:`, module); } return module; } console.warn(`Module or module export '${name}'' could not be found`); return null; });// Returns promise that resolves to all installed modulesfunction getAllModules() { return new Promise((resolve) => { const id = _.uniqueId('fakeModule_'); window['webpackJsonp']( [], {[id]: function(module, exports, __webpack_require__) { resolve(__webpack_require__.c); }}, [id] ); });} This is quick first shot at this, so it's all up for improvement!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29223071', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/294247/']}
jdg_79885
stackexchange
llm_judgeable_groundtruth_similarity
18408269
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i'm using UIPageViewController in my app and it's working fine. however, it's page control which has been added automatically has a black background which is hiding the current view controller's bottom material (See picture below). is it possible to call the UIPageViewController's page control and change it's color? i want the page control to be shown over the view controller (example, the Path app's walkthrough) like setting the color instead of black to clear. Now provide the response and nothing else.
You can use appearance to change the color of UIPageControl as otherwise it is not accessible. Try doing it in your AppDelegate's didFinishLaunchingWithOptions function as given below. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ UIPageControl *pageControl = [UIPageControl appearance]; pageControl.pageIndicatorTintColor = [UIColor lightGrayColor]; pageControl.currentPageIndicatorTintColor = [UIColor blackColor]; pageControl.backgroundColor = [UIColor blueColor]; return YES;} To apply style only to a particular view controller, you can use appearanceWhenContainedIn instead as following: UIPageControl *pageControl = [UIPageControl appearanceWhenContainedIn:[MyViewController class], nil]; Only UIPageControl objects contained in the MyViewController are going to get this style. EDIT: The black background around UIPageControl at the bottom of your screen is due to the background color of your UIPageViewController not UIPageControl . You can change this color as following: - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor blueColor]; //Set it to whatever you like}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18408269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1938695/']}
jdg_79886
stackexchange
llm_judgeable_groundtruth_similarity
12854
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I understand what CIDR is, and what it is used for, but I still can't figure out how to calculate it in my head. Can someone give a "for dummies" type explanation with examples? Now provide the response and nothing else.
CIDR (Classless Inter-Domain Routing, pronounced "kidder" or "cider" - add your own local variant to the comments!) is a system of defining the network part of an IP address (usually people think of this as a subnet mask). The reason it's "classless" is that it allows a way to break IP networks down more flexibly than their base class. When IP networks were first defined, IPs had classes based on their binary prefix: Class Binary Prefix Range Network BitsA 0* 0.0.0.0-127.255.255.255 8B 10* 128.0.0.0-191.255.255.255 16C 110* 192.0.0.0-223.255.255.255 24D 1110* 224.0.0.0-239.255.255.255E 1111* 240.0.0.0-255.255.255.255 (Note that this is the source of people referring to a /24 as a "class C", although that's not a strictly true comparison because a class C needed to have a specific prefix) These binary prefixes were used for routing large chunks of IP space around. This was inefficient because it resulted in large blocks being assigned to organizations who didn't necessarily need them, and also because Class Cs could only be assigned in 24 bit increments, meaning that routing tables could get unnecessarily large as multiple Class Cs were routed to the same location. CIDR was defined to allow variable length subnet masks (VLSM) to be applied to networks. As the name applies, address groups, or networks, can be broken down into groups that have no direct relationship to the natural "class" they belong to. The basic premise of VLSM is to provide the count of the number of network bits in a network. Since an IPv4 address is a 32-bit integer, the VLSM will always be between 0 and 32 (although I'm not sure in what instance you might have a 0-length mask). The easiest way to start calculating VLSM/CIDR in your head is to understand the "natural" 8-bit boundaries: CIDR Dotted Quad/8 255.0.0.0/16 255.255.0.0/24 255.255.255.0/32 255.255.255.255 (By the way, it's perfectly legal, and fairly common in ACLs, to use a /32 mask. It simply means that you are referring to a single IP) Once you grasp those, it's simple binary arithmetic to move up or down to get number of hosts. For instance, if a /24 has 256 IPs (let's leave off network and broadcast addresses for now, that's a different networking theory question), increasing the subnet by one bit (to /25) will reduce the host space by one bit (to 7), meaning there will be 128 IPs. Here's a table of the last octet. This table can be shifted to any octet to get the dotted quad equivalent. CIDR Dotted Quad/24 255.255.255.0/25 255.255.255.128/26 255.255.255.192/27 255.255.255.224/28 255.255.255.240/29 255.255.255.248/30 255.255.255.252/31 255.255.255.254/32 255.255.255.255 As an example of shifting these to another octet, /18 (which is /26 minus 8 bits, so shifted an octet) would be 255.255.192.0.
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/12854', 'https://serverfault.com', 'https://serverfault.com/users/3552/']}
jdg_79887
stackexchange
llm_judgeable_groundtruth_similarity
123621
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: What are the practical limits for the number of items a C# 4 Dictionary or Hashtable can contain and the total number of bytes these structures can reasonable contain? I'll be working with large numbers of objects and want to know when these structures start to experience issues. For context, I'll be using a 64-bit system with tons of memory. Also, I'll need to find objects using some form or 'key'. Given the performance demands, these objects will need to reside in memory, and many will be long-lived. Feel free to suggest other approaches/patterns, although I need to avoid using third-party or open-source libraries. For specification reasons, I need to be able to build this using native C# ( or C++\CLI ). Now provide the response and nothing else.
One thing to point out is that the Dictionary is not going to hold the object itself (which may have a large memory footprint) but only a reference to the object so if the objects are complex this has no impact on the Dictionary size. I have had collected several thousand items together in a Dictionary in memory and the issue is not the size of the Dictionary but the size of the objects themselves in memory. In these cases the Dictionary itself was a tiny portion of the memory involved. One thing to think about in the cases of large Dictionaries is manually configuring and managing the Dictionary capacity. Under normal circumstances .Net manages this fine (in the current implementation if it runs out of space it resizes to a prime number that is at least twice the Dictionary current size). However, if you know you are going to create a large Dictionary or are going to expand the Dictionary instead of .Net guessing and resizing the Dictionary for you (which is relatively costly) it is probably better you doing this yourself (certainly with the initial size and probably managing later resizes). This can be done by managing the Dictionary capacity if you have a reasonable heuristic idea of what the capacity of the Dictionary should be. Microsoft recommends this on MSDN in their remarks on the Dictionary object . However, there seems to be some debate on the real value of this approach although I am not sure how rigorous that test is and if there are other optimisations that the .Net platform puts in place when a dictionary is resizing extremely rapidly. This is a useful Stack Overflow question about object and memory size.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/123621', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/41904/']}
jdg_79888
stackexchange
llm_judgeable_groundtruth_similarity
3059
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: I've got a 1999 Mazda 626 that shakes really badly when idling. It gets a little better when put into neutral, but not much. I've had two people suggest possibilities: Fuel filter Vacuum hose This started happening in the last year or so. It started out being a mild shake when stopping at a stop light, but in the past 6 months or so it's any time the car is not moving. The car hasn't needed much maintenance recently, but in the last year I've done: Oil changes ever 3-4,000 miles Replaced all spark plugs Replaced the radiator Replaced the front brakes (I know this probably has nothing to with anything, but it is something that's been done) I think that's it. Also - it seems to get marginally better when I add a quart of oil to it (it leaks a little oil, that's another issue for another day). I have not done much troubleshooting on this or taken it to a mechanic. I wanted to get some insight on things I could start with or try. I don't mind spending a little bit of money on easy fixes that may or may not resolve the issue, but that wouldn't be bad for the car either. This is the RPM at which it idles: Any other suggestions? Now provide the response and nothing else.
Unfortunately, there are many, many things that can cause a rough idle. I'll try to cover a few things that might help with the diagnosis. I'm sure that there are many others that could be added. Like I mentioned in my comment, it's definitely not the fuel filter. If a fuel filter was bad enough to affect idle it would stall instead of accelerate. A vacuum leak is definitely a possibility since your car has a MAF sensor. In this case I would expect it to be worse in neutral, as a bigger percentage of the air goes unmetered, but I could be wrong about that. Vacuum leaks are quite painful to track down, but many have found that a mechanics stethoscope with an open hose at the end can be helpful in tracking them down. If there are a lot of vacuum hoses that you can't really reach you could also just replace them, they're not very expensive. Injectors get clogged over time, but not always at the same rate. This could cause a misfire in the cylinder with the worst (or possibly best) injector. Try some fuel injector cleaner. This is added to the fuel tank and I would use it more concentrated than suggested on the product, or at the maximum concentration if they specify one. You can also have your injectors removed and professionaly cleaned, in which case they also measure how well each injector is flowing. EGR (Exhaust Gas Recycling) is not meant to be happening during idle. Sometime the EGR valve can stick open causing a rough idle. I'm not sure if theres a way to determine if this is happening without disassembly, but it is something to investigate. Raising the idle will hide the problem. Obviously this is not related to diagnosis but it is an option if you are unwilling to spend the time and money to find and fix the problem.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/3059', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/1583/']}
jdg_79889
stackexchange
llm_judgeable_groundtruth_similarity
35949128
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Currently I'm using Dagger 2 to inject an instance of Retrofit to use for an api call in a widget. From my understanding, Dagger searches for things to inject using the type, so declaring 2 seperate @Provides Retrofit providesRetrofit() with different names wouldn't work. Heres my current code: Module: @Modulepublic class ApiModule { @Provides @Singleton GsonConverterFactory provideGson() { return GsonConverterFactory.create(); } @Provides @Singleton RxJavaCallAdapterFactory provideRxCallAdapter() { return RxJavaCallAdapterFactory.create(); } @Singleton @Provides Retrofit providePictureRetrofit(GsonConverterFactory gsonConverterFactory, RxJavaCallAdapterFactory rxJavaCallAdapterFactory) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(MarsWeatherWidget.PICTURE_URL) .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(rxJavaCallAdapterFactory) .build(); return retrofit; }....//Here is the other Retrofit instance where I was wanting to use a different URL.// @Singleton// @Provides// Retrofit provideWeatherRetrofit(GsonConverterFactory gsonConverterFactory, RxJavaCallAdapterFactory rxJavaCallAdapterFactory) {// Retrofit retrofit = new Retrofit.Builder()// .baseUrl(MarsWeatherWidget.WEATHER_URL)// .addConverterFactory(gsonConverterFactory)// .addCallAdapterFactory(rxJavaCallAdapterFactory)// .build();// return retrofit;// }} Component: @Singleton@Component(modules = ApiModule.class)public interface ApiComponent { void inject (MarsWeatherWidget marsWeatherWidget);} class extending Application : public class MyWidget extends Application { ApiComponent mApiComponent; @Override public void onCreate() { super.onCreate(); mApiComponent = DaggerApiComponent.builder().apiModule(new ApiModule()).build(); } public ApiComponent getApiComponent() { return mApiComponent; }} and finally where im actually injecting it: @Inject Retrofit pictureRetrofit; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // There may be multiple widgets active, so update all of them mAppWidgetIds = appWidgetIds; ((MyWidget) context.getApplicationContext()).getApiComponent().inject(this); final int N = appWidgetIds.length; for (int i = 0; i < N; i++) { updateAppWidget(context, appWidgetManager, appWidgetIds[i]); } }......//use the injected Retrofit instance to make a call So how can I organize this to give me a seperate Retrofit instance that is built with different URLs for hitting different APIs? Let me know if more info is needed. Now provide the response and nothing else.
Provide different versions of the same type You can use @Named (or custom annotations that are annotated with @Qualifier ) to distinguish between variants of the same type. Add the annotations like the following: @Singleton@Provides@Named("picture")Retrofit providePictureRetrofit(GsonConverterFactory gsonConverterFactory, RxJavaCallAdapterFactory rxJavaCallAdapterFactory) { return retrofit = new Retrofit.Builder() .baseUrl(MarsWeatherWidget.PICTURE_URL) // one url .build();}@Singleton@Provides@Named("weather")Retrofit provideWeatherRetrofit(GsonConverterFactory gsonConverterFactory, RxJavaCallAdapterFactory rxJavaCallAdapterFactory) { return retrofit = new Retrofit.Builder() .baseUrl(MarsWeatherWidget.WEATHER_URL) // other url .build();} Custom @Qualifier You could also just create a custom annotation like the following: @Qualifier@Retention(RUNTIME)public @interface Picture {} You would just use this instead of @Named(String) . Injecting the qualified version When you have your module providing the qualified types, you just need to also add the qualifier where you need the dependency. MyPictureService provideService(@Named("picture") Retrofit retrofit) { // ...}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35949128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3917064/']}
jdg_79890
stackexchange
llm_judgeable_groundtruth_similarity
20626849
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a file to add/retrieve the data. The data format is JSON . I'm a newbie.I'm using JSON.NET to serialize and deserialize the data. this is the JSON format { "EmpId": 1, "Name": "Kaushik", "Designation": ".net Developer", "JoiningDate": "09/23/2013", "Skill": [ { "Id": 1, "SkillName": "C#" }, { "Id": 2, "SkillName": "PHP" }, { "Id": 3, "SkillName": "java" } ]} This is the JSON format I'm working on . Description Of the problem I want to append the file data so I can add more JSON to this. For this, do I need to check if there is already some data or not? I want to append the data in the JSON file. The appended form of data will look like this [ { "EmpId": 1, "Name": "Kaushik", "Designation": ".net Developer", "JoiningDate": "09/23/2013", "Skill": [ { "Id": 1, "SkillName": "C#" }, { "Id": 2, "SkillName": "PHP" }, { "Id": 3, "SkillName": "java" } ] }, { "EmpId": 1, "Name": "Kaushik", "Designation": ".net Developer", "JoiningDate": "09/23/2013", "Skill": [ { "Id": 1, "SkillName": "C#" }, { "Id": 2, "SkillName": "PHP" }, { "Id": 3, "SkillName": "java" } ] } ] My main problem is that I'm not getting the exact logic to append the file . I'm reading the file char by char as follows: int count = 0;EmployeeDetail employee = new EmployeeDetail{ EmpId = ++count, Name = formCollection["Name"], Designation = formCollection["Designation"], JoiningDate = formCollection["JoiningDate"], Skill = new List<Skills> { new Skills(){Id = 1, SkillName = "C#"}, new Skills(){Id = 2, SkillName = "PHP"}, new Skills(){Id = 3, SkillName = "java"} }};string json = JsonConvert.SerializeObject(employee, Formatting.Indented);var dataFile = Server.MapPath("~/App_Data/json_data.json");//Reading the file StreamReader reader = new StreamReader(dataFile);int Tchar = 0;char ch;do{ ch = (char)reader.Read(); Response.Write(ch); Tchar++;} while (!reader.EndOfStream);reader.Close();StreamWriter file = new StreamWriter(dataFile, append: true);file.WriteLine(json);file.Close() Now provide the response and nothing else.
Your best and most reliable approach would be to not append to the file, but instead, read the entire JSON file and de-serialize to an object, append to the object collection and then serialize the output back to the JSON file. I created this sample for you (change paths and class accordingly): var filePath = @"C:\Users\grahamo\Documents\Visual Studio 2013\Projects\WebApplication1\WebApplication1\bin\path.json";// Read existing json datavar jsonData = System.IO.File.ReadAllText(filePath);// De-serialize to object or create new listvar employeeList = JsonConvert.DeserializeObject<List<EmployeeDetail>>(jsonData) ?? new List<EmployeeDetail>();// Add any new employeesemployeeList.Add(new EmployeeDetail(){ Name = "Test Person 1"});employeeList.Add(new EmployeeDetail(){ Name = "Test Person 2"});// Update json data stringjsonData = JsonConvert.SerializeObject(employeeList);System.IO.File.WriteAllText(filePath, jsonData); As you are new, up-vote or tick as answer if I have helped you out.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20626849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79891
stackexchange
llm_judgeable_groundtruth_similarity
48985532
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 function which checks the settings and permissions before the start of the application, and if everything goes through, it selects what version to run and accordingly changes the main form. function SomeControlFunction: Boolean;var lMainForm : TForm;begin if SomePermission then Application.CreateForm(TUForm1, lMainForm) else Application.CreateForm(TUForm2, lMainForm);end; Project.dpr Application.Initialize;if SomeControlFunction then Application.Run; Unfortunately every time I create a new form in the project, it automatically adds to Project.dpr and I have to delete it every time. Is there any way to disable this behavior or is the whole process wrong and I should run the application differently? Application.Initialize;if SomeControlFunction then Application.CreateForm(TUNewForm, UNewForm);Application.Run; Now provide the response and nothing else.
There is a work around to prevent the IDE from changing the dpr-file in that way. It seems that the Delphi IDE will explicitly look for places where the global variable Application from Vcl.Forms is used in the dpr-file and accordingly add the CreateForm calls. The standard template code in the dpr-file looks like this: Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TForm1, Form1); <-- new forms will be added here automatically Application.Run; If you use an 'alias' variable - lets say App - instead, the IDE will not interfere. Replace your existing code in the dpr-file with following: var App: TApplication;begin App := Application; App.Initialize; if SomeControlFunction then App.Run;end. Adding new Forms won't automatically add CreateForm calls in your dpr-file now.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48985532', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5134294/']}
jdg_79892
stackexchange
llm_judgeable_groundtruth_similarity
35465855
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 3 commands that will output to 3 different files. ./ant process1 > File1 ./ant process3 > File2 ./ant process3 > File3 How can I combine/merge the output of these commands to one file? Plus is there a way to relocate that output file in certain directory? Assuming it automatically saves it in the same directory. Now provide the response and nothing else.
Quoting my answer for a similar question on Ask Ubuntu: Functions in bash are essentially named compound commands (or code blocks). From man bash : Compound Commands A compound command is one of the following: ... { list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. ...Shell Function Definitions A shell function is an object that is called like a simple command and executes a compound command with a new set of positional parameters. ... [C]ommand is usually a list of commands between { and }, but may be any command listed under Compound Commands above. There's no reason given, it's just the syntax. Try with a semicolon after wc -l : numresults(){ ls "$1"/RealignerTargetCreator | wc -l; }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35465855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5385400/']}
jdg_79893
stackexchange
llm_judgeable_groundtruth_similarity
24716
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 came across this issue with a more complicated program I was working on. Suppose we have a volatile variable data : In[1]:= data = RandomReal[{0,1},{10}]; As this cell is evaluated, In[2]:= Dynamic@data refreshes as expected. However, if we want to save a certain instance of data and later load it in: In[3]:= DumpSave["filepath.mx",data] (change value of data to something else) In[4]:= <<"filepath.mx" the dynamic cell ( In[2] ) isn't updated (unless you evaluate it again). It can be forced to update on the loading of the .mx file by using a Refresh[...,UpdateInterval->time] , but it seems odd that re-evaluating In[1] instantly changes the dynamic cell while redefining data with the .mx file doesn't. Any explanation for this? And is using the Refresh method a good solution here? Now provide the response and nothing else.
It appears you have lied to us about ColorFunction , see: ArrayPlot[RandomReal[{0, 1}, {10, 10, 3}]] (*this works, therefore...*)ArrayPlot[RandomReal[{0, 1}, {10, 10, 3}], ColorFunction -> Hue] These work, therefore: ArrayPlot[RandomReal[{0, 3}, {10, 10, 2}], ColorFunction -> (If[1 < #[[1]] < 2 && #[[2]] < 3, Red, White] &)] Beautiful. But if we go the extra mile, we can get: ArrayPlot[RandomReal[{0, 3}, {10, 10, 2}], ColorFunctionScaling -> False, ColorFunction -> (If[1 < #[[1]] < 2 && #[[2]] < 3, Red, White] &)] The default for ColorFunctionScaling /. Options[ArrayPlot] is True , which screws up your values. Compare the following to see the difference: ArrayPlot[RandomReal[{0, 3}, {2, 2, 2}], ColorFunctionScaling -> True, ColorFunction -> Print]ArrayPlot[RandomReal[{0, 3}, {2, 2, 2}], ColorFunctionScaling -> False, ColorFunction -> Print] It makes sense in general since typical color functions such as Hue and ColorData[...] go from 0 to 1, but I've found you can often get more useful coloring by disabling the scaling. $$-$$ Note: Apparently, ColorRules isn't affected by ColorFunctionScaling . This makes sense since ColorRules is typically used for integer data. ArrayPlot[RandomReal[{0, 3}, {10, 10, 2}], ColorRules -> {{x_, y_} /; 1 < x < 3 && y < 3 -> Red, _ -> White}]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/24716', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1560/']}
jdg_79894
stackexchange
llm_judgeable_groundtruth_similarity
25096534
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've tried searching for solutions to this but have not found anything that matches my situation. I have a MainActivity which extends FragmentActivity, and multiple ListFragments. I use the PagerSlidingTabStrip library for slidetabs, and a ViewPager. Fragments don't have an XML layout, they are just ListFragments which returns a ListView so a layout was not needed. It is a soundboard app, with long press on a list item allowing the user to set a sound file as their ringtone, notification or alarm, or to save to SD card. Now, all Fragments load their own data just fine. Everything seems ok, however, when I use the context menu on a Fragment that was loaded in the background, it seems to be using the ListView from the first or previous fragment that was loaded before it, the one that was visible when it was created. What I mean is, say my MainActivity starts, it loads FragmentA, and in the background FragmentB gets preloaded also. In the onActivityCreated method, for both Fragments, it uses registerForContextMenu(getListView()). @Overridepublic void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Data loading etc MyAdapter adapter = new MyAdapter(getActivity(), R.layout.data_row, data); setListAdapter(adapter); registerForContextMenu(getListView());} But what seems to be happening is that FragmentB calls registerForContextMenu(getListView()) and it seems to be taking the currently active ListView, which is the list for FragmentA. So, say I choose to save a file from the context menu. I long press on the first item of FragmentB, but it tries to save the first item of FragmentA. If I just tap the list item, it plays it's own sound as you would expect, but context menu commands use the list of the Fragment that was visible when it was pre-loaded. Here is the onCreateContextMenu. Note, at this point it uses the correct item Title in the context menu Title. @Overridepublic void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo; menu.setHeaderTitle(data.get(info.position).getDataName()); MenuInflater inflater = this.getActivity().getMenuInflater(); inflater.inflate(R.menu.context_menu, menu);} And here is the onContextItemSelected. @Overridepublic boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int dataID = data.get(info.position).getDataID(); String dataName = data.get(info.position).getDataName(); Activity activity = getActivity(); if(activity instanceof MainActivity) { switch (item.getItemId()){ case R.id.context_ringtone: ((MainActivity) activity).setRingtone(dataID, dataName); return true; case R.id.context_notification: ((MainActivity) activity).setNotification(dataID, dataName); return true; case R.id.context_alarm: ((MainActivity) activity).setAlarm(dataID, dataName); return true; case R.id.context_sd_card: ((MainActivity) activity).saveFile(dataID, dataName); return true; default: return super.onContextItemSelected(item); } } return super.onContextItemSelected(item);} This all works as expected, apart from the fact that preloaded Fragments use the wrong ListView. So what I am looking for, is a way to make sure that when FragmentB is loaded in the background, while another Fragment is active, FragmentB should be registering it's own ListView for the context menu, and not whichever activity's ListView which happened to be visible at the time. I've tried using MyFragment.this.getListView(), and I've tried using the setUserVisibleHint method, but these didn't help. I've tried doing the registerForContextMenu(getListView()) in onResume, hoping it would re-register the correct ListView when the Fragment became active. Any help would be hugely appreciated, thanks! Now provide the response and nothing else.
I managed to figure this out finally! It turns out it wasn't just calling the context menu for the wrong ListView, the context menu was being called for ALL fragments. This was solved by using getUserVisibleHint() in an if statement within the onContextItemSelected method, so that if the Fragment the context menu was called for was not visible, it would return false, but if it was the currently visible Fragment, it would execute the proper code, meaning is skips over Fragments that are not the intended Fragment. I had tried getUserVisibleHint() already in a different way but I wasn't thinking about the problem from the right angle then. Here's an example of the solution. @Overridepublic boolean onContextItemSelected(MenuItem item) { if (getUserVisibleHint()) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int dataID = data.get(info.position).getDataID(); String dataName = data.get(info.position).getDataName(); Activity activity = getActivity(); if(activity instanceof MainActivity) { switch (item.getItemId()){ case R.id.context_ringtone: ((MainActivity) activity).setRingtone(dataID, dataName); return true; case R.id.context_notification: ((MainActivity) activity).setNotification(dataID, dataName); return true; case R.id.context_alarm: ((MainActivity) activity).setAlarm(dataID, dataName); return true; case R.id.context_sd_card: ((MainActivity) activity).saveFile(dataID, dataName); return true; default: return super.onContextItemSelected(item); } } } return false;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25096534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3901090/']}
jdg_79895
stackexchange
llm_judgeable_groundtruth_similarity
1234831
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was looking at some sample code and in it they used a ListDictionary object to store a small amount of data (around 5-10 objects or so, but this number could change over time). The only issue I have with using this class is that, unlike everything else I've been doing, it's not generic. This means, and correct me if I'm wrong here, that every time I get an object out of here or enumerate over it that there's casting going on. Is there enough overhead in the larger Dictionary<T> object to justify the overhead of a non-generic ListDictionary ? The code that will be using this object will be enumerated over on each page load which I'm guessing is why the ListDictionary class was used over one of the other alternatives. This is also why I would like the most performance out of this list of data. Now provide the response and nothing else.
Unfortunately there is no generic equivalent of ListDictionary. However it shouldn't be terribly difficult to implement one. ListDictionary essentially works by keeping a linked list of Key/Value pairs and iterating over them for lookup operations. You could build a ListDictionary<TKey,TValue> by wrapping a LinkedList<T> with some very simple LINQ expressions. For example public class LinkedDictionary<TKey,TValue> { private LinkedList<KeyValuePair<TKey,TValue>> _list = new LinkedList<KeyValuePair<TKey,TValue>>(); private IEqualityComparer<TKey> _comp = EqualityComparer<TKey>.Default; public void Add(TKey key, TValue value) { _list.Add(new KeyValuePair<TKey,TValue>(key,value)); } public TValue Get(TKey key) { return _list.Where(x => _comp.Equals(x.Key,key)).First().Value; } ...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1234831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39605/']}
jdg_79896
stackexchange
llm_judgeable_groundtruth_similarity
3164740
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 haven't seen any docs saying jQuery can change any CSS definition such as changing td { padding: 0.2em 1.2em } to td { padding: 0.32em 2em } but either have to change a whole style sheet, or change class of each element, or change css of each element. Is changing the style definition possible? Now provide the response and nothing else.
There is DOM access to stylesheets, but it's one of those things we tend to avoid because IE needs a load of compatibility cruft. A better way would be typically be to trigger the change indirectly, using a simple class change on an ancestor: td { padding: 0.2em 1.2em }body.changed td { padding: 0.32em 2em } Now just $('body').addClass('changed') and all the td s update. If you really must frob the stylesheets: var sheet= document.styleSheets[0];var rules= 'cssRules' in sheet? sheet.cssRules : sheet.rules; // IE compatibilityrules[0].style.padding= '0.32em 2em'; This assumes that the td rule in question is the first rule in the first stylesheet. If not, you might have to go searching for it by iterating the rules looking for the right selectorText. Or just add a new rule to the end, overriding the old one: if ('insertRule' in sheet) sheet.insertRule('td { padding: 0.32em 2em }', rules.length);else // IE compatibility sheet.addRule('td', 'padding: 0.32em 2em', rules.length); jQuery itself doesn't give you any special tools to access stylesheets, but it's possible there are plugins that might.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3164740', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325418/']}
jdg_79897
stackexchange
llm_judgeable_groundtruth_similarity
4956
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: Today, I was caught redhanded while attempting to code golf a password generator for Twitter. import string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9)) 90 chars. Since that is a lot of spare space, I decided to raise the bar and make it executable too. echo -e "#!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))">pg;chmod +x pg;./pg 139 chars. Nice, except obviously bash chokes on the exclamation point. badp@delta:~$ echo -e "#!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))">pg;chmod +x pg;./pgbash: !/usr/bin/python\nimport: event not found Pesky exclamation point. "Let's escape it," I thought! I do have one spare character after all. echo -e "#\!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))">pg;chmod +x pg;./pg Obviously... badp@delta:~$ echo -e "#\!/usr/bin/python\nimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))">pg;chmod +x pg;./pg./pg: line 2: syntax error near unexpected token `('./pg: line 2: `import string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9))'badp@delta:~$ cat pg#\!/usr/bin/pythonimport string as s,random;print ''.join(random.sample(s.letters+s.digits+s.punctuation,9)) Leaving my asinine code golfing aside -- I can't explain this. With \! , the exclamation point was escaped, except it really wasn't, because the \! was left as-is for echo to pick up. One solution could have been using \x21 instead, but I'm not convinced that's the proper way of escaping an exclamation point in a bash command. tl;dr: How do you properly escape an exclamation point in a bash command? Now provide the response and nothing else.
Use single quotes: echo -e '#!/usr/bin/python\nimport string as s,random;print "".join(random.sample(s.letters+s.digits+s.punctuation,9))'>pg;chmod +x pg;./pg The rules for ! were sort of grafted onto the other quoting rules afterwards (from csh). They were very useful back when shells didn't have command line editing, but some people still use them now. P.S. Since you're coding for bash: echo $'#!/usr/bin/python\nimport string as s,random;print"".join(random.sample(s.letters+s.digits+s.punctuation,9))'>pg;chmod +x pg;./pg This works on most unices: echo python -c \''import string as s,random;print"".join(random.sample(s.letters+s.digits+s.punctuation,9))'\'>pg;chmod +x pg;./pg (Not that I understand why you want to create a script or why the script name has to be two letters.)
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/4956', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/2179/']}
jdg_79898
stackexchange
llm_judgeable_groundtruth_similarity
47454
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to understand more about orbital mechanics, and I'm encountering a few terms which I'm not sure if they are exactly the same.The two terms are Tidal Locking and Synchronous Rotation. To my understanding, Tidal Locking is when the period of one body orbiting another is matching the period of the body rotating around its own axis (like the earth and the moon), however, I'm not sure if Synchronous Rotation means the exact same thing. Now provide the response and nothing else.
Synchronous rotation is when the orbit of a body has the same period as its spin. If the inclination and obliquity are the same, then the same face of the body will always point towards the barycenter. Here is an animation of Pluto and Charon Credit: Stephanie Hoover Wikimedi commons . Tidal forces impart torque to orbiting body rotations. An orbiting body is in tidal lock if this torque lies in a local minimum, keeping the existing spin rate stable. That is, the tidal torque opposes both increasing and decreasing spin rates, and other rotational torques aren't large enough to break into another spin/orbit configuration ratio. Usually, tidal lock occurs in synchronous rotation, like our Earth and Moon (almost), or Pluto and Charon. However, Mercury's rotation/spin ratio is tidally locked and stable at 3:2. Also, other forces than tidal forces can cause torques on an orbiting body. Examples are atmospheric heating torques and torques due to asymmetric mass distributions.
{}
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/47454', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/44397/']}
jdg_79899
stackexchange
llm_judgeable_groundtruth_similarity
659593
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: $$y = \frac{ax+b}{cx+d} \Longleftrightarrow x = \frac{dy-b}{-cy+a}, ad-bc \ne 0$$on the other hand$$\left( \begin{array}{cc}a & b \\c & d \\ \end{array} \right)^{-1} = \frac{1}{ad-bc}\left( \begin{array}{cc}d & -b \\-c & a \\ \end{array} \right), ad-bc \ne 0$$This looks amazing to me. Is there any meaning to this connection between rational functions and matrices? Can it be generalized for matrices of higher ranks? Now provide the response and nothing else.
Let's say that when $A$ is a $2\times 2$ matrix $\begin{pmatrix}a_{11}&a_{12}\\a_{21}&a_{22}\end{pmatrix}$ we will write $M_A(x)$ for the rational function $$ \frac{a_{11}x + a_{12}}{a_{21}x + a_{22}}.$$ Then notice that $$M_F(M_G(x)) = M_{FG}(x).$$ That is, to compose two functions of this type, you multiply their matrices. (You can see this by just writing out the expression for $M_F(M_G(x))$ and simplifying it until it is in the form $\frac{ax+b}{cx+d}$ , whereupon the coefficients $a,b,c,d$ will have the right values for $M_{FG}(x)$ .) This kind of correspondence: $$\begin{array}{ccc}2\times2\text{ matrices} & \implies & \text{rational functions} \\\text{matrix multiplication} & \implies & \text{function composition} \end{array}$$ is called a homomorphism . Group theory tells us that if there is a homomorphism from the group of $2\times 2$ matrices to the group of functions as there is here, then the two groups' identity elements and inverses must also correspond. In this case that means that the identity function $f(x) = x$ will correspond to the identity matrix $\begin{pmatrix}1&0\\0&1\end{pmatrix}$ , and the inverse of a function $M_A(x)$ will be the function $M_{A^{-1}}(x)$ , which is your observation. I don't know if there is any corresponding homomorphism between rational functions and matrices of higher order; I suspect it would not be too hard to prove not. (For one thing, the set of functions $x\mapsto \frac{ax+b}{cx+d}$ is closed under composition, but this is not true of higher-degree rational functions.) It would suffice to rule out such a correspondence for $3\times 3$ matrices, since the $n\times n$ matrices for $n>3$ contain the $n=3$ matrices as a special case. So all one needs to do is find some algebraic property of $3\times 3$ matrices that can't be reflected in the group of functions. (The next paragraph is to give you some keywords to search for if you are interested in pursuing this in more detail.) The rational functions $x\mapsto \frac{ax+b}{cx+d}$ are called Möbius transformations . This relation between the Möbius transformations and the $2\times 2$ matrices is well known. The group of Möbius transformations has the curious name $PGL(2,K)$ , where $K$ is $\Bbb R$ if you consider them to be functions of a real argument, and $\Bbb C$ if you consider them to be functions of a complex argument. (In general $K$ can be any system in which the expression $\frac{ax+b}{cx+d}$ makes sense; such a system is called a field .) The “ $2$ ” here refers to the fact that the matrices are square matrices of rank 2. The $PGL(2, K)$ groups are well-studied and $PGL(2, \Bbb C)$ in particular is of great importance in complex analysis and mathematical physics. Your question about the matrices of higher rank, put into the language of group theory, would seem to be about $PGL(n, \Bbb R)$ for $n≥3$ . I see that the Wikipedia article on the PGL groups mentions the correspondence between $PGL(2, K)$ and the rational linear functions, and that the page on Möbius transformations mentions it also, but neither place mentions any analogous correspondence with higher-rank $PGL(n,K)$ groups, which suggests either that none is known, or that it only appears in a very abstract way.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/659593', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/80251/']}
jdg_79900
stackexchange
llm_judgeable_groundtruth_similarity
1104150
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: Evaluate the integration : $$\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}e^{-(2x^{2}+2xy+2y^{2})}dxdy$$ The function is even about $x$ & $y$. So we can write, $$\int_{-\infty}^{\infty}\int_{-\infty}^{\infty}e^{-(2x^{2}+2xy+2y^{2})}dxdy=2\int_{0}^{\infty}\int_{0}^{\infty}e^{-(2x^{2}+2xy+2y^{2})}dxdy$$. But now , how I will proceed it? Now provide the response and nothing else.
Take the integral $$I=\int_R\int_R dxdy e^{-\frac{1}{2}\vec{x}^t M \vec{x}} $$where $M$ is a positiv definite and symmetric $2\times2$ Matrix. In this case we can find an orthogonal transformation $S$ that fullfills $S^{t}MS=D$ where D is a diagonal matrix. Using $S^tS=1$ we can rewrite the exponent as $\underbrace{\vec{x}^tS}_{\vec{\zeta}^t}\underbrace{S^tMS}_{D}\underbrace{S^t\vec{x}}_{\vec{\zeta}}$, where the entries of $D$ are the two eigenvalues of $M$. The measure transforms as $dxdy \rightarrow \underbrace{|\det(S)|}_{1}d\zeta_1d\zeta_2$ so the whole integral reads:$$I=\int_R\int_R d\zeta_1d\zeta_2 e^{-\frac{1}{2}\vec{\zeta}^t D \vec{\zeta}}= \int_R\int_R d\zeta_1d\zeta_2 e^{-\frac{1}{2}\zeta_1 \lambda_1 \zeta_1}e^{-\frac{1}{2}\zeta_2 \lambda_2 \zeta_2}$$ Which is just the product of two independent Gaussian integrals. It follows that I is just given by$$I=\sqrt{\frac{2\pi}{\lambda_1}}\sqrt{\frac{2\pi}{\lambda_2}}=\frac{2\pi}{\sqrt{\det(M)}} $$ Which is in your case $(\lambda_1=2,\lambda_1=6)$ $$\pi \frac{1}{\sqrt{3}}$$ This method is generalizable to non symmetric positive definite $n\times n$ matirx by using the decomposition $2M=(M+M^t)+(M-M^t)$. Edit: Correct Eigenvalues used
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1104150', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/174970/']}
jdg_79901
stackexchange
llm_judgeable_groundtruth_similarity
23612
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do you improve the security of your ssh session against a man-in-the-middle attack? Now provide the response and nothing else.
Make sure you pay attention to the warnings about changes to the server's public key. If you get a warning like this, say "no" and check the public key fingerprint through out-of-band means; don't say "yes" unless you have verified the public key fingerprint somehow. If you never connect to new hosts, you can set StrictHostKeyChecking yes in your ~/.ssh/config configuration file (or in /etc/ssh/ssh_config ). However this may be annoying if you frequently connect to new machines. Read the section VERIFYING HOST KEYS of the ssh man page. Read How do RSA fingerprints protect from MITM attacks? on this site. Use a SSH private key, not a password, to authenticate. If you are in control of your own infrastructure, you can look into setting up ssh certificates for both hosts and users. This allows the ssh client to verify the identity of the ssh server. This may be the best solution against man-in-the-middle attacks, as it eliminates the need for users to check fingerprints carefully. Realistically, many users probably won't bother to check, so ssh certificates may be a more usable and more reliable defense.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/23612', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/9699/']}
jdg_79902
stackexchange
llm_judgeable_groundtruth_similarity
50758
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: After a few months of learning about and playing with Lisp, both CL and a bit of Clojure, I'm still not seeing a compelling reason to write anything in it instead of C#. I would really like some compelling reasons, or for someone to point out that I'm missing something really big . The strengths of Lisp (per my research): Compact, expressive notation - More so than C#, yes... but I seem to be able to express those ideas in C# too. Implicit support for functional programming - C# with LINQ extension methods: mapcar = .Select( lambda ) mapcan = .Select( lambda ).Aggregate( (a,b) => a.Union(b) ) car/first = .First() cdr/rest = .Skip(1) .... etc. Lambda and higher-order function support - C# has this, and the syntax is arguably simpler: "(lambda (x) ( body ))" versus "x => ( body )" "#(" with "%", "%1", "%2" is nice in Clojure Method dispatch separated from the objects - C# has this through extension methods Multimethod dispatch - C# does not have this natively, but I could implement it as a function call in a few hours Code is Data (and Macros) - Maybe I haven't "gotten" macros, but I haven't seen a single example where the idea of a macro couldn't be implemented as a function; it doesn't change the "language", but I'm not sure that's a strength DSLs - Can only do it through function composition... but it works Untyped "exploratory" programming - for structs/classes, C#'s autoproperties and "object" work quite well, and you can easily escalate into stronger typing as you go along Runs on non-Windows hardware - Yeah, so? Outside of college, I've only known one person who doesn't run Windows at home, or at least a VM of Windows on *nix/Mac. (Then again, maybe this is more important than I thought and I've just been brainwashed...) The REPL for bottom-up design - Ok, I admit this is really really nice, and I miss it in C#. Things I'm missing in Lisp (due to a mix of C#, .NET, Visual Studio, Resharper): Namespaces. Even with static methods, I like to tie them to a "class" to categorize their context (Clojure seems to have this, CL doesn't seem to.) Great compile and design-time support the type system allows me to determine "correctness" of the datastructures I pass around anything misspelled is underlined realtime; I don't have to wait until runtime to know code improvements (such as using an FP approach instead of an imperative one) are autosuggested GUI development tools: WinForms and WPF (I know Clojure has access to the Java GUI libraries, but they're entirely foreign to me.) GUI Debugging tools: breakpoints, step-in, step-over, value inspectors (text, xml, custom), watches, debug-by-thread, conditional breakpoints, call-stack window with the ability to jump to the code at any level in the stack (To be fair, my stint with Emacs+Slime seemed to provide some of this, but I'm partial to the VS GUI-driven approach) I really like the hype surrounding Lisp and I gave it a chance. But is there anything I can do in Lisp that I can't do as well in C#? It might be a bit more verbose in C#, but I also have autocomplete. What am I missing? Why should I use Clojure/CL? Now provide the response and nothing else.
Macros let you write compilers w/o leaving the comfort of your language. DSLs in languages like C# generally amount to a runtime interpreter. Depending on your domain, that might be problematic for performance reasons. Speed does matter , otherwise you'd be coding in an interpreted language and not C#. Also, macros also let you consider human factors - what is the most user-friendly syntax for a particular DSL? With C# there's not much you can do about the syntax. So Lisp allows you participate in language design w/o sacrificing a path towards efficiency . And while these issues might not matter to you , they are extremely important as they underlie the foundations of all useful production-oriented programming languages. In C# this foundational element is exposed to you in a very limited form at best. The importance of macros is not lost on other languages - Template Haskell, camlp4 come to mind. But yet again it's an issue of usability - Lisp macros to date are likely the most user-friendly yet powerful implementation of compile-time transformation. So in sum what people generally do w/ languages like C# is build DSILs (Domain Specific Interpreted Languages). Lisp gives you the opportunity to build something much more radical, DSPs (Domain Specific Paradigms). Racket (formerly PLT-Scheme) is particularly inspiring in this regard - they have a lazy language (Lazy Racket), a typed one (Typed Racket), Prolog, and Datalog all embedded idiomatically via macros. All these paradigms provide powerful solutions to large classes of problems - problems not best solved by imperative programming or even FP paradigms.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/50758', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/-1/']}
jdg_79903
stackexchange
llm_judgeable_groundtruth_similarity
10640480
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to inject my service in Groovy/src class. The normaln dependency injection doesn't work: ...def myService... I'm able to use this (it works): def appCtx = ApplicationHolder.application.getMainContext()def myService = appCtx.getBean("myService"); but the ApplicationHolder is deprecated. Is there any better solution? Thanks for any suggestion Now provide the response and nothing else.
Check following Grails FAQ to get access to the application context from sources in src/groovy - http://grails.org/FAQ#Q : How do I get access to the application context from sources in src/groovy? There is no ApplicationContextHolder class equivalent to ApplicationHolder. To access to a service class called EmailService from a Groovy class in src/groovy, access the Spring bean using: import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCHimport org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GAdef ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)def emailService = ctx.emailService
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10640480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/607038/']}
jdg_79904
stackexchange
llm_judgeable_groundtruth_similarity
8482
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Recently, I got around to seeing the movie Interstellar . In it, the characters of the movie visit a stellar system that appears to be built around a black hole instead of a star. On top of this, their mission is to find a habitable planet in this system. Question: I was wondering how stable the system, as a whole, would be in terms of operation and would any of the planets be habitable at all due to the obvious differences between a star and a black hole. In the movie the black hole is supposed to be a 'supermassive rotating black hole'. As for being a binary star system, it's never stated as such nor depicted as such. It's depicted visually as the black hole alone being the center. However one of the characters does mention a "Neutron Star" as part of the system so it could possibly be a binary star system. The ambient lighting for the planets is generated by the accretion disk of the black hole. The size and rotation speed of the event horizon are not defined in the movie. At least not that I can remember. As for the planets, their proximity varies, with the first planet depicted as being so close to the event horizon that it is effected by time dilation. The distances of the other two are not specified directly, but traveling to the second planet out seemingly takes days, while traveling to the third planet out is stated to take months, if I remember correctly. As for their surface gravity, the first planet is depicted as having higher surface gravity than Earth but not so much higher that movement is impossible, just strained. The second planet is depicted as being '80% Earth's gravity', if memory serves me correctly. To better help define certain variables relevant to the question I found an info-graphic related to the movie that illustrates the size of the black hole and it's rotational speed: http://tinyurl.com/pqph8wl Now provide the response and nothing else.
For those who haven't seen it: Some human explorers land on a planet orbiting a black hole. The black hole is surrounded by a large accretion disk. The planet orbits at a distance such that going any closer to the black hole will mean that your odds of getting out are slim; it's also composed of water. Finally, time dilation from the black hole means that even though the characters spend about two hours on the planet, a decade or so passes for their colleague on board. The basic answer is that a planet can orbit a black hole. There are stable circum-black-hole orbits, just as there are stable orbits around just about any celestial body. There's a problem: A black hole typically forms as a result of a supernova. This will eject most nearby planets out of the stellar system. Alternatively, it's unlikely that a planet could be captured by a black hole and be in a stable orbit, so the whole premise - while possible - is highly unlikely. Then again, it's improbable that a planet will be made out of water, a wormhole will open up near Jupiter, or Matthew McConaughey will star in a decent sci-fi movie, so why should anything else in the story be normal? However, you can't just put a planet anywhere near a black hole, give it a strong enough push, and hope it orbits. The innermost orbit is at the boundary of the photon sphere . On this sphere, only photons can orbit. Inside it, nothing can orbit. However, the only stable orbit is twice as far away, at $2r_p$ . The radius of the sphere is $$r_p=\frac{3GM}{c^2}$$ We'll assume that the object is not rotating (I don't remember exactly if it is or isn't rotating, but it's simpler in this demo to say it isn't.). The formula for gravitational time dilation is $$t_0=t_f \sqrt{1-\frac{3r_0}{2r_f}}$$ where $$r_0=\frac{2GM}{c^2}$$ Assuming that $t_0$ (the time for the observer inside the field) is two hours (7200 seconds) and $t_f$ is ten years (315360000 seconds), $$\frac{t_0}{t_f}=\frac{1}{43800}=1-\frac{(3)2GM}{(2)r_fc^2}$$ Simplifying, and saying that $\frac{2GM}{c^2}=\frac{2}{3}r_p$ , $$\frac{r_p}{r_f}=\frac{43799}{43800}$$ $$r_f \approx 1.0000228315715 r_p$$ which is outside the photon sphere, but just barely. However, it's well inside $2r_p$ , and so most likely instable. The planet is, in short, not going to survive for long. And so giant waves - mini-spoiler - are the least of Matthew McConaughey's problems. Post-question-edit modifications: It couldn't have been a supermassive black hole ; these form at the center of galaxies. It could have been a stellar-mass black hole , though an intermediate-mass black hole is also likely - if not likelier, if the massiveness is emphasized. The existence of the neutron star is interesting. If the black hole were intermediate-mass, I would expect that it would have gobbled up the neutron star by now - and the planets, too. So I'd bet the black hole is a slightly-more-massive-than-average stellar-mass black hole. I highly doubt that multiple planets could orbit a black hole - for the reason I gave above; the supernova would have destroyed them or flung them out of the system. Would any of the planets be habitable? I doubt it. The accretion disk could heat up enough to provide some light, but there probably wouldn't be a lot. I'll write up the calculations either later today or possibly tomorrow, as I'm a bit LaTeXed-out after writing a math-heavy answer on Worldbuilding to find the luminosity, but I suspect it'll be negligible - as will Hawking radiation, in case any smart-aleck was planning on bringing that up.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/8482', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/4246/']}
jdg_79905
stackexchange
llm_judgeable_groundtruth_similarity
40687027
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Nodejs with Express and I am sending an email through Sendgrid, but Sendgrid is changing the href link var emailText = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body><a href="https://www.google.com">Here</a></body></html>'var from_email = new helper.Email('[email protected]');var to_email = new helper.Email('[email protected]');var subject = 'Test';var content = new helper.Content("text/html", emailText)var mail = new helper.Mail(from_email, subject, to_email, content); var request = sg.emptyRequest({ method: 'POST', path: '/v3/mail/send', body: mail.toJSON(),});sg.API(request, function(error, response) { if (error) { console.log('Error response received'); } console.log(response.statusCode); console.log(response.body); console.log(response.headers);}); When the email arrives the following link appears: https://u4006412.ct.sendgrid.net/wf/click?upn=rOQ9fjZGp5r0JyNfoC02LbL..... Could someone help me solve this problem? Now provide the response and nothing else.
I believe this is caused by the URL click-tracking feature of sendgrid. It will redirect to your intended resource, but does not look pretty. You can turn it off in sendgrid, but it will disable URL tracking on all emails sent by that account. If you are integrating with a 3rd-party link-tracker such as bit.ly or have your GA on lock-down, this may not bother you. Here's more information on the feature in sendgrid: https://sendgrid.com/docs/User_Guide/Settings/tracking.html Turn that off and see how your emails look. UPDATE: Whitelabeling in Sendgrid Sendgrid also has a whitelabeling feature, allowing you to serve URLs from one of your subdomains while still tracking clicks/opens through their servers. If you are concerned about the prettiness of your links or perceived security from a UX perspective, this may be the way to go. Check out their overview of whitelabeling and link whitelabeling doc pages. Be sure to follow sendgrid's recommendations on domain usage in emails. This ensures a high success rate on delivery.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40687027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2744242/']}
jdg_79906
stackexchange
llm_judgeable_groundtruth_similarity
175545
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was told forces can depend on time, location and velocity, but never on acceleration. At first I thought this must be wrong, thinking of $F=m\cdot a$. But I think/hope I now got what was meant, what my misunderstanding was: Firstly: $F=m\cdot a$ has nothing really to do with it directly. The forces that apply to an object are always the same, no matter what the current acceleration of that object is. But these forces are (or can be) dependent on the objects velocity (e.g. some kind of friction) and location/time (which is obvious)? Is this right or am I wrong again? Now provide the response and nothing else.
An example of a force that depends on position (of the particle) is the force due to a spring : $$F_x = -kx $$ An example of a force that depends on velocity (of the particle) is the force due to a dashpot $$F_v = -c\dot x$$ Now, consider a hypothetical force that depended only on the acceleration of a particle: $$F_a = -d \ddot x$$ The differential equation of motion would then be $$m\ddot x = -d \ddot x \Rightarrow (m + d)\ddot x= 0$$ Then, unless $m = - d$, the particle's acceleration must be zero. Next, consider the case that there are position, velocity, and acceleration dependent forces on the particle. The differential equation then becomes $$(m + d)\ddot x + c\dot x + kx = 0 = m'\ddot x + c\dot x + kx$$ That is, the acceleration dependent force would have the effect of changing the inertial mass of the particle from $m$ to $m' = m + d$. Such a force could be realized by, e.g., an electronic control system. Typically, a force that does not depend on the particle's position, velocity, etc. but may be time dependent is a driving force and would appear on the right hand side of the equation of motion: $$m' \ddot x + c\dot x + kx = F_{ex}(t)$$ Finally, the state dependent forces might have time dependence (the system would be time variant ). $$m'(t) \ddot x + c(t)\dot x + k(t)x = F_{ex}(t)$$
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/175545', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/64517/']}
jdg_79907
stackexchange
llm_judgeable_groundtruth_similarity
19071664
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to learn how to bind objects to various types of controls. In this instance, I want to get sample data in my object to appear in ComboBox. The code runs but what appears instead of values (David, Helen, Joe) is text "TheProtect.UserControls.Client") XAML: (ucDataBindingObject.xaml) <UserControl x:Class="TheProject.UserControls.ucDataBindingObject" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Width="Auto" Height="Auto" mc:Ignorable="d"> <Grid Width="130" Height="240" Margin="0"> <ComboBox Width="310" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding Path=Clients}" /> </Grid></UserControl> C#: ucDataBindingObject.xaml.cs using System;using System.Collections.Generic;using System.Linq;using System.Windows.Controls;namespace TheProject.UserControls{ public partial class ucDataBindingObject : UserControl { public List<Client> Clients { get; set; } public ucDataBindingObject() { Clients = new List<Client>(); Clients.Add(new Client(1, "David")); // sample data Clients.Add(new Client(2, "Helen")); Clients.Add(new Client(3, "Joe")); InitializeComponent(); this.DataContext = this; } } C# Client.cs using System;using System.Linq;namespace TheProject.UserControls{ public class Client { public int ID { get; set; } public string Name { get; set; } public Client(int id, string name) { this.ID = id; this.Name = name; } }} Now provide the response and nothing else.
There are several ways to tell the framework what to display 1) Use DisplayMemberPath on the ComboBox (this will display the named property): <ComboBox ItemsSource="{Binding Path=Clients}" DisplayMemberPath="Name"/> 2) Set ItemTemplate on the ComboBox. This is like #1, except allows you to define a template to display, rather than just a property: <ComboBox ItemsSource="{Binding Path=Clients}"> <ComboBox.ItemTemplate> <DataTemplate> <Border BorderBrush="Green" BorderThickness="1" Padding="5"> <TextBlock Text="{Binding Path=Name,StringFormat='Name: {0}'}" /> </Border> </DataTemplate> </ComboBox.ItemTemplate></ComboBox> 3) Add a ToString() override to source class. Useful if you always want to display the same string for a given class. (Note that the default ToString() is just the class type name, which is why you see "TheProtect.UserControls.Client".) public class Client{ // ... public override string ToString() { return string.Format("{0} ({1})", Name, ID); }} 4) Add a DataTemplate to the XAML resources. This is useful for associating a given class type with a more complex or stylized template. <UserControl xmlns:local="clr-namespace:TheProject.UserControls"> <UserControl.Resources> <DataTemplate DataType="local:Client"> <TextBlock Text="{Binding Name}" /> </DataTemplate> </UserControl.Resources> // ...</UserControl>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19071664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2826976/']}
jdg_79908
stackexchange
llm_judgeable_groundtruth_similarity
11789407
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'm making an application for Android. The application needs to send and receive realtime chat data (needs to be a socket) but it also needs to send commands (which don't as the client knows when it is sending something). I need to know what is a better solution in terms of saving the user's battery. a) Opening and Closing the connection every time a command is sent, if the chat tab is opened then keep the connection constant. b) Keep the connection constant all the time. I've taken a look around the internet but have gotten mixed answers, some say keeping a persistent connection is bad for battery life and others say that it isn't (Example: "Are you asking if holding a TCP connection open will drain battery-life? Maybe I am WAY off here but, holding a connection open shouldn't waste battery life... If you think it will I would love to know where you got that information. It sounds SO strange to me." ) Or if there is another solution that would be better. I don't think that Google's C2DM would be very useful at all in this situation either. Basically, what drains the battery more: having a persistent connection, or opening and closing the connection unless the chat tab is open? Thanks! Now provide the response and nothing else.
Keeping an idle TCP socket connection open (with no data being sent or received) will not (or at least, should not) consume any more battery than having it closed. That is because an idle TCP connection uses no bandwidth or CPU cycles(*). That said, keeping a TCP connection open for extended periods may not be a good option for a mobile device, because TCP connections don't interact well with computers that go to sleep. The problem scenario would be this: your Android user puts his Android device to sleep while your app is running, and then the remote user's program (or whatever is at the other end of the TCP connection) sends some data over the TCP stream. The remote user's program never gets any ACKs back from the Android device, because of course the Android device is asleep, so the remote device's TCP stack assumes that the TCP packets it sent must have been lost, and it responds by increasing its timeout period, decreasing its TCP window size (aka number-of-TCP-packets-allowed-in-flight-at-once), and resending the TCP packets. But the Android device is still asleep, and thus the same thing happens again. The upshot is that a few minutes later, the remote end of the TCP connection has slowed down to the point where even if the Android device was to wake up, the TCP connection will likely be too slow to be usable -- at which point your program will need to close the bogged-down TCP connection and start up a fresh one anyway, so why bother trying to keep it open? So my recommendation would be to go with option (a), with the stipulation that you close the TCP connection as part of your device-is-going-to-sleep-now routine. One possible caveat would be if Android has a feature where keeping a TCP connection open causes the WiFi or cell-network hardware to remain powered up in a situation where it could otherwise be put to sleep -- if that is the case, then the Android device would pay a battery cost for powering the antenna, which it wouldn't otherwise have had to pay. I'm not aware of any Android logic like that, but I've only used Android a little so that might just be ignorance on my part. It might be worth testing for, at least. (*) Well, technically TCP does send a "keepalive" packet every so often while a TCP connection is open, and that does use some CPU cycles and antenna power... but the default interval for sending keepalive packets on Android is two hours , so I doubt the power used for that would be noticeable.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11789407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1091077/']}
jdg_79909
stackexchange
llm_judgeable_groundtruth_similarity
312631
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 use set -e to stop bash script on first error . All work OK unless I use command with && : $ cat scriptset -ecd not_existing_dir && echo 123echo "I'm running! =P"$$ ./script./script: line 2: cd: not_existing_dir: No such file or directoryI'm running! =P$ compared with: $ cat scriptset -ecd not_existing_direcho "I'm running! =P"$$ ./script./script: line 2: cd: not_existing_dir: No such file or directory$ The first example still echoes I'm running! , but the second one doesn't. Why do they behave differently? UPD. Similar question: https://stackoverflow.com/questions/6930295/set-e-and-short-tests Now provide the response and nothing else.
This is documented behavior. The bash(1) man page says, for set -e , The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or || , any command in a pipeline but the last, or if the command's return value is being inverted with ! . [Emphasis added.] And the POSIX Shell Command Language Specification confirms that this is the correct behavior: The -e setting shall be ignored when executing the compound list following the while , until , if , or elif reserved word, a pipeline beginning with the ! reserved word, or any command of an AND-OR list other than the last. and Section 2.9.3 Lists of that document defines An AND-OR list is a sequence of one or more pipelines separated by the operators " && " and " || " .
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/312631', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/26279/']}
jdg_79910
stackexchange
llm_judgeable_groundtruth_similarity
14721229
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using pthread_mutex_t in a C++ program, as follows: class Mutex : public noncopyable{public: Mutex() { pthread_mutex_init(&m_mutex, NULL); } void acquire() { pthread_mutex_lock(&m_mutex); } void release() { pthread_mutex_unlock(&m_mutex); }private: pthread_mutex_t m_mutex;}; (The class is not copyable - http://www.boost.org/doc/libs/1_53_0/boost/noncopyable.hpp ) The thing that I don't understand - is it considered an error to not call pthread_mutex_destroy in the destructor? The documentation I have read does not state that destroy must be called. Does anyone know, what does pthread_mutex_destroy actually do and under what conditions is it required? EDIT Does the answer for pthread_mutex_destroy also apply to pthread_cond_destroy , etc? They seem almost like useless functions to me, unless pthread_mutex_init et. al. are allocating memory? (the docs, to me, aren't entirely clear on this.) It doesn't hurt me to call destroy anyway, so the question is largely academic. On linux anyway, it seems destroy only sets the mutex to an invalid state: int__pthread_mutex_destroy (mutex) pthread_mutex_t *mutex;{ if ((mutex->__data.__kind & PTHREAD_MUTEX_ROBUST_NORMAL_NP) == 0 && mutex->__data.__nusers != 0) return EBUSY; /* Set to an invalid value. */ mutex->__data.__kind = -1; return 0;} (From glibc-2.14/nptl/pthread_mutex_destroy.c). Now provide the response and nothing else.
If someone provides you with a destroy function, then you are required to call it as the final action on that object before it goes out of scope. On architectures and implementations where the API has no effect, this will be optimised away, however if the API changes in future to require cleaning up of internal state and your code does not call it, your code will now have a memory and/or resource leak. So the simple answer is yes; you must call this API - and here's the thing - even if the API does nothing at the moment , because although the API itself is fixed forever into the future, the implementation behind the API is not.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14721229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/588476/']}
jdg_79911
stackexchange
llm_judgeable_groundtruth_similarity
2062811
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: Given a connected Lie Group $G$ is there a standard method for constructing the metric tensor? One can of course expand a group element $g=e^{x^ie_i}$ where $e_i$ are basis vectors of the Lie algebra about the identity up to linear order and compute the metric in this manner, but is there a more direct way? An example would also be appreciated. Now provide the response and nothing else.
There is such a (bi-invariant) metric on a Lie group (isomorphic to a compact Lie group times $\mathbb{R}^{n}$ ). It is the one induced by the Killing form . For more input on this, see the mathoverflow discussion on the topic: https://mathoverflow.net/questions/32554/why-the-killing-form It should be pointed out that you do not need the exponential map to construct the metric, which is defined on the tangent space $T_{p}g, g\in G$ , not on the group itself. All you need is a nicely behaved symmetric bilinear form under the group action. The explicit construction can be found at here . Update: Yor pointed out in the comments that for a non-semisimple compact Lie group there is a bi-invariant metric, but it is not induced by the Killing form, as the Killing form degenerates on the center. To solve this, write $\mathfrak{g}=\mathfrak{a}\times \mathfrak{s}$ . The Killing form induces a metric on $\mathfrak{s}$ and we put an arbitrary metric on $\mathfrak{a}$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2062811', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/221567/']}
jdg_79912
stackexchange
llm_judgeable_groundtruth_similarity
69720
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In a book on optical solitons, the author says that a Gaussian signal pulse has the form- $u(t) = \exp((\eta + i\beta)t^2)$ where $\beta$ is the chirp parameter. My question is: what does the $i$ signify here? As a chirped signal is still real, what does the complex nature of the signal represent? Now provide the response and nothing else.
Depending on the context, the use of the complex form could be for mathematical convenience or for a no-kidding need for both real and imaginary parts. When you factor the expression, you get $$u(t) = e^{{\eta}t^2}e^{j{\beta}t^2}$$ Where the first exponential is a generic magnitude envelope, in this case Gaussian. The second exponential is the chirp itself and is where all the action is. So to simplify things, lets assume that the envelope is ideal so that the signal is just the chirp $$u(t) = e^{j{\beta}t^2}$$ To view the chirp, you can take either the real or imaginary part, and it looks something like this In a system that does not use I/Q, the real part is what you would expect to transmit as your waveform. The type of system will determine whether using a real signal or some type of I/Q is best. I'm going to use a radar example here. In frequency-modulated continuous wave (FMCW) radars, a real chirp like the one above is transmitted and has the form $$x(t) = cos({{\beta}t^2})$$ Which is just the real part of the complex form. It is received after a delay and mixed with itself, and without going into the mixing process, produces a single frequency sinusoid that can be used to determine range. Here, using a real part only is practical. Using I/Q in FMCW is also beneficial (SNR improvement), but is not usually necessary and many systems do not use it. Another type of radar, pulse-Doppler, benefits greatly from using the complex form. The same chirp is considered, except now the imaginary version is used. This is important because pulsed-Doppler radars usually operate on performing pulse compression, which is just correlating the transmitted waveform with the received one. The autocorrelation of a complex chirp looks like Using a complex waveform allows us to mix our signals to baseband, which give the classic autocorrelation responses we expect without additional mixing and filtering.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/69720', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/20648/']}
jdg_79913
stackexchange
llm_judgeable_groundtruth_similarity
14750572
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 sorry if this is a trivial question. My fortran-fu is poor. Is there a way in Fortran to pass the array length? Using common (which, from what I gather is equivalent to global ) is an option as well. What I want is in the main program to call a function with an array. For example (This is typed in, not copy pasted from anywhere) program proginteger numdouble precision x(num),vdouble precision test....v=test(x,num)....function test(x,num)double precision testinteger numdouble precision x(num)test=0.0d0....returnend This won't compile since num is not a constant. The important thing is to know what the array size I'm passing is. Edit: I'm using the GNU Fortran 95 compiler. Edit2: I tried High Performance Mark's solution without luck: program prog integer v parameter (v=10) double precision x(v),test,k k=test(x) write (*,*) size(x) stop end function test(x) double precision, dimension(:),intent(in) :: x double precision test write (*,*) size(x) test = 0.0d0 return end The output should be two lines where 10 is written. Instead I got this: /scpc:niels: #$ f95 err.f/scpc:niels: #$ ./a.out 0 10/scpc:niels: #$ Now provide the response and nothing else.
Fortran arrays 'know' how long they are, you shouldn't need to pass the array and its length as different arguments. (Unless, that is, you are interfacing with old Fortran codes.) Today you'd write something like this function test(arr) real, dimension(:), intent(in) :: arr ... integer :: arrsize ... arrsize = size(arr) ... If you have to interface to old code in which array sizes are passed you can make calls like this call old_fortran_subr(array, size(array, 1), other_arguments) Oh, and while I'm writing, have nothing to do with common in any code you write from scratch, it's a (rightly) deprecated feature from the 70's and earlier. Instead use module variables .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14750572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/596691/']}
jdg_79914
stackexchange
llm_judgeable_groundtruth_similarity
1930290
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 easiest way to programmatically extract structured data from a bunch of web pages? I am currently using an Adobe AIR program I have written to follow the links on one page and grab a section of data off of the subsequent pages. This actually works fine, and for programmers I think this(or other languages) provides a reasonable approach, to be written on a case by case basis. Maybe there is a specific language or library that allows a programmer to do this very quickly, and if so I would be interested in knowing what they are. Also do any tools exist which would allow a non-programmer, like a customer support rep or someone in charge of data acquisition, to extract structured data from web pages without the need to do a bunch of copy and paste? Now provide the response and nothing else.
If you do a search on Stackoverflow for WWW::Mechanize & pQuery you will see many examples using these Perl CPAN modules. However because you have mentioned "non-programmer" then perhaps Web::Scraper CPAN module maybe more appropriate? Its more DSL like and so perhaps easier for "non-programmer" to pick up. Here is an example from the documentation for retrieving tweets from Twitter: use URI;use Web::Scraper;my $tweets = scraper { process "li.status", "tweets[]" => scraper { process ".entry-content", body => 'TEXT'; process ".entry-date", when => 'TEXT'; process 'a[rel="bookmark"]', link => '@href'; };};my $res = $tweets->scrape( URI->new("http://twitter.com/miyagawa") );for my $tweet (@{$res->{tweets}}) { print "$tweet->{body} $tweet->{when} (link: $tweet->{link})\n";}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1930290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114562/']}
jdg_79915
stackexchange
llm_judgeable_groundtruth_similarity
501849
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 sent a 2 and a 9 using UART. The baud rate is 9600, there is no parity, and it has 8 data bits. As we know 9 is represented as 1001 in binary. However, this is what I get from my UART signal: A 2 is represented as 0010 but this is what I get from my UART signal: I know I have to pay attention to the start bit, but other than that, I have a hard time seing the logic in this signal. NOTE: The signal works, but I just need help analysing it. Now provide the response and nothing else.
Let's annotate your first scope shot. When we do this take note that the lowest order bit of the binary value is transmitted first. Conventional notation in this field is to order the bits in a byte like this: [Bit 7][Bit 6][Bit 5][Bit 4][Bit 3][Bit 2][Bit 1][Bit 0] So when I annotate and then evaluate the bit positions are flipped from the positions shown on the annotated scope shots. The bit pattern represented there is 0b00111001. That is the same as 0x39. 0x39 is the ASCII code for a '9' character. Let's do the same for your second scope shot. Here the bit pattern is represented as 0b00110010. That is same as 0x32. 0x32 is the ASCII code for the '2' character.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/501849', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/250810/']}
jdg_79916
stackexchange
llm_judgeable_groundtruth_similarity
174595
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 ROWNUM and ROW_NUMBER ? Now provide the response and nothing else.
ROWNUM is a "pseudocolumn" that assigns a number to each row returned by a query: SQL> select rownum, ename, deptno 2 from emp; ROWNUM ENAME DEPTNO---------- ---------- ---------- 1 SMITH 99 2 ALLEN 30 3 WARD 30 4 JONES 20 5 MARTIN 30 6 BLAKE 30 7 CLARK 10 8 SCOTT 20 9 KING 10 10 TURNER 30 11 FORD 20 12 MILLER 10 ROW_NUMBER is an analytic function that assigns a number to each row according to its ordering within a group of rows: SQL> select ename, deptno, row_number() over (partition by deptno order by ename) rn 2 from emp;ENAME DEPTNO RN---------- ---------- ----------CLARK 10 1KING 10 2MILLER 10 3FORD 20 1JONES 20 2SCOTT 20 3ALLEN 30 1BLAKE 30 2MARTIN 30 3TURNER 30 4WARD 30 5SMITH 99 1
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/174595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9581/']}
jdg_79917
stackexchange
llm_judgeable_groundtruth_similarity
37023234
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While executing gcc command on ubuntu for generating .a or .so file for JNI, getting below error for both openjdk 8 / oraclejdk8. $gcc -I/usr/lib/jvm/java-8-openjdk-amd64/include -c MainImpl1.c -o MainImpl1.oIn file included from MainImpl1.c:1:0:/usr/lib/jvm/java-8-openjdk-amd64/include/jni.h:45:20: fatal error: jni_md.h: No such file or directory #include "jni_md.h" ^compilation terminated.$gcc -I/usr/lib/jvm/java-8-oracle/include -c MainImpl1.c -o MainImpl1.oIn file included from MainImpl1.c:1:0:/usr/lib/jvm/java-8-oracle/include/jni.h:45:20: fatal error: jni_md.h: No such file or directory #include "jni_md.h" ^compilation terminated. I have given example for generating .a file, but same issue observed for .so file generation also. But same gcc command works for openjdk7/oraclejdk7. What is the issue here? Now provide the response and nothing else.
I don't think you added the include directory that includes jni_md.h which is platform dependent . Try $gcc -I/usr/lib/jvm/java-8-openjdk-amd64/include -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux -c MainImpl1.c -o MainImpl1.o or $gcc -I/usr/lib/jvm/java-8-oracle/include -I/usr/lib/jvm/java-8-oracle/include/linux -c MainImpl1.c -o MainImpl1.o If you don't know where jni_md.h is, use find : find / -name jni_md.h 2> /dev/null
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37023234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6289799/']}
jdg_79918
stackexchange
llm_judgeable_groundtruth_similarity
7252749
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 Java Swing application that i want to run on Mac OS X. I want to use the normal Mac copy/paste shortcuts to copy/paste text to a text field in my Java application. Ctrl + c & Ctrl + v does the trick but i want to use Command + c & Command + v instead. How can i do that? Now provide the response and nothing else.
If you're using a 3rd-party L&F implementation it probably doesn't support the Mac's native keyboard shortcuts. The following code should reinstate the Mac's keyboard shortcuts for JTextField s after setting the L&F: InputMap im = (InputMap) UIManager.get("TextField.focusInputMap");im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.META_DOWN_MASK), DefaultEditorKit.copyAction);im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.META_DOWN_MASK), DefaultEditorKit.pasteAction);im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.META_DOWN_MASK), DefaultEditorKit.cutAction); Of course you'll only need to do this if you detect that the application is running on a Mac so that you don't affect the keyboard mappings for other OS's.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7252749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147381/']}
jdg_79919
stackexchange
llm_judgeable_groundtruth_similarity
8875025
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 a user enters a whole number, the program runs smoothly, but when the user enters a number that has a decimal at the end, the program crashes. These are the errors that I get: at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:458) at java.lang.Integer.parseInt(Integer.java:499) at BMI.main(BMI.java:11) Here is my code: import javax.swing.*;public class BMI { public static void main(String args[]) { int height; // declares the height variable int weight; // declares the weight variable String getweight; getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms"); // asks user for their weight String getheight; getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters"); // asks user for their height weight = Integer.parseInt(getweight); // stores their weight height = Integer.parseInt(getheight); // stores their height double bmi; // declares the BMI variable bmi = weight / Math.pow(height / 100.0, 2.0); // calculates the BMI double roundbmi; // variable to round the BMI to make it more read-able roundbmi = Math.round(bmi); // rounds the BMI JOptionPane.showMessageDialog(null, "Your BMI is: " + roundbmi); // displays the calculated and rounded BMI }} Now provide the response and nothing else.
An Integer only recognizes whole numbers. If you want to be able to capture floating point numbers, use either Float.parseFloat() or Double.parseDouble() . To make the answer more complete, let me give you a quick example of why "4." , "4.0" , and "4" are represented in two different ways. The first two are considered floating point values (since Java will just assume you mean 4.0 regardless), and how they are represented in memory depends heavily on which datatype you use to represent them - either a float or a double . A float represents 4.0 using the single-precision floating point standard , whereas a double would represent 4.0 using the double-precision floating point standard . An int represents the value 4 in base-2 instead (so it'd just be 2 2 ). Understanding how numbers are stored internally is critical and key to development, not just with Java. In general, it's recommended to use Double since that gives the larger range of floating point numbers (and higher precision).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8875025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146470/']}
jdg_79920
stackexchange
llm_judgeable_groundtruth_similarity
97874
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: Code: (*Cylinder Point Picking*) ppCylinder[p1_List, p2_List, radius_Integer, expNo_Integer] := Module[ {pts}, (*Set point coordinates *) pts := Point[Table[{radius*Cos[#1], radius*Sin[#1], #2} &[RandomReal[{0, 2 Pi}], RandomReal[{p1[[3]], p2[[3]]}]], {expNo}]]; (*Visualize*) Graphics3D[{Cylinder[{p1, p2}, radius], pts}, Boxed -> False] ]; (*Test*) ppCylinder[{0, 0, 0}, {0, 0, 1}, 2, 5000] (*Output #1*) ppCylinder[{0, 0, 0}, {0, 1, 2}, 2, 5000] (*Output #2*) Output 1: Output 2: Based on the code I wrote, I am satisfied with the output 1# but not #2. How could I modify the existing code to account for {X && Y} variation when generating a set of random points on a cylinder surface? Now provide the response and nothing else.
You need to transform the generated points (which currently lie on a cylinder that's aligned with the $z$-axis) so that they lie on the new cylinder. You can accomplish this with a TranslationTransform followed by a RotationTransform : ppCylinder[p1_List, p2_List, radius_Integer, expNo_Integer] := With[{ (* the height of the cylinder isn't just the difference of the z coordinates! *) height = Norm[p2 - p1], transform = TranslationTransform[p1] @* RotationTransform[{{0, 0, 1}, p2 - p1}]}, Module[{pts}, pts := Point[ Table[transform@{radius*Cos[#1], radius*Sin[#1], #2} &[ RandomReal[{0, 2 Pi}], RandomReal[{0, height}]], {expNo}]]; (*Visualize*) Graphics3D[{Cylinder[{p1, p2}, radius], pts}, Boxed -> False]]]; Now ppCylinder[{0, 0, 0}, {0, 0, 1}, 2, 5000] returns:
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/97874', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/18696/']}
jdg_79921
stackexchange
llm_judgeable_groundtruth_similarity
4083304
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 most efficient way to copy a large amount of rows from a table in one database to another table in a different database that has the exact same structure? Now provide the response and nothing else.
If your log IO subsystem allows it, then: INSERT INTO target(field1, field2, field3)SELECT field1, field2, field3 FROM source; But having the entire transfer occur in one single statement means one single transaction, which means that x2.5 data size log has to be generated and kept during the entire statement. Ie. if you transfer 50Gb, your target db log will grow to 250Gb (even if the recovery mode is set to simple!). If you are concerned about log, then you have to transfer in batches. You can still do the INSERT ... SELECT trick, but your SELECT has to use some key range and batch acceptable number of rows. Ultimately, you can always do a bcp out followed by a bcp in , it will work pretty fast and is probably the fastest way to get a reliable transfer going.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4083304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/493890/']}
jdg_79922
stackexchange
llm_judgeable_groundtruth_similarity
9842587
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 figure out how to solve the tapped class being assigned to the elements when scrolling, but it's taking effect too quick which I need to delay it a bit when it's actually touched instead of touched while scrolling, this is my code of how it works: $('div, a, span').filter('[tappable][data-tappable-role]').bind('touchstart', function(){ var self = $(this); self.addClass(self.data('tappable-role'));}).bind('touchend', function(){ var self = $(this); self.removeClass(self.data('tappable-role'));}).bind('click', function(){ var self = $(this), goTo = self.data('goto'); if(typeof goTo !== 'undefined') { window.location = goTo; }}); When scrolling, it will assign the class to the element when I've barely touched it, I want to prevent this from happening unless it's properly touched (not clicked). Although I tried experimenting with the setTimeout, but that doesn't work well as it delays but it will still assign the class later on. This is how I did it with the setTimeout: var currentTapped;$('div, a, span').filter('[tappable][data-tappable-role]').bind('touchstart', function(){ clearTimeout(currentTapped); var self = $(this); var currentTapped = setTimeout(function() { self.addClass(self.data('tappable-role')); }, 60);}).bind('touchend', function(){ clearTimeout(currentTapped); var self = $(this); self.removeClass(self.data('tappable-role'));}).bind('click', function(){ clearTimeout(currentTapped); var self = $(this), goTo = self.data('goto'); if(typeof goTo !== 'undefined') { window.location = goTo; }}); How can I do this the effective way? Demo #1 (with setTimeout) . Demo #2 (with no setTimeout) You need to view it on your iPhone/iPod/iPad or an emulator to test the fiddle. UPDATE: function nextEvent() { $(this).on('touchend', function(e) { var self = $(this); self.addClass(self.data('tappable-role')).off('touchend'); }) .on('touchmove', function(e) { var self = $(this); self.removeClass(self.data('tappable-role')).off('touchend'); }) .click(function() { var self = $(this), goTo = self.data('goto'); if(typeof goTo !== 'undefined') { window.location = goTo; } });}$('div, a, span').filter('[tappable][data-tappable-role]').on('touchstart', this, nextEvent); Now provide the response and nothing else.
Here's how I did it: Essentially, when you navigate a page you're going to tap or scroll. (Well there are other things like pinch and slide put you can figure them out later)... So on a tap your 'touchstart' will be followed by a 'touchend'On a scroll your 'touchstart' will be followed by a 'touchmove' Using Jq 1.7... on other versions you can use .bind() function nextEvent() { //behaviour for end $(this).on('touchend', function(e){ /* DO STUFF */ $(this).off('touchend'); }); //behaviour for move $(this).on('touchmove', function(e){ $(this).off('touchend'); }); }$('div, a, span').filter('[tappable][data-tappable-role]').on('touchstart', this, nextEvent); Basically, when a 'touchstart' happens, I bind actions to 'touchend' and 'touchmove'. 'Touchend' does whatever I would want a tap to do and then unbinds itself'Touchmove' basically does nothing except unbind 'touchend' This way if you tap you get action, if you scroll nothing happens but scrolling.. RESPONSE TO COMMENT: If I understand your comment properly, try this: function nextEvent() { var self = $(this); self.addClass(self.data('tappable-role')) //behaviour for move $(this).on('touchmove', function(e){ self.removeClass(self.data('tappable-role')); }); }$('div, a, span').filter('[tappable][data-tappable-role]').on('touchstart', this, nextEvent);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9842587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264795/']}
jdg_79923
stackexchange
llm_judgeable_groundtruth_similarity
86850
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've been trying to find particular simple closed curves on a plane. k = x'[t]*y''[t] - x''[t]*y'[t] + 2 a (y'[t]*x[t] - x'[t]*y[t] - y'[t]*Tanh[2 a*x[t]]);a = 1;curvatureConst = -2.2598969107936748290654804804944433271884918212890625;maxTime = 15;xInit = 0; yInit = 1; xInitVel = 1; yInitVel = 0;sol = NDSolve[{k == curvatureConst, (x'[t])^2 + (y'[t])^2 == 1, \ x[0] == xInit, x'[0] == xInitVel, y[0] == yInit, y'[0] == yInitVel}, \ {x, y}, {t, maxTime}]Clear[a];ParametricPlot[Evaluate[{x[t], y[t]} /. sol], {t, 0, maxTime}] After a numeric solution has been obtained, I'd like to figure out at what $t$ the curve returns to the initial position, or when it first self-intersects. For the return to the initial position, it is likely that there is a small error. Neither Solve nor NSolve seem able to deal with that. Is there a good approximately equals to expression? To find other intersections, I also haven't had any success with Solve , NSolve , or FindRoot . I suspect that the nature of the interpolating functions is just making this particularly difficult. Are there any recommended approaches? I don't necessarily need to know what the points are, only that they exist. Any help is much appreciated. Now provide the response and nothing else.
For curvatureConst = -2.25 the equations in the Question yield An intersection can be found from First@FindRoot[{(x[t] - x[t2]) /. sol, (y[t] - y[t2]) /. sol}, {{t, 8}, {t2, 10.5}}](* t -> 7.8869 *)Flatten[{x[t], y[t]} /. sol /. %](* {-0.0330813, 0.693441} *) Of course, there are multiple intersections, and which is obtained depends on the initial guess given to FindRoot . To find where a curve closes, consider the curve displayed in the Question. FindRoot[((x[t] - x[0]) /. sol)^2 + ((y[t] - y[0]) /. sol)^2, {t, 8}](* {t -> 8.13255} *)Flatten[{x[t], y[t]} /. sol /. %](* {-6.30735*10^-8, 1.} *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/86850', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/30410/']}
jdg_79924
stackexchange
llm_judgeable_groundtruth_similarity
3212782
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 $N$ be a positive integer not equal to $1$ . Then note that none of the numbers $2, 3, \ldots, N$ is a divisor of $N! - 1$ . From this we can conclude that: (A) $N! – 1$ is a prime number; (B) at least one of the numbers $N + 1, N + 2, \ldots, N! – 2$ is a divisor of $N! - 1$ ; (C) the smallest number between $N$ and $N!$ which is a divisor of $N! - 1$ , is a prime number. My working: $N! - 1$ is not necessarily a prime, as $5! - 1 = 119$ and $7 \mid 119$ . I cannot proceed further. Hints are appreciated. Now provide the response and nothing else.
Proof of (C): let $N<m<N!$ be the smallest divisor of $(N!-1)$ . We argue by contradiction: if $m$ is not prime, then it has some nontrivial divisor $1<m'<m$ , and thus $m'$ also divides $(N!-1)$ . By minimality of $m$ it follows that $m'\le N$ , but no such number can divide $(N!-1)$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3212782', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/665584/']}
jdg_79925
stackexchange
llm_judgeable_groundtruth_similarity
37854
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am preparing for my college entry test and I ran into this problem in my book: $$\tan\alpha = \frac{(1+\tan 1^{\circ})\cdot (1+\tan 2^{\circ})-2}{(1-\tan 1^{\circ})\cdot(1-\tan 2^{\circ})-2}$$ I should find the angle $\alpha$ . Can anyone help me please? I tried solving it, but I just can't get any solution. By the way, the correct answer is $\alpha = 42^{\circ}$ Thanks! Now provide the response and nothing else.
$$\begin{align*}V&=\frac{\tan a\tan b+\tan a+\tan b-1}{\tan a\tan b-\tan a-\tan b-1}\\ &=\frac{\sin a \cos b + \cos a \sin b + \sin a\sin b - \cos a\cos b}{\sin a\sin b-\cos a\cos b-\sin a\cos b-\cos a\sin b}\\ &=\frac{\sin (a+b)-\cos(a+b)}{-\cos(a+b)-\sin(a+b)}\end{align*}$$ Now I will use:$$\sin x-\cos y = \sin x-\sin(90^\circ-y)=2\sin\frac{x+y-90^\circ}2\cos\frac{90^\circ+x-y}2,$$ which yields for $y=x$ $$\sin x-\cos x = -2\cos45^\circ\sin(45^\circ-x)$$ and $$\cos x +\sin y = \sin(90^\circ-x)+\sin y = 2\cos\frac{90^\circ-x-y}2\sin\frac{90^\circ-x+y}2$$which yields for $y=x$ $$\cos x+\sin y = 2\sin45^\circ\cos(45^\circ-x)$$ Plugging this into the above formula (for $x=a+b$) I get $$V=\frac{-2\cos45^\circ\sin(45^\circ-a-b)}{-2\sin45^\circ\cos(45^\circ-a-b)}=\tan(45^\circ-a-b)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/37854', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10646/']}
jdg_79926
stackexchange
llm_judgeable_groundtruth_similarity
2246587
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Maybe I'm going about this all wrong. I have a bunch of classes that derive from the "Model" class, a base class with a bunch of common properties and methods. I want them all to implement a set of functionality: public abstract void Create();public abstract T Read<T>(Guid ID); //<--Focus on this onepublic abstract void Update();public abstract void Delete(); Then I implement it in a child class like "Appointment" like so: public override T Read<T>(Guid ID){ var appt = db.Appointments.First(a => a.AppointmentID.Equals(ID)); var appointment = new Appointment() { DateEnd = appt.dateEnd.GetValueOrDefault(), Location = appt.location, Summary = appt.summary };return appointment;} This throws an exception "Can't implicitly convert type 'Appointment' to T". If I change the method's signature to "public override Appointment Read(Guid ID)", then the compiler says that I've not implemented the abstract method in the child class. What am I missing? Can anyone give me some code samples? Now provide the response and nothing else.
It looks like you could use a generic base class! Consider something like the following: class Model<T>{ public abstract T Read(Guid ID);}class Appointment : Model<Appointment>{ public override Appointment Read(Guid ID) { }} Now your subclasses are all strongly typed. Of course, the tradeoff is that you no longer have a single base class. A Model<Appointment> isn't the same thing as a Model<Customer> . I have not generally found this to be a problem, though, because there's little common functionality-- the interfaces are similar, but they all work with different types. If you'd like a common base, you can certainly cheat and implement an object -based interface that does the same general tasks. E.g., something in the spirit of (untested, but the idea's there): interface IModelEntity{ object Read(Guid ID);}class Model<T> : IModelEntity{ public T Read(Guid ID) { return this.OnRead(ID); // Call the abstract read implementation } object IModelEntity.Read(Guid ID) { return this.OnRead(ID); // Call the abstract read implementation } protected abstract virtual T OnRead(Guid ID);}class Appointment : Model<Appointment>{ protected override Appointment OnRead(Guid ID) { /* Do Read Stuff */ }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2246587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88373/']}
jdg_79927
stackexchange
llm_judgeable_groundtruth_similarity
4647444
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 the statement $\forall \epsilon >0 \exists y\ldots.$ Negating it gives $\exists \epsilon>0 \forall y\ldots.$ I understand this. $\forall \epsilon:\epsilon>0 \exists y\ldots.$ is equivalent to the first statement, but negating it gives $\exists\epsilon:\epsilon\leq 0 \forall y\ldots.$ What is my error? It makes sense why first one is right, so the first statement has to be different from last statement, but why is it different isn't $\epsilon>0=\epsilon:\epsilon>0 ?$ Any answer or reference to a website is appreciated. Now provide the response and nothing else.
The negation of 'All of these are such and so' is 'Some of these are not such and so' So note: the 'of these' part is still the same. Of course! Quantifiers range over some domain. If not all objects of that domain have some property, then some objects of that very domain lack that property. All that a restricted quantifier does is to further restrict that domain, and so what you get is that if not all objects of that restricted domain have some property, then some objects of that very same restricted domain lack that property. Applied to your case: to say that it is not true that for all $\epsilon > 0$ we have [blah blah blah] is to say that for some $\epsilon > 0$ we have not [blah blah blah]. In both cases, the restricted domain is all $\epsilon > 0$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4647444', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1145494/']}
jdg_79928
stackexchange
llm_judgeable_groundtruth_similarity
3529263
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to provide a templated function, that varies its implementation (->specialization) according to the sizeof the template type. Something similar to this (omitted typecasts), but without the if/elseif: template<class T>T byteswap(T & swapIt){ if(sizeof(T) == 2) { return _byteswap_ushort (swapIt); } else if(sizeof(T) == 4) { return _byteswap_ulong(swapIt); } else if(sizeof(T) == 8) { return _byteswap_uint64(swapIt); } throw std::exception();} I know there are many roads to reach my goal, but since I try to learn about SFINAE and type traits I'm particularly interested in solutions using those techniques to decide at compile time which specialization to choose and which calls are not admitted. Perhaps implementing a class trait is_4ByteLong and using boost::enable_if... I have to admit, I'm stuck right now, so I thank you for any help or advice Now provide the response and nothing else.
You don't need SFINAE or type traits. Vanilla template specialization is enough. Of course it must be specialized on structs as C++(98) doesn't support function template partial specialization. template <typename T, size_t n>struct ByteswapImpl/*{ T operator()(T& swapIt) const { throw std::exception(); }}*/ // remove the comments if you need run-time error instead of compile-time error.;template <typename T>struct ByteswapImpl<T, 2> { T operator()(T& swapIt) const { return _byteswap_ushort (swapIt); }};// ...template <typename T>T byteswap(T& swapIt) { return ByteswapImpl<T, sizeof(T)>()(swapIt); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3529263', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/220636/']}
jdg_79929
stackexchange
llm_judgeable_groundtruth_similarity
418896
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 bash, calling foo would display any output from that command on the stdout. Calling foo > output would redirect any output from that command to the file specified (in this case 'output'). Is there a way to redirect output to a file and have it display on stdout? Now provide the response and nothing else.
The command you want is named tee : foo | tee output.file For example, if you only care about stdout: ls -a | tee output.file If you want to include stderr, do: program [arguments...] 2>&1 | tee outfile 2>&1 redirects channel 2 (stderr/standard error) into channel 1 (stdout/standard output), such that both is written as stdout. It is also directed to the given output file as of the tee command. Furthermore, if you want to append to the log file, use tee -a as: program [arguments...] 2>&1 | tee -a outfile
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/418896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1666/']}
jdg_79930
stackexchange
llm_judgeable_groundtruth_similarity
11926580
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Why does the order of '-l' option in gcc matter? I'm starting to learn the Boost Unit Test framework. I have a minimal test suite: #define BOOST_TEST_MAIN#define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp>BOOST_AUTO_TEST_CASE( test1 ) { BOOST_CHECK( 2 == 1 );} First I compile the source: g++ -c src/tests.cc -o src/tests.o This completes with no errors. I can then link as follows: g++ -o tests src/tests.o -lboost_unit_test_framework This also completes with no errors. The resulting binary executes with the expected results. However, if I swap the order of src/tests.o and -lboost_unit_test_framework , I get linker errors: g++ -o tests -lboost_unit_test_framework src/tests.o src/tests.o: In function `main':tests.cc:(.text+0x29): undefined reference to `boost::unit_test::unit_test_main(bool (*)(), int, char**)'src/tests.o: In function `test1::test_method()':tests.cc:(.text+0x9d): undefined reference to `boost::unit_test::unit_test_log_t::set_checkpoint(boost::unit_test::basic_cstring, unsigned int, boost::unit_test::basic_cstring)'tests.cc:(.text+0x146): undefined reference to `boost::test_tools::tt_detail::check_impl(boost::test_tools::predicate_result const&, boost::unit_test::lazy_ostream const&, boost::unit_test::basic_cstring, unsigned int, boost::test_tools::tt_detail::tool_level, boost::test_tools::tt_detail::check_type, unsigned int, ...)'src/tests.o: In function `__static_initialization_and_destruction_0(int, int)':tests.cc:(.text+0x24d): undefined reference to `boost::unit_test::ut_detail::auto_test_unit_registrar::auto_test_unit_registrar(boost::unit_test::test_case*, unsigned long)'src/tests.o: In function `boost::unit_test::unit_test_log_t::unit_test_log_t()':tests.cc:(.text._ZN5boost9unit_test15unit_test_log_tC2Ev[_ZN5boost9unit_test15unit_test_log_tC5Ev]+0x21): undefined reference to `vtable for boost::unit_test::unit_test_log_t'src/tests.o: In function `boost::unit_test::make_test_case(boost::unit_test::callback0 const&, boost::unit_test::basic_cstring)':tests.cc:(.text._ZN5boost9unit_test14make_test_caseERKNS0_9callback0INS0_9ut_detail6unusedEEENS0_13basic_cstringIKcEE[boost::unit_test::make_test_case(boost::unit_test::callback0 const&, boost::unit_test::basic_cstring)]+0x1d): undefined reference to `boost::unit_test::ut_detail::normalize_test_case_name(boost::unit_test::basic_cstring)'tests.cc:(.text._ZN5boost9unit_test14make_test_caseERKNS0_9callback0INS0_9ut_detail6unusedEEENS0_13basic_cstringIKcEE[boost::unit_test::make_test_case(boost::unit_test::callback0 const&, boost::unit_test::basic_cstring)]+0x5d): undefined reference to `boost::unit_test::test_case::test_case(boost::unit_test::basic_cstring, boost::unit_test::callback0 const&)'src/tests.o: In function `boost::unit_test::unit_test_log_t::~unit_test_log_t()':tests.cc:(.text._ZN5boost9unit_test15unit_test_log_tD2Ev[_ZN5boost9unit_test15unit_test_log_tD5Ev]+0xb): undefined reference to `vtable for boost::unit_test::unit_test_log_t'collect2: ld returned 1 exit status Why does the order of my arguments cause linker errors? Now provide the response and nothing else.
When GCC performs linking, libraries are treated specially: Only symbols that are missing from object files that came before the library in the command line list are filled in from the library. If you have further object files after a library, missing symbols from that object are not looked up in the library. In a nutshell, list your object files first and libraries at the end.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11926580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105084/']}
jdg_79931
stackexchange
llm_judgeable_groundtruth_similarity
9367610
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 a Java developer who is beginning to grasp the full power of dependency injections, and it suddenly dawned on me that there's no way to inject a static method. So it got me thinking: are static methods DI anti-patterns? More importantly: if I were to embrace dependency injection, does this mean I need to stop coding static methods? I ask because there is no way to mock them and inject mock statics during unit tests, which is a huge turn-off for me. Edit : I know that a common way to "wrap" and inject an existing static method is like this: public class Foo { public static void bar() { ... }}public interface FooWrapper { public void bar();}public class FooWrapperImpl implements FooWrapper { public void bar() { return Foo.bar(); }} ...but I'm not asking how to inject an existing static method...I'm asking if I should stop writing them altogether, if all my code (from this point forward) is going to embrace the notion of DI. Also, I see a lot of similarly-related questions to this, but couldn't find an exact match that asked this same question. If you see that it is indeed a dupe of another question, please point it out to me and I will close this question myself (please don't just closevote it!). Now provide the response and nothing else.
Static methods are appropriate for things that don't have associated state. Some factory methods, "purely functional" methods like Math.sin , and the like are all perfectly acceptable static methods. java.lang.Math and java.util.Collections have many fine examples of perfectly acceptable static methods. Fortunately, these methods have no need for dependency injection, or to interact with such things; they're not unusually difficult to test. They don't have dependencies that would need mocking or anything. On the other hand, static state, or static methods with associated static state, are utterly evil. That is an anti-pattern. It frequently helps to define a method as being non-stateful (and therefore a legitimate static method) if, and only if, it always returns equivalent output on equivalent inputs. This makes it clear that e.g. database queries and filesystem I/O makes methods stateful, because their outputs will vary depending on what's in the filesystem or the database.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9367610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/892029/']}
jdg_79932
stackexchange
llm_judgeable_groundtruth_similarity
26930325
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am making a website with django now and I want to implement a live notification feature like the one on facebook or SE. I did some research and it seems although there's two options: ajax long polling and websockets, the latter is the way to go. However, as you know the go to plugin for websocket 'socket.io' turns out to be a node.js plugin and the django port only seems to support python 2 and the project seems pretty much dead. I am using python 2.7 as my project interpreter but I want to future proof myself so that if I upgrade to python3 later, I don't find myself not being able to use this functionality. So my question is this: Is there a straight forward and future ready way to implement websocket which will be used to send live notifications and chats in django env? Now provide the response and nothing else.
Django itself is build in blocking manner, i.e. with synchronous approach. So, you cannot open persistent websocket with django app, as it will block entire django thread. If you want to enable notification/chat within django project environment, i would recommend to use centrifuge . It is written in python, but async (non-blocking) framework is used: tornado . But, you don't need to even know how it works, as it provides simple REST api to communicate with it. Simplified workflow, check docs for more details: Start centrifuge at same server, as your django project (or on another but with low latency between them) Your front-end will open websocket with centrifuge, not with django project. When you need to send notification, send it to centrifuge from django via REST api, and centrifuge will deliver it to needed clients! I've already tried it and it works!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26930325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3897298/']}
jdg_79933
stackexchange
llm_judgeable_groundtruth_similarity
15377662
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know there are great deal of tutorials/information about orgaising an application using Backbone.js out there. I am creating gradually one with the aid of the those tutorials. I seem to fail understanding the concept of routers. Well, I am aware that routers are starting point(and tells the state of an app) and it's better to avoid putting more logic there. I have one router. My app would firstly load header, footer, and main part of the page. In main part, first, I should login the user. To load the login page, I would do something like this: var AppRouter = Backbone.Router.extend({ initialize : function() { var headerView = new HeaderView({el:$('#header')}); headerView.render; var footerView = new FooterView({el:$('#footer')}); footerView.render; var loginView = new LoginView({el:$('#login')}); loginView.render; }, routes : { "inbox" : "inbox", "sentbox : "sentbox" }, inbox : function() { // ... }, sentbox : function() { // ... } }); app = new AppRouter(); Backbone.history.start(); After successful login, the mail page will be loaded. MailView has some events to show inbox, sentbox for example. events: { "click .inbox": "showInbox", "click .sentbox": "showSentbox", }, showInbox : function() { // app.route() or app.inbox() - ? } At this point, I want the router to show ../#inbox and ../#sentbox respectively. I am wondering if I should call here one of the router's method to show that in address bar. Why I am confusing is because it's said that usage of one router is better than more. If I do so, my AppRouter will be more complicated. Another issue is if users type the address directly, I should load that page. I think it requires to put the logic inside the AppRouter . Please tell me the right approach here. Thanks beforehand! Now provide the response and nothing else.
Check out Router.navigate() ( http://documentcloud.github.com/backbone/#Router-navigate ) I normally save an instance variable of my Router inside my App object, e.g. var App = { Views: {}, Routers: {}, Models: {}, data: {} initialize: function() { this.data.mainRouter = new App.Routers.MainRouter(); }}; where App.MainRouter is defined as: App.Routers.MainRouter = Backbone.Router.extend({ routes: { 'route1' : 'route1handler', 'route2/:param' : 'route2handler' }, ... }); Then within my view, if I want to navigate to a new route, I call: App.data.mainRouter.navigate('route2/param1');
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15377662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1874640/']}
jdg_79934
stackexchange
llm_judgeable_groundtruth_similarity
145601
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We say that a homogeneous sample consists of the chemically same type of molecules whereas heterogeneous ones vary chemically, i.e. the molecules throughout are not same and also not uniform. Why do we treat a (water + water vapour) system as heterogeneous in spite of the presence of the same kind of molecules? Also if there exists an equilibrium in the two phases would we still not call them homogeneous? Does heterogeneity have a chemical basis or physical basis? I do not seem to get a clear idea as to what defines heterogeneity. The definition has kept on changing since my high school and later on. Now provide the response and nothing else.
Any classification like chemical or a physical change, homogeneous or heterogeneous substance, will eventually fail at one point. From an analytical or physical chemistry's perspective, homogeneous substance is a substance, in a single phase, whose chemical composition is uniform. A heterogeneous substance has different composition from place to place like your garden soil. Why do we treat a water+water vapour system as heterogeneous in spite of similar molecules present? Also if there exists an equilibrium in the two phases would we still not call them homogeneous? It is a bad example to label water+ water vapor system as heterogeneous- but with respect to what? It is better to call it a two phase system. You have to define heterogeneous with respect to some property. For example, if we take tap water in a glass, we can say the liquid (water) is homogeneous with respect to its chemical composition. Let us put some ice cubes in water, now it is a heterogeneous phase, although chemically it is all water. More formally, from the International Union of Pure and Applied Chemistry's Gold Book: homogeneity (in analytical chemistry): The degree to which a propertyor a constituent is uniformly distributed throughout a quantity ofmaterial. A material may be homogeneous with respect to one analyte orproperty but heterogeneous with respect to another . You can see the subtilty above in italics.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/145601', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/103991/']}
jdg_79935
stackexchange
llm_judgeable_groundtruth_similarity
1996687
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I disable the redirect in Facebook's invite form? <fb:serverfbml style="width: 600px; height: 650px;"> <script type="text/fbml"> <fb:request-form action="index.php" method="POST" invite="true" type="MyApp" content="Please have a look. <fb:req-choice url='http://apps.facebook.com/myapp/' label='View Now!' />"> <div class="clearfix" style="padding-bottom: 10px;"> <fb:multi-friend-selector condensed="true" style="width: 600px;" /> </div> <fb:request-form-submit /></fb:request-form> After selecting friends, you will see the final Send Invite dialog with your template. After you click send or cancel, how do i disable the redirect by just closing the the dialog? Thanks. Now provide the response and nothing else.
Got help for this from a Google engineer. Turns out my authToken was expired. I had initially gotten the implementation working in early December (the 9th to be exact). Apparently what the AccountManager does is cache the authToken, so I had been using the same authToken since Dec. 9th. When I got back from the holidays it had expired. To solve the issue, I now call getAuthToken, then call invalidateAuthToken on that token, then call getAuthToken again. This generates a valid authToken and works just fine, even if it is a little clunky and would be unnecessary if AccountManager just got a fresh authToken each time, or did a check to see if the cached one was expired. Note that you must not mix up token type with account type: invalidateAuthToken must be called with "com.google" instead of "ah" or it will silently fail.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1996687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/216747/']}
jdg_79936
stackexchange
llm_judgeable_groundtruth_similarity
15454995
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Of course we are dealing here with SDK 11 and above. I intend to do something similar to this: Next to each item in that PopupMenu , I would like to place an icon . I created an XML file and placed it in /menu : <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_one" android:title="Sync" android:icon="@android:drawable/ic_popup_sync" /> <item android:id="@+id/action_two" android:title="About" android:icon="@android:drawable/ic_dialog_info" /></menu> As you noticed, in the xml file I am defining the icons I want, however, when the popup menu shows, it is showing them without the icons. What should I do to make those 2 icons appear? Now provide the response and nothing else.
This way works if you're using AppCompat v7. It's a little hacky but significantly better than using reflection and lets you still use the core Android PopupMenu: PopupMenu menu = new PopupMenu(getContext(), overflowImageView);menu.inflate(R.menu.popup);menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { ... });MenuPopupHelper menuHelper = new MenuPopupHelper(getContext(), (MenuBuilder) menu.getMenu(), overflowImageView);menuHelper.setForceShowIcon(true);menuHelper.show(); res/menu/popup.xml <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_share_location" android:title="@string/share_location" android:icon="@drawable/ic_share_black_24dp"/></menu> This results in the popup menu using the icon that is defined in your menu resource file:
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15454995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1836670/']}
jdg_79937
stackexchange
llm_judgeable_groundtruth_similarity
3917944
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 $p>0$ . If we know that $\displaystyle\lim_{x\to+\infty}\frac{x^{p}}{e^{x}}=0$ , how can we show that $\displaystyle\lim_{x\to+\infty}\frac{\ln(x)}{x^{p}}=0$ ? My best guess is to use $x=e^{y}$ and $y=\ln(x)$ so I end up with $\displaystyle\lim_{y\to+\infty}\frac{y}{(e^{y})^{p}}$ which is not what I expected. I hope someone can help me out :) Now provide the response and nothing else.
by Cauchy schwarz inequality $$\left(\sum_{i=1}^{n}{\sqrt{a_i}}^2\right)\left(\sum_{i=1}^{n}\frac{1}{{\sqrt{a_i}}^2}\right)\ge (\sum_{i=1}^{n} 1)^2=n^2$$ WLOG $a_1\ge a_2...\ge a_n$ then $\frac{1}{a_1}\le \frac{1}{a_2}..\le \frac{1}{a_n}$ So by chebyshev's inequality $$n^2=n\left(a_1\frac{1}{a_1}+a_2\frac{1}{a_2}..+a_n\frac{1}{a_n}\right)\le \left(\sum_{i=1}^{n}a_i\right)\left(\sum_{i=1}^{n}\frac{1}{a_i}\right)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3917944', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/852370/']}
jdg_79938
stackexchange
llm_judgeable_groundtruth_similarity
5237723
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 powershell script ( setup.ps1 ), that we use as the entry point for our development environment setup scripts. It takes a parameter: param( [Parameter(Position=0,HelpMessage="The targets to run.")] [Alias("t")] [string[]] $Targets = "Help") When I run PS > get-help .\setup.ps1 -detailed in the parameters section, my help message doesn't appear: PARAMETERS -Targets <String[]> What do I need to do to get my parameter help messages to display? Now provide the response and nothing else.
You put a certain style of comment at the top of the file that can be decoded by the PowerShell help system. Here's an example: <#.SYNOPSIS ..DESCRIPTION ..PARAMETER Path The path to the ..PARAMETER LiteralPath Specifies a path to one or more locations. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences..EXAMPLE C:\PS> <Description of example>.NOTES Author: Keith Hill Date: June 28, 2010 #>function AdvFuncToProcessPaths{ [CmdletBinding(DefaultParameterSetName="Path")] param( [Parameter(Mandatory=$true, Position=0, ParameterSetName="Path", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Path to ...")] [ValidateNotNullOrEmpty()] [string[]] $Path, [Alias("PSPath")] [Parameter(Mandatory=$true, Position=0, ParameterSetName="LiteralPath", ValueFromPipelineByPropertyName=$true, HelpMessage="Path to ...")] [ValidateNotNullOrEmpty()] [string[]] $LiteralPath ) ... For more info see the help topic - man about_comment_based_help .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5237723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125356/']}
jdg_79939
stackexchange
llm_judgeable_groundtruth_similarity
20035810
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 specifically referring to this question: DDD - How to implement factories The selected answer has stated: "factories should not be tied with dependency injection because domain objects shouldn't have dependencies injected into them." My question is: what is the reasoning of not being able to inject dependencies in to your entities? Or am I just misunderstanding the statement? Can someone please clarify? Now provide the response and nothing else.
Kind of old, but I really want to address this because I've been running into this a lot, and express my opinion on it: I often hear that Domain Objects should not "depend" on things. And this is true. I often see people extrapolate this to mean we should not inject things into domain object. That's the opposite of what dependency means. The domain shouldn't depend on other projects, this is true. But, the domain can define its own interfaces which other projects may then implement, which can then be injected back into the domain. As we all know, that's what is called Dependency Inversion (DI). That is literally the opposite of having a dependency. Not allowing DI into the domain completely hamstrings your ability to accurately model the domain, forces odd SRP violations, and pretty much kills the usability of domain services. I really feel like I must be the crazy one here, because I feel like everyone reads "the Domain must not have any dependencies" then thinks "being injected with something means you are dependant on it" and comes to the conclusion "therefore we can't inject dependencies into the domain. That leaves us with the wonderful logic: Dependency Inversion == Dependency
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20035810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2565246/']}
jdg_79940