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
10945270
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 only want the person who I have assigned the task to see the task in the project module. I don't want other users of the project to see this persons tasks. However currently any user who has user access rights can see all the tasks even if they were not assigned it. Is there a work around this ? Now provide the response and nothing else.
OpenERP/Odoo has two kinds of security restrictions that can be assigned to a user group: Access Rights are CRUD yes/no flags (similar to Unix FS permissions), and allow per-model access control. They state whether members of this group may perform a Create, Read, Update, and Delete operation on any document of a certain document model (e.g. a project task). The default policy is DENY, so by default any operation will be refused if the user does not explicitly have the right to perform it via one of her groups' access rights. Record Rules are filters applied on CRUD operations, and allow per-document access-control, once access right are already granted. Users will only be able to perform an operation on a given document if the document matches at least one of the record rules. The default policy is ALLOW, so if no rule exists for a given model, all documents of that model may be accessed by users who have the necessary access rights. Both Access Rights and Record Rules may also be defined globally without assigning them to a specific group, in which case they apply to everyone. There is one pitfall for Record Rules: global rules may NOT be relaxed by other rules (on purpose!), so use with care. In your case it looks like you should define one extra Record Rule on the Project User group that explicitly restricts access on Project Tasks to your own tasks (and presumably those that are not assigned yet). You need to create a new entry in the Security Rules menu with these parameters: object/model: project.task name: See own tasks only domain: ['|',('user_id','=',False),('user_id','=',user.id)] (means: your own tasks and unassigned ones) apply for read: [x] apply for write: [x] apply for create: [x] apply for delete: [x] groups: Project / User The domain of a record rule is a standard OpenERP/Odoo domain that is evaluated on the records on which you are trying to perform the operation, and can refer to a user variable that contains the current user's data (technically, a browse_record on the current user). The documentation has a description of domain . If you want to allow special users (e.g. Project Managers) to view all tasks in the system, you can relax this rule for them by adding another rule to the Project Manager group which allows access to all tasks. There is a special "domain filter" that means "ALLOW ALL" and is useful to relax another stricter rule: [(1,'=',1)] . Note 1 : Have a look at the existing Record Rules to see what they're doing first, and be sure to read the explanations on the Record Rule form when you are adding yours. One important thing to keep in mind is that group-specific rules are combined with an OR operator. So if you add the rule I described above, you may not see any restriction effect because other group-specific rules are still giving access. You may have to disable them, edit them, or change the user group they apply to, to get the exact effect you want. Note 2 : Remember that if you do something wrong with Access Rights and Record Rules, you can always fix the mess with the admin account, as these security restrictions do not apply to the admin (similarly to the root user on Unix).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10945270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/976847/']}
jdg_377341
stackexchange
llm_judgeable_groundtruth_similarity
55819473
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an icon font that I preload in Chrome with <link rel="preload" as="font" type="font/ttf" href="/static/media/IconFont.ad47b1fb.ttf" crossorigin="anonymous"> and reference later in my CSS with @font-face { font-family: "IconFont"; src: url(/static/media/IconFont.d9fff078.eot); src: url(/static/media/IconFont.d9fff078.eot#iefix) format("embedded-opentype"), url(/static/media/IconFont.ad47b1fb.ttf) format("truetype"), url(/static/media/IconFont.c8a8e064.woff) format("woff"), url(/static/media/IconFont.979fb19e.svg#IconFont) format("svg"); font-weight: normal; font-style: normal;} Within one second of the page loading I use Unicode code point U+E95B with my icon font. I still get a warning from Chrome, though, that says: The resource http://localhost:3000/static/media/IconFont.ad47b1fb.ttf waspreloaded using link preload but not used within a few seconds from thewindow's load event. Please make sure it has an appropriate `as` value andit is preloaded intentionally. How do I get rid of this warning? Now provide the response and nothing else.
Try changing from rel="preload" to rel="prefetch". <link rel="prefetch" as="font" type="font/ttf" href="/static/media/IconFont.ad47b1fb.ttf" crossorigin="anonymous"> rel="prefetch" is used for a specific resource that is required but not use immediately. Chrome apparently isn't registering it's use in time and gives the warning, which is my guess. If prefetch doesn't work try rel="dns-prefetch". rel="dns-prefetch" tells the browser to resolve the dns so when it is needed it can be loaded quickly. I think prefetch should work though, as it actually requests and downloads the resource and stores it in the cache for later use, but it doesn't cause the browser warning if it isn't used quickly. [EDIT] According to this page this page, load your css first also using preload, then your font, i.e. <link rel="preload" as="style" href="[your-css-file-here.css]"> <link rel="preload" as="font" crossorigin type="font/tff" href="/static/media/IconFont.ad47b1fb.ttf"> Both the css and the font are preloaded then the page renders, so the css doesn't have to be loaded after the font. In your css file add "local('IconFont')," shown below, full example here src: local('IconFont'), url(/static/media/IconFont.ad47b1fb.ttf) format("truetype"), url(/static/media/IconFont.ad47b1fb.ttf) format("woff"), /* continue your font declaration */ About all I can think of to help with this. Hope this helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55819473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1568890/']}
jdg_377342
stackexchange
llm_judgeable_groundtruth_similarity
30632759
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to have a broadcast receiver when user turns off Ultra Power Saving Mode (Samsung) or Ultra Stamina Mode (Sony) and so with Ultra modes implemented by different device vendors? I have a alarm manager running which triggers my IntentService after a certain interval, when I turn on Ultra mode on either Sony or Samsung, alarm manager is not available, but when I turn off the ultra mode, I want the action broadcasted so that I can receive it and start my alarm manager as normally we do on Boot_Completed. I found some info online, such as POWER_SAVE_MODE but it also stated it was only available in lollipop. Appreciate the help. Thanks Now provide the response and nothing else.
As mentioned bulk_create does not trigger these signals - https://docs.djangoproject.com/en/1.8/ref/models/querysets/#bulk-create This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are). This has a number of caveats though: The model’s save() method will not be called, and the pre_save and post_save signals will not be sent. It does not work with child models in a multi-table inheritance scenario. If the model’s primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does. It does not work with many-to-many relationships. The batch_size parameter controls how many objects are created in single query. The default is to create all objects in one batch, except for SQLite where the default is such that at most 999 variables per query are used. So you have to trigger them manually. If you want this for all models you can override the bulk_create and send them yourself like this - class CustomManager(models.Manager): def bulk_create(items,....): super().bulk_create(...) for i in items: [......] # code to send signal Then use this manager - class Task(models.Model): objects = CustomManager() ....
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30632759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/328518/']}
jdg_377343
stackexchange
llm_judgeable_groundtruth_similarity
2374863
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 a makefile, I build all my .o files in a build directory: program: class1.o class2.o class3.o g++ $(BUILDDIR)class1.o $(BUILDDIR)class2.o $(BUILDDIR)class3.o -o $@ It would be cool to generate $(BUILDDIR)class1.o $(BUILDDIR)class2.o $(BUILDDIR)class3.o from the dependencies list... I know that $^ would give me the list of all dependencies, separated by spaces, but I can't deal with the sub-directory. Is it possible ? And if I have program: class1.o class2.o class3.o configure , can I exclude configure from the list ? Thank you :) Edit: Michael's solutions works well, but doing that, make does not find the dependencies and has to build everything everytime... Isn't there a simpler way, when making implicit rules like program: class1.o class2.o class3.o , to tell it to put the binaries in a build directory ? Now provide the response and nothing else.
Taking everyone's suggestions together, your final solution will look like: #include <iostream> using std::cout;usind std::endl;class foo; // tell the compiler there's a foo out there.class bar { public: // If you want to store a pointer to each type of function you'll // need two different pointers here: void (*freeFunctionPointer)(); void (foo::*memberFunctionPointer)();}; class foo { public: bar myBar; void hello(){ cout << "hello" << endl; }}; void byebye() { cout << "bye" << endl; } int main() { foo testFoo; testFoo.myBar.freeFunctionPointer = &byebye; testFoo.myBar.memberFunctionPointer = &foo::hello; ((testFoo).*(testFoo.myBar.memberFunctionPointer))(); // calls foo::hello() testFoo.myBar.freeFunctionPointer(); // calls byebye() return 0; } The C++ FAQ Lite has some guidance on how to simplify the syntax. Taking Chris' idea and running with it, you could get yourself something like this: #include <iostream>using std::cout; using std::endl;class foo;typedef void (*FreeFn)();typedef void (foo::*MemberFn)();class bar{public: bar() : freeFn(NULL), memberFn(NULL) {} void operator()(foo* other) { if (freeFn != NULL) { freeFn(); } else if (memberFn != NULL) { ((other)->*(memberFn))(); } else { cout << "No function attached!" << endl; } } void setFreeFn(FreeFn value) { freeFn = value; memberFn = NULL; } void setMemberFn(MemberFn value) { memberFn = value; freeFn = NULL; }private: FreeFn freeFn; MemberFn memberFn;};class foo{public: bar myBar; void hello() { cout << "foo::hello()" << endl; } void operator()() { myBar(this); }};void bye() { cout << "bye()" << endl; }int main(){ foo testFoo; testFoo(); testFoo.myBar.setMemberFn(&foo::hello); testFoo(); testFoo.myBar.setFreeFn(&bye); testFoo(); return 0;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2374863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/194594/']}
jdg_377344
stackexchange
llm_judgeable_groundtruth_similarity
2005268
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 $F: \mathbb Z \times \mathbb Z \to \mathbb Z$ be defined by $$F(x,y) = x^2 - y^2$$ How do I formally prove this is NOT a surjection? Now provide the response and nothing else.
I say that $f(x,y) = 2$ is not possible. If we look at the problem modulo $4,$ a perfect square is equivalent to $1$ or $0$ modulo $4.$ $f(x,y)$ reduces to $4$ cases.$0-0, 1-0, 0-1, 1-1,$ none of which equal $2.$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2005268', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/381999/']}
jdg_377345
stackexchange
llm_judgeable_groundtruth_similarity
54368686
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 think i'm experiencing a systematic offset in a LSTM model, between the predictions and the ground truth values. What's the best approach to continue further from now on? The model architecture, along with the predictions & ground truth values are shown below. This is a regression problem where the historical data of the target plus 5 other correlated features X are used to predict the target y . Currently the input sequence n_input is of length 256, where the output sequence n_out is one. Simplified, the previous 256 points are used to predict the next target value. X is normalized. The mean squared error is used as the loss function. Adam with a cosine annealing learning rate is used as the optimizer ( min_lr=1e-7 , max_lr=6e-2 ). _________________________________________________________________Layer (type) Output Shape Param # =================================================================cu_dnnlstm_8 (CuDNNLSTM) (None, 256) 270336 _________________________________________________________________batch_normalization_11 (Batc (None, 256) 1024 _________________________________________________________________leaky_re_lu_11 (LeakyReLU) (None, 256) 0 _________________________________________________________________dropout_11 (Dropout) (None, 256) 0 _________________________________________________________________dense_11 (Dense) (None, 1) 257 =================================================================Total params: 271,617Trainable params: 271,105Non-trainable params: 512_________________________________________________________________ Increasing the node size in the LSTM layer, adding more LSTM layers (with return_sequences=True ) or adding dense layers after the LSTM layer(s) only seems to lower the accuracy. Any advice would be appreciated. Additional information on the image. The y-axis is a value, x-axis is the time (in days). NaNs have been replaced with zero, because the ground truth value in this case can never reach zero. That's why the odd outliers are in the data. Edit: I made some changes to the model, which increased accuracy. The architecture is the same, however the features used have changed. Currently only the historical data of the target sequence itself is used as a feature. Along with this, n_input got changed so 128 . Switched Adam for SGD , mean squared error with the mean absolute error and finally the NaNs have been interpolated instead of being replaced with 0. One step ahead predictions on the validation set look fine: However, the offset on the validation set remains: It might be worth noting that this offset also appears on the train set for x < ~430: Now provide the response and nothing else.
It looks like your model is overfitting and is simply always returning the value from the last timestep as a prediction. Your dataset is probably too small to have a model with this amount of parameters converge. You'll need to resort to techniques that combat overfitting: agressive dropout, adding more data, or try simpler, less overparameterized methods. This phenomenon (LSTMs returning a shifted version of the input) has been a recurring theme in many stackoverflow questions. The answers there might contain some useful information: LSTM Sequence Prediction in Keras just outputs last step in the input LSTM model just repeats the past in forecasting time series LSTM NN produces “shifted” forecast (low quality result) Keras network producing inverse predictions Stock price predictions of keras multilayer LSTM model converge to a constant value Keras LSTM predicted timeseries squashed and shifted LSTM Time series shifted predictions on stock market close price Interesting results from LSTM RNN : lagged results for train and validation data Finally, be aware that, depending on the nature of your dataset, there simply might be no pattern to be discovered in your data at all. You see this a lot with people trying to predict the stock market with LSTMs (there is a question on stackoverflow on how to predict the lottery numbers).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54368686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3482325/']}
jdg_377346
stackexchange
llm_judgeable_groundtruth_similarity
38155039
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can you please help understand what are the main differences (if any) between the native int type and the numpy.int32 or numpy.int64 types? Now provide the response and nothing else.
There are several major differences. The first is that python integers are flexible-sized (at least in python 3.x). This means they can grow to accommodate any number of any size (within memory constraints, of course). The numpy integers, on the other hand, are fixed-sized. This means there is a maximum value they can hold. This is defined by the number of bytes in the integer ( int32 vs. int64 ), with more bytes holding larger numbers, as well as whether the number is signed or unsigned ( int32 vs. uint32 ), with unsigned being able to hold larger numbers but not able to hold negative number. So, you might ask, why use the fixed-sized integers? The reason is that modern processors have built-in tools for doing math on fixed-size integers, so calculations on those are much, much, much faster. In fact, python uses fixed-sized integers behind-the-scenes when the number is small enough, only switching to the slower, flexible-sized integers when the number gets too large. Another advantage of fixed-sized values is that they can be placed into consistently-sized adjacent memory blocks of the same type. This is the format that numpy arrays use to store data. The libraries that numpy relies on are able to do extremely fast computations on data in this format, in fact modern CPUs have built-in features for accelerating this sort of computation. With the variable-sized python integers, this sort of computation is impossible because there is no way to say how big the blocks should be and no consistentcy in the data format. That being said, numpy is actually able to make arrays of python integers. But rather than arrays containing the values, instead they are arrays containing references to other pieces of memory holding the actual python integers. This cannot be accelerated in the same way, so even if all the python integers fit within the fixed integer size, it still won't be accelerated. None of this is the case with Python 2. In Python 2, Python integers are fixed integers and thus can be directly translated into numpy integers. For variable-length integers, Python 2 had the long type. But this was confusing and it was decided this confusion wasn't worth the performance gains, especially when people who need performance would be using numpy or something like it anyway.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38155039', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6510497/']}
jdg_377347
stackexchange
llm_judgeable_groundtruth_similarity
3266
Below is a question asked on the forum devops.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been using AWS for a while now. I always have the difficulty tracking AWS resources and how they are interconnected. Obviously, I am using Terraform but still, there is always ad-hoc operations that cut down my visibility. Since I have been charged multiple times for resources/services that are present but not used by me. Unused services include resources that are not pointing to other services but present in the AWS environment. Tools suggestions are also welcome. Now provide the response and nothing else.
There are a few ways to approach deleting unused resources, perhaps tagging items that are part of some trusted or known group, as some have suggested here and then manually monitoring for resources that isn’t tagged appropriately. You could then extend this to a python script that you run every so often to ID and delete these resources. However, there are other (potentially less intensive) options. 1) AWS already provide a way for us to monitor our resources, identify unused ones and terminate them with CloudWatch alarms. You can start by configuring some alarming based on some set of checks that you might already be doing manually. Once you are comfortable that the alarming is accurate, you can add a termination step to the chain. 2) Alternatively, our friends at Netflix made this chill tool called JanitorMonkey to monitor and delete unused Instances, EBS Volumes, EBS Snapshots and Autoscaling groups. It is part of the original so-called “Simian Army” open source pack from Netflix and written in Java. Even thought it’s a few years old now, this thing is highly configurable and well worth a look. Both options here allow you to configure warnings and business rules that fit your needs. Additionally, using CloudWatch might also be a good opportunity to learn more about AWS logs and anomaly identification.
{}
{'log_upvote_score': 4, 'links': ['https://devops.stackexchange.com/questions/3266', 'https://devops.stackexchange.com', 'https://devops.stackexchange.com/users/3628/']}
jdg_377348
stackexchange
llm_judgeable_groundtruth_similarity
664886
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I do 0 == "0" it evaluates to true. Try, if( -777 == "-777" ) alert("same"); alert happens. And, it's also noticeable that true == "true" doesn't evaluate to true. Try, if( false == "false" ) alert("same"); alert doesn't happen. Why is it so? Now provide the response and nothing else.
The behavior of == is a bit lengthy, but clearly defined in the ecma-262 spec : 11.9.3 The Abstract Equality Comparison Algorithm The comparison x == y, where x and yare values, produces true or false.Such a comparison is performed asfollows: If Type(x) is different from Type(y), go to step 14. If Type(x) is Undefined, return true. If Type(x) is Null, return true. If Type(x) is not Number, go to step 11. If x is NaN, return false. If y is NaN, return false. If x is the same number value as y, return true. If x is +0 and y is −0, return true. If x is −0 and y is +0, return true. Return false. If Type(x) is String, then return true if x and y are exactly the samesequence of characters (same lengthand same characters in correspondingpositions). Otherwise, return false. If Type(x) is Boolean, return true if x and y are both true or bothfalse. Otherwise, return false. Return true if x and y refer to the same object or if they refer toobjects joined to each other (see 13.1.2). Otherwise, return false. If x is null and y is undefined, return true. If x is undefined and y is null, return true. If Type(x) is Number and Type(y) is String, return the result of thecomparison x == ToNumber(y). If Type(x) is String and Type(y) is Number, return the result of thecomparison ToNumber(x) == y. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y. If Type(y) is Boolean, return the result of the comparison x ==ToNumber(y). If Type(x) is either String or Number and Type(y) is Object, returnthe result of the comparison x ==ToPrimitive(y). If Type(x) is Object and Type(y) is either String or Number, return theresult of the comparisonToPrimitive(x) == y. Return false. Step 16 applies to your former example: 0 == "0" // apply 16≡ 0 == toNumber("0")≡ 0 == 0 // apply 7≡ true And step 18, then step 16, apply to the latter: true == "true" // apply 18≡ toNumber(true) == "true"≡ 1 == "true" // apply 16≡ 1 == toNumber("true")≡ 1 == NaN // apply 6≡ false
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/664886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65412/']}
jdg_377349
stackexchange
llm_judgeable_groundtruth_similarity
3743186
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a measure $\mu$ with support $S \subseteq [0,1]$ such that it satisfies: (i) $S$ has Lebesgue measure zero but is dense on $[0,1]$ with respect to the standard metric; (ii) $\mu(S)<\infty$ ; and (iii) $\forall \epsilon>0$ , $\forall a,b \in [0,1]$ such that $b-a\geq \epsilon >0$ , $\mu((a,b])\geq k(\epsilon)>0$ . The Cantor distribution fails (i).It is unclear to me that taking the route of the answers here ensures (iii). The main reason I am asking this is that this possibility is mentioned in Diaconis and Freedman, 1990, p. 1317 , but I'm struggling to construct such a measure. Edit: (iii) should hold $\forall \epsilon>0$ . Apologies for the imprecision. Now provide the response and nothing else.
Let $e_i\in W$ satisfy $(e_i)_j=1$ if $i=j$ and $(e_i)_j=0$ otherwise. Then $$\langle Te_i,e_j\rangle=\cases{1\,\,{\rm if}\,\,j\leq i,\\0 \,\,{\rm if}\,\,j>i.}$$ Thus if $T^*$ exists: $$\langle e_i,T^*e_j\rangle=\cases{1\,\,{\rm if}\,\,j\leq i,\\0 \,\,{\rm if}\,\,j>i.}$$ So we have $(T^*e_j)_i=1$ for all $i\geq j$ which contradicts $T^*e_j\in W$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3743186', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/339195/']}
jdg_377350
stackexchange
llm_judgeable_groundtruth_similarity
954023
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 trying to find the partial sum formula of the following series: $$\sum_{y=1}^{\infty} \frac{4y^2-12y+9}{(y+3)(y+2)(y+1)y}$$ I have tried using Faulhaber's formula without success. I have also tried rewriting the system using partial fraction decomposition to obtain 4 terms. This didn't solve the issue either. When I use WolframAlpha to evaluate the sum, (or other computational software), it becomes 1/2. Is there some way to derive the this infinite sum to a partial sum formula? This partial sum formula is according to WolframAlpha:$$\frac{n^3-2n^2+3n}{2(n+1)(n+2)(n+3)}$$ Thank you in advance!J Now provide the response and nothing else.
Decompose the fraction on simple elements: $$\frac{4y^2-12y+9}{(y+3)(y+2)(y+1)y}=\frac{a}{y}+\frac{b}{y+1}+\frac{c}{y+2}+\frac{d}{y+3}$$and since the series is convergent then we have $a+b+c+d=0$. Now the partial sum is $$\sum_{y=1}^n \frac{a}{y}+\frac{b}{y+1}+\frac{c}{y+2}+\frac{d}{y+3}=a\sum_{y=1}^n \frac{1}{y}+b\sum_{y=2}^{n+2} \frac{1}{y}+c\sum_{y=3}^{n+3} \frac{1}{y}+d\sum_{y=4}^{n+4} \frac{1}{y}$$and the simplification is clear. Can you take it from here?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/954023', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/120897/']}
jdg_377351
stackexchange
llm_judgeable_groundtruth_similarity
8626392
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to Haskell and have some difficulties wrapping my head around some of it's concepts. While playing around with IO I wanted to flatten an IO [[String]]. An example of what I have tried: module DatabaseTestSO whereimport Database.HDBCimport Database.HDBC.MySQLimport Data.FoldableconvSqlValue :: [SqlValue] -> [String]convSqlValue xs = [ getString x | x <- xs ] where getString value = case fromSql value of Just x -> x Nothing -> "Null"listValues :: [[SqlValue]] -> [[String]]listValues [] = []listValues xs = [ convSqlValue x | x <- xs ]flatten :: [[a]] -> [a]flatten = Data.Foldable.foldl (++) []domains :: IO [[String]]domains = do conn <- connectMySQL defaultMySQLConnectInfo { mysqlHost = "hostname", mysqlDatabase = "dbname", mysqlUser = "username", mysqlPassword = "pass" } queryDomains <- quickQuery conn "SELECT name FROM domains" [] return (listValues queryDomains) That works with [[String]] in GHCi as expected: *DatabaseTestSO> flatten [["blah","blab","wah"],["bloh","blob","woh"],["blih","blib","wuh"]]["blah","blab","wah","bloh","blob","woh","blih","blib","wuh"] but does not with IO [[String]] where I get *DatabaseTestSO> flatten domains <interactive>:1:9: Couldn't match expected type `[[a0]]' with actual type `IO [[String]]' In the first argument of `flatten', namely `domains' In the expression: flatten domains In an equation for `it': it = flatten domains I guess I can not use a function that is supposed to be pure with IO types?Can I convert IO [[String]] to [[String]] ?How do I solve this problem correctly? Now provide the response and nothing else.
You have to realize what IO something means. It's not a something , it's an action that will return a something (In this case, something is [[String]] ). So, you cannot do anything with the thing that the action returns, until you perform the action, which returns that thing. You have two options to solve your problem. Perform the action, and use the result. This is done like this: do ds <- domains -- Perform action, and save result in ds return $ flatten ds -- Flatten the result ds Create a new action that takes the result of some action, and applies a function to it. The new action then returns the transformed value. This is done with the liftM function in the Control.Monad module. import Control.Monad-- ...do -- Creates a new action that flattens the result of domains let getFlattenedDomains = liftM flatten domains -- Perform the new action to get ds, which contains the flattened result ds <- getFlattenedDomains return ds PS. You might want to rename your domains variable to getDomains to clarify what it does. It's not a pure value; it's a monadic action that returns a pure value.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8626392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/367180/']}
jdg_377352
stackexchange
llm_judgeable_groundtruth_similarity
937166
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: Question states: Prove the law of double complements for sets: If $A$ is a set and $A^\complement$ is its complement than prove that: $$ (A^\complement)^\complement = A$$ I started with: $$ A^\complement = U - A$$where U is the universal set. But I do not understand how to go further. Now provide the response and nothing else.
Let $A$ be a subset of some universe $U$. We'll prove this by proving that the two sets are subsets of each other (and must therefore be equal). We'll use nothing but the definition that if $x \in X$, then $x \notin X^C$ (and what clearly follows: if $x \notin X$, then $x \in X^C$). Take $a \in A$. Then $a \notin A^C$. Then $a \in (A^C)^C$, by definition of the complement. So $A \subseteq (A^C)^C$. Now take $a \in (A^C)^C$. That means $a \notin A^C$. Therefore $a \in A$. So $(A^C)^C \subseteq A$. As $A \subseteq (A^C)^C$ and $(A^C)^C \subseteq A$, we conclude that $A = (A^C)^C$. For other techniques, see here . This is, in some sense, a duplicate question.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/937166', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/129081/']}
jdg_377353
stackexchange
llm_judgeable_groundtruth_similarity
46245844
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 embarking on my first attempt at utilizing a docker container. I have a python script that calls a couple API's and parses a file. The script took parameters for the URL of the server for the API, the API key, and the file path for the file to parse. I used argparse to handle these in the script. How do I get get these passed into Docker? I do not want to hard code anything as I am looking to hand this script off to an engineer who needs to run this periodically and take action based on the results. Thanks for your help. I have been searching but it seems like hard coding things into the dockerfile is the suggestion - I want the user to be able to put these in at run time. Or perhaps I have found the answer and am just not understanding it.... I apologize if my lingo is not right - this is my first attempt at utilizing Docker. Now provide the response and nothing else.
The way you do it depends on how your using docker. If you want to run your script in an already running container, you can use exec: docker exec <yourContainerName> python <yourScript> <args> Alternatively, if you have a docker image where your script is the ENTRYPOINT, any arguments you pass to the docker run command will be added to the entrypoint. So, if your docker file looks like this: FROM yourbase....ENTRYPOINT <yourScript> Then you can just run the script by running the container itself: docker run --rm <yourImageName> <args> Based on your comment below, it looks like you want this option. You should change your dockerfile to specify ENTRYPOINT ["python","./script.py"] (instead of using CMD)and then you can run via: docker run --rm <yourImageName> -a API_KEY - f FILENAME -o ORG_ID
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46245844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/858103/']}
jdg_377354
stackexchange
llm_judgeable_groundtruth_similarity
13426052
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 question concerning ObjectAnimator in Android. I am trying to model a Bounce effect whereby the View slides up (decreasing Y value) and back down after by the same amount 'n', followed by the View sliding up and down again but this time by 'n/2' (so half the distance). So a bigger bounce, followed by a shallower bounce - i.e., the kinda thing a Mac icon does in the tray when it wants your attention. Here is what I've tried so far (assume v is a View ): float y = v.getTranslationY(),distance = 20F; AnimatorSet s = new AnimatorSet(); s.play(ObjectAnimator.ofFloat(v, "translationY", y- distance).setDuration(500)) .before(ObjectAnimator.ofFloat(v, "translationY", y).setDuration(500)) .before(ObjectAnimator.ofFloat(v, "translationY", y- (distance/2)).setDuration(500)) .before(ObjectAnimator.ofFloat(v, "translationY", y).setDuration(500)); s.start(); Ignore the code quality, it's a POC! I was hoping this would work, but it seems to only 'bounce' once as if its combined the animations despite the use of .before() . Could you please show me how I can create complex AnimatorSet chains that do not amalgamate in to one, as I seem to be missing something? BONUS: For extra points, how can I set the repeat of an AnimatorSet? Many thanks! Now provide the response and nothing else.
OK so I eventually found a fairly neat way to achieve sequential animation by ignoring the fluent builder, and just using the playSequentially() method such that: AnimatorSet as = new AnimatorSet();as.playSequentially(ObjectAnimator.ofFloat(...), // anim 1 ObjectAnimator.ofFloat(...), // anim 2 ObjectAnimator.ofFloat(...), // anim 3 ObjectAnimator.ofFloat(...)); // anim 4as.setDuration(600);as.start(); Still haven't worked out repeating though, other than a dirty hack involving the callback onAnimationEnd in a listener. Must be a simpler way, so perhaps someone can edit this when they know of one. Anyway, hope the above helps someone.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13426052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/300037/']}
jdg_377355
stackexchange
llm_judgeable_groundtruth_similarity
40691451
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to remove digits from the end of a string, but I have no idea. Can the split() method work? How can I make that work? The initial string looks like asdfg123 ,and I only want asdfg instead. Thanks for your help! Now provide the response and nothing else.
No, split would not work, because split only can work with a fixed string to split on. You could use the str.rstrip() method : import stringcleaned = yourstring.rstrip(string.digits) This uses the string.digits constant as a convenient definition of what needs to be removed. or you could use a regular expression to replace digits at the end with an empty string: import recleaned = re.sub(r'\d+$', '', yourstring)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40691451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7181735/']}
jdg_377356
stackexchange
llm_judgeable_groundtruth_similarity
25289056
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 set a global environment variable in Inno Setup? Background: I am using the Inno install utility and need to set a global environment variable before I do the actual install. Now provide the response and nothing else.
Try this: [Registry]Root: HKCU; Subkey: "Environment"; ValueType:string; ValueName: "VARIABLE_NAME"; \ ValueData: "new_value"; Flags: preservestringtype You might need to add this: [Setup]; Tell Windows Explorer to reload the environmentChangesEnvironment=yes Alternatively try: [Run]Filename: "{app}\MyProg.exe"; BeforeInstall: SetEnvPath[Code]#ifdef UNICODE #define AW "W"#else #define AW "A"#endiffunction SetEnvironmentVariable(lpName: string; lpValue: string): BOOL; external 'SetEnvironmentVariable{#AW}@kernel32.dll stdcall';procedure SetEnvPath;begin if not SetEnvironmentVariable('VARIABLE_NAME', 'new_value') then MsgBox(SysErrorMessage(DLLGetLastError), mbError, MB_OK);end; Reference: Inno Setup Frequently Asked Questions - Setting Environment Variables If the variable change is not propagated (see Environment variable not recognized [not available] for [Run] programs in Inno Setup ) [Run]...; AfterInstall: RefreshEnvironment[Code]const SMTO_ABORTIFHUNG = 2; WM_WININICHANGE = $001A; WM_SETTINGCHANGE = WM_WININICHANGE;type WPARAM = UINT_PTR; LPARAM = INT_PTR; LRESULT = INT_PTR;function SendTextMessageTimeout(hWnd: HWND; Msg: UINT; wParam: WPARAM; lParam: PAnsiChar; fuFlags: UINT; uTimeout: UINT; out lpdwResult: DWORD): LRESULT; external 'SendMessageTimeoutA@user32.dll stdcall'; procedure RefreshEnvironment;var S: AnsiString; MsgResult: DWORD;begin S := 'Environment'; SendTextMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, PAnsiChar(S), SMTO_ABORTIFHUNG, 5000, MsgResult);end; More details: Inno Setup: Setting a System Environment Variable Under more modern (in other words, proper) operating systems, such as Windows 2000, XP, and Windows 2003 Server, environment variables are stored in the Registry under the following key: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\ Environment Variables are added by creating a new value under this key or by modifying a value if it already exists. To delete a variable, you simply delete its Registry value, unless you are removing part of an expanded value, such as PATH, in which case you only remove the part you want. At this point, Windows will not be aware of your changes unless you log off or reboot. To get around this, SetEnv will broadcast a WM_SETTINGCHANGE to all of the windows in the system. This allows other running applications—for example, Explorer.exe—to be notified of your change. If you run SetEnv from a command prompt, this will not update the environment variable for the current DOS window. This is mainly due to the fact that a process (SetEnv) cannot change the environment of its parent (The Command Prompt). However, any new DOS/Command Prompts that you open will show the new variable/value.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25289056', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/907655/']}
jdg_377357
stackexchange
llm_judgeable_groundtruth_similarity
65183
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I connect to the internet using my company's Wi-Fi and Tor. Can they still see the websites I visit? Now provide the response and nothing else.
Generally speaking No . Assuming: You follow Tor's best practices Tor does not protect all of your computer's Internet traffic when you run it. Tor only protects your applications that are properly configured to send their Internet traffic through Tor. To avoid problems with Tor configuration, we strongly recommend you use the Tor Browser. so if it's not setup correctly things can still leak like DNS requests for example. You are using a private computer (or at least one the company doesn't control). If they are admins on your computer they could install VNC or some logging software that will record your actions regardless of what software you use.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/65183', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/53673/']}
jdg_377358
stackexchange
llm_judgeable_groundtruth_similarity
101268
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 are the lesser-known but useful features of the Python programming language? Try to limit answers to Python core. One feature per answer. Give an example and short description of the feature, not just a link to documentation. Label the feature using a title as the first line. Quick links to answers: Argument Unpacking Braces Chaining Comparison Operators Decorators Default Argument Gotchas / Dangers of Mutable Default arguments Descriptors Dictionary default .get value Docstring Tests Ellipsis Slicing Syntax Enumeration For/else Function as iter() argument Generator expressions import this In Place Value Swapping List stepping __missing__ items Multi-line Regex Named string formatting Nested list/generator comprehensions New types at runtime .pth files ROT13 Encoding Regex Debugging Sending to Generators Tab Completion in Interactive Interpreter Ternary Expression try/except/else Unpacking+ print() function with statement Now provide the response and nothing else.
Chaining comparison operators: >>> x = 5>>> 1 < x < 10True>>> 10 < x < 20 False>>> x < 10 < x*10 < 100True>>> 10 > x <= 9True>>> 5 == x > 4True In case you're thinking it's doing 1 < x , which comes out as True , and then comparing True < 10 , which is also True , then no, that's really not what happens (see the last example.) It's really translating into 1 < x and x < 10 , and x < 10 and 10 < x * 10 and x*10 < 100 , but with less typing and each term is only evaluated once.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/101268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2679/']}
jdg_377359
stackexchange
llm_judgeable_groundtruth_similarity
907465
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If f is a function that is two times differentiable at x = a then: $\lim\limits_{h \to 0} \frac{f(a+h)-f(a)-hf'(a)}{h^2/2}=f''(a)$ I don't know how to prove or disprove this. I know I have to use the definition of derivation but I have no clue how to go on. Sorry for my grammar. English it's not my native language. Now provide the response and nothing else.
We have:$$ I = \frac{1}{4}\int_{0}^{1}z^{-2/3}(1-z)^{-2/3}\log z \,dz$$hence:$$ I =\frac{1}{4}\left. \frac{d}{d\alpha}\left(\int_{0}^{1}z^{-2/3+\alpha}(1-z)^{-2/3}\,dz\right) \right|_{\alpha=0}=\frac{\Gamma(1/3)}{4}\left.\frac{d}{d\alpha}\left(\frac{\Gamma(1/3+\alpha)}{\Gamma(2/3+\alpha)}\right)\right|_{\alpha=0}$$ and by using the identity $\Gamma' = \Gamma\cdot\frac{d}{dz}(\log \Gamma)=\Gamma\cdot\psi$ we have:$$ \left.\frac{d}{d\alpha}\left(\frac{\Gamma(1/3+\alpha)}{\Gamma(2/3+\alpha)}\right)\right|_{\alpha=0}=\frac{\Gamma(1/3)}{\Gamma(2/3)}\left(\psi(1/3)-\psi(2/3)\right) $$so:$$\color{blue}{I = \frac{\Gamma(1/3)^3}{8}\cdot\frac{\sqrt{3}}{\pi}(\psi(1/3)-\psi(2/3))}$$and the claim follows from the reflection formula for the digamma function.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/907465', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/171355/']}
jdg_377360
stackexchange
llm_judgeable_groundtruth_similarity
775
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The word of the LORD that came to Joel the son of Pethuel. Hearthis, ye old men, and give ear, all ye inhabitants of the land. Haththis been in your days, or in the days of your fathers? Tell ye yourchildren of it, and let your children tell their children, and theirchildren another generation ( JPS Joel 1:1-3). Understanding the historical context in which Joel is writing is central to unearthing the thematic and theological significance of his prophecies and how they relate to other stories in Tanakh. Question When did Joel write his book and deliver these prophecies? Related Now provide the response and nothing else.
[JPS translation and verse numbering throughout, unless otherwise noted] Joel is a short book (just three or four chapters depending on how their broken up), rich with themes of eschatology, repentance, redemption and a very sardonic description of famine: Awake, ye drunkards, and weep, and wail, all ye drinkers of wine, because of the sweet wine, for it is cut off from your mouth (1:5). As pointed out in this answer , the text has almost no temporal anchors and is difficult to date. However, most of the Bible scholars and commentaries I've read assume that Joel was written during the Second Temple period, anywhere from 520 to 200 BCE. (See for example, Marco Treves, “The Date of Joel” Vetus Testamentum, Vol. 7, Fasc. 2 (Apr., 1957), pp. 149-156.) The Argument for Late Authorship Many of the arguments provided for the Second Temple authorship argument are not compelling, eg: the "wall" referenced in 2:7, 9 implies that the prophecy was given after Nechemia's wall was built (Nechemiah 1:3). The three best arguments for late authorship that I'm aware of are as follows: “For, behold, in those days, and in that time, when I shall bring back the captivity of Judah and Jerusalem” (4:1) – implies that there was recently some exile from Judah, the Southern Kingdom of Israel. The Second Temple period was a time when the nation of Israel was returning to its land in Israel. “the children also of Judah and the children of Jerusalem have ye sold unto the sons of Jevanim [Greeks?], that ye might remove them far from their border” (4:6) – some scholars use this verse to date the book to the time of Ptolmey Soter , a Greek general who conquered much of the middle east and according to Josephus, sold many Israelites as slaves. In his book, Joel mentions a lot of different categories of people including: priests, elders, all inhabitants of the land, children, nursing infants, the bridegroom and the bride, but never once does he mention or make reference to an Israelite king or monarchy, implying that there wasn't a functional monarchy at the time. The Argument for Early Authorship I think the book was written before the destruction of the first Temple and after the exile of the Northern Kingdom of Israel, during the reign of King Menasseh. According to this early authorship theory, the Greeks mentioned in 4:6 are the early Ionians who controlled the local trade routes at the time, and the return of exiles in 4:1 is a reference to those of the Southern kingdom who were exiled during the Assyrian conquest of Northern Israel during the reign of Hosea the son of Elah of the Northern kingdom and King Hezekiah of the Southern kingdom (the father of Menasseh): Now in the fourteenth year of king Hezekiah did Sennacherib king of Assyria come up against all the fortified cities of Judah, and took them (II Kings 18:13). Prophecies of return were common around this time, see for example Jeremiah 31 and Hoshea 6:11. Prophecies of return during the reign of Chizkiyahu and Menasseh were fulfilled shortly after during the reign of Josiah (the son of Menasseh): Go, and proclaim these words toward the north, and say: return, thou backsliding Israel, saith the LORD; I will not frown upon you; for I am merciful, saith the LORD, I will not bear grudge for ever (Jeremiah 3:12). Textually, there is strong evidence which anchors the book of Joel in the historical and literary context of other First Temple prophets. Joel loved to make allusions, references and variations on other Biblical texts. To list just some of the book's striking parallels to other First Temple prophets: “All faces are waxed pale” (Joel 2:6, see Nahum 2:10) “A day of darkness and gloominess, a day of clouds and thick darkness” (Joel 2:2, see Zephaniah 1:15) “Bring back the captivity of Judah” (Joel 3:1, see Jeremiah 30:3 and 31:23) Joel 4:18 is parallel to Ezekiel 47:1-12 Joel 2:3 is parallel to Ezekiel 36:35 Isaiah 2:4 describes: And He shall judge between the nations, and shall decide for many peoples; and they shall beat their swords into plowshares, and their spears into pruninghooks ; nation shall not lift up sword against nation, neither shall they learn war any more. In 4:10, Joel parodies this imagery: Beat your plowshares into swords, and your pruning-hooks into spears ; let the weak say: 'I am strong.' In most cases, Joel is making reference to an earlier prophecy, in other cases, later prophets may be making reference to him. What's clear to me however, is that Joel is in direct conversation with these texts and is writing in a First Temple - Later Prophets context. The most compelling argument I found for the early authorship of Joel is an article published by Victor Avigdor Hurowitz from Ben Gurion University, Israel in 1993 titled: “Joel's Locust Plague in Light of Sargon II's Hymn to Nanaya.” Hurowitz points to striking parallels between Joel and an Akkadian hymn, titled: “Sargon II's Hymn to Nananya” (unearthed in the early 20th century). Sargon II reigned from 721 – 705 BCE and Manasseh took thrown in the year 687 BCE (about twenty years later). The hymn: The evil locust which destroys the crop/grain, the wicked dwarf-locust which dries up the orchards, which cuts off the regular offerings of the gods and goddesses - (Verily) Ellil listens to you, and Tutu is before you - may by your command it be turned into nothing. The parallels: The hymn gives two different names to the locust plague, “erebu” and “zirziru.” This is parallel to the four different types of locust that Joel enumerates twice in the book (1:4, 2:25): What the locust swarm has left the great locusts have eaten; what the great locusts have left the young locusts have eaten; what the young locusts have left other locusts have eaten (1:4). (NIV translation here) (There is some scholarly debate about how to translate the four destructive critters listed in 1:4. Ovid R. Sellers, “Stages of Locust in Joel” The American Journal of Semitic Languages and Literatures, Vol. 52, No. 2 (Jan., 1936), pp. 81-85, makes a compelling argument that the four terms are four stages in the development of locust.) “Which destroys the grain” - this is parallel to Joel 1:11: ...the harvest of the field is destroyed. “Which dries up the orchards” - this is parallel to Joel 1:12: The vine is withered [dried up], and the fig-tree languisheth; the pomegranate-tree, the palm-tree also, and the apple-tree, even all the trees of the field, are withered [dried up]; for joy is withered away from the sons of men. The Hebrew word “yabash,” meaning “dried up,” is found five times in the first part of Joel: 1:10, 12, 17, 20 (and three more times in the form of a pun meaning “embarrassed”). “Which cuts off the regular offerings” - this is directly parallel to Joel 1:13: Gird yourselves, and lament, ye priests, wail, ye ministers of the altar; come, lie all night in sackcloth, ye ministers of my God; for the meal-offering and the drink-offering is withholden from the house of your God. The Hebrew word “karat” meaning “cut off” is found in 1:5 and 16. The hymn ends with a prayer for the gods to “command” the locust to disappear. This is parallel to the salvation described in Joel 2:18 – 27. After a careful analysis of locust imagery throughout the rest of Tanakh, Hurowitz sums up: In other words, the common images shared by Joel and other descriptions of locust plagues (eating, huge numbers, extended duration) are not found in the Nanaya hymn, while the rare motifs shared by the Nanaya hymn and Joel (destroying, desiccating) are not found in other biblical or Akkadian accounts. The correlation is thus unique. Joel, more than other prophets, loved to make allusions to other texts. We know that he used this technique extensively in alluding to other Biblical passages and now we see that he also alluded to contemporaneous extra-biblical texts of his time. (How the Israelites had access to this text is actually a bit mysterious, and it's possible that the people's awareness of this hymn only was indirect and second-hand.) Why is Menasseh missing? Assuming early authorship, the absence of king Menasseh in the book of Joel is a fundamental and important issue. “Why is Menasseh missing from Joel,” is parallel to the question: why would Joel write a book that's so difficult to date? A careful study of all the Later Prophets (Isaiah, Jeremiah, Ezekiel and the twelve minor prophets) reveals a consistent historical trend: good kings get more prophets and prophecies than bad kings. For example, the vast majority of Jeremiah's prophecies are directed at Josiah who is described as a righteous king and the vast majority of Isaiah's prophecies are directed at Hezekiah who is described as a righteous king. Mediocre kings like Achaz get some prophecies. Evil kings like those in the Northern kingdom of Israel get little to none. According to the book of Kings, Menasseh was one of the worst kings in all of Israel's history: And he did that which was evil in the sight of the LORD, after the abominations of the nations, whom the LORD cast out before the children of Israel. For he built again the high places which Hezekiah his father had destroyed; and he reared up altars for Baal, and made an Asherah, as did Ahab king of Israel, and worshiped all the host of heaven, and served them. And he built altars in the house of the LORD, whereof the LORD said: 'In Jerusalem will I put My name.' And he built altars for all the host of heaven in the two courts of the house of the LORD (2-5). The only explicit prophecy that mentions king Menasseh in all of Tanakh is an impersonal statement of doom found in the book of Jeremiah: And I will cause them to be a horror among all the kingdoms of the earth, because of Manasseh the son of Hezekiah king of Judah, for that which he did in Jerusalem (15:4). (...and possibly one other source which is similar but escapes my memory at the moment.) So...why do only the good kings get active prophets? Why does Joel act like Menasseh doesn't exist? Here are some possibilities: Wayward kings (and the wayward societies that they reflect) won't listen to a prophet anyway, so most regular types of prophecy is that society would be pointless. The capacity for prophecy is a reflection of the health of a society. Prophecy cannot exist in a context where the people have no relationship with God. The most poignant and disrespectful thing a prophet can do to a wayward king is to completely ignore his existence. IMHO: Assuming that Joel is addressing himself to a nation steeped in idolatry, rebounding from a terrible military defeat at the hands of Assyria and sandwiched between two of the most righteous kings Israel ever had, the book's themes of repentance, war, calamity and redemption become uniquely interesting and important.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/775', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/76/']}
jdg_377361
stackexchange
llm_judgeable_groundtruth_similarity
25116635
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 implementing typeahead using AngularUI-Bootstrap. I need to show the results grouped based on some values coming from the database. Here's a sample scenario There are some users in the database, each user has a "Department". One user name can be available in multiple departments. The end-user types in the names to search users from the database and retrieves the list in the typeahead list. Since one user name can belong to multiple departments, the requirement is to show the user names grouped by different departments. Something like this: Then the user can select the desired user name and proceed. As per the Typeahead documentation present here , I don't see any option to cater to my requirement. I have tried the this workaround: Whenever the typeahead array is getting formed, I appended the user department to the array element: $scope.fetchUsers = function(val) { console.log("Entered fetchUsers function"); return $http.get("http://localhost:8080/TestWeb/users", { params : { username : val } }).then(function(res) { console.log("Response:",res); var users = []; angular.forEach(res.data, function(item) { users.push(item.UserName + " - " + item.UserDepartment); }); console.log("users=",users); return users; }); }; This way, at least the end user sees the department. But when I select the record, the selected value is the full content of the array element. Below is sample screenshot to elaborate: HTML Users from local service <pre>Model: {{userList | json}}</pre><input type="text" ng-model="userList" placeholder="Users loaded from local database" typeahead="username for username in fetchUsers($viewValue)" typeahead-loading="loadingUsers" class="form-control"><i ng-show="loadingUsers" class="glyphicon glyphicon-refresh"></i> User types in the string User selects one record I want to avoid the department (in this case, string - Desc 4 ) when user selects a record. Is there any way I can achieve this grouping without any workaround? Or is there any way I can enhance my workaround? Now provide the response and nothing else.
I used to have a similar requirement and here is how I did it that time. Example Plunker: http://plnkr.co/edit/zujdouvB4bz7tFX8HaNu?p=preview The trick is to set the typeahead-template-url to a custom item template: <input type="text" class="form-control" placeholder="Users loaded from local database" ng-model="selectedUser" typeahead="user as user.name for user in getUsers($viewValue)" typeahead-template-url="typeahead-item.html" /> The item template, this represent each item in a dropdown: <div class="typeahead-group-header" ng-if="match.model.firstInGroup">Desc {{match.model.group}}</div><a> <span ng-bind-html="match.label | typeaheadHighlight:query"></span></a> As you can see, there is an ng-if to show a group header if that item has a property firstInGroup set to true. The firstInGroup properties are populated like this using lodashjs: $scope.getUsers = function (search) { var filtered = filterFilter(users, search); var results = _(filtered) .groupBy('group') .map(function (g) { g[0].firstInGroup = true; // the first item in each group return g; }) .flatten() .value(); return results;} Hope this fit to your requirement too.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25116635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/639258/']}
jdg_377362
stackexchange
llm_judgeable_groundtruth_similarity
13806626
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 this syntax var=`myscript.sh` or var=$(myscript.sh) Will capture the result ( stdout ) of myscript.sh into var . I could redirect stderr into stdout if I wanted to capture both. How to save each of them to separate variables? My use case here is if the return code is nonzero I want to echo stderr and suppress otherwise. There may be other ways to do this but this approach seems it will work, if it's actually possible. Now provide the response and nothing else.
There is no way to capture both without temp file. You can capture stderr to variable and pass stdout to user screen (sample from here ): exec 3>&1 # Save the place that stdout (1) points to.output=$(command 2>&1 1>&3) # Run command. stderr is captured.exec 3>&- # Close FD #3.# Or this alternative, which captures stderr, letting stdout through:{ output=$(command 2>&1 1>&3-) ;} 3>&1 But there is no way to capture both stdout and stderr: What you cannot do is capture stdout in one variable, and stderr in another, using only FD redirections. You must use a temporary file (or a named pipe) to achieve that one.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13806626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1339987/']}
jdg_377363
stackexchange
llm_judgeable_groundtruth_similarity
140879
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 am trying to reduce 5 volts high current source to 4 volts with at least 1.5 amperes. I searched the internet, but I could not find 3 pin voltage regulator, 5V(in) 4V(out)voltage regulator. I think voltage divider is an option, but it consumes lots of power, LMZ12002 is an option but it requires at least 9 components. Is there other options? Now provide the response and nothing else.
Consider connecting a diode in series with the load. edit: Depending on the application, this might be enough, but the forward voltage drop of a diode (or two) does vary with the load current and the temperature of the diode(s). Also, some power (1 W per A) is wasted. Depending on the duty cycle, heat sinking for the diode(s) may need to be considered. If you, for example, want to drop the voltage supplied to a DC motor to make it run a little slower, a diode in series is good. edit by Russell McMahon: A 2A rated silicon diode or 2 x 1A diodes in series will typically have 0.6 to 1.0 Volts drop at near rated current. Actual value varies with type - see data sheet. Voltage drop increases with current. Whether this is precise enough depends on application (the O.P. needs to give more information about the application).
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/140879', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/52631/']}
jdg_377364
stackexchange
llm_judgeable_groundtruth_similarity
6481517
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: is this okay to implement payment system on ios apps? I would like to make an app that can browse products on my e-commerce website then let people buy products on my app. I'm asking this question because i've heard it is violating apple's policy. Now provide the response and nothing else.
It apparently depends on the what is being sold. The definitive answer can only be gotten from your lawyer's reading of the Apple agreement, of course, but I can speak from a little experience. Apple themselves say that: if a product is sold in-app, it must use Apple's IAP (which gives Apple their 30% cut), and not be offered for less through other channels. However , there is an extensive list of things that are not eligible for purchase with IAP at all. Chief among these are: physical products ; and services performed outside the application . I have worked on two apps, both free, that are clients for fee-based web services (continuing education classes in one case, an employee scheduling service in the other). Neither used IAP, just linked to a purchasing web page. Both were accepted by Apple without comment. It seems that since the products were (arguably) not eligible for IAP, using an alternative purchase method was permitted. I'm sure it helps that Apple itself does not compete with either of these services. Bear in mind Apple has also rejected apps that are just "wrappers" for web sites and offer no real app functionality; or for any of a long list of sillier reasons. (e.g.: I had one app rejected for using the word "Sample" in the name; but a change to "Free", with identical functionality, made it OK.) So consult a lawyer before taking any risk predicated on the developer agreement. [edited to add:] For dev program members, the relevant legalese is to be found here (login required), "iOS Developer Program License Agreement", attachment 2 (about 2/3 through the document.) A few relevant phrases from the Jun 12 2012 version, emphases mine: You may not use the In-App Purchase API to offer goods or services to be used outside of Your Application . You may not enable end-users to purchase Currency of any kind through the In-App Purchase API, including but not limited to any Currency for exchange, gifting, redemption, transfer, trading or use in purchasing or obtaining anything within or outside of Your Application. Rentals of content, services or functionality through the In-App Purchase API are not allowed You may not use the In-App Purchase API to send any software updates to Your Application or otherwise add any additional executable code to Your Application. (not that this is even physically possible. --R.) [except] as permitted under Section 3.3.23 (In-App Purchase API), an Application may not provide, unlock or enable additional features or functionality through distribution mechanisms other than the App Store or VPP/B2B Program Site. By my reading, this means that anything besides unlocking functionality within an app is fair game for an alternative purchase mechanism, and forbidden categories of items require such. But ask a real lawyer. [edited to add, much later:] After a fun update fiasco with one of the above mentioned apps, these anecdotes are not entirely true anymore. Apple booted one of them because of a tenuous link to a signup web page for some paid services. So be careful, and be prepared for Apple to yank things arbitrarily if you wander anywhere close to the line.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6481517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100240/']}
jdg_377365
stackexchange
llm_judgeable_groundtruth_similarity
25736
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: Main question: I am writing a script to perform a backup. I make a list of files in the following way: LISTOFFILES=$(find ~ \( -name '*.[pP][dD][fF]' -o -name '*.[oO][dD][tT]' \)) The variable LISTOFFILES stores more or less something like: /home/user/file1.pdf /home/user/file2.odt /home/user/Python Tutorial.pdf My next step is: tar cvf backup.tar $LISTOFFILES Bash response is: /home/user/file1.pdf/home/user/file2.odt/home/user/Python: Cannot stat: No such file or directorytar: Tutorial.pdf I understand that Bash assumes that Python and Tutorial.pdf are different files. Is there a way to do a list of files with backslash included with find or should I change to use ls with pipes? I'd like read your tips and advices. My other question: The answer to this question is not really important, but one tip could help How to list files only with the file name without the file path? For example: file instead of /home/user/file . I've trying with find command with prune and path options, but I have not succeeded. Now provide the response and nothing else.
As for your main question, you'll need to take a different approach. Your method is putting all of the files into a single string in $LISTOFFILES. Then when you go to access it, you're not using quotes which causes it to split on spaces and give you the result you're seeing. The simplest way to get the result you want is the following: find ~ \( -name '*.[pP][dD][fF]' -o -name '*.[oO][dD][tT]' \) -print0 | xargs -0 tar cvf backup.tar What we did there was to run find, and separate each result with a NULL char (the -print0 part). The output of find is then piped to xargs which reads in a list of files separated by the NULL char (the -0 argument tells xargs to do this), and pass that list of files as arguments to 'tar'. For your second question:If you want to get just filenames only from the find command, use printf find /path/to -printf '%f\n'file.txt If you mean in general, not just with find, it's easiest to use basename . # basename /path/to/file.txtfile.txt basename is designed to do exactly that, and nothing else.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/25736', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/12287/']}
jdg_377366
stackexchange
llm_judgeable_groundtruth_similarity
1102692
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 c++ , I want to do alpha blend using the following code. #define CLAMPTOBYTE(color) \ if ((color) & (~255)) { \ color = (BYTE)((-(color)) >> 31); \ } else { \ color = (BYTE)(color); \ }#define GET_BYTE(accessPixel, x, y, scanline, bpp) \ ((BYTE*)((accessPixel) + (y) * (scanline) + (x) * (bpp))) for (int y = top ; y < bottom; ++y) { BYTE* resultByte = GET_BYTE(resultBits, left, y, stride, bytepp); BYTE* srcByte = GET_BYTE(srcBits, left, y, stride, bytepp); BYTE* srcByteTop = GET_BYTE(srcBitsTop, left, y, stride, bytepp); BYTE* maskCurrent = GET_GREY(maskSrc, left, y, width); int alpha = 0; int red = 0; int green = 0; int blue = 0; for (int x = left; x < right; ++x) { alpha = *maskCurrent; red = (srcByteTop[R] * alpha + srcByte[R] * (255 - alpha)) / 255; green = (srcByteTop[G] * alpha + srcByte[G] * (255 - alpha)) / 255; blue = (srcByteTop[B] * alpha + srcByte[B] * (255 - alpha)) / 255; CLAMPTOBYTE(red); CLAMPTOBYTE(green); CLAMPTOBYTE(blue); resultByte[R] = red; resultByte[G] = green; resultByte[B] = blue; srcByte += bytepp; srcByteTop += bytepp; resultByte += bytepp; ++maskCurrent; } } however I find it is still slow, it takes about 40 - 60 ms when compose two 600 * 600 image.Is there any method to improve the speed to less then 16ms? Can any body help me to speed this code? Many thanks! Now provide the response and nothing else.
Use SSE - start around page 131. The basic workflow Load 4 pixels from src (16 1 byte numbers) RGBA RGBA RGBA RGBA (streaming load) Load 4 more which you want to blend with srcbytetop RGBx RGBx RGBx RGBx Do some swizzling so that the A term in 1 fills every slot I.e xxxA xxxB xxxC xxxD -> AAAA BBBB CCCC DDDD In my solution below I opted instead to re-use your existing "maskcurrent" array but having alpha integrated into the "A" field of 1 will require less loads from memory and thus be faster. Swizzling in this case would probably be: And with mask to select A, B, C, D. Shift right 8, Or with origional, shift right 16, or again. Add the above to a vector that is all -255 in every slot Multiply 1 * 4 (source with 255-alpha) and 2 * 3 (result with alpha). You should be able to use the "multiply and discard bottom 8 bits" SSE2 instruction for this. add those two (4 and 5) together Store those somewhere else (if possible) or on top of your destination (if you must) Here is a starting point for you: //Define your image with __declspec(align(16)) i.e char __declspec(align(16)) image[640*480] // so the first byte is aligned correctly for SIMD. // Stride must be a multiple of 16. for (int y = top ; y < bottom; ++y) { BYTE* resultByte = GET_BYTE(resultBits, left, y, stride, bytepp); BYTE* srcByte = GET_BYTE(srcBits, left, y, stride, bytepp); BYTE* srcByteTop = GET_BYTE(srcBitsTop, left, y, stride, bytepp); BYTE* maskCurrent = GET_GREY(maskSrc, left, y, width); for (int x = left; x < right; x += 4) { //If you can't align, use _mm_loadu_si128() // Step 1 __mm128i src = _mm_load_si128(reinterpret_cast<__mm128i*>(srcByte)) // Step 2 __mm128i srcTop = _mm_load_si128(reinterpret_cast<__mm128i*>(srcByteTop)) // Step 3 // Fill the 4 positions for the first pixel with maskCurrent[0], etc // Could do better with shifts and so on, but this is clear __mm128i mask = _mm_set_epi8(maskCurrent[0],maskCurrent[0],maskCurrent[0],maskCurrent[0], maskCurrent[1],maskCurrent[1],maskCurrent[1],maskCurrent[1], maskCurrent[2],maskCurrent[2],maskCurrent[2],maskCurrent[2], maskCurrent[3],maskCurrent[3],maskCurrent[3],maskCurrent[3], ) // step 4 __mm128i maskInv = _mm_subs_epu8(_mm_set1_epu8(255), mask) //Todo : Multiply, with saturate - find correct instructions for 4..6 //note you can use Multiply and add _mm_madd_epi16 alpha = *maskCurrent; red = (srcByteTop[R] * alpha + srcByte[R] * (255 - alpha)) / 255; green = (srcByteTop[G] * alpha + srcByte[G] * (255 - alpha)) / 255; blue = (srcByteTop[B] * alpha + srcByte[B] * (255 - alpha)) / 255; CLAMPTOBYTE(red); CLAMPTOBYTE(green); CLAMPTOBYTE(blue); resultByte[R] = red; resultByte[G] = green; resultByte[B] = blue; //---- // Step 7 - store result. //Store aligned if output is aligned on 16 byte boundrary _mm_store_si128(reinterpret_cast<__mm128i*>(resultByte), result) //Slow version if you can't guarantee alignment //_mm_storeu_si128(reinterpret_cast<__mm128i*>(resultByte), result) //Move pointers forward 4 places srcByte += bytepp * 4; srcByteTop += bytepp * 4; resultByte += bytepp * 4; maskCurrent += 4; } } To find out which AMD processors will run this code (currently it is using SSE2 instructions) see Wikipedia's List of AMD Turion microprocessors . You could also look at other lists of processors on Wikipedia but my research shows that AMD cpus from around 4 years ago all support at least SSE2. You should expect a good SSE2 implimentation to run around 8-16 times faster than your current code. That is because we eliminate branches in the loop, process 4 pixels (or 12 channels) at once and improve cache performance by using streaming instructions. As an alternative to SSE, you could probably make your existing code run much faster by eliminating the if checks you are using for saturation. Beyond that I would need to run a profiler on your workload. Of course, the best solution is to use hardware support (i.e code your problem up in DirectX) and have it done on the video card.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1102692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/25749/']}
jdg_377367
stackexchange
llm_judgeable_groundtruth_similarity
387899
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: When wiring resistors to a battery, it generates heat and in the worst case, sets on fire but when it is used to limit current, for example in series to an LED, do they still generate heat ? Now provide the response and nothing else.
Yes. This is really basic physics. Voltage times current is power, which a resistor turns into heat. From the above and Ohm's law, you can find the power dissipated by a resistor from its resistance and either the voltage across it or the current thru it. In common units: W = V A W = V 2 / Ω W = A 2 Ω where W is power in Watts, V is EMF in Volts, A is current in Amperes, and Ω is resitance in Ohms.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/387899', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/194168/']}
jdg_377368
stackexchange
llm_judgeable_groundtruth_similarity
8337730
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an application where I need to adjust view position according to current focused subview (it's a list with focusable items, current focused item must be in the center of the screen - used for a tv application controlled from tv remote). Position must be adjusted with animation. I got it working with just one problem: if the user changes focus before the animation is complete (quickly taps "up" button twice) next animation starts with "jump" - it starts from the same position as did the first one. So what I try to do is I cancel previous animation and start another, but then new animation starts from the point where first animation was started, so user can see a very obvious jumps in the animation, which look really awful. Here's the code: @Overridepublic void requestChildFocus(final View child, final View focused) { super.requestChildFocus(child, focused); //this test code included for explanation Rect r = new Rect(); child.getDrawingRect(r); //this will return view's position ignoring animation state Rect r2 = new Rect(); child.getGlobalVisibleRect(r2); //as will this one too Log.d("Top: " + child.getTop() + "; Drawing rect: " + r.toString() + "; global visible rect: " + r2.toString()); //all of this methods will ignore changes that were made //by animation object - they'll return numbers from LayoutParam //calculate current position inside view and position to move to //cursorOffset - is the "center" of the screen final int currentPosition = child.getTop(); final int requaredPosition = cursorOffset - focused.getTop(); //cancel current running animation - layout params will not change //if i do change layout params when cancelling animation, it looks even worse //because of jumping back list jumps forward if (currentAnimation != null) { Animation animation = currentAnimation; currentAnimation = null; animation.cancel(); } //just a regular translate animation TranslateAnimation animation = new TranslateAnimation(0, 0, 0, requaredPosition - currentPosition); animation.setDuration(300); animation.setFillEnabled(true); animation.setFillBefore(true); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { currentAnimation = animation; } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { if (animation == currentAnimation) { //change layout params if animation finished running (wasn't cancelled) RelativeLayout.LayoutParams params = (LayoutParams) child.getLayoutParams(); params.setMargins(0, requaredPosition, 0, 0); child.setLayoutParams(params); } } }); child.startAnimation(animation);} So must question is: how can I start translate animation from the point where previous translate animation left on (assuming that it was cancelled)? Or, in a simplier words, how can I determine current visible rect of a view? Now provide the response and nothing else.
Apparently you can't get current view position, but you can get current animation state. So you can get current y offset by doing this: Transformation transformation = new Transformation();float[] matrix = new float[9];currentAnimation.getTransformation(AnimationUtils.currentAnimationTimeMillis(), transformation);transformation.getMatrix().getValues(matrix);float y = matrix[Matrix.MTRANS_Y]; And that's how I was able to cancel one animation and start another one exactly from the point where I left of. If anyone cares, heres the complete code: private Animation currentAnimation;private float[] matrix = new float[9];private Transformation transformation = new Transformation();@Overridepublic void requestChildFocus(final View child, final View focused) { super.requestChildFocus(child, focused); final int currentPosition; if (currentAnimation != null) { currentAnimation.getTransformation(AnimationUtils.currentAnimationTimeMillis(), transformation); transformation.getMatrix().getValues(matrix); float y = matrix[Matrix.MTRANS_Y]; RelativeLayout.LayoutParams params = (LayoutParams) child.getLayoutParams(); params.topMargin += y; //child.getTop() will return wrong position until layout actually happens, //so I use params.topMargin as a current position in case I need to cancel currentPosition = params.topMargin; child.requestLayout(); currentAnimation.setAnimationListener(null); currentAnimation.cancel(); currentAnimation = null; } else { currentPosition = child.getTop(); } final int requaredPosition = cursorOffset - focused.getTop(); TranslateAnimation animation = new TranslateAnimation(0, 0, 0, requaredPosition - currentPosition); animation.setDuration(300); animation.setFillEnabled(true); animation.setFillBefore(true); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { currentAnimation = animation; } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { if (animation == currentAnimation) { RelativeLayout.LayoutParams params = (LayoutParams) child.getLayoutParams(); params.setMargins(0, requaredPosition, 0, 0); child.requestLayout(); } currentAnimation = null; } }); child.startAnimation(animation);} Hope somebody finds this useful.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8337730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/333278/']}
jdg_377369
stackexchange
llm_judgeable_groundtruth_similarity
290646
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: It's a pretty established convention that database table names, in SQL at least, should be singular. SELECT * FROM user; See this question and discussion . It's also a pretty established convention that RESTful API resource names should be plural. GET /users/123 and POST /users See this one . In the simplest database-backed API, the name of the resource in the URL would be the table, and the data elements in the URL and request/response bodies would map directly to the columns in the DB. Conceptually, I don't see a difference between operating on the data through this theoretical API versus operating on it directly through SQL. And because of that, the difference in naming conventions between user and users doesn't make sense to me. How can the difference in pluralization be justified when, conceptually, the REST API and the SQL are doing the same thing? Now provide the response and nothing else.
The REST spec (whatever level you want to go with) wasn't designed as database access. It is trying to bring standardization to API access. The SQL conventions mentioned (whether you want to use them or not) were not designed with API access in mind. They are for writing SQL queries. So the issue to unpack here is the conceptual understanding that an API maps directly to the database. We can find this described as an anti-pattern at least as far back to 2009 . The principal reason this is bad? The code describing "how does this operation affect my data?" becomes client code . This has some pretty terrible effects on the API. (not an exhaustive list) It makes integrating with the API difficult I imagine the steps to create a new user documented as something like this: POST /users { .. } POST /usersettings { .. } with some default values POST /confirmemails { .. } But how do you handle a failure of step #2? How many times is this same handling logic copy-pasta'd to other clients of your API? These data operations are often easier to sequence on the server side, while being initiated from the client as a single operation. E.g. POST /newusersetup . DBAs may recognize this as a stored procedure, but the API operation may have effects beyond just the database. Securing the API becomes a black hole of despair Let's say you need to merge two user accounts. GET /users/1 PUT /users/2 { .. } DELETE /users/1 How are you going to setup a user permission to allow the merge feature while not allowing user deletion? Is deleting a user even fairly represented by DELETE /users/1 when /usersettings also exists? API operations should be looked at as higher-(than-database)-level operations which may cause multiple changes in the system. Maintenance becomes harder ... because your clients depend on your database structure. Based on my experience with this scenario: You cannot rename or remove existing tables/columns. Even when they are named incorrectly for their function or are no longer used. Clients will break. New features can't change existing data structures, so its data and functionality is often artificially separated even when it holistically belongs with an existing feature. The code base gradually becomes harder to understand due to fragmentation, confusing names, and left-over baggage which can't be removed safely. All but trivial changes become increasingly risky and time-consuming. The system stagnates and is eventually replaced. Don't expose your database structure directly to clients... especially clients you do not have developmental control over. Use an API to narrow the client down to just valid operations. So if you are using an API as just an interface straight into a database, pluralization is the least of your worries. For other than a throw-away experiment, I would suggest spending some time determining the higher-level operations the API should represent. And when you look at it that way, there's no conflict between pluralized API entity names and singular SQL entity names. They are there for different reasons.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/290646', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/188412/']}
jdg_377370
stackexchange
llm_judgeable_groundtruth_similarity
23975835
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to ruby on rails and having trouble getting this work. Basically I have a user registration page which has a password confirmation. In the User class I have the following validation: validates :password, confirmation: true And in the controller I have def create vals = params[:user] if(User.exists(vals[:username])) flash[:warning] = "#{vals[:username]} already exists! Please try a new one. " else vals[:create_date] = DateTime.current user = User.create(vals, :without_protection => :true) if user==false or user==nil or user==vals flash[:warning] = "#{vals[:username]} has not been registered successfully. " else flash[:notice] = "#{vals[:username]} has been registered. " end end redirect_to users_pathend The problem is that when the password does match the confirmation, I am still getting the notice message showing that the registration is successful. As you can see I have tried several return values for create but none of them seems to succeed. I am pretty sure that the validation is working because I cannot see the user that I just created if password does not match with confirmation. In addition, when I use create! , I can see the website crashes with the validation error. Can anyone help telling me what create should return when the record is not validated? Thanks. Now provide the response and nothing else.
The answer to your question is, User.create returns a User instance if it succeeds or fails. If it fails because of validations, the instance will be invalid and will have errors: user.valid? # <= returns falseuser.errors.count # <= will be > 0user.errors.blank? # <= will be false So your code would change from this: if user==false or user==nil or user==vals to this: if !user.valid? You can also use this pattern: user.attributes = valsif user.save ... save succeeded ...else ... save failed ...end The save method returns a boolean true or false since you are calling it on an existing instance. But lets get you on the right track in a few other ways: First: you have this: if User.exists(vals[:username]) (I'm assuming exits is a method you put on your User model because that's not a Rails thing). Instead of doing that check in your controller, you can just use another validation on the model: class User < ActiveRecord::Base ... validates :username, unique: true ...end Now when you try to create the user, it will fail validation if you already have one with that name. Second: You have this: vals[:create_date] = DateTime.current This is unnecessary. If you add a column to your model called created_at it will hold the creation date automatically (managed by ActiveRecord). You can add this, and its partner updated_at to your model in your migration like this: create_table :users do |t| ... t.timestamps # <= tells rails to add created_at and updated_atend Or, since you already have a users table: add_column :users, :created_at, :datetimeadd_column :users, :updated_at, :datetime Now you will always have the date/time of creation and last update on your user model with no need for additional code. Third: You have this: user = User.create(vals, :without_protection => :true) Don't do this. Instead, change this: vals = params[:user] To this: vals = params.require(:user).permit(:username, :password, :password_confirmation) And then keep protection on: user = User.create(vals) You can add any additional columns you want to bring from your form to the permit() call. This is very important because it is hard to fix this kind of thing later. "If once you go down the dark path, forever will it dominate your destiny." Fourth: You should not redirect to the user_path if the save failed, because there will be no user model to show. Instead you should re-render your new form. You also don't need flash messages for the errors. If the new form renders, it can check @user.errors and report error messages accordingly. See the ActiveRecord error object documentation . Finally: You mention that you your validation fails even when your password is properly confirmed. I can't say for sure without seeing your form code, but make sure your password field is called password and the confirmation field is called password_confirmation . Rails looks for this *_confirmation field value specifically when validating for confirmation. If that doesn't do it, post your form code and I'll revise.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23975835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2103884/']}
jdg_377371
stackexchange
llm_judgeable_groundtruth_similarity
4753629
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 create a Vector class that is generic for all numeric types.my original attempt was to write a class for all Types like this: class Vector3f(val x:Float, val y:Float, val z:Float) since scala supports the specialised annotation I could use this to generate me these classes for all numeric types class Vector3[A <: What?](val x:A,val y:A, val z:A) but everything I found as a super type for numbers was AnyVal, but AnyVal does not support + - * /. So what is the right way to do this, but without sacrificing the performance of unboxed number types? Now provide the response and nothing else.
You can't. Not right now. Maybe when, and if, Numeric gets specialized. Say you get the simplest parameterized class possible: class Vector3[@specialized T](val x: T, val y: T, val z: T)(implicit num: Numeric[T]) { def +(other: Vector3[T]) = new Vector3(num.plus(x, other.x), num.plus(y, other.y), num.plus(z, other.z))} The method + will compile into something roughly like this: override <specialized> def +$mcD$sp(other: Vector3): Vector3 = new Vector3$mcD$sp( scala.Double.unbox( Vector3$mcD$sp.this.Vector3$$num.plus( scala.Double.box(Vector3$mcD$sp.this.x()), scala.Double.box(other.x$mcD$sp()))), scala.Double.unbox( Vector3$mcD$sp.this.Vector3$$num.plus( scala.Double.box(Vector3$mcD$sp.this.y()), scala.Double.box(other.y$mcD$sp()))), scala.Double.unbox( Vector3$mcD$sp.this.Vector3$$num.plus( scala.Double.box(Vector3$mcD$sp.this.z()), scala.Double.box(other.z$mcD$sp()))), Vector3$mcD$sp.this.Vector3$$num); That's scalac -optimize -Xprint:jvm output. Now there are even subclasses for each specialized type, so that you can initialize a Vector3 without boxing, but as long as Numeric is not specialized, you can't go further. Well... you can write your own Numeric and specialize that, but, at that point, I'm not sure what you are gaining by making the class parameterized in first place.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4753629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/479905/']}
jdg_377372
stackexchange
llm_judgeable_groundtruth_similarity
13987300
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my HTML page, I had a textbox for user to input keyword for searching. When they click the search button, the JavaScript function will generate a URL and run in new window. The JavaScript function work properly when the user clicks the search button by mouse, but there is no response when the user presses the ENTER key. function searching(){ var keywordsStr = document.getElementById('keywords').value; var cmd ="http://XXX/advancedsearch_result.asp?language=ENG&+"+ encodeURI(keywordsStr) + "&x=11&y=4"; window.location = cmd;} <form name="form1" method="get"> <input name="keywords" type="text" id="keywords" size="50" > <input type="submit" name="btn_search" id="btn_search" value="Search" onClick="javascript:searching(); return false;" onKeyPress="javascript:searching(); return false;"> <input type="reset" name="btn_reset" id="btn_reset" value="Reset"></form> Now provide the response and nothing else.
Form approach As scoota269 says, you should use onSubmit instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form) <form action="#" onsubmit="handle"> <input type="text" name="txt" /></form><script> function handle(e){ e.preventDefault(); // Otherwise the form will be submitted alert("FORM WAS SUBMITTED"); }</script> Textbox approach If you want to have an event on the input-field then you need to make sure your handle() will return false, otherwise the form will get submitted. <form action="#"> <input type="text" name="txt" onkeypress="handle(event)" /></form><script> function handle(e){ if(e.keyCode === 13){ e.preventDefault(); // Ensure it is only this code that runs alert("Enter was pressed was presses"); } }</script>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13987300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/788679/']}
jdg_377373
stackexchange
llm_judgeable_groundtruth_similarity
41526504
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 will define value. But this value may be in value of key of hash. I will use rescue for define value is nil if this keys is not exist.for example foo = bar[:a][:b][:c] rescue nil But in practice tell me bad style because me using rescue in its modifier form. I will change logic to use check three condition. foo = bar[:a][:b][:c] if bar.key?(:a) && bar[:a].key?(:b) && bar[:a][:b].key?(:c) I really would like to know why should we avoid using rescue in its modifier form? Now provide the response and nothing else.
Why should we avoid using rescue in its modifier form in rails? Firstly, because it hides all errors, including the ones you expect and the ones you don't, and a blanket rescue doesn't make it clear to future readers of your code which errors were expected or unexpected. This might not be a problem now , with a simple foo[:a][:b][:c] , but at any given point in time somebody might modify that statement to read foo[:a][:b][some_method] and suddenly any errors that should bubble out of some_method are also swallowed. Secondly, there is usually a better less all-encompassing solution that is more explicitly designed to handle only the error you intend to ignore: A missing index or a nil return value. In your case, the alternative is not the massive if && && && you're suggesting. For a hash, you can use either dig , which has all the benefits of rescue without swallowing every type of exception that could be raised: foo = bar.dig(:a, :b, :c) Similarly, for chained method invocations, you can use try (in Rails) or the safe navigation operator (in Ruby 2.3): foo = bar.try(:a).try(:b).try(:c)# orfoo = bar&.a&.b&.c
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41526504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4268217/']}
jdg_377374
stackexchange
llm_judgeable_groundtruth_similarity
59518015
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: GitHub repo if needed, Maven web project (pom.xml), SQL script under resources directory. I'm aware this is my fault, the problem is I haven't been able to fix it in the entire day, its likely something simple and over my head, also please ignore the relations regarding the table names and columns, it's a sample project to show the problem. Expected: Store the new child along its parent relation (the child has a column for it), without storing the parent again. Error: CascadeType.ALL causes the parent to duplicate, but attempting to remove it to use the other types throws: java.sql.SQLIntegrityConstraintViolationException: Column 'user_id' cannot be null Column 'user_id' is the name of the column in the child table that stores the parent relation. I will skip some annotations among other things so this doesn't become a wall of code User entity private Long id;private String name;@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH})private List<Username> usernameList = new ArrayList<>(); Username entity private Long id;private String username;@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)@JoinColumn(name = "user_id")private User user; Again, using anything but CascadeType.All throws an error for some reason UsernameDAO ( this is the method being used to store the child, username, which duplicates the parent, user ) Session session = factory.getCurrentSession();session.save(username); UsernameService usernameDAO.save(username); Now provide the response and nothing else.
I have received below errors when running Spring Boot Project for AWS SNS i.InstanceMetadataServiceResourceFetcher : Fail to retrieve tokencom.amazonaws.util.EC2MetadataUtils : Unable to retrieve the requested metadata (/latest/dynamic/instance-identity/document). Failed to connect to service endpoint:Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instanceError creating bean with name 'org.springframework.cloud.aws.core.env.ResourceIdResolver.BEAN_NAME': Invocation of init method failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'stackResourceRegistryFactoryBean' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Unsatisfied dependency expressed through method 'stackResourceRegistryFactoryBean' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'amazonCloudFormation' defined in class path resource [org/springframework/cloud/aws/autoconfigure/context/ContextStackAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: There is no EC2 meta data available, because the application is not running in the EC2 environment. Region detection is only possible if the application is running on a EC2 instance Resolution applied:Add below code snippet to SpringBootApplication & Click on Run Button in the IDE @SpringBootApplication( exclude = { org.springframework.cloud.aws.autoconfigure.context.ContextInstanceDataAutoConfiguration.class, org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration.class, org.springframework.cloud.aws.autoconfigure.context.ContextRegionProviderAutoConfiguration.class })
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59518015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10976657/']}
jdg_377375
stackexchange
llm_judgeable_groundtruth_similarity
10939602
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my rails project I'm getting the following error when I view /subscription/new : NoMethodError in Subscriptions#newShowing /redacted/app/views/subscriptions/new.html.erb where line #4 raised:undefined method `subscriptions_path' for #<#<Class:0x007fd02c8bbb28>:0x007fd0308f7a48>Extracted source (around line #4):1: <div class="grid_6">2: <h1>New Subscription</h1>3: <p>4: <%= form_for @subscription, :html => { class: 'form_dark' } do |f| %>5: <% if @subscription.errors.any? %>6: <div class="error_messages">7: <h1><%= pluralize(@subscription.errors.count, "error") %> prohibited this subscription from being saved:</h1> My routes file contains resource :subscription for this. Additional code information: User model: class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :password_confirmation, :remember_me has_one :subscriptionend Subscription model: class Subscription < ActiveRecord::Base attr_accessible :status, :stripe_token, :user_id, :last_charge, :stripe_card_token belongs_to :user has_many :payments, :dependent => :destroy belongs_to :plan attr_accessor :stripe_card_tokenend My SubscriptionsController new method: def new @subscription = User.find(current_user.id).build_subscription end Any help is appreciated, thanks! Now provide the response and nothing else.
I believe that when you pass form_for an object like @subscription (which has class Subscription), it expects the url subscriptions_path by default. But since you have declared subscription as a singlular resource, the url subscription_path is defined instead. You should explicitly specify this route <%= form_for @subscription, url: subscription_path, :html => { class: 'form_dark' } do |f| %>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10939602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1272323/']}
jdg_377376
stackexchange
llm_judgeable_groundtruth_similarity
3662899
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: OWASP says: "C library functions such as strcpy (), strcat (), sprintf () and vsprintf () operate on null terminated strings and perform no bounds checking." sprintf writes formatted data to string int sprintf ( char * str, const char * format, ... ); Example: sprintf(str, "%s", message); // assume declaration and // initialization of variables If I understand OWASP's comment, then the dangers of using sprintf are that 1) if message 's length > str 's length, there's a buffer overflow and 2) if message does not null-terminate with \0 , then message could get copied into str beyond the memory address of message , causing a buffer overflow Please confirm/deny. Thanks Now provide the response and nothing else.
You're correct on both problems, though they're really both the same problem (which is accessing data beyond the boundaries of an array). A solution to your first problem is to instead use std::snprintf , which accepts a buffer size as an argument. A solution to your second problem is to give a maximum length argument to snprintf . For example: char buffer[128];std::snprintf(buffer, sizeof(buffer), "This is a %.4s\n", "testGARBAGE DATA");// std::strcmp(buffer, "This is a test\n") == 0 If you want to store the entire string (e.g. in the case sizeof(buffer) is too small), run snprintf twice: int length = std::snprintf(nullptr, 0, "This is a %.4s\n", "testGARBAGE DATA");++length; // +1 for null terminatorchar *buffer = new char[length];std::snprintf(buffer, length, "This is a %.4s\n", "testGARBAGE DATA"); (You can probably fit this into a function using va or variadic templates.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3662899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409976/']}
jdg_377377
stackexchange
llm_judgeable_groundtruth_similarity
281831
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 porting an MFC application to .NET WinForms. In the MFC application, you can right click on a menu or on a context menu item and we show another context menu with diagnostic and configuration items. I am trying to port this functionality to .NET, but I am having trouble. I have been able to capture the right click, disable the click of the underlying menu and pop up a context menu at the right location, but the original menu disappears as soon as it loses focus. In MFC, we show the new context menu by calling TrackPopupMenuEx with the TPM_RECURSE flag. ContextMenu and the newer ContextMenuStrip classes in .NET only have a Show method. Does anyone know how to do this in .NET? EDIT I have tried using TrackPopupMenuEx through a p/invoke, but that limits you to using a ContextMenu instead of a ContextMenuStrip which looks out of place in our application. It also still does not work correctly. It doesn't work with the new MenuStrip and ContextMenuStrip . I have also tried subclassing ToolStripMenuItem to see if I can add a context menu to it. That is working for MenuStrip , but ContextMenuStrip still allows the right click events to pass through as clicks. Now provide the response and nothing else.
Edit, due to a comment: In: protected override void OnClick(EventArgs e){ if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right) { base.OnClick(e); }} this part MouseButtons != MouseButtons.Right should and does compile as it is a call to Control.MouseButtons. Since the Form inherits Control class, it is sufficient to call MouseButtons property directly. Hope this helps: public partial class Form1 : Form{ class CustomToolStripMenuItem : ToolStripMenuItem { private ContextMenuStrip secondaryContextMenu; public ContextMenuStrip SecondaryContextMenu { get { return secondaryContextMenu; } set { secondaryContextMenu = value; } } public CustomToolStripMenuItem(string text) : base(text) { } protected override void Dispose(bool disposing) { if (disposing) { if (secondaryContextMenu != null) { secondaryContextMenu.Dispose(); secondaryContextMenu = null; } } base.Dispose(disposing); } protected override void OnClick(EventArgs e) { if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right) { base.OnClick(e); } } } class CustomContextMenuStrip : ContextMenuStrip { private bool secondaryContextMenuActive = false; private ContextMenuStrip lastShownSecondaryContextMenu = null; protected override void Dispose(bool disposing) { if (disposing) { if (lastShownSecondaryContextMenu != null) { lastShownSecondaryContextMenu.Close(); lastShownSecondaryContextMenu = null; } } base.Dispose(disposing); } protected override void OnControlAdded(ControlEventArgs e) { e.Control.MouseClick += new MouseEventHandler(Control_MouseClick); base.OnControlAdded(e); } protected override void OnControlRemoved(ControlEventArgs e) { e.Control.MouseClick -= new MouseEventHandler(Control_MouseClick); base.OnControlRemoved(e); } private void Control_MouseClick(object sender, MouseEventArgs e) { ShowSecondaryContextMenu(e); } protected override void OnMouseClick(MouseEventArgs e) { ShowSecondaryContextMenu(e); base.OnMouseClick(e); } private bool ShowSecondaryContextMenu(MouseEventArgs e) { CustomToolStripMenuItem ctsm = this.GetItemAt(e.Location) as CustomToolStripMenuItem; if (ctsm == null || ctsm.SecondaryContextMenu == null || e.Button != MouseButtons.Right) { return false; } lastShownSecondaryContextMenu = ctsm.SecondaryContextMenu; secondaryContextMenuActive = true; ctsm.SecondaryContextMenu.Closed += new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed); ctsm.SecondaryContextMenu.Show(Cursor.Position); return true; } void SecondaryContextMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e) { ((ContextMenuStrip)sender).Closed -= new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed); lastShownSecondaryContextMenu = null; secondaryContextMenuActive = false; Focus(); } protected override void OnClosing(ToolStripDropDownClosingEventArgs e) { if (secondaryContextMenuActive) { e.Cancel = true; } base.OnClosing(e); } } public Form1() { InitializeComponent(); CustomToolStripMenuItem itemPrimary1 = new CustomToolStripMenuItem("item primary 1"); itemPrimary1.SecondaryContextMenu = new ContextMenuStrip(); itemPrimary1.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { new ToolStripMenuItem("item primary 1.1"), new ToolStripMenuItem("item primary 1.2"), }); CustomToolStripMenuItem itemPrimary2 = new CustomToolStripMenuItem("item primary 2"); itemPrimary2.DropDownItems.Add("item primary 2, sub 1"); itemPrimary2.DropDownItems.Add("item primary 2, sub 2"); itemPrimary2.SecondaryContextMenu = new ContextMenuStrip(); itemPrimary2.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { new ToolStripMenuItem("item primary 2.1"), new ToolStripMenuItem("item primary 2.2"), }); CustomContextMenuStrip primaryContextMenu = new CustomContextMenuStrip(); primaryContextMenu.Items.AddRange(new ToolStripItem[]{ itemPrimary1, itemPrimary2 }); this.ContextMenuStrip = primaryContextMenu; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/281831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30827/']}
jdg_377378
stackexchange
llm_judgeable_groundtruth_similarity
734664
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is Hilbert's Nullstellensatz in the sense of the generalization of "fundamental theorem of algebra"? I've seen that in some texts it was referred to as the generalization of the fundamental theorem of algebra in several variables. How exactly does Hilbert's Nullstellensatz relate to the fundamental theorem of algebra? Also could you please provide some examples to show that it is related? Now provide the response and nothing else.
Let's prove that the Nullstellensatz implies the fundamental theorem of algebra in the 1D case. Let $p \in \Bbb C[z]$. The Nullstellensatz says that if we have another polynomial $f \in \Bbb C[z]$, such that $f$ has the same zeroes as some $g \in \langle p \rangle$, then $f^r \in \langle p \rangle$ for some $r \in \Bbb N$. Now assume there exists a polynomial $p \in \Bbb C[z]$ that has no zeroes. Clearly the polynomial $1$ has the same zero set (the empty set!); the Nullstellensatz says that $1 = 1^r \in \langle p \rangle$ for some $r \in \Bbb N$. Since $1 \in \langle p \rangle$, $p$ is constant. Thus by contraposition every nonconstant polynomial in $\Bbb C[z]$ has a root.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/734664', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12796/']}
jdg_377379
stackexchange
llm_judgeable_groundtruth_similarity
216887
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: In my ASP MVC application I decided to add another Business Layer and made the model only to have properties. All other functionality like save to db, get from db is done on this new Business layer. So now the controller will be calling this business layer and model for various operations. Is it a good approach to design like this? I decided not to use model for this purpose because I would need a number of models for different actions. (for eg, one for edit and other for create) Now provide the response and nothing else.
That sounds like an eminently sensible decision to me. MVC is a presentation pattern, therefore business logic and persistence operations have no place in the UI layer of the application. Ideally an MVC model is just the data you are presenting to be rendered by the view. This is not at all necessarily the same as an equivalent domain entity - for instance, the model may need to be tagged with UI validation attributes, may contain values for multiple selection, or may contain data transformed for display such as dates, currency values. or language translations. Because of this, it is sensible to make the M in MVC distinct from your business entities, and map from entities to models in your controller logic. A controller action should not really need to do anything more complicated than make calls to the underlying business logic layer and marshal the data returned into models for render.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/216887', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/101864/']}
jdg_377380
stackexchange
llm_judgeable_groundtruth_similarity
1304124
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: if $U$ and $W$ are subspaces of $\mathbb{R}^7$ and $\dim U = \dim W =4$ then in $U \cap W$ there's a vector different then $0$. I think that it's true, am I correct? Now provide the response and nothing else.
Yes. If their intersection was $\{0\}$, then their sum $U+W$ would be a direct sum, so $\dim (U+W)$ would be equal to $8$, which is impossible, since it is a subspace of $\mathbb{R}^7$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1304124', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/151615/']}
jdg_377381
stackexchange
llm_judgeable_groundtruth_similarity
21585914
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried this code - UPDATE TableSET Name = RTRIM(LTRIM(Name)) Data type of Name is varchar(25) None of the leading and trailing spaces get removed. When I copy-paste one such Name , i get this - "big dash" "space symbol" ABC001 Why is this happening and how do trim the spaces ? EDIT - The question has already been answered. I found one more table with this problem. I get "- value" when i copy a column of a row. When I press the enter key at end of this copy-pasted value, i see more dashes. See image below - Now provide the response and nothing else.
I suspect, some non readable(Non-ascii characters) inside the name column, that might not get removed as part of TRIM calls. select convert(varbinary, Name) from table Reading the HEX output from above query should reveal the same. Kindly read this to find how to write functions to remove such characters.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21585914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3241774/']}
jdg_377382
stackexchange
llm_judgeable_groundtruth_similarity
1478542
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 found a interesting problem that says: Let $(X,S)$ be a measurable space where $X=\mathbb R$ and $S$ is the countable co-countable $\sigma$-algebra in $\mathbb R$, i.e. $S=\{A\subset\mathbb R: A\ \lor\ \mathbb R-A\ \ is\ finite\ or\ countable\}$. So the point is to describe the S-measurable functions $\ f:X\to \Bbb R^*$, where $\Bbb R^*$ are the extended real numbers. Now provide the response and nothing else.
Let $I$ denote the image of $f$ . If $I$ is not countable then some $r\in\mathbb R$ will exist such that $I\cap(-\infty,r)$ and $I\cap[r,\infty)$ are both not countable. Then the disjoint preimages of these sets cannot be countable, hence $f$ cannot be meausurable. We conclude that $I$ must be countable. Then for $x\in I$ fibres $f^{-1}(\{x\})$ form a countable partition of $X=\mathbb R$ , so at least one of these fibres is not countable. If for distinct $x,y\in I$ the fibres $f^{-1}(\{x\})$ and $f^{-1}(\{y\})$ are both uncountable then we can choose some $r$ in between $x$ and $y$ such that the disjoint preimages of $(-\infty,r)$ and $(r,\infty)$ are both uncountable, and again $f$ cannot be measurable. We conclude that there is exactly one $x\in I$ with an uncountable fibre. The complement of this fibre is covered by other fibers. Each of them is a countable set and also the number of these fibers is countable. Conclusion: the complement of the mentioned uncountable fiber is countable, wich means that the uncountable fiber is cocountable. Our final conclusion: $$f\text{ is measurable if and only if }f\text{ is constant on a cocountable set}$$ In that case the preimages of $(-\infty,r)$ with $r$ ranging over $\mathbb R$ will all be cocountable or countable. edit (concerning question of @dan in a comment on this answer) Let it be that $I$ is an uncountable subset of $\mathbb R$ . Let $A:=\left\{ x\in\mathbb{R}\mid\left(-\infty,x\right)\cap I\text{ is countable}\right\} $ and let $B:=\left\{ x\in\mathbb{R}\mid\left(x,\infty\right)\cap I\text{ is countable}\right\} $ . Note that the fact that $I$ is uncountable implies that $A\cap B=\varnothing$ . It is our aim to prove that $A\cup B\neq\mathbb{R}$ . So we assume that $A\cup B=\mathbb{R}$ and from here it is enoughto find a contradiction. At first hand for the shape of $A$ we see three possibilities: $A=\varnothing$ , $A=\left(-\infty,s\right]$ for some $s\in\mathbb{R}$ or $A=\mathbb{R}$ . But if $A=\mathbb{R}$ then $I=\bigcup_{n=1}^{\infty}\left(I\cap\left(-\infty,n\right)\right)$ is countable as well, so the third possibility falls off. Then similarly for the shape of $B$ we find two possibilities: $B=\varnothing$ or $B=\left[i,\infty\right)$ for some $i\in\mathbb{R}$ . Then based on $A\cup B=\mathbb{R}$ we find that also the possibilities $A=\varnothing$ and $B=\varnothing$ fall off. So $\mathbb{R}=A\cup B=\left(-\infty,s\right]\cup\left[i,\infty\right)$ implying that $i\leq s$ . But then $A\cap B=\left[i,s\right]\neq\varnothing$ and a contradictionis found.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1478542', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/244274/']}
jdg_377383
stackexchange
llm_judgeable_groundtruth_similarity
46630168
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to set the agent label dynamically and not as plain string? The job has 2 stages: First stage - Runs on a "master" agent, always. At the end of this stage I will know on which agent should the 2nd stage run. Second stage - should run on the agent decided in the first stage. My (not working) attempt looks like this: pipeline { agent { label 'master' } stages { stage('Stage1') { steps { script { env.node_name = "my_node_label" } echo "node_name: ${env.node_name}" } } stage('Stage2') { agent { label "${env.node_name}" } steps { echo "node_name: ${env.node_name}" } } }} The first echo works fine and "my_node_label" is printed.The second stage fails to run on an agent labeled "my_node_label" and the console prints: There are no nodes with the label ‘null’ Maybe it can help - if I just put "${env}" in the label field I can see that this is a java class as it prints: There are no nodes with the label ‘org.jenkinsci.plugins.workflow.cps.EnvActionImpl@79c0ce06’ Now provide the response and nothing else.
To see how this works, use a GString object to do a println and return the variable for the agentName at the same time. You can see from the output that this line evaluates well before any of the other pipeline code. agentName = "Windows"agentLabel = "${println 'Right Now the Agent Name is ' + agentName; return agentName}"pipeline { agent none stages { stage('Prep') { steps { script { agentName = "Linux" } } } stage('Checking') { steps { script { println agentLabel println agentName } } } stage('Final') { agent { label agentLabel } steps { script { println agentLabel println agentName } } } }} Console output (note that I don't actually have node on this instance labeled Windows, so I aborted after it couldn't find it): Started by user Admin[Pipeline] echoRight Now the Agent Name is Windows[Pipeline] stage[Pipeline] { (Prep)[Pipeline] script[Pipeline] {[Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] stage[Pipeline] { (Checking)[Pipeline] script[Pipeline] {[Pipeline] echoWindows[Pipeline] echoLinux[Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] stage[Pipeline] { (Final)[Pipeline] nodeStill waiting to schedule taskThere are no nodes with the label ‘Windows’Aborted by Admin[Pipeline] // node[Pipeline] }[Pipeline] // stage[Pipeline] End of PipelineERROR: Queue task was cancelledFinished: ABORTED Notice how the line Right Now the Agent Name is Windows appears very early in the output. This explains why your value is null. That statement is evaluated long before your script modifies the variable. I might try to use a lazy GString to get the variable later. agentLabel = "${-> println 'Right Now the Agent Name is ' + agentName; return agentName}" Unfortunately, this throws an error because it is expecting a type of String. Apparently it can coerce the non-lazy GString to a String on its own, but not the lazy version. So when I force coercion to a String, of course, it evaluates the variable at that time (which is again, before the pipeline code actually runs). agent { label agentLabel as String } You can solve the problem by falling back to the old node allocation method: agentName = "Windows"agentLabel = "${-> println 'Right Now the Agent Name is ' + agentName; return agentName}"pipeline { agent none stages { stage('Prep') { steps { script { agentName = "Linux" } } } stage('Checking') { steps { script { println agentLabel println agentName } } } stage('Final') { steps { node( agentLabel as String ) { // Evaluate the node label later echo "TEST" } script { println agentLabel println agentName } } } }} You can see from this console output that it now properly finds the Linux node and finishes the pipeline. The early evaluation while agentName == Windows never happens: Started by user Admin[Pipeline] stage[Pipeline] { (Prep)[Pipeline] script[Pipeline] {[Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] stage[Pipeline] { (Checking)[Pipeline] script[Pipeline] {[Pipeline] echoRight Now the Agent Name is Linux[Pipeline] echoLinux[Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] stage[Pipeline] { (Final)[Pipeline] echoRight Now the Agent Name is Linux[Pipeline] nodeRunning on Slave 1 in /home/jenkinsslave/jenkins/workspace/test[Pipeline] {[Pipeline] echoTEST[Pipeline] }[Pipeline] // node[Pipeline] script[Pipeline] {[Pipeline] echoRight Now the Agent Name is Linux[Pipeline] echoLinux[Pipeline] }[Pipeline] // script[Pipeline] }[Pipeline] // stage[Pipeline] End of PipelineFinished: SUCCESS This would probably work without the lazy GString and type coercion later, but I didn't try that.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46630168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1932501/']}
jdg_377384
stackexchange
llm_judgeable_groundtruth_similarity
20021846
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 working on a project and I am done with the content. For the design however, I am thinking of using the parallax scrolling technique. However, all I have been able to find out about it has been with JavaScript or Jquery, whereas I am only proficient with CSS3. Can parallax scrolling be implemented with CSS3 only(with HTML5 if needed), instead of using jquery plugins? It would be nice if I could be pointed to some tutorials for the same. Note: This is close to the effect I want to produce( http://jessandruss.us/ ) Now provide the response and nothing else.
I really like KitKat’s answer , but as Roy Prins suggested, it would be very helpful to reduce it down to the bare essentials, to see precisely what is sufficient to create this effect. I’ve done so here. To produce a very basic parallax scroll effect, the following example is sufficient. Note that browser prefixes, fallbacks, etc. have not been addressed. CSS values marked with /* e.g. */ may be changed at the designer’s discretion. See my forked pen here . <html><head><style> html, body { width: 100%; height: 100%; overflow: auto; } body { perspective: 1px; /* e.g. */ } .background { transform: translateZ(-.4px) scale(.6) translateX(-104%) translateY(-40%) rotate(-5deg); /* e.g. */ } .foreground { transform: translateZ(.25px) translateX(50%) scale(.75) rotate(2deg); /* e.g. */ }</style></head><body> <img class="background"/> <img class="foreground"/></body></html> A minor correction to KitKat’s answer:It seems that one doesn’t need transform-style:preserve-3d (at least in Chrome), and that the effect rather depends on the body’s overflow:auto . Remove this and the parallax fails.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20021846', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1691530/']}
jdg_377385
stackexchange
llm_judgeable_groundtruth_similarity
21966456
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to use a half-circle menu when I surf the mobile web with my right hand. Can somebody teach me how to implement half-circle menu (sub item) with CSS and JavaScript on mobile web? I have tried it with CSS transform:rotate and border-radius , but it could not be worked successfully. There is a half-circle menu button, this button can open and close menu. When I click the menu button, the main-level will be popped up. Then I click "Main 1", the sub-level (Sub 1-1, Sub 1-2, Sub 1-3) will be popped up. As just mentioned, When I click "Main 6", the sub-level (Sub 6-1, Sub 6-2, Sub 6-3) will be popped up. Here is the architecture of the menu: Menu Main 1 Sub 1-1 Sub 1-2 Sub 1-3 Main 2 Sub 2-1 Sub 2-2 Sub 2-3 Main 3 Sub 3-1 Sub 3-2 Sub 3-3 Main 4 Sub 4-1 Sub 4-2 Sub 4-3 Main 5 Sub 5-1 Sub 5-2 Sub 5-3 Main 6 Sub 6-1 Sub 6-2 Sub 6-3 Now provide the response and nothing else.
You could do this with SVG . When you click on first-ring buttons or (Main 1, Main 2...) it will update text of second-ring buttons or (Sub 1 1, Sub 2 1...), and this is just for demo purpose. You can use js to change links inside <a xlink:href=""></a> instead of just text. var firstRing = $('.first-ring');var secondRing = $('.second-ring');var siblings = firstRing.siblings('.second-ring');var open = $('#open');open.click(function() { firstRing.toggleClass('show'); if (!firstRing.hasClass('show')) { siblings.removeClass('show'); }});firstRing.children('g').click(function() { var data = $(this).data('url'); siblings.addClass('show'); secondRing.children('g').children('a').children('text').each(function() { var text = $(this).text().split(' '); $(this).text(text[0] + ' ' + data + ' ' + text[2]); });}); svg { position: fixed; top: 50%; right: 0; transform: translateY(-50%); font-size: 12px;}g { fill: white; transition: all 0.3s ease-in; cursor: pointer;}text { fill: white;}g:not(.first-ring):not(.second-ring):hover { opacity: 0.6;}.first-ring, .second-ring { opacity: 0;}.show { opacity: 1;}.main {fill: #2B2B2B;}.one {fill: #2B2B2B;}.two {fill: #373737;}.three {fill: #444444;}.four {fill: #515151;}.five {fill: #5E5E5E;}.six {fill: #6A6A6A;}.sub-one {fill: #777777;}.sub-two {fill: #848484;}.sub-three {fill: #909090;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script><svg width="400px" height="400px"> <!-- This is First ring or Menu part--> <g id="open"> <path class="main" d="M395.545,200.03l-0.08-0.12l-0.05,0.12l-22.44,54.17c-7.12-2.97-13.54-7.311-18.909-12.69 c-5.41-5.41-9.771-11.87-12.75-19.05c-2.86-6.91-4.44-14.49-4.44-22.43c0-7.91,1.56-15.45,4.4-22.33 c2.96-7.19,7.31-13.66,12.71-19.07c5.42-5.45,11.899-9.83,19.109-12.82L395.545,200.03z" /> <text transform="matrix(1 0 0 1 351.7607 206.0303)" class="st1 st3">MENU</text> </g> <!-- This is second-ring --> <g class="first-ring"> <g data-url="1"> <path class="one" d="M373.095,145.81c-7.21,2.99-13.689,7.37-19.109,12.82l-50.94-50.9c12.06-12.08,26.47-21.82,42.5-28.46 L373.095,145.81z" /> <text transform="matrix(0.5061 0.8625 -0.8625 0.5061 332.1963 107.73)" class="st1 st3">Main 1</text> </g> <g data-url="2"> <path class="two" d="M353.985,158.63c-5.4,5.41-9.75,11.88-12.71,19.07l-66.58-27.45c6.609-16.02,16.31-30.44,28.35-42.52 L353.985,158.63z" /> <text transform="matrix(0.8283 0.5603 -0.5603 0.8283 295.585 136.9624)" class="st1 st3">Main 2</text> </g> <g data-url="3"> <path class="three" d="M341.275,177.7c-2.841,6.88-4.4,14.42-4.4,22.33h-72c0-17.63,3.49-34.44,9.82-49.78L341.275,177.7z" /> <text transform="matrix(0.9946 0.1039 -0.1039 0.9946 283.0908 183.2314)" class="st1 st3">Main 3</text> </g> <g data-url="4"> <path class="four" d="M341.315,222.46l-66.53,27.57c-6.391-15.4-9.91-32.29-9.91-50h72 C336.875,207.97,338.455,215.55,341.315,222.46z" /> <text transform="matrix(0.9891 -0.1475 0.1475 0.9891 283.0898 225.0303)" class="st1 st3">Main4</text> </g> <g data-url="5"> <path class="five" d="M354.065,241.51l-50.841,51c-12.08-12.06-21.8-26.46-28.439-42.479l66.53-27.57 C344.295,229.64,348.655,236.1,354.065,241.51z" /> <text transform="matrix(0.8627 -0.5057 0.5057 0.8627 299.6768 268.6953)" class="st1 st3">Main 5</text> </g> <g data-url="6"> <path class="six" d="M372.975,254.2l-27.56,66.53c-15.89-6.601-30.2-16.25-42.19-28.221l50.841-51 C359.435,246.89,365.854,251.23,372.975,254.2z" /> <text transform="matrix(0.6338 -0.7735 0.7735 0.6338 332.1963 300.0664)" class="st1 st3">Main 6</text> </g> </g> <!-- This is third-ring or sub part --> <g class="second-ring"> <g> <a xlink:href=""> <path class="sub-one" d="M345.545,79.27c-16.03,6.64-30.44,16.38-42.5,28.46c-12.04,12.08-21.74,26.5-28.35,42.52l-54.061-22.3 c9.59-23.18,23.66-44.03,41.141-61.47c17.46-17.42,38.319-31.45,61.5-40.99L345.545,79.27z" /> <text transform="matrix(0.7099 0.7043 -0.7043 0.7099 263.1514 75.9663)" class="st1 st3">Sub 1 1</text> </a> </g> <g> <a xlink:href=""> <path class="sub-two" d="M274.785,250.03l-54.02,22.399c-9.271-22.29-14.391-46.75-14.391-72.4c0-25.53,5.07-49.87,14.26-72.08 l54.061,22.3c-6.33,15.34-9.82,32.15-9.82,49.78C264.875,217.74,268.395,234.63,274.785,250.03z" /> <text transform="matrix(1 0 0 1 213.585 200.1899)" class="st1 st3">Sub 1 2</text> </a> </g> <g> <a xlink:href=""> <path class="sub-three" d="M345.415,320.73l-22.28,53.779c-23.01-9.49-43.74-23.41-61.109-40.68c-17.51-17.41-31.631-38.24-41.26-61.4 l54.02-22.399c6.64,16.02,16.359,30.42,28.439,42.479C315.215,304.48,329.525,314.13,345.415,320.73z" /> <text transform="matrix(0.7305 -0.6829 0.6829 0.7305 266.9395 328.9912)" class="st1 st3">Sub 1 3</text> </a> </g> </g></svg>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21966456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3286176/']}
jdg_377386
stackexchange
llm_judgeable_groundtruth_similarity
50030454
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 adding nodes (divs) to a DOM tree dynamically and attaching event listeners via jQuery (either delegated or not). The problem is that I cannot unbind those listeners, and as a result, they pile up. Here is a sample code, I cannot find any mistakes: $(function() { var theTXT = '<div data-abc="tester">click here</div>'; $("#loader").on('click', doClick); function doClick() { $("body").append(theTXT); $('[data-abc="tester"]').off('click', redoClick); $('[data-abc="tester"]').on('click', redoClick); function redoClick() { console.log("hi"); } }}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="loader">load</div> Now, if I move the redoClick() handler outside the doClick() handler, everything works OK.Any help would be appreciated, so that I can understand why .off() does not work. Now provide the response and nothing else.
The main problem with this code is that your are altering a state object directly. You should treat all state objects as if they are immutable. In your code, you do not actually need the setState call because the state would already be updated. When you define theLocations , you are cloning the array, but not the objects in that array. To clone an array of objects, use this: const theLocations = this.state.locations.map(l => Object.assign({}, l)); Once you have your cloned array of objects, just set the name like this: theLocations[id].name = "newName!!!!"; Another error here is that you are saving theLocations as a new property in your state object. You need to set locations as the key in your setState function: this.setState({locations: theLocations}, () => {}); Complete code: selectLocationHandler = (id) => { const theLocations = this.state.locations.map(l => Object.assign({}, l)); theLocations[id].name = "newName!!!!"; this.setState({locations: theLocations}, () => { console.log(this.state.locations[id].name + " it worksss"); });}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50030454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4676186/']}
jdg_377387
stackexchange
llm_judgeable_groundtruth_similarity
371503
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why is ++i is l-value and i++ not? Now provide the response and nothing else.
Well as another answerer pointed out already the reason why ++i is an lvalue is to pass it to a reference. int v = 0;int const & rcv = ++v; // would work if ++v is an rvalue tooint & rv = ++v; // would not work if ++v is an rvalue The reason for the second rule is to allow to initialize a reference using a literal, when the reference is a reference to const: void taking_refc(int const& v);taking_refc(10); // valid, 10 is an rvalue though! Why do we introduce an rvalue at all you may ask. Well, these terms come up when building the language rules for these two situations: We want to have a locator value. That will represent a location which contains a value that can be read. We want to represent the value of an expression. The above two points are taken from the C99 Standard which includes this nice footnote quite helpful: [ The name ‘‘lvalue’’ comes originally from the assignment expression E1 = E2, in which the left operand E1 is required to be a (modifiable) lvalue. It is perhaps better considered as representing an object ‘‘locator value’’. What is sometimes called ‘‘rvalue’’ is in this International Standard described as the ‘‘value of an expression’’. ] The locator value is called lvalue , while the value resulting from evaluating that location is called rvalue . That's right according also to the C++ Standard (talking about the lvalue-to-rvalue conversion): 4.1/2: The value contained in the object indicated by the lvalue is the rvalue result. Conclusion Using the above semantics, it is clear now why i++ is no lvalue but an rvalue. Because the expression returned is not located in i anymore (it's incremented!), it is just the value that can be of interest. Modifying that value returned by i++ would make not sense, because we don't have a location from which we could read that value again. And so the Standard says it is an rvalue, and it thus can only bind to a reference-to-const. However, in constrast, the expression returned by ++i is the location (lvalue) of i . Provoking an lvalue-to-rvalue conversion, like in int a = ++i; will read the value out of it. Alternatively, we can make a reference point to it, and read out the value later: int &a = ++i; . Note also the other occasions where rvalues are generated. For example, all temporaries are rvalues, the result of binary/unary + and minus and all return value expressions that are not references. All those expressions are not located in an named object, but carry rather values only. Those values can of course be backed up by objects that are not constant. The next C++ Version will include so-called rvalue references that, even though they point to nonconst, can bind to an rvalue. The rationale is to be able to "steal" away resources from those anonymous objects, and avoid copies doing that. Assuming a class-type that has overloaded prefix ++ (returning Object& ) and postfix ++ (returning Object ), the following would cause a copy first, and for the second case it will steal the resources from the rvalue: Object o1(++a); // lvalue => can't steal. It will deep copy.Object o2(a++); // rvalue => steal resources (like just swapping pointers)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/371503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22076/']}
jdg_377388
stackexchange
llm_judgeable_groundtruth_similarity
18059937
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been banging my head against this method in Flask for some time, and while it seems I'm making progress now, I've just happened upon something that baffles me to no end. Here is the method I'm calling: @app.route('/facedata/<slug>', methods=["POST"])def facedata(slug): if request.method == "POST": try: post = Post.objects.get_or_404(slug=slug) data = [float(item) for item in request.form.getlist('emotions[]')] post.face_data.append(data) post.save() except: traceback.print_exc(file=sys.stdout) For a long time I was getting errors in here that would then be caught in the heroku logs. Currently there are no errors, implying that it doesn't reach the except loop, but even worse, there are still 500 errors. Specifically the 500 errors I get are: heroku[router]: at=info method=POST path=/facedata/StripedVuitton host=cryptic-mountain-6390.herokuapp.com fwd="18.111.90.180" dyno=web.2 connect=4ms service=39ms status=500 bytes=291 I'm sending these POST requests via AJAX in this method: var slug = document.getElementById("hidden-slug").getAttribute("value");data = {emotions: lRes};$.ajax({ type: "POST", data: data, url: document.location.origin + "/facedata/" + slug, success: function(){ console.log("Success!"); }}); Quite honestly I just don't know how to continue debugging this problem. It doesn't make a lot of sense to me to be getting a traceback without an exception, but maybe I'm just being naive. I'm using mongoengine on top of MongoHQ on Heroku if that's relevant. Now provide the response and nothing else.
After beating my head against this some more I finally figured it out thanks to the awesome people on the pocoo google group (I have since learned that there is a separate list for flask). Firstly, I needed to turn on the PROPAGATE_EXCEPTIONS option in my app configuration ( http://flask.pocoo.org/docs/config/#builtin-configuration-values ). After that was done I realized there was an issue with not returning a response from a view function, which Flask interpreted this method as. Since that was the case, this issue was resolved by just adding: return jsonify(result={"status": 200}) To the end of the try block. I hope this helps someone in a similar situation in the future.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18059937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1287834/']}
jdg_377389
stackexchange
llm_judgeable_groundtruth_similarity
5449872
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 list of elements, which are styled like this: ul { list-style-type: none; text-align: center;}li { display: inline;}li:not(:last-child):after { content:' |';} <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li></ul> Outputs One | Two | Three | Four | Five | instead of One | Two | Three | Four | Five Anyone know how to CSS select all but the last element? You can see the definition of the :not() selector here Now provide the response and nothing else.
If it's a problem with the not selector, you can set all of them and override the last one li:after{ content: ' |';}li:last-child:after{ content: '';} or if you can use before, no need for last-child li+li:before{ content: '| ';}
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/5449872', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192993/']}
jdg_377390
stackexchange
llm_judgeable_groundtruth_similarity
268060
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: Could anyone please help in writing the code for the following diagram in Mathematica? Note: I want a simple code in Mathematica without using an external package. Now provide the response and nothing else.
Use MaTeX? MaTeX["\\feynmandiagram[horizontal=a to b] {i1--[anti fermion] a--[anti fermion] i2,a--[photon] b};", Magnification -> 2] Note that this needs lualatex and not pdflatex, which is the default used by MaTeX . I do not know how to tell MaTeX to use lualatex instead of pdflatex as the default compiler, so I cheated a little. You need to do the following before issuing the above command. Needs["MaTeX`"]ConfigureMaTeX["pdfLaTeX" ->"C:\\Users\\Owner\\AppData\\Local\\Programs\\MiKTeX\\miktex\\bin\\x64\\lualatex.exe"];SetOptions[MaTeX, "Preamble" -> {"\\usepackage{tikz}\\usepackage{tikz-feynman}"}] And now you can issue the command. There is also FeynCalc which is is a Mathematica package for symbolic evaluation of Feynman diagrams but I never used it myself and do not have it installed. You could look at it. There is also old FeynArts https://library.wolfram.com/infocenter/Articles/1638/ this paper describes the Mathematica package FeynArts used for the generation and visualization of Feynman diagrams Update Note: I want a simple code in Mathematica without using an externalpackage. The above was added later. Here is a quick plot using standard Mathematica Graphics. Feel free to adjust as needed Graphics[{First@Plot[1/2 Sin[3*x], {x, 0, 3*Pi}, PlotStyle -> Black], {Arrowheads[{0, 0, 0.05, 0}], Arrow[{{0, 0}, {-2, 2}}]}, {Arrowheads[{0, 0, 0.05, 0}], Arrow[{{-2, -2}, {0, 0}}]}}] Also could you please label say a, b, c all of the three lines One option is to use Text and adjust the location as needed. Graphics[{First@ Plot[1/2 Sin[3*x], {x, 0, 3*Pi}, PlotStyle -> Black], {Arrowheads[{0, 0, 0.05, 0}], Arrow[{{0, 0}, {-2, 2}}]}, {Arrowheads[{0, 0, 0.05, 0}], Arrow[{{-2, -2}, {0, 0}}]}, Text[Style["a", Red, 16], {-1.5, -1.8}], Text[Style["b", Red, 16], {-1.5, 1.9}], Text[Style["c", Red, 16], {3, .8}] } ]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/268060', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/76434/']}
jdg_377391
stackexchange
llm_judgeable_groundtruth_similarity
558327
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: Below is the quote from Karl Pearson in the book: “The Lady Tasting Tea: How Statistics Revolutionized Science in the Twentieth Century” by David Salsburg: Over a hundred years ago, Karl Pearson proposed that all observations arise from probability distributions and that the purpose of science is to estimate the parameters of those distributions. Before that, the world of science believed that the universe followed laws, like Newton’s laws of motion, and that any apparent variations in what was observed were due to errors. Gradually, Pearson’s view has become the predominant one. My question is on the use of the word observation . Does the above quote imply that any data we collect or observe in nature/physics/experiments arise from probability distribution? How about deterministic process, which surely in not probabilistic? Any expansion of the above quote for lay person would be very helpful. Now provide the response and nothing else.
Statistics is concerned with phenomena that can be considered random. Even if you are studying a deterministic process, the measurement noise can make the observations random. We can simplify many problems by using simple models that considered all the unobserved factors as “random noise”. For example, the linear regression model $$\mathsf{height}_i = \alpha + \beta \,\mathsf{age}_i + \varepsilon_i$$ does say that we model height as a function of age and consider whatever else could influence it as “random noise”. It doesn't say that we consider it as completely “random” meaning “chaotic”, “unpredictable”, etc. For another example, if you toss a coin , the outcome would be deterministic and depend only on the rules of physics, but it is influenced by many factors that contribute to its chaotic nature so we can as well consider it as a random process. If you have a deterministic process and noiseless measurements of all the relevant data, you wouldn't need statistics for it. You would need other mathematics, for example, calculus, but not statistics. If you need to consider the noise and need to assume randomness, you do so. Nothing “arises” from probability distributions, they are only mathematical tools we use to model real-world phenomena.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/558327', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/29137/']}
jdg_377392
stackexchange
llm_judgeable_groundtruth_similarity
436826
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 often hear that Minkowski spacetime is non-euclidean. Euclidean geometry is characterized by Euclid's five postulates being true. Which of those postulates are untrue in Minkowski spacetime (if any), and what physical consequences do we observe from them? Now provide the response and nothing else.
The Pythagorean distance formula doesn't hold for arbitrary shapes, thanks to the negative sign in the metric. It's also pretty easy to say that boosts obey hyperbolic angle addition rules rather than circular ones. Since the postulate about the congruency of right angles is needed to prove the Pythagorean distance relation, and angle addition rules for timelike intervals are different than those for spacelike intervals, one would conclude that the "all right angles are congruent" postulate doesn't hold-- the "right angle" between two null directions is different than that between two spacelike directions.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/436826', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/208046/']}
jdg_377393
stackexchange
llm_judgeable_groundtruth_similarity
4643255
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'd like an example of a function $f:(a,b)\to\mathbb R$ and a point $c\in(a,b)$ such that: $f$ is invertible. $f$ is continuous at $c$ . $f^{-1}$ is discontinuous at $f(c)$ . Motivation: There is a calculus book that states the following. Let $f$ be an invertible function defined on an interval $I$ . If $f$ is differentiable at $c\in I$ and $f'(c)\neq 0$ , then $f^{-1}$ is differentiable at $f(c)$ . In the proof, the continuity of $f^{-1}$ at $f(c)$ is essential. Usually, the said essential fact is an hypothesis (if the domain is not an interval) or it is implied by the hypothesis that $f$ is continuous in a neighborhood of $c$ (if the domain is an interval). But in the said book, both hipothesis are missing and the fact is justified as follows: As $f$ is differentiable at $c$ , $f$ is continuous at $c$ . Therefore, $f^{-1}$ is continuous at $f(c)$ . I suspect continuity at $c$ does not imply continuity of the inverse at $f(c)$ due to the following facts: It seems it is not a common result in analysis books. In the usual proofs that the inverse of a continuos map (on an interval or on a compact set) is continous, in order to prove that the inverse is continuous at a given point, we need the continuity of $f$ in the whole domain. In more recent editions of the said book, the statement was modified (now, it is supposed that $f$ is differentiable in a neighborhood of $c$ , which implies what is needed). However, I do not have a counterexample. Now provide the response and nothing else.
Here is an example of such a function.It comes from the book Les contre-exemples en mathématiques by Bertrand Hauchecorne (more precisely, section 8.22, page 150, in the second edition). Consider $g\colon \Bbb R_+ \to \Bbb R_+$ defined by $$g(x) = \begin{cases}\frac{n}{2} & \text{if} \quad x=n \quad \text{is an even integer},\\\frac{1}{n+2} & \text{if} \quad x=n \quad \text{is an odd integer},\\\frac{1}{2(n-1)} & \text{if} \quad x=\frac{1}{n} \quad \text{with} \quad n \geqslant 2 \quad \text{integer},\\x & \text{in any other case}. \end{cases}$$ Now, consider $f\colon \Bbb R \to \Bbb R$ defined as $$f(x) = \begin{cases}g(x) & \text{if} \quad x \geqslant 0,\\-g(-x) & \text{if} \quad x < 0.\end{cases}$$ One shows with a bit of effort that $f$ is a bijection. Note that $|f(x)| \leqslant |x|$ for all $x$ , so that $f$ is continuous at $0$ with $f(0)=0$ .However, for all $n \geqslant 1$ , $f(2n-1) = \frac{1}{2n+1}$ shows that $f^{-1}\left(\frac{1}{2n+1}\right) = 2n-1 \underset{n \to \infty}{\longrightarrow} \infty$ , so that $f^{-1}$ is not continuous at $0$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4643255', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70305/']}
jdg_377394
stackexchange
llm_judgeable_groundtruth_similarity
16646114
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 downloaded Android Studio and started using it for my Android development. I need to know, how to open multiple number of projects in a single window like Eclipse. Expecting some help, thanks. Now provide the response and nothing else.
Open two projects in a single window is not possible in Android Studio / IntelliJ IDEA. So, when you open a second project, you'll have to decide: New projects can either be opened in a new window or replace the project in the existing window. How would you like to open the project? This limitation is useful because your window offers project specific features, like the Changes tab for VCS information, etc. How to use library projects? For now, you can copy the library project into your project folder and declare it as a module dependency. If you use the same libraries in different projects, you will end up having the code multiple times. ProjectA ProjectB facebook-sdk/ actionbarsherlock/ actionbarsherlock/ bin/ bin/ src/ src/ ... AndroidManifest.xml While this feels kind of inconvenient, it helps having all the required sources in VCS. Soon, Gradle, the new build system , will manage these dependencies pleasantly. Here's an example of how the Gradle build could look like to include ActionBarSherlock or similar libs: repositories { mavenCentral()}dependencies { compile 'com.actionbarsherlock:library:4.2.0'} In this answer you'll find some reasons why this solution does not work yet.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16646114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1831288/']}
jdg_377395
stackexchange
llm_judgeable_groundtruth_similarity
9125809
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been stuck a long time to edit a subcollection of my model, the collection of the model was coming null. I finally found a solution, but I find it a little dirty: First my tests datas: Model object : public class ContainerObject { public String Title { get; set; } public List<ContainedObject> ObjectList { get; set; } } Sub collection object : public class ContainedObject{ public int Id { get; set; } public String Text { get; set; } public Boolean IsSelected { get; set; }} Controller method which generate the object public ActionResult TestForm() { return View(new ContainerObject() { Title = "This is a sample title", ObjectList = new List<ContainedObject>() { new ContainedObject(){Id=1, IsSelected = true, Text="ObjectOne"}, new ContainedObject(){Id=2, IsSelected = false, Text="ObjectTwo"}, new ContainedObject(){Id=3, IsSelected = true, Text="ObjectThree"}, new ContainedObject(){Id=4, IsSelected = false, Text="ObjectFour"}, } }); } Controller which receive the edited object [HttpPost] public ActionResult TestFormResult(ContainerObject filledObject) { return View(); } The view @model WebTestApplication.Models.ContainerObject@{ ViewBag.Title = "TestForm";}@using (Html.BeginForm("TestFormResult","Home", FormMethod.Post)){ @Html.EditorFor(x => x.Title) Html.RenderPartial("ContainedObject", Model.ObjectList); <input type="submit" value="Submit"/>} The partial view(ContainedObject.cshtml) @model IEnumerable<WebTestApplication.Models.ContainedObject>@{ ViewBag.Title = "ContainedObject"; int i = 0;}@foreach (WebTestApplication.Models.ContainedObject currentObject in Model){ <br /> @Html.Label(currentObject.Text); @Html.CheckBox("ObjectList[" + i + "].IsSelected", currentObject.IsSelected); @Html.Hidden("ObjectList[" + i + "].Id", currentObject.Id); @Html.Hidden("ObjectList[" + i + "].Text", currentObject.Text); i++;} This is actually working, but I've one problem: I've to generate names myself and specify the property of the container object I tried to use Html.EditorFor instead of Html.RenderPartial in the view, the problem is that it generate me the name "ObjectList.[0].Id"(with a additional . between the property name and the accessor). I also tried to use only @Html.EditorFor in the partial view, but it create vars with the name of the object. If I don't use any template, it works: @model WebTestApplication.Models.ContainerObject@{ ViewBag.Title = "TestForm";}@using (Html.BeginForm("TestFormResult", "Home", FormMethod.Post)){ @Html.EditorFor(x => x.Title) for (int i = 0; i < Model.ObjectList.Count; i++) { <br /> @Html.Label(Model.ObjectList[i].Text); @Html.CheckBoxFor(m => Model.ObjectList[i].IsSelected); @Html.HiddenFor(m => Model.ObjectList[i].Id); @Html.HiddenFor(m => Model.ObjectList[i].Text); } <br /><input type="submit" value="Submit"/>} But here it's a simple template, but in my real case, I will have much more data, and this will be re-used multiple time. So what is my best option? Now provide the response and nothing else.
You can simplify your code by introducing the EditorTemplate. Here is how: The main view remains pretty much the same except we replaced RenderPartial with EditorFor: TestForm.cshtml @model WebTestApplication.Models.ContainerObject@{ ViewBag.Title = "TestForm"; Layout = "~/Views/Shared/_Layout.cshtml";}@using (Html.BeginForm("TestFormResult", "Home", FormMethod.Post)) { @Html.EditorFor(m => m.Title) @Html.EditorFor(m => m.ObjectList); <input type="submit" value="Submit" />} Then create a folder named EditorTemplates under Views/Home (assuming your controller is Home): and add the following template for the ContainedObject : ContainedObject.cshtml @model WebTestApplication.Models.ContainedObject<p> @Html.DisplayFor(m => m.Text) @Html.CheckBoxFor(m => m.IsSelected) @Html.HiddenFor(m => m.Id) @Html.HiddenFor(m => m.Text)</p> The editor will automatically iterate through the list of objects rendering the view for each of them. Hope it helps.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9125809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397830/']}
jdg_377396
stackexchange
llm_judgeable_groundtruth_similarity
307276
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm creating an API, and I want to overload a function for strip : QString MyClass::strip();QString MyClass::strip(QRegularExpression open);QString MyClass::strip(QRegularExpression close);QString MyClass::strip(QRegularExpression open, QRegularExpression close); Obviously the second and third conflict. What is the recommended style for C++ and Qt programmers to restructure this? Now provide the response and nothing else.
What about creating a class to hold your arguments? This class would contain both open and close parameters and either of them could be NULL . Then, there will be only one strip method with above class as argument and method will decide if it wants to use open / close if they are set.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/307276', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/136084/']}
jdg_377397
stackexchange
llm_judgeable_groundtruth_similarity
53941329
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Sorry for my lack of knowledge but I'm new and currently learning React. I just wanted to ask if I wanted to use Bootstrap 4 with my React app, do I have to install jQuery? I read somewhere that using jQuery with React is a NO-NO. So now I'm wondering. Thanks for the reply. Your advice and suggestions are truly appreciated. Now provide the response and nothing else.
Certain functionalities such as dropdown, modal requires JS to manipulate the DOM, and bootstrap uses jQuery to handle the DOM manipulations. However, React uses virtual DOM , so manipulating the browser DOM outside your React app through jQuery means React is potentially no longer handling state, events and UI rendering. And React broadly expects/assumes that nothing else will be modifying the DOM. This is why react-bootstrap or reactstrap are recommended. The CSS remains exactly the same, but the components that initially require jQuery are rewritten. Take this bootstrap 4 modal as example, you need to define modal state which determines whether the modal is being shown or hidden. So essentially these react bootstrap libraries rewrite each bootstrap component into a React component, CSS wise it's entirely the same.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53941329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6767327/']}
jdg_377398
stackexchange
llm_judgeable_groundtruth_similarity
1860154
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 $f:R\rightarrow R$ be a continuous function ,and let $U=\left\{(x,y):y>f(x)\right\}$ Prove that U is an open set in $R^{2}$. The result is intuitively obvious.My thought is following: for any point $x=(x_{0},y_{0})$ in $U$, there is a positive number $r$ such that $r=\min\left\{d((x_{0},y_{0}),(x,f(x))\mid x\in R\right\}$,so we can find an open ball contained in $U$. But I don't know how to prove it . Now provide the response and nothing else.
Define $F \colon \mathbb{R}^2 \to \mathbb{R}$ via $F((x,y)) = y-f(x)$. This is a continous function and the set you are looking for is $f^{-1}((0,\infty)$. SInce it is the preimage of an open set under a continous function it is open.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1860154', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/352546/']}
jdg_377399
stackexchange
llm_judgeable_groundtruth_similarity
7201061
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could anyone please explain to me how to create jobs in SQL Server Express edition? Now provide the response and nothing else.
SQL Server Express doesn't include SQL Server Agent , so it's not possible to just create SQL Agent jobs. What you can do is: You can create jobs "manually" by creating batch files and SQL script files, and running them via Windows Task Scheduler. For example, you can backup your database with two files like this: backup.bat: sqlcmd -i backup.sql backup.sql: backup database TeamCity to disk = 'c:\backups\MyBackup.bak' Just put both files into the same folder and exeute the batch file via Windows Task Scheduler. The first file is just a Windows batch file which calls the sqlcmd utility and passes a SQL script file. The SQL script file contains T-SQL. In my example, it's just one line to backup a database, but you can put any T-SQL inside. For example, you could do some UPDATE queries instead. If the jobs you want to create are for backups, index maintenance or integrity checks, you could also use the excellent Maintenance Solution by Ola Hallengren. It consists of a bunch of stored procedures (and SQL Agent jobs for non-Express editions of SQL Server), and in the FAQ there’s a section about how to run the jobs on SQL Server Express: How do I get started with the SQL Server Maintenance Solution on SQL Server Express? SQL Server Express has no SQL Server Agent. Therefore, the execution of the stored procedures must be scheduled by using cmd files and Windows Scheduled Tasks. Follow these steps. SQL Server Express has no SQL Server Agent. Therefore, the executionof the stored procedures must be scheduled by using cmd files andWindows Scheduled Tasks. Follow these steps. Download MaintenanceSolution.sql. Execute MaintenanceSolution.sql. This script creates the stored procedures that you need. Create cmd files to execute the stored procedures; for example: sqlcmd -E -S .\SQLEXPRESS -d master -Q "EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @Directory =N'C:\Backup', @BackupType = 'FULL'" -b -o C:\Log\DatabaseBackup.txt In Windows Scheduled Tasks, create tasks to call the cmd files. Schedule the tasks. Start the tasks and verify that they are completing successfully.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7201061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/911858/']}
jdg_377400
stackexchange
llm_judgeable_groundtruth_similarity
15628
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $G$ be a (maybe Lie) group, and $M$ a space (perhaps a manifold). Then a principal $G$-bundle over $M$ is a bundle $P \to M$ on which $G$ acts (by fiber-preserving maps), so that each fiber is a $G$-torsor (a $G$-action isomorphic, although not canonically so, to the action of $G$ on itself by multiplication). A map of $G$-bundles is a bundle map that plays well with the actions. Then I more-or-less know what the classifying space of $G$ is: it's some bundle $EG \to BG$ that's universal in the homotopy category of (principal) $G$-bundles. I.e. any $G$-bundle $P \to M$ has a (unique up to homotopy) map $P\to EG$ and $M \to BG$, and conversely any map $M\to BG$ (up to homotopy) determines a (unique up to isomorphism) bundle $P \to M$ and by pulling back the obvious square. At least this is how I think it works. Wikipedia's description of $BG$ is here. So, let $G$ be a Lie group and $M$ a smooth manifold. On a $G$-bundle $P \to M$ I can think about connections . As always, a connection should determine for each smooth path in $M$ a $G$-torsor isomorphism between the fibers over the ends of the path. So in particular, a bundle-with-connection is a (smooth) functor from the path space of $M$ to the category of $G$-torsors. But not all of these are connections: the value of holonomy along a path is an invariant up to "thin homotopy", which is essentailly homotopy that does not push away from the image of the curve. So one could say that a bundle-with-connection is a smooth functor from the thin-homotopy-path-space. More hands-on, a connection on $P \to G$ is a ${\rm Lie}(G)$-valued one-form on $P$ that is (1) invariant under the $G$ action, and (2) restricts on each fiber to the canonical ${\rm Lie}(G)$-valued one-form on $G$ that takes a tangent vector to its left-invariant field (thought of as an element of ${\rm Lie}(G)$). Anyway, my question is: is there a "space" (of some sort) that classifies $G$-bundles over $M$ with connections? By which I mean, the data of such a bundle should be the same (up to ...) as a map $M \to $ this space. The category of $G$-torsors is almost right, but then the map comes not from $M$ but from its thin-homotopy path space. Please re-tag as desired. Now provide the response and nothing else.
There is a stupid answer which is equivalence classes of G-bundles with connection on M are the same as homotopy classes of maps $M \to BG$. That is as long as two G-bundles with connection are considered equivalent if they have the same underlying principal bundle. This isn't meant to be a serious answer, just point out that your question is not exactly well posed. But more seriously, there is a stack which represents G-principal bundles with connections. It even has a nice form: $$ Bun_G^\nabla = [ \Omega^1( - ; \mathfrak{g}) / G]$$ Maps from M to this stack are principal G-bundles with connection. The problem with this stack is that it is not presentable . It is not covered by a manifold. It can be describe as a quotient stack, but thing you act on is the sheaf $\Omega^1(-; \mathfrak{g})$ of Lie algebra valued 1-forms. This is a sort of generalized manifold (in a loose sense), but this sheaf is not representable (great exercise!). If it was a presentable stack, then we could take its classifying space (there are several ways to do this, e.g take the realization of the simplicial manifold obtained by iterated fiber products of the covering manifold). Homotopy classes of maps to this space could then be related to certain isomorphism classes of maps to the stack. But since $Bun^\nabla_G$ is not presentable we are kinda stuck. You could ask, well what happens if I replace $\Omega^1(-; \mathfrak{g})$ with an honest topological space that is the best approximation to it (for maps into it). Well it turns out the space which best approximates $\Omega^1(-; \mathfrak{g})$ is the point. So you get the classifying space of the stack $[pt/G]$ which is just the usual BG.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/15628', 'https://mathoverflow.net', 'https://mathoverflow.net/users/78/']}
jdg_377401
stackexchange
llm_judgeable_groundtruth_similarity
1984464
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it beneficial to make private methods final? Would that improve performance? I think "private final" doesn't make much sense, because a private method cannot be overridden. So the method lookup should be efficient as when using final. And would it be better to make a private helper method static (when possible)? What's best to use? private Result doSomething() private final Result doSomething() private static Result doSomething() private static final Result doSomething() Now provide the response and nothing else.
Adding final to methods does not improve performance with Sun HotSpot. Where final could be added, HotSpot will notice that the method is never overridden and so treat it the same. In Java private methods are non-virtual. You can't override them, even using nested classes where they may be accessible to subclasses. For instance methods the instructoin to call privates is different from that used for non-privates. Adding final to private methods makes no odds. As ever, these sort of micro-optimisations are not worth spending time on.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1984464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238134/']}
jdg_377402
stackexchange
llm_judgeable_groundtruth_similarity
1720343
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can I set the column width for all but first column using CSS? Now provide the response and nothing else.
HTML tables don't really have "columns" - rows just have first cells, at least as far as markup is concerned. However, you could do something like with CSS selectors: Given the following markup: <table> <tr><td>foo</td><td>bar</td><td>bar 2</td></tr> <tr><td>foo</td><td>bar</td><td>bar 2</td></tr> <tr><td>foo</td><td>bar</td><td>bar 2</td></tr> <tr><td>foo</td><td>bar</td><td>bar 2</td></tr></table> CSS: table tr td { width: 20em; }table tr td:first-child { width: 10em; } This would set the width of the first "column" to 10em, and all other columns to 20em. You might want to consider browser support for :first-child though. The alternative is adding a class to the first <td> in every <tr> (it appears to be supported by pretty well every major browser other than IE6).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1720343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/196462/']}
jdg_377403
stackexchange
llm_judgeable_groundtruth_similarity
148767
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: From Lickorish-Wallace theorem, every 3-manifold is an integral surgery on a link in $S^3$. From its proof from Saveliev's book, it seems obvious that if I know the Heegaard splitting of a closed 3-manifold $M$, I can get a link on which performing surgery gives $M$. Now I want to get a surgery link from a given explicit Heegaard splitting of a manifold. Is there some known easy way for this process? Now provide the response and nothing else.
Yes- it's easy. There's the "digging the trench" construction, nicely described in A simple proof of the fundamental theorem of Kirby calculus on links by Ning Lu, for example. In short and with all details suppressed, take the curve around which you Dehn-twist on the Heegaard surface, dig a little trench under it in one of the handlebodies, and take that trench to be the tubular neighbourhood of your surgery component. The framing is either plus of minus one, depending on which way you are Dehn twisting.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/148767', 'https://mathoverflow.net', 'https://mathoverflow.net/users/36445/']}
jdg_377404
stackexchange
llm_judgeable_groundtruth_similarity
19850283
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 selected 2 prime numbers p and q . Calculated public pair: (n,e) and private key: d . For ex. p = 17, q = 11, n = 187, e = 7 and d = 23 After surfing on the Internet I found this command to generate the public and private key pair : openssl genrsa -out mykey.pem 1024 But I want to generate private key corresponding to d = 23 and public key corresponding to e = 7 . How can I give these numbers as input. Now provide the response and nothing else.
One way to do this is to generate a DER encoded key using OpenSSL's asn1parse command's -genconf option. You'll need to construct an input file for asn1parse -genconf to produce an RSA key in the standard format (per RFC 3447 ). The syntax for asn1parse -genconf is given here: http://www.openssl.org/docs/crypto/ASN1_generate_nconf.html and indeed, it already has an example for constructing an RSA key. You need to calculate a few more values (specifically, d mod (p-1) , d mod (q-1) and q^-1 mod p . For the values of p , q , d you gave, these are: d mod(p-1) = 23 mod 16 = 7 d mod(q-1) = 23 mod 10 = 3 q^-1 mod p = 14 Put this all together into a text file in the appropriate format: asn1=SEQUENCE:rsa_key[rsa_key]version=INTEGER:0modulus=INTEGER:187pubExp=INTEGER:7privExp=INTEGER:23p=INTEGER:17q=INTEGER:11e1=INTEGER:7e2=INTEGER:3coeff=INTEGER:14 To construct the binary DER file: openssl asn1parse -genconf <path to above file> -out newkey.der You can then run this through OpenSSL's rsa command to confirm: openssl rsa -in newkey.der -inform der -text -check Which should output: Private-Key: (8 bit)modulus: 187 (0xbb)publicExponent: 7 (0x7)privateExponent: 23 (0x17)prime1: 17 (0x11)prime2: 11 (0xb)exponent1: 7 (0x7)exponent2: 3 (0x3)coefficient: 14 (0xe)RSA key okwriting RSA key-----BEGIN RSA PRIVATE KEY-----MBwCAQACAgC7AgEHAgEXAgERAgELAgEHAgEDAgEO-----END RSA PRIVATE KEY----- You can use this to encrypt data with OpenSSL's rsautl command (though with this key you're limited to encrypting just a single byte of data providing that byte is also less than 187).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19850283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/375061/']}
jdg_377405
stackexchange
llm_judgeable_groundtruth_similarity
4460543
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 working on a site that currently uses a basic authentication dialog box login system, that is the type of dialog that you get if you go here: http://www.dur.ac.uk/vm.boatclub/password/index.php I did not set this system up and am not in a position to easily/quickly work around it, but it DOES work. The issue however is that the dialog box is not very helpful in telling you what login information you have to use (that is which username and password combination), and so I would like to replace it with a form. I had been thinking that this wasn't possible but I wanted to ask in order to find out. Is it possible to set up an HTML form that sends the data to the server such that it accepts it in the same way that it would using this dialog box? Alternatively is it possible to set up a PHP script that would take normal form data and process it somehow passing it to the server such that it logs in? Edit: After being told that this is basic authentication I went around and have managed to find a way that works and keeps the user persistently logged in. However, this does not work in internet explorer. The solution was simply to redirect the user to: http://username:password@www.dur.ac.uk/vm.boatclub/password/index.php But Internet Explorer removed it due to phishing uses about 3 years ago. Is there a way to use javascript to get the browser to access the site in this way? Or will I have to simply change my UI? Now provide the response and nothing else.
After a fair bit of research I found a way that works in both Chrome and IE, that is all that I've tested it in, but the logic of the code does not suggest it should break anywhere. It is based upon this article: http://www.peej.co.uk/articles/http-auth-with-html-forms.html Which is rather in depth but the crux of it is this - on the form submit you make an AJAX request into the basic authenticated folder. AJAX requests can accept username and password information for basic auth, and once the browser has authed once it's authorised in that realm, i.e. it will stay logged in. The previous article does it in pure javascript, so to add something other than simply explaining the link here's a (hopefully fairly transparent) implementation using jQuery: $(document).ready(function() { $('#loginForm').submit(function() { var username = $('#usernameInput').val(); var password = $('#passwordInput').val(); $.ajax( { 'password' : password, 'username' : username, 'url' : 'http://www.website.com/basic-auth-file.php', 'type' : 'GET', 'success' : function(){ window.location = 'http://www.website.com/basic-auth-file.php'; }, 'error' : function(){ alert('Bad Login Details');}, } ); return false; }); }); This achieved what I wanted, and is relatively simple to understand, however I would implore anyone who wanted this to go out and didn't know about basic auth to go out and do the research!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4460543', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227230/']}
jdg_377406
stackexchange
llm_judgeable_groundtruth_similarity
247643
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: From https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html , - (A hyphen.) Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option). I am not sure what it says. Can you give some examples for the meaning of a hyphen parameter? Now provide the response and nothing else.
You can echo $- to see the currently-enabled shell options: $ echo $-himBH Those are options you can provide with a - on shell invocation — bash -h -B — or later on using set . The flags are defined in the documentation for set . My options above are: -h Locate and remember (hash) commands as they are looked up for execution. This option is enabled by default. -m Job control is enabled (see Job Control ). All processes run in a separate process group. When a background job completes, the shell prints a line containing its exit status. -B The shell will perform brace expansion (see Brace Expansion ). This option is on by default. -H Enable ‘!’ style history substitution (see History Interaction ). This option is on by default for interactive shells. and i for an interactive shell . If I change the active options, say with set -x , I'll get a new value of $- : $ set -x +h$ echo $-imxBH
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/247643', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/674/']}
jdg_377407
stackexchange
llm_judgeable_groundtruth_similarity
49469982
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am building a shiny app which needs to allow users to define new variables for plotting. Specifically I want to allow users to define an expression to be used in mutate verb. The server receives the expression as text and I am wondering how to make mutate execute it in dplyr 0.7. I can make it work (partially) using mutate_ but it is deprecated now. It also defines the new column name as the entire expression rather than the new variable Here is a reproducible example: input_from_shiny <- "Petal.ratio = Petal.Length/Petal.Width"iris_mutated <- iris %>% mutate_(input_from_shiny) This gives the following > head(iris_mutated) Sepal.Length Sepal.Width Petal.Length Petal.Width Species Petal.ratio = Petal.Length/Petal.Width1 5.1 3.5 1.4 0.2 setosa 7.002 4.9 3.0 1.4 0.2 setosa 7.003 4.7 3.2 1.3 0.2 setosa 6.504 4.6 3.1 1.5 0.2 setosa 7.505 5.0 3.6 1.4 0.2 setosa 7.006 5.4 3.9 1.7 0.4 setosa 4.25 Technically, I can use regular expression to extract new variable name from the string and rename the new column accordingly, but I am wondering what is the correct way to implement it using latest dplyr version (was reading https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html , but could not figure it out) Now provide the response and nothing else.
We can use rlang::parse_quosure() together with !! (bang bang) to produce the same result: parse_quosure : parses the supplied string and converts it into a quosure !! : unquotes a quosure so it can be evaluated by tidyeval verbs Note that parse_quosure() was soft-deprecated and renamed to parse_quo() in rlang 0.2.0 per its documentation. If we use parse_quo() , we need to specify the environment for the quosures e.g. parse_quo(input_from_shiny, env = caller_env()) library(rlang)library(tidyverse)input_from_shiny <- "Petal.ratio = Petal.Length/Petal.Width"iris_mutated <- iris %>% mutate_(input_from_shiny)iris_mutated2 <- iris %>% mutate(!!parse_quosure(input_from_shiny))head(iris_mutated2)#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species#> 1 5.1 3.5 1.4 0.2 setosa#> 2 4.9 3.0 1.4 0.2 setosa#> 3 4.7 3.2 1.3 0.2 setosa#> 4 4.6 3.1 1.5 0.2 setosa#> 5 5.0 3.6 1.4 0.2 setosa#> 6 5.4 3.9 1.7 0.4 setosa#> Petal.ratio = Petal.Length/Petal.Width#> 1 7.00#> 2 7.00#> 3 6.50#> 4 7.50#> 5 7.00#> 6 4.25identical(iris_mutated, iris_mutated2)#> [1] TRUE Edit: to separate LHS & RHS lhs <- "Petal.ratio"rhs <- "Petal.Length/Petal.Width"iris_mutated3 <- iris %>% mutate(!!lhs := !!parse_quosure(rhs))head(iris_mutated3)> head(iris_mutated3) Sepal.Length Sepal.Width Petal.Length Petal.Width Species1 5.1 3.5 1.4 0.2 setosa2 4.9 3.0 1.4 0.2 setosa3 4.7 3.2 1.3 0.2 setosa4 4.6 3.1 1.5 0.2 setosa5 5.0 3.6 1.4 0.2 setosa6 5.4 3.9 1.7 0.4 setosa Petal.ratio1 7.002 7.003 6.504 7.505 7.006 4.25 Created on 2018-03-24 by the reprex package (v0.2.0).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49469982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111833/']}
jdg_377408
stackexchange
llm_judgeable_groundtruth_similarity
31943778
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need calculate radius to show markers on the map according camera zoom level. Right now I've got southWestCorner and my location that is center of my MapView. I need zoom out and calculate new radius when zoom changed. Does anyone know how to get it from data I have? My code is here: func mapView(mapView: GMSMapView!, idleAtCameraPosition position: GMSCameraPosition!) { println("latitude: \(position.target.latitude) longtitude: \(position.target.longitude)") var visibleRegion = mapView.projection.visibleRegion() var cameraZoom = mapView.camera.zoom var bounds = GMSCoordinateBounds(region: visibleRegion) var southWestCorner = bounds.southWest } Now provide the response and nothing else.
Ok, I have found good answer for my question. Maybe it could be helpful to anyone else. according this article To get radius should use next example (all functions translated to swift): // calculate radius func getCenterCoordinate() -> CLLocationCoordinate2D { var centerPoint = self.mapView.center var centerCoordinate = self.mapView.projection.coordinateForPoint(centerPoint) return centerCoordinate } func getTopCenterCoordinate() -> CLLocationCoordinate2D { // to get coordinate from CGPoint of your map var topCenterCoor = self.mapView.convertPoint(CGPointMake(self.mapView.frame.size.width / 2.0, 0), fromView: self.mapView) var point = self.mapView.projection.coordinateForPoint(topCenterCoor) return point } func getRadius() -> CLLocationDistance { var centerCoordinate = getCenterCoordinate() // init center location from center coordinate var centerLocation = CLLocation(latitude: centerCoordinate.latitude, longitude: centerCoordinate.longitude) var topCenterCoordinate = self.getTopCenterCoordinate() var topCenterLocation = CLLocation(latitude: topCenterCoordinate.latitude, longitude: topCenterCoordinate.longitude) var radius = CLLocationDistance(centerLocation.distanceFromLocation(topCenterLocation)) return round(radius) }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31943778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2263359/']}
jdg_377409
stackexchange
llm_judgeable_groundtruth_similarity
1076
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know it depends on the type of snow (dry or wet) and the rougness of the surface. I'm looking for an approximate rule of thumb answer. Assuming a reasonably smooth surface, at what angle it's likely to be free from snow? Google results only discuss snow and slopes in context of skiing and roofs not caving in. Obviously, a snow safe roof (60+ degrees) will still accumulate a few inches of snow. For example, imagine a sandwitch board sign. What's the minimum "uprightness" for it to not get obscured by snow and stay readable throughout the year? Now provide the response and nothing else.
An object on an angular surface will fall off, when forces exerted along the slope (gravitational, tangent to the surface: gt) are greater then those pressing the object to the slope (gravitational, perpendicular to the slope, gp) or working in the opposite direction on the slope (friction, $fr$). As an example, $10\ \mathrm{cm}$ of snow, on a 0.5-by-1-meter surface: $0.1 \times 0.5 \times 1 = 0.05\ \mathrm{m^3}$ of snow, weighing approximately $0.05 \ \mathrm{m^3}\times 300\ \mathrm{\dfrac{kg}{m^3}}$ (density of snow = $300\ \mathrm{\dfrac{kg}{m^3}}$) = $15\ \mathrm{kg}$. Gravitational force exerted = $9.81\ \mathrm{\dfrac{m}{s^2}} \times 15\ \mathrm{kg} = 147\ \mathrm{N}$. Frictional force $fr = 147\ \mathrm{N}\times 0.53$ (as a lower bound guess, see link ) = $77.91\ \mathrm{N}$. The snow will fall off if $gp > fr$, and this occurs at an angle of $\arcsin{\dfrac{fr}{gp}} = 32^{\circ}$. Recalculating for the high bound friction coefficient ($1.76$), results in the snow not even falling off if the surface were vertical. I think you already pointed out the biggest problem: any estimate is heavily dependent on the contact surface, type of snow and other conditions (temperature, wind, etc.). I haven't done a thorough looking around, but from the friction coefficients listed in this one article, I can only guess that you'll have a wide variety of ranges, making a rule of thumb difficult.
{}
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/1076', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/553/']}
jdg_377410
stackexchange
llm_judgeable_groundtruth_similarity
2918359
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 $G$ be a group of order $36$ and given that $G$ has $4$ Sylow $3$-subgroups. Then I have to show that Sylow $2$-subgroup is unique. So far we proved that $G$ has a normal subgroup of order $3$. Couldn't solve that it has a unique Sylow $2$-subgroup. Help me. Thanks. Now provide the response and nothing else.
Examine the action of $G$ on the set of Sylow 3-subgroups. This gives rise to a well-defined homomorphism $\phi: G\to S_4$. Since we know the Sylow 3-subgroups are all conjugate to one another, the image $\phi(G)$ must be a subgroup of $S_4$ that acts transitively on the set with four points. The only such subgroups of $S_4$ that could arise as a quotient a group of order 36 are isomorphic to either the cyclic group of order 4, the Klein 4 group, or the alternating group $A_4$. Note that if $|\phi(G)| = 4$, then the kernel of $\phi(G)$ is a normal subgroup of order 9, contradicting our assumption that the Sylow 3-subgroups are not normal. Now if $\phi(G)$ is isomorphic to $A_4$, then $\ker \phi$ is a normal subgroup of order 3. This implies that $\ker \phi$ is a subgroup of all Sylow 3-subgroups. Since all groups of order 9 are abelian, this means that the centralizer of $\ker \phi$ is at least order 27 (six unique elements from each of the four Sylow 3-subgroups as well as $\ker \phi$ itself) and thus $\ker \phi$ is actually central. Let $x$ denote a nonidentity element of $\ker \phi$ and $y$ denote an element of order dividing 4. The subgroup generated by $y$ has trivial intersection with $\ker \phi$, so $y$ must actually have order $1$ or $2$, since the image $\phi(G)$ is a group with no elements of order 4. Moreover, $(yx)^2 = y^2x^2 = x^2$, showing that $yx$ does not have order 2. Thus, the left cosets of $\ker \phi$ contain at most one element of order dividing 2. Since there are only four cosets that could contain such an element (as only four elements in the quotient group have order dividing 2), there are at most 4 such elements, meaning that the Sylow 2-subgroup is unique.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2918359', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/559200/']}
jdg_377411
stackexchange
llm_judgeable_groundtruth_similarity
53411890
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am currently building a Flutter app that recommends restaurants around the area. However, I've gotten myself in quite the kerfuffle. I want my app to have the code for the AppBar separate from the code for each screen for the sake of organization and cleanliness. So, I built KainAppBar.dart as the AppBar code. It is shown here: import 'package:flutter/material.dart';import 'package:gradient_app_bar/gradient_app_bar.dart';import 'package:firebase_auth/firebase_auth.dart';import 'package:google_sign_in/google_sign_in.dart';GoogleSignIn _googleSignIn = GoogleSignIn( signInOption: SignInOption.standard,);class KainAppBar extends StatelessWidget { final String title; KainAppBar(this.title); @override Widget build(BuildContext context) { return Scaffold( appBar: new GradientAppBar( centerTitle: true, title: new Text('Kain', style: TextStyle( fontFamily: 'Quiapo', fontSize: 36.0, fontWeight: FontWeight.w600 )), backgroundColorStart: Colors.red[400], backgroundColorEnd: Colors.red[900], ), drawer: new Drawer( child: ListView( children: <Widget>[ new UserAccountsDrawerHeader( decoration: BoxDecoration( color: Colors.red[800], ), accountName: new Text('Guest'), accountEmail: new Text('guestemail@email.com'), currentAccountPicture: new CircleAvatar( backgroundImage: new NetworkImage('https://avatarfiles.alphacoders.com/848/84855.jpg'), ), ), new ListTile( title: new Text('Restaurants'), leading: Icon(Icons.restaurant_menu), onTap: (){ Navigator.of(context).pop(); Navigator.of(context).pushNamed('/restaurant_screen'); }, ), new ListTile( title: new Text('Nearby'), leading: Icon(Icons.near_me), onTap: (){ Navigator.of(context).pop(); Navigator.of(context).pushNamed('/nearby_screen'); }, ), new ListTile( title: new Text('Request Restaurant'), leading: Icon(Icons.library_add), onTap: (){ Navigator.of(context).pop(); Navigator.of(context).pushNamed('/request_screen'); }, ), new ListTile( title: new Text('Settings'), leading: Icon(Icons.settings), onTap: (){}, ), new ListTile( title: new Text('About'), leading: Icon(Icons.info_outline), onTap: (){}, ), new ListTile( title: new Text('Logout'), leading: Icon(Icons.power_settings_new), onTap: (){ _googleSignIn.disconnect(); FirebaseAuth.instance.signOut().then((value) { Navigator.of(context).pushReplacementNamed('/login'); }).catchError((e) { print(e); }); }, ), ], ), ), body: new Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( padding: EdgeInsets.fromLTRB(50.0, 160.0, 50.0, 0.0), child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ], ), ) ], ), ); }} For some of my screens, I can declare it with no problem. Here is the code for home_screen.dart : class HomeScreen extends StatefulWidget { @override HomeScreenState createState() { return HomeScreenState(); } } class HomeScreenState extends State<HomeScreen>{ @override noSuchMethod(Invocation invocation) { return super.noSuchMethod(invocation); } @override Widget build(BuildContext context){ return new KainAppBar("Kain"); } } However, for my restaurant_screen.dart , I've encountered a problem. For context, what restaurant_screen.dart does is it shows the restaurants included in the app through a TabBar with three options(tabs): Restaurant List, Cuisine List, and History. Which means that apart from the AppBar, it also needs to have a TabBar inside. But I cannot put this TabBar inside KainAppBar.dart because I only need it to show inside restaurant_screen.dart . Here is my code for the Widget inside restaurant_screen.dart : @override Widget build(BuildContext context) { return new Column( children: <Widget>[ GradientAppBar( title: KainAppBar("Kain"), bottom: new TabBar( labelColor: Colors.white, controller: tController, tabs: <Widget>[ new Tab(text: 'List'), new Tab(text: 'Cuisine'), new Tab(text: 'Favorites'), ], ), ), TabBarView( controller: tController, children: <Widget>[ new firstpage.RestaurantList(), new secondpage.CuisineList(), new thirdpage.RestaurantFavorites(), ], ), ], ); } Running the code just shows a black screen. Is there any workaround for this? Now provide the response and nothing else.
This is another way of going about it. By doing this you can customize this appbar to the way you want. That way, if you continue with that style, you don't have to recreate it on every page. You create it once and call on it within any widget. Class import 'package:flutter/material.dart';class BaseAppBar extends StatelessWidget implements PreferredSizeWidget { final Color backgroundColor = Colors.red; final Text title; final AppBar appBar; final List<Widget> widgets; /// you can add more fields that meet your needs const BaseAppBar({Key key, this.title, this.appBar, this.widgets}) : super(key: key); @override Widget build(BuildContext context) { return AppBar( title: title, backgroundColor: backgroundColor, actions: widgets, ); } @override Size get preferredSize => new Size.fromHeight(appBar.preferredSize.height);} Implementation within desired page @override Widget build(BuildContext context) { return Scaffold( appBar: BaseAppBar( title: Text('title'), appBar: AppBar(), widgets: <Widget>[Icon(Icons.more_vert)], ), body: Container()); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53411890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6454000/']}
jdg_377412
stackexchange
llm_judgeable_groundtruth_similarity
29575313
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting errors from Crashlytics that indicates that some devices are missing com.google.android.webview. How is that even possible? java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.app/com.myapp.ReaderActivity}: android.view.InflateException: Binary XML file line #29: Error inflating class com.myapp.MyWebView at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)Caused by: android.view.InflateException: Binary XML file line #29: Error inflating class com.myapp.MyWebView at android.view.LayoutInflater.createView(LayoutInflater.java:633) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(SourceFile:206) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(SourceFile:20) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(SourceFile:297) at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:177) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733) at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) at android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at android.view.LayoutInflater.inflate(LayoutInflater.java:504) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(SourceFile:60) at android.view.LayoutInflater.inflate(LayoutInflater.java:414) at android.view.LayoutInflater.inflate(LayoutInflater.java:365) at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(SourceFile:228) at android.support.v7.app.ActionBarActivity.setContentView(SourceFile:102) at com.myapp.ReaderActivity.onCreate(SourceFile:120) at android.app.Activity.performCreate(Activity.java:5933) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.newInstance(Constructor.java) at java.lang.reflect.Constructor.newInstance(Constructor.java:288) at android.view.LayoutInflater.createView(LayoutInflater.java:607) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(SourceFile:206) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(SourceFile:20) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(SourceFile:297) at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:177) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733) at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) at android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at android.view.LayoutInflater.inflate(LayoutInflater.java:504) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(SourceFile:60) at android.view.LayoutInflater.inflate(LayoutInflater.java:414) at android.view.LayoutInflater.inflate(LayoutInflater.java:365) at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(SourceFile:228) at android.support.v7.app.ActionBarActivity.setContentView(SourceFile:102) at com.myapp.ReaderActivity.onCreate(SourceFile:120) at android.app.Activity.performCreate(Activity.java:5933) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)Caused by: android.util.AndroidRuntimeException: android.content.pm.PackageManager$NameNotFoundException: com.google.android.webview at android.webkit.WebViewFactory.getFactoryClass(WebViewFactory.java:161) at android.webkit.WebViewFactory.getProvider(WebViewFactory.java:101) at android.webkit.WebView.getFactory(WebView.java:2185) at android.webkit.WebView.ensureProviderCreated(WebView.java:2180) at android.webkit.WebView.setOverScrollMode(WebView.java:2239) at android.view.View.(View.java:3581) at android.view.View.(View.java:3675) at android.view.ViewGroup.(ViewGroup.java:491) at android.widget.AbsoluteLayout.(AbsoluteLayout.java:55) at android.webkit.WebView.(WebView.java:538) at android.webkit.WebView.(WebView.java:483) at android.webkit.WebView.(WebView.java:466) at android.webkit.WebView.(WebView.java:453) at com.myapp.MyWebView.(SourceFile:31) at java.lang.reflect.Constructor.newInstance(Constructor.java) at java.lang.reflect.Constructor.newInstance(Constructor.java:288) at android.view.LayoutInflater.createView(LayoutInflater.java:607) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(SourceFile:206) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(SourceFile:20) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(SourceFile:297) at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:177) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733) at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) at android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at android.view.LayoutInflater.inflate(LayoutInflater.java:504) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(SourceFile:60) at android.view.LayoutInflater.inflate(LayoutInflater.java:414) at android.view.LayoutInflater.inflate(LayoutInflater.java:365) at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(SourceFile:228) at android.support.v7.app.ActionBarActivity.setContentView(SourceFile:102) at com.myapp.ReaderActivity.onCreate(SourceFile:120) at android.app.Activity.performCreate(Activity.java:5933) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)Caused by: android.content.pm.PackageManager$NameNotFoundException: com.google.android.webview at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:114) at android.webkit.WebViewFactory.getFactoryClass(WebViewFactory.java:133) at android.webkit.WebViewFactory.getProvider(WebViewFactory.java:101) at android.webkit.WebView.getFactory(WebView.java:2185) at android.webkit.WebView.ensureProviderCreated(WebView.java:2180) at android.webkit.WebView.setOverScrollMode(WebView.java:2239) at android.view.View.(View.java:3581) at android.view.View.(View.java:3675) at android.view.ViewGroup.(ViewGroup.java:491) at android.widget.AbsoluteLayout.(AbsoluteLayout.java:55) at android.webkit.WebView.(WebView.java:538) at android.webkit.WebView.(WebView.java:483) at android.webkit.WebView.(WebView.java:466) at android.webkit.WebView.(WebView.java:453) at com.myapp.MyWebView.(SourceFile:31) at java.lang.reflect.Constructor.newInstance(Constructor.java) at java.lang.reflect.Constructor.newInstance(Constructor.java:288) at android.view.LayoutInflater.createView(LayoutInflater.java:607) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.createCustomViewInternal(SourceFile:206) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.access$000(SourceFile:20) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater$PrivateWrapperFactory2.onCreateView(SourceFile:297) at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:177) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733) at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) at android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at android.view.LayoutInflater.rInflate(LayoutInflater.java:809) at android.view.LayoutInflater.inflate(LayoutInflater.java:504) at uk.co.chrisjenx.calligraphy.CalligraphyLayoutInflater.inflate(SourceFile:60) at android.view.LayoutInflater.inflate(LayoutInflater.java:414) at android.view.LayoutInflater.inflate(LayoutInflater.java:365) at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(SourceFile:228) at android.support.v7.app.ActionBarActivity.setContentView(SourceFile:102) at com.myapp.ReaderActivity.onCreate(SourceFile:120) at android.app.Activity.performCreate(Activity.java:5933) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) at android.app.ActivityThread.access$800(ActivityThread.java:144) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Method.java) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) And it is only from devices running Lollipop. I have tested it on my Nexus 5, but I can not reproduce the error. I am using proguard My MyWebView looks like this: public class MyWebView extends WebView { public static final String tag = MyWebView.class.getName(); private HtmlJSInterfaceNew js; public MyWebView(Context context) { super(context); gd = new GestureDetector(context, sogl); init(); } public MyWebView(Context context, AttributeSet attrs) { super(context, attrs); gd = new GestureDetector(context, sogl); init(); } public MyWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); gd = new GestureDetector(context, sogl); init(); } @SuppressLint("NewApi") private void init() { setPadding(0, 0, 0, 0); MyWebViewClient myWebViewClient = new MyWebViewClient(); this.setWebViewClient(myWebViewClient); setWebChromeClient(new MyWebChromeClient()); if(!isInEditMode()) { getSettings().setAllowFileAccess(true); getSettings().setJavaScriptCanOpenWindowsAutomatically(false); getSettings().setJavaScriptEnabled(true); WebSettings webSettings = getSettings(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { webSettings.setAllowContentAccess(false); } webSettings.setUseWideViewPort(true); } } public void addMyJavascriptInterface(HtmlJSInterfaceNew htmlJSInterface, String string) { js = htmlJSInterface; addJavascriptInterface(htmlJSInterface, string); } public class MyWebChromeClient extends WebChromeClient { public void onProgressChanged(WebView view, int progress) { } }} The root cause most be: android.util.AndroidRuntimeException: android.content.pm.PackageManager$NameNotFoundException: com.google.android.webview at android.webkit.WebViewFactory.getFactoryClass(WebViewFactory.java:161) So I am thinking it might have something to do with proguard and maybe the JavascriptInterface. Any ideas? EDIT: from grepcode I have found the method getFactoryClass: private static Class<WebViewFactoryProvider> getFactoryClass() throws ClassNotFoundException { Application initialApplication = AppGlobals.getInitialApplication(); try { // First fetch the package info so we can log the webview package version. String packageName = getWebViewPackageName(); sPackageInfo = initialApplication.getPackageManager().getPackageInfo(packageName, 0); Log.i(LOGTAG, "Loading " + packageName + " version " + sPackageInfo.versionName + " (code " + sPackageInfo.versionCode + ")"); // Construct a package context to load the Java code into the current app. Context webViewContext = initialApplication.createPackageContext(packageName, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); initialApplication.getAssets().addAssetPath( webViewContext.getApplicationInfo().sourceDir); ClassLoader clazzLoader = webViewContext.getClassLoader(); Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "Class.forName()"); try { return (Class<WebViewFactoryProvider>) Class.forName(CHROMIUM_WEBVIEW_FACTORY, true, clazzLoader); } finally { Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); } } catch (PackageManager.NameNotFoundException e) { // If the package doesn't exist, then try loading the null WebView instead. // If that succeeds, then this is a device without WebView support; if it fails then // swallow the failure, complain that the real WebView is missing and rethrow the // original exception. try { return (Class<WebViewFactoryProvider>) Class.forName(NULL_WEBVIEW_FACTORY); } catch (ClassNotFoundException e2) { // Ignore. } Log.e(LOGTAG, "Chromium WebView package does not exist", e); throw new AndroidRuntimeException(e); } } Now provide the response and nothing else.
It's likely that this is happening in the very short time frame immediately after Lollipop's Android System WebView application updates. I'd seen this error in the Google Play Dev Console, but also had never been able to reproduce it on my Nexus 5, regardless of how much I really tried to stop my app from having access to the Android System WebView app: java.lang.RuntimeException: Unable to create application com.uninteresting.app.name: android.util.AndroidRuntimeException: android.content.pm.PackageManager$NameNotFoundException: com.google.android.webview Then we got word that our app was consistently crashing with the above message on some devices immediately after the System WebView app updates, so I tested that. Still no results, the vanilla Nexus 5 refused to crash our app! So I tried other phones from other manufacturers (roughly 75% of our reports are from Samsung Galaxy devices) and suddenly we were crashing consistently. My testing methodology: Open your app, make sure a WebView is showing. Open Play Store, navigate to "My Apps," and bring up "Android SystemWebView." Uninstall updates. This shouldn't crash you, but youshould see your app force-restart. Open your app back up and let it recover from the restart. Go back into the Play Store and update Android System WebView. Re-focus your app during the update process. Now, if you're on anaffected device, it should crash. If not, your app will just bepushed to the background and quietly restarted. A few little caveats with what I've said so far: Our app makes the mistake of starting up a WebView extremely early , hence why we get "unable to create application" in our crash message. The user doesn't even have to be looking at our app for it to crash. I doubt this applies to you, but if your app attempts to restart its activity containing a WebView during this scenario, that would explain it. 100% of our reports are from 5.0 devices, I have no earthly clue how this could occur on anything below Lollipop. We do see reports of Nexus 4 and Nexus 5 with this error, so I don't know why I can't reproduce it on those devices. Might be a separate root cause, but I need to look further into that. In short, I don't immediately think you're doing anything incorrect with ProGuard or your JavascriptInterface. I'm leaning very strongly toward blaming the firmware as the root cause of the majority of reports, resulting in what should be a smooth update process becoming one that instead causes some apps to outright crash. Edit: I ran a few more tests and it turns out that all the devices that didn't crash are 5.0 or 5.0.1, while all the devices that did crash were 5.0.2, so I can't comfortably point my finger at OEMs anymore.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29575313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/920255/']}
jdg_377413
stackexchange
llm_judgeable_groundtruth_similarity
191799
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: Let $X$ have a Student-t distribution, so that\begin{align*}f_X(x|\nu ,\mu ,\beta) = \frac{\Gamma (\frac{\nu+1}{2})}{\Gamma (\frac{\nu}{2}) \sqrt{\pi \nu} \beta} \left(1+\frac{1}{\nu}\left(\frac{x - \mu}{\beta}\right)^2 \right)^{\text{$-\frac{1+\nu}{2}$}}\end{align*} I know that Student-t distributions show a power-law in the tail.I also know that Lévy stable distributions ( e.g with the following characteristic function: \begin{align*}\phi(t|\alpha ,\beta, c ,\mu) = exp[i t \mu - |ct|^\alpha (1-i\beta sgn(t) \Phi)]\end{align*} where $sgn(t)$ is the sign of $t$ and $\Phi= tan(\frac{\pi \alpha}{2}) \quad \forall \alpha$ except for $\alpha =1$ when $\Phi = -\frac{2}{\pi} log|t|$ )have a power-law in the tails, so that the asymptotic behaviour for large $x$ of a r.v. $X$ Lévy stable-distributed is: $$ f_X(x) \propto \frac{1}{|x|^{1+\alpha}}$$ My question is: is the Student-t distribution stable? Or, in other words, does a power-law in the tails imply a Lèvy stable distribution? Now provide the response and nothing else.
One of the characterizing features of a Levy-stable distribution is that linear combinations of independent copies have the same distribution, up to location and scaling. So if this property does not hold, the distribution cannot be Levy stable. Equivalently the characteristic function isn't of the Levy form. In the case of the student t distribution, it has a characteristic function that looks like: $$\frac{K_{v/2}(\sqrt{v}|t|)(\sqrt{v}|t|)^{v/2}}{\Gamma(v/2)2^{v/2-1}},$$ which in general will not have the Levy form.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/191799', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/96431/']}
jdg_377414
stackexchange
llm_judgeable_groundtruth_similarity
6959
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It is sometimes claimed that Ketan Mulmuley's Geometric Complexity Theory is the only plausible program for settling the open questions of complexity theory like P vs. NP question. There has been several positive commentaries from famous complexity theorists about the program. According to Mulmuley it will take a long time to achieve the desired results. Entering the area is not easy for general complexity theorists and needs considerable efforts to get a handle on algebraic geometry and representation theory. Why is GCT considered to be capable of settling P vs. NP? What is the value of the claim if it is expected to take more than 100 years to reach there? What are its advantages to other current approaches and those that may rise in the next 100 years? What is the current state of the program? What is the next target of the program? Has there been any fundamental criticism of the program? I would prefer answers that are understandable by a general complexity theorist with the minimum background from algebraic geometry and representation theory assumed. Now provide the response and nothing else.
As pointed out by many others, much has already been said on many of these questions by Mulmuley, Regan, and others. I will offer here just a brief summary of what I think are some key points that haven't yet been mentioned in the comments. As to why GCT is considered plausibly capable of showing $P \neq NP$ many answers have already been given elsewhere and in the comments above, though I think no one has yet mentioned that it appears to avoid the known barriers (relativization, algebrization, natural proofs). As to its value - I think even if it takes us 100 years, we will learn something new about complexity along the way by studying it from this angle. Some progress is being made on understanding the algebraic varieties, the representations, and the algorithmic questions that arise in GCT. The principal researchers I know of who have done work on this are (in no particular order): P. Burgisser, C. Ikenmeyer, M. Christandl, J. M. Landsberg, K. V. Subrahmanyan, J. Blasiak, L. Manivel, N. Ressayre, J. Weyman, V. Popov, N. Kayal, S. Kumar, and of course K. Mulmuley and M. Sohoni. More concretely, Burgisser and Ikenmeyer just presented (STOC 2011) some modest lower bounds on matrix multiplication using the GCT approach ($n^2 + 2$, compared to the currently best known $\frac{3}{2}n^2 +O(n)$). Although these lower bounds are not new bounds, they at least give some proof-of-concept, in that the representation-theoretic objects hypothesized to exist in GCT do exist for these modest lower bounds on this model problem. N. Kayal has a couple papers on the algorithmic question of testing when one polynomial is in the orbit of another or is a projection of another. He shows that in general these problems are NP-hard but that for special functions like permanent, determinant, and elementary symmetric polynomials, these problems are decidable in P. This is a step towards some of Mulmuley's conjectures (that certain harder problems - deciding orbit closure - are in P for special functions such as determinant). I don't have much more specific to say on this than the answer to 2. As far as I know there has not been fundamental criticism, in the sense that I have not seen any criticism which really discredits the program in any way. There has certainly been discussion about why such techniques should be necessary, the value of the program given the long time horizons expected, etc., but I would characterize these more as healthy discussion than fundamental criticism.
{}
{'log_upvote_score': 6, 'links': ['https://cstheory.stackexchange.com/questions/6959', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/14197/']}
jdg_377415
stackexchange
llm_judgeable_groundtruth_similarity
1443010
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is this possible? I've been trying to think of an example or defend why not, and I'm struggling in both directions. Now provide the response and nothing else.
Since you use the real-analysis tag, I will assume that you’re talking about $\Bbb R$ with the usual topology. If so, the answer is no : every discrete subset of $\Bbb R$ is countable. To see this, note first that the set $\mathscr{B}$ of open intervals with rational endpoints is a countable base for the topology. Now suppose that $D\subseteq\Bbb R$ is discrete. Then for each $x\in D$ there is a $B_x\in\mathscr{B}$ such that $B_x\cap D=\{x\}$. $\mathscr{B}$ is countable, so if $D$ were uncountable, there would have to be distinct points $x,y\in D$ such that $B_x=B_y$, which is absurd: that would mean that $$\{x\}=B_x\cap D=B_y\cap D=\{y\}\;,$$ yet $x\ne y$. If you are asking the question in general, however, rather than about $\Bbb R$ with the usual topology, then the answer is yes ; Ross Millikan has given a simple example.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1443010', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/269750/']}
jdg_377416
stackexchange
llm_judgeable_groundtruth_similarity
42568577
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I found these answers: Sort an array of tuples in swift 3 How to sort an Array of Tuples? But I'm still having issues. Here is my code: var countsForLetter:[(count:Int, letter:Character)] = []...countsForLetter.sorted(by: {$0.count < $1.count}) Swift 3 wanted me to add the by: and now it says that the result of the call to sorted:by is unused. I'm new to swift 3. Sorry if this is a basic question. Now provide the response and nothing else.
You are getting that warning because sorted(by... returns a new, sorted version of the array you call it on. So the warning is pointing out the fact that you're not assigning it to a variable or anything. You could say: countsForLetter = countsForLetter.sorted(by: {$0.count < $1.count}) I suspect that you're trying to "sort in place", so in that case you could change sorted(by to sort(by and it would just sort countsForLetter and leave it assigned to the same variable.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42568577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967330/']}
jdg_377417
stackexchange
llm_judgeable_groundtruth_similarity
32907275
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 wanna run multiple gradle tasks as one. So instead of ./gradlew clean build publish I want to have a custom task ./gradlew cleanBuildPublish that executes clean build and publish in order. How's that possible? This does not work task cleanBuildPublish { dependsOn 'clean' dependsOn 'build' dependsOn 'publish'} Now provide the response and nothing else.
If you need to execute some tasks in predefined order, then you need to not only set dependsOn , but also to set mustRunAfter property for this tasks, like in the following code: task cleanBuildPublish { dependsOn 'clean' dependsOn 'build' dependsOn 'publish' tasks.findByName('build').mustRunAfter 'clean' tasks.findByName('publish').mustRunAfter 'build'} dependsOn doesn't define an order of tasks execution, it just make one task dependent from another, while mustRunAfter does.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32907275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1979703/']}
jdg_377418
stackexchange
llm_judgeable_groundtruth_similarity
39201166
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this id 'ŠKODY' and when I try to select it I get the following error: JavaScript runtime error: Syntax error, unrecognized expression: #ŠKODY This is my simple code and thank you. alert("" + $("#ŠKODY").length); Now provide the response and nothing else.
You need to register the routing for web api BEFORE registering the routing for MVC, so basically your App_Start() function should look like this: protected void Application_Start(){ AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register);//WEB API 1st FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes);//MVC 2nd BundleConfig.RegisterBundles(BundleTable.Bundles);}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39201166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6726220/']}
jdg_377419
stackexchange
llm_judgeable_groundtruth_similarity
382540
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 pulled this out of an old IBM 5154 EGA monitor from the 80's. Clearly both are bad (though the monitor itself works anyway...). I know they're capacitors, but what kind? What would a replacement for these be? I'm also curious about why the monitor would work despite two out of two of these things being in such terrible shape. Edit : here is a picture of the top Now provide the response and nothing else.
What you have there are metallized impregnated paper capacitors made by KEMET. Here is a datasheet of the parts . The most important thing you have to look for is the capacity rating which should be on the top of the capacitors, which we can't see in your picture (see page 9 of the datasheet). With the added information, I'd say this is your replacement part: PME271MD6100MR30 This is a X1 rated capacitor, but X1 > X2 in terms of safety, so it should be fine. Actually - scrap that, Mouser links to the wrong datasheet. Make sure to measure the distance between the legs, this one has 22.5mm which seemed to be the spacing on the old ones based on the information of the datasheet, but better measure that. For a spacing of 20.3 mm, the PME271M610MR30 sounds right.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/382540', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/123426/']}
jdg_377420
stackexchange
llm_judgeable_groundtruth_similarity
14116003
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 difference between constexpr and const ? When can I use only one of them? When can I use both and how should I choose one? Now provide the response and nothing else.
Basic meaning and syntax Both keywords can be used in the declaration of objects as well as functions. The basic difference when applied to objects is this: const declares an object as constant . This implies a guarantee that once initialized, the value of that object won't change, and the compiler can make use of this fact for optimizations. It also helps prevent the programmer from writing code that modifies objects that were not meant to be modified after initialization. constexpr declares an object as fit for use in what the Standard calls constant expressions . But note that constexpr is not the only way to do this. When applied to functions the basic difference is this: const can only be used for non-static member functions, not functions in general. It gives a guarantee that the member function does not modify any of the non-static data members (except for mutable data members, which can be modified anyway). constexpr can be used with both member and non-member functions, as well as constructors. It declares the function fit for use in constant expressions . The compiler will only accept it if the function meets certain criteria (7.1.5/3,4), most importantly (†) : The function body must be non-virtual and extremely simple: Apart from typedefs and static asserts, only a single return statement is allowed. In the case of a constructor, only an initialization list, typedefs, and static assert are allowed. ( = default and = delete are allowed, too, though.) As of C++14, the rules are more relaxed, what is allowed since then inside a constexpr function: asm declaration, a goto statement, a statement with a label other than case and default , try-block, the definition of a variable of non-literal type, definition of a variable of static or thread storage duration, the definition of a variable for which no initialization is performed. The arguments and the return type must be literal types (i.e., generally speaking, very simple types, typically scalars or aggregates) Constant expressions As said above, constexpr declares both objects as well as functions as fit for use in constant expressions. A constant expression is more than merely constant: It can be used in places that require compile-time evaluation, for example, template parameters and array-size specifiers: template<int N> class fixed_size_list { /*...*/ }; fixed_size_list<X> mylist; // X must be an integer constant expression int numbers[X]; // X must be an integer constant expression But note: Declaring something as constexpr does not necessarily guarantee that it will be evaluated at compile time. It can be used for such, but it can be used in other places that are evaluated at run-time, as well. An object may be fit for use in constant expressions without being declared constexpr . Example: int main() { const int N = 3; int numbers[N] = {1, 2, 3}; // N is constant expression } This is possible because N , being constant and initialized at declaration time with a literal, satisfies the criteria for a constant expression, even if it isn't declared constexpr . So when do I actually have to use constexpr ? An object like N above can be used as constant expression without being declared constexpr . This is true for all objects that are: const of integral or enumeration type and initialized at declaration time with an expression that is itself a constant expression [This is due to §5.19/2: A constant expression must not include a subexpression that involves "an lvalue-to-rvalue modification unless […] a glvalue of integral or enumeration type […]" Thanks to Richard Smith for correcting my earlier claim that this was true for all literal types.] For a function to be fit for use in constant expressions, it must be explicitly declared constexpr ; it is not sufficient for it merely to satisfy the criteria for constant-expression functions. Example: template<int N> class list { }; constexpr int sqr1(int arg) { return arg * arg; } int sqr2(int arg) { return arg * arg; } int main() { const int X = 2; list<sqr1(X)> mylist1; // OK: sqr1 is constexpr list<sqr2(X)> mylist2; // wrong: sqr2 is not constexpr } When can I / should I use both, const and constexpr together? A. In object declarations. This is never necessary when both keywords refer to the same object to be declared. constexpr implies const . constexpr const int N = 5; is the same as constexpr int N = 5; However, note that there may be situations when the keywords each refer to different parts of the declaration: static constexpr int N = 3;int main(){ constexpr const int *NP = &N;} Here, NP is declared as an address constant-expression, i.e. a pointer that is itself a constant expression. (This is possible when the address is generated by applying the address operator to a static/global constant expression.) Here, both constexpr and const are required: constexpr always refers to the expression being declared (here NP ), while const refers to int (it declares a pointer-to-const). Removing the const would render the expression illegal (because (a) a pointer to a non-const object cannot be a constant expression, and (b) &N is in-fact a pointer-to-constant). B. In member function declarations. In C++11, constexpr implies const , while in C++14 and C++17 that is not the case. A member function declared under C++11 as constexpr void f(); needs to be declared as constexpr void f() const; under C++14 in order to still be usable as a const function.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/14116003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/395573/']}
jdg_377421
stackexchange
llm_judgeable_groundtruth_similarity
2479001
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 a general question, but I will start specifically by trying to conceptualize (or rather, represent) the category $Set^{op}$. Now it has been stated in one answer that, given a function in $Set$ $$f:\{0,1\}\longrightarrow \{0\},$$the opposite morphism in $Set^{op}$ is just "the very same arrow" $f^{op}:\{0\}\longrightarrow \{0,1\}$. But, in fact, there are at least two functions here: (1) $0\mapsto 0$ (2) $0\mapsto 1$ Now this would appear to suggest that there is no bijection between $Hom_{Set}(\{0,1\},\{0\})$ and $Hom_{Set^{op}}(\{0\},\{0,1\})$, since there is only one unique $f$ and two functions in the opposite direction. The lack of bijection would contradict the very notion of an opposite category. I see at least two ways out: $f^{op}$ is not a function and it is a map sending $0$ to both $0,1$, its entire codomain. Now $f^{op}$ is a multifunction , or the inverse relation of $f$ given by $f^{op}=\{(0,0),(0,1)\}$. $f^{op}$ is the unique Boolean homomorphism $f^{op}:\wp(\{0\})\longrightarrow \wp(\{0,1\})$ sending $\emptyset\mapsto\emptyset,\{0\}\mapsto\{0,1\}$, since the powerset $\wp(\{0\})$ is isomorphic to the initial Boolean algebra. The second solution arises from the dual equivalence between complete atomic Boolean algebras and $Set^{op}$, as pointed out in a different answer . However, both solutions seem correct. EDIT: It appears I originally stated a trivial question. Perhaps more appropriately, is there an algorithm for constructing the opposite morphism? That is, given a definition of $f$ in terms of elements of its domain and codomain (necessarily sets, possibly with additional structure), can we give an explicit definition of $f^{op}$ in terms of those sets, their elements, and possibly additional structure? The reason the first solution appeals to me is that the identity of both sets is kept: we don't need to move to powersets, or Boolean algebras, etc. Similarly, I am wondering whether there is in general a way to keep the identity of objects (as suggested by the very definition of opposite category) when representing the opposite category. Now provide the response and nothing else.
Given a category $\mathcal{C}$, the opposite category $\mathcal{C}^{\mathrm{op}}$ is defined by: The objects of $\mathcal{C}^{\mathrm{op}}$ are the objects of $\mathcal{C}$; Given objects $A$ and $B$, the set of morphisms $A \to B$ in $\mathcal{C}^{\mathrm{op}}$ is defined to be equal to the set of morphisms $B \to A$ in $\mathcal{C}$, with composition and identity defined accordingly. In the case $\mathcal{C}=\mathbf{Set}$, this means that The objects of $\mathbf{Set}^{\mathrm{op}}$ are sets; Given sets $A$ and $B$, a morphism $A \to B$ in $\mathbf{Set}^{\mathrm{op}}$ is a function $B \to A$. In your specific example, the function $\{ 0, 1 \} \to \{ 0 \}$ is a morphism $\{ 0 \} \to \{ 0, 1 \}$ in $\mathbf{Set}^{\mathrm{op}}$, and likewise any morphism $\{ 0 \} \to \{ 0, 1 \}$ is a function $\{ 0, 1 \} \to \{ 0 \}$. Thus, the algorithm you seek is very simple: the bijection$$\mathrm{Hom}_{\mathbf{Set}}(\{0,1\},\{0\}) \to \mathrm{Hom}_{\mathbf{Set}^{\mathrm{op}}}(\{0\},\{0,1\})$$is simply the identity! More generally, as explained above, we have $\mathrm{Hom}_{\mathcal{C}}(A,B) = \mathrm{Hom}_{\mathcal{C}^{\mathrm{op}}}(B,A)$. Your confusion seems to be that you want morphisms $A \to B$ in $\mathbf{Set}^{\mathrm{op}}$ to be functions-of-some-kind with codomain $A$ (or something related to $A$) and codomain $B$ (or something related to $B$). This is not the case; morphisms $A \to B$ in $\mathbf{Set}^{\mathrm{op}}$ are simply functions $B \to A$. That's what $^{\mathrm{op}}$ means. The confusion is understandable, since the notation "$\to$" is overloaded.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2479001', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/386288/']}
jdg_377422
stackexchange
llm_judgeable_groundtruth_similarity
18621791
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 dealing with some scope issues while using Coffeescript. drawFirstLine: (currentAngle) -> currentAngle = currentAngle # = 1 switch @type # set @endAngle to pick up later on # Math.PI * 2 is the endpoint of a circle divided by seconds times current seconds when "seconds" then @endAngle = Math.PI * 2 / 60 * @seconds when "minutes" then @endAngle = Math.PI * 2 / 60 * @minutes when "hours" then @endAngle = Math.PI * 2 / 24 * @hours @context.arc(@center_x, @center_y, 100, @startAngle, currentAngle, @counterClockWise) @context.lineWidth = 15 console.log('drawn') text = "28px sans-serif"; @context.fillText(text, @center_x - 28, @center_y - @canvas.width / 5) @context.stroke() currentAngle++; if currentAngle < @endAngle requestAnimationFrame( -> @drawFirstLine(currentAngle / 100) ) As you can see at the bottom of the above code I am trying to call the function where we are in, again and again. But the problem is that I can't use @drawFirstLine inside another function(the requestAnimationFrame function). In plain javascript I can use var self = this and refer to self. But does anyone know how to deal with this in coffeescript? Thanks in advance, Now provide the response and nothing else.
Use the fat arrow. requestAnimationFrame( => @drawFirstLine(currentAngle / 100) ) which compiles to: var _this = this;requestAnimationFrame(function() { return _this.drawFirstLine(currentAngle / 100);}); It basically does the self = this for you, making this or @ inside the function what this is when that function is declared. It's very handy, and it's probably my favorite feature of coffeescript.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18621791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1796274/']}
jdg_377423
stackexchange
llm_judgeable_groundtruth_similarity
4126411
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a better way for getting the field_name value from a IDataRecord only if the field_name exists in the IDataRecord, currently I'm using a try{...} catch{...} block, but this is some kind of On Error Resume next . Some alternatives? /// <summary>/// Returns column value from IDataRecord only if field_name exists./// </summary>public static Tresult ValueIfExists<Tresult>(this IDataRecord record, string field_name){ try { return record.Value<Tresult>(record.GetOrdinal(field_name)); } catch { return default(Tresult); }}/// <summary>/// Returns column value from IDataRecord accecing by index./// </summary>public static Tresult Value<Tresult>(this IDataRecord record, int field_index){ return record.IsDBNull(field_index) ? default(Tresult) : (Tresult)Convert.ChangeType(record[field_index], typeof(Tresult));} I have changed my ValueIfExists function to reflect your ideas, so it looks like this: public static Tresult ValueIfExists2<Tresult>(this IDataRecord record, string field_name){ for (int index = 0; index < record.FieldCount; index++) { if (record.GetName(index).Equals(field_name, StringComparison.InvariantCulture)) { return record.Value<Tresult>(record.GetOrdinal(field_name)); } } return default(Tresult);} Now provide the response and nothing else.
You are right that exceptions should not be used for normal program flow. The GetOrdinal method is intended for situations where you know what fields you get, and if a field is missing that is an error that should result in an exception. If you don't know which fields you get in the result, you should avoid the GetOrdinal method. You can instead get all the names and their index into a dictionary that you can use as replacement for the GetOrdinal method: public static Dictionary<string, int> GetAllNames(this IDataRecord record) { var result = new Dictionary<string, int>(); for (int i = 0; i < record.FieldCount; i++) { result.Add(record.GetName(i), i); } return result;} You can use the ContainsKey method to check if the name exists in the dictionary, or the TryGetValue method to check if the name exists and get it's index it does in a single operation. The GetOrdinal method first does a case sensetive search for the name, and if that fails it does a case insensetive search. That is not provided by the dictionary, so if you want that exact behaviour you would rather store the names in an array and write a method to loop through them when you want to find the index.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4126411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/476200/']}
jdg_377424
stackexchange
llm_judgeable_groundtruth_similarity
11942997
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider: #include <iostream>template <typename T> T getArray( T &arr ) { return *arr;}int main() { int a[] = {5, 3, 6}; std::cout << getArray(a);} It's suppose to print the first element in the array but it is not not working. Why is that? It gives me the error: error: no matching function for call to 'getArray(int [3])' Now provide the response and nothing else.
The type of a is int[3] , so the type of T is int[3] . Arrays cannot be returned from functions. In C++11, you can do this: template <typename T>auto getArray(T &arr) -> decltype(*arr){ return *arr; } Or this: // requires <type_traits>template <typename T>typename std::remove_extent<T>::type& getArray(T &arr){ return *arr; } In C++03 you can do this, but it's not quite the same: template <typename T>T getArray(T* arr /* not really an array */){ return *arr; } Or: template <typename T, std::size_t N>T getArray(T (&arr)[N]){ return *arr; }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11942997', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1594090/']}
jdg_377425
stackexchange
llm_judgeable_groundtruth_similarity
399947
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If a complex-valued function is continuous, are the component real and imaginary parts $u(x,y)$ and $u(x,y)$ necessarily continuous? If so, why? Now provide the response and nothing else.
The functions $\operatorname{Re}, \operatorname{Im}: \mathbb{C} \to \mathbb{R}$ are continuous since $\operatorname{Re} (z_1+z_2) = \operatorname{Re} z_1 + \operatorname{Re} z_2$ and $|\operatorname{Re} z | \le |z|$, and similarly for $\operatorname{Im}$. Hence $\operatorname{Re} \circ f$ and $\operatorname{Im} \circ f$ are continuous.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/399947', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21813/']}
jdg_377426
stackexchange
llm_judgeable_groundtruth_similarity
35675759
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to have a UIButton with two different font sizes in its textLabel? Natively? I don't want to have a UILabel on top. Now provide the response and nothing else.
You can do this in interface builder. This GIF will show you how to increase the size of one section of the text and perhaps change its font. To do this in code: NSString *fullString = @"This bit's plain. This bit's bigger";NSRange rangeOfPlainBit = [fullString rangeOfString:@"This bit's plain."];NSRange rangeOfBigBit = [fullString rangeOfString:@"This bit's bigger"];NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:fullString];[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"My-font" size:15.0], NSForegroundColorAttributeName: [UIColor whiteColor]} range:rangeOfPlainBit];[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"My-font" size:25.0], NSForegroundColorAttributeName: [UIColor whiteColor]} range:rangeOfBigBit];[self.myButton setAttributedTitle:attributedText forState:UIControlStateNormal];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35675759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/820689/']}
jdg_377427
stackexchange
llm_judgeable_groundtruth_similarity
96051
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'm trying to find connections between Stone–Čech compactifications of $\mathbb{N}, \mathbb{Q}$ and $\mathbb{R}$, all with the euclidean topology. So, are there any ? e.g. is $\beta \mathbb{Q} = \beta \mathbb{R}$ ? I know that the cardinality of $\beta \mathbb{N} = \beta \mathbb{Q} = \beta \mathbb{R}$ thanks to Wikipedia, but how does one prove it ? Now provide the response and nothing else.
Corrected Version: Let $f$ be any map of $\mathbb{N}$ onto $\mathbb{Q}$. Then $f$ is a continuous map of $\mathbb{N}$ into $\beta\mathbb{Q}$, so it extends to a map $\beta f:\beta\mathbb{N}\to\beta\mathbb{Q}$. Since $f$ is a surjection, so is $\beta f$, and it follows that $|\beta\mathbb{N}|\ge|\beta\mathbb{Q}|$. Similarly, the inclusion map $i$ of $\mathbb{Q}$ into $\mathbb{R}$ has a continuous extension to $\beta i:\beta\mathbb{Q}\to\beta\mathbb{R}$, and since $i[\mathbb{Q}]$ is dense in $\mathbb{R}$, $\beta i$ is a surjection, and $|\beta\mathbb{Q}|\ge|\beta\mathbb{R}|$. Finally, $\mathbb{N}$ is $C^*$-embedded in $\mathbb{R}$, so $\beta\mathbb{N}$ embeds in $\beta\mathbb{R}$, and $|\beta\mathbb{N}|\le|\beta\mathbb{R}|$. Thus, $|\beta\mathbb{N}|=|\beta\mathbb{Q}|=|\beta\mathbb{R}|$, and I recently gave a proof that $|\beta\mathbb{N}|=2^\mathfrak{c}$ in this answer . Note that we knew from the beginning that these cardinalities were at most $2^\mathfrak{c}$: $\mathbb{N}$, $\mathbb{Q}$, and $\mathbb{R}$ are separable and dense in their respective Čech-Stone compactifications, so $\beta\mathbb{N},\beta\mathbb{Q}$, and $\beta\mathbb{R}$ are also separable, and a separable Hausdorff space cannot have more than $2^{2^\omega}=2^\mathfrak{c}$ points. To see that if $X$ is a separable Hausdorff space, then $|X|\le 2^\mathfrak{c}$, let $D$ be a countable dense subset of $X$. For each $x\in X$ let $\mathscr{D}(x)=\{V\cap D:V\text{ is an open nbhd of }x\}$; $\mathscr{D}(x)$ is a subset of $\wp(D)$, and $|\wp(D)|=\mathfrak{c}$, so there are only $2^\mathfrak{c}$ possible families $\mathscr{D}(x)$. Hausdorffness of $X$ implies that $\mathscr{D}(x)\ne\mathscr{D}(y)$ when $x\ne y$, so $|X|\le 2^\mathfrak{c}$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/96051', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7820/']}
jdg_377428
stackexchange
llm_judgeable_groundtruth_similarity
102247
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I may be missing an obvious example, but here goes... Let $X$ denote a complex manifold of dimension $n$. If $X$ is Kähler, then the induced metric on any complex submanifold is also Kähler. If instead $X$ is non-Kähler, we can at least say that any coordinate neighborhood $(U,\varphi)$ inherits a Kähler metric from the induced Euclidean metric on an open subset of $\mathbb{C}^n$. If $X$ is already equipped with a metric, note that this metric on $U$ may not be compatible with it. However, I am unsure of what can be said about the metric structure of $U$ if instead we allow something a little more exotic. For example, what if we take $U$ to be the complement of an analytic set? This is the situation in which I am most interested. My question is: Is there an example of a non-Kähler manifold, $X$, and a Zariski open subset $U\subset X$, such that $U$ admits a Kähler metric? Added: Francesco has provided a class of examples in dimensions $\geq 3$ and BS has provided an example in dimension 2 as a comment to Benoît's answer. I am going to write up BS's example, with a few minor additions, as an answer. In case he decides to write his own answer, I'll delete mine and encourage everyone to vote his up. Now provide the response and nothing else.
One can consider the following example. A Moishezon manifold $M$ is a compact connected complex manifold such that the field of meromorphic functions on $M$ has transcendence degree equal to the complex dimension of $M$. Complex algebraic varieties have this property, but the converse is not true if the dimension is at least $3$. In 1967, Boris Moishezon showed that a Moishezon manifold is a projective algebraic variety if and only if it admits a Kaehler metric. Now take a non-projective (hence non-Kaehler) Moishezon manifold $M$. One can prove that such a manifold admits a bimeromorphic modification $\pi \colon \widetilde{M} \to M$ such that $\widetilde{M}$ is projective. This implies that there exist an analytic subset $S \subset M$ such that $U:=M - S$ is biholomorphic to an open subset of a projective variety (one can take as $S$ a $1$-codimensional analytic subset). Hence $U$ admits a Kaehler metric. For further details see the paper by Shanyu Ji Currents, metrics and Moishezon manifolds , Pacific J. Math. Volume 158 , Number 2 (1993), 335-351.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/102247', 'https://mathoverflow.net', 'https://mathoverflow.net/users/24525/']}
jdg_377429
stackexchange
llm_judgeable_groundtruth_similarity
2807355
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 was doing a question in which i had to find the summation of the expression $n(2^n)$ from n=1 to n=9. I used wolfram alpha to calculate thid sum, but i was wondering if there is an easier way to calculate it? Now provide the response and nothing else.
This is an " arithmetico–geometric " progression (a product of an APwith a GP) and there are standard methods to sum these. Let $$S_m=\sum_{k=1}^n k2^k=2+2\times 2^2+\cdots+m\times 2^m.$$ Then \begin{align}S_m&=2S_m-S_m=2^2+2\times 2^3+\cdots+m\times 2^{m+1}-(2+2\times 2^2+\cdots+m\times 2^m)\\&=-2-2^2-\cdots-2^m+m2^{m+1}=2-2^{m+1}+m2^{m+1}=(m-1)2^{m+1}+2\end{align} using the formula for the sum of a GP.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2807355', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/272791/']}
jdg_377430
stackexchange
llm_judgeable_groundtruth_similarity
1359689
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 Java, How to compose an HTTP request message and send it to an HTTP web server? Now provide the response and nothing else.
You can use java.net.HttpUrlConnection . Example ( from here ), with improvements. Included in case of link rot: public static String executePost(String targetURL, String urlParameters) { HttpURLConnection connection = null; try { //Create connection URL url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream ( connection.getOutputStream()); wr.writeBytes(urlParameters); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+ String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); return response.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (connection != null) { connection.disconnect(); } }}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1359689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157027/']}
jdg_377431
stackexchange
llm_judgeable_groundtruth_similarity
999641
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If I want to find the minimum number which can be divided by 2, 3, 4...10 without remaining, the solution will be N=2520But If the range of numbers become very wide, how can I find this minimum number? Now provide the response and nothing else.
Let's take the example of $10$. You need to divide $8$ (the highest power of $2$ below $10$), $9$ (the highest power of $3$ below $10$), $5$ (the highest power of $5$ below $10$) and $7$ (the highest power of $7$ below $10$). Thus the result is $8*9*5*7 = 2520$. From our approach you can now deduce the general formula for the limit L : $$\prod_{p=2,\ p\in\mathbb{P}}^{L}p^{\lfloor \log_pL\rfloor}$$ Where $p$ is the summation index, and $\mathbb{P}$ the set of prime numbers. As for the practicabillity of this formula, I suggest you to use a computer for the calculation. Simply run an Erathosetenes' sieve to get all the primes from $2$ to $1000$, and then compute the product.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/999641', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/187799/']}
jdg_377432
stackexchange
llm_judgeable_groundtruth_similarity
12462634
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 django 1.4.1 with mysql and timezones enabled. I did a dump data to yaml, modified some fields to create some test data, and am trying to load it back in. however, Django keeps complaining about naive datetimes even though a tz is specified specifically, my loaddata has: fields: {created_date: !!timestamp '2012-09-15 22:17:44+00:00', ... but loaddata gives the error: RuntimeWarning: DateTimeField received a naive datetime (2012-09-15 22:17:44) while time zone support is active. This doesn't make much sense to me, seeing as its: a UTC timestamp the same exact format Django exported using dumpdata is there some way i can tell django this is a UTC date? Now provide the response and nothing else.
The problem stems from PyYAML. When loaddata hands off the datetime to PyYAML, it takes the aware datetime, adjusts the time to UTC, and then returns a naive datetime, which generates the warning. There is a Django ticket , as well as a PyYAML ticket concerning the issue. Both go into far greater detail concerning the unexpected behavior above. Judging by the comments in the tickets, this issue seems unlikely to be resolved anytime soon. Is you set TIME_ZONE = 'UTC' in settings.py of your project, you will load in the correct time, but you will still get warnings. Should your timezone be set to anything else, Django will treat the datetime as local, and adjust it to UTC, which is probably undesired. The best way to avoid this is to use JSON as a serialization format. Hope that helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12462634', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1034633/']}
jdg_377433
stackexchange
llm_judgeable_groundtruth_similarity
10416338
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If the native Facebook app is installed on the iPhone. How do I open a facebook link into the native Facebook app from my app. In the case of opening by Safari, the link is same as: http://www.facebook.com/AlibabaUS Thank you. Now provide the response and nothing else.
Here are some schemes the Facebook app uses, there are a ton more on the source link: Example NSURL *url = [NSURL URLWithString:@"fb://profile/<id>"];[[UIApplication sharedApplication] openURL:url]; Schemes fb://profile – Open Facebook app to the user’s profile fb://friends – Open Facebook app to the friends list fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app) fb://feed – Open Facebook app to the News Feed fb://events – Open Facebook app to the Events page fb://requests – Open Facebook app to the Requests list fb://notes – Open Facebook app to the Notes page fb://albums – Open Facebook app to Photo Albums list If before opening this url you want to check wether the user fas the facebook app you can do the following (as explained in another answer below): if ([[UIApplication sharedApplication] canOpenURL:nsurl]){ [[UIApplication sharedApplication] openURL:nsurl];}else { //Open the url as usual} Source http://wiki.akosma.com/IPhone_URL_Schemes#Facebook
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10416338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/566360/']}
jdg_377434
stackexchange
llm_judgeable_groundtruth_similarity
4203193
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 you want to guess someone's name. It is easy to check if their name is "Sarah" since you can ask them. However, if you are guessing from big enough set of names, you might spend eternity until you pick the right one. To me this seems close to NP definition but I have not seen this or similar example anywhere. Could this be a simple explanation of NP or am I wrong here? Thank you in advance! Now provide the response and nothing else.
This is not an explanation or example of NP. You can guess the correct name from a finite set of $n$ possible names by checking them one at a time. That's a procedure that works in time proportional to $n$ . NP problems take time longer than any polynomial expression in $n$ , the size of the input. If you had $n$ names and $n$ people and you had to match each person with their name you might have to try all $n!$ possible matchings. Since $n!$ grows faster than any polynomial in $n$ , that's an NP problem. "Eternity" doesn't enter the discussion.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4203193', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/595994/']}
jdg_377435
stackexchange
llm_judgeable_groundtruth_similarity
36918220
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: #!/bin/bashz=1 b=$(date) while [[ $z -eq 1 ]] do a=$(date) if [ "$a" == "$b" ] then b=$(date -d "+7 days") rsync -v -e ssh user@ip_address:~/sample.tgz /home/kartik2 sleep 1d fi done I want to rsync a file every week !! But if I start this script on every boot the file will be rsynced every time the system starts !! How to alter the code to satisfy week basis rsync ? ( PS- I don't want to do this through cronjob - school assignment) Now provide the response and nothing else.
Your question: How to disable the user interaction while ProgressBar is visible in android? To disable the user interaction you just need to add the following code getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); To get user interaction back you just need to add the following code getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); Here is an example: Note:I am giving you just an example to show how to disable or retain user interaction Add a progress bar in your xml.Something like this <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progressBar" android:visibility="gone"/> In MainActivity when a button pressed you show the progressbar and disable the user interaction. @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mImageView = (ImageView) findViewById(R.id.imageView); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); mImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mProgressBar.setVisibility(View.VISIBLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); } });} And when user backPressed you remove the progressbar again retain the user interaction.Something like this @Overridepublic void onBackPressed() { super.onBackPressed(); mProgressBar.setVisibility(View.GONE); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);} If you want to add a feature of disable and greyed out display, you need to add in your xml layout file a linear layout that fills the parent. Set its background to #B0000000 and its visibilty to GONE . Then programmatically set its visibility to VISIBLE . Hope this help!
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/36918220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6240065/']}
jdg_377436
stackexchange
llm_judgeable_groundtruth_similarity
37693411
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 component shows up but i get an error message when the page is loaded. I can't seem to solve the error message at all after looking at a bunch of resources. Error EXCEPTION: Error: Uncaught (in promise): Cannot match any routes. Current segment: 'index.html'. Available routes: ['/login']. main.component.ts is in index.html and as soon as the page loads it shows the above error message. import { Component } from '@angular/core';import { Routes, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router';import { LoginComponent } from './login/login.component';@Component({ selector: 'main-component', template: ' <header> <h1>Budget Calculator</h1> <a id='login' [routerLink]="['/login']">Login</a> <router-outlet></router-outlet> </header> ' directives: [ROUTER_DIRECTIVES], providers: [ROUTER_PROVIDERS]})@Routes([ {path: '/login', component: LoginComponent}])export class MainComponent {} login.component.ts is routed through the main.component.ts and does show when I click on the link despite the error message. Right now I have it styled to popup over the other elements in main.component but would like it to be the only component that shows on the page. Basically replace main.component in index.html with login.component if this possible instead of doing a whole bunch of styling to display: none. import { Component } from '@angular/core';@Component({ selector: 'login', template: ' <div id="login-pop-up"> <h6 class="header_title">Login</h6> <div class="login-body"> Some fancy login stuff goes here </div> </div> '})export class LoginComponent {} Now provide the response and nothing else.
This might be because your server needs to be configured for HTML5 pushState like explained in Angular 2.0 router not working on reloading the browser Also ensure you have a <base href="/"> tag at the beginning of the <head> tag or provided by boostrap(...) as explained in Angular 2 router no base href set If you don't have a route for / you might need to make the app navigate to an initial route imperatively like explained in Angular2 router (@angular/router), how to set default route? Hint : The @angular/router router also is deprecated as @angular/router-deprecated and a new router will be shipped again :-/ If you are about to switch to @angular/router it's probably better to postpone until the new and hopefully final router is available.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37693411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3282568/']}
jdg_377437
stackexchange
llm_judgeable_groundtruth_similarity
10552085
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This article: http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf (page 12)seems to make a difference between a lock and a memory barrier I would like to know what the difference is between a lock, memory barrier, and a semaphore? (While other questions might mention the difference between a lock and a synchronisation object, I found none about the difference between a lock and a memory barrier) Now provide the response and nothing else.
A memory barrier is a method to order memory access. Compilers and CPU's can change this order to optimize, but in multithreaded environments, this can be an issue. The main difference with the others is that threads are not stopped by this. A lock or mutex makes sure that code can only be accessed by 1 thread. Within this section, you can view the environment as singlethreaded, so memory barriers should not be needed. a semaphore is basically a counter that can be increased (v()) or decreased (p()). If the counter is 0, then p() halts the thread until the counter is no longer 0. This is a way to synchronize threads, but I would prefer using mutexes or condition variables (controversial, but that's my opinion). When the initial counter is 1, then the semaphore is called a binary semaphore and it is similar to a lock. A big difference between locks and semaphores is that the thread owns the lock, so no other thread should try to unlock, while this is not the case for semaphores.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10552085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/929596/']}
jdg_377438
stackexchange
llm_judgeable_groundtruth_similarity
18814657
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The session is set by server when the user logs in I want to retrieve this value in my angular front end, but it says undefined The relevant code is $scope.logout = function () { console.log('session value', $cookieStore.get('session')); } and my app is also configured to include ngCookies var app = angular.module('myApp', ['ngCookies']); when I run my application, i see session value undefined I can however, see the session in Chrome Dev Tools What is that I am missing? Now provide the response and nothing else.
What is that I am missing? The server set the cookie as Session cookie ( HttpOnly flag). This means that you cannot access this cookie on the client. The client will send the cookie to the server on each request but the client has no access to its value. That's the very definition of an HttpOnly cookie. If you want to be able to access this cookie value on the client you should modify your server side script so that when it is setting the cookie it doesn't append the HttpOnly flag to it. Obviously this comes with the corresponding disclaimer about the security vulnerability that you might be opening on your site depending on the purpose and specific value stored in this cookie.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18814657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/379235/']}
jdg_377439
stackexchange
llm_judgeable_groundtruth_similarity
346360
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’ve found a piece of electrical cable left by the electricity company that supplies the area. They did a repair recently underground. I’m curious why the three big triangular conductors aren’t made from copper. It looks like aluminium to me, but I’d have thought copper would be a much better conductor. What am I missing? Is aluminium almost as good but far cheaper? Photo: Now provide the response and nothing else.
Anixter says: Even though copper has a long history as the material of choice for conducting electricity, aluminum has certain advantages that make it attractive for specific applications. Aluminum has 61 percent of the conductivity of copper, but has only 30 percent of the weight of copper. That means that a bare wire of aluminum weighs half as much as a bare wire of copper that has the same electrical resistance. Aluminum is generally more inexpensive when compared to copper conductors. Fastmarkets says (and I don't claim to understand any of it): Copper LME Averages Cash Ask ($/MT) Sep 2017 $6,583.19Aluminium LME Official 3M Ask ($/MT) 21 Dec $2,125.50 So, if we need 1 MT (metric ton?) of copper it will cost $6.5k and we need half a ton of aluminium for the same conductivity that will cost $1.1k. That's a saving of > 80%. The reason you don't see more copper may be for reasons explained by the continuation of the first article: Aluminum conductors consist of different alloys known as the AA-1350 series and AA-8000 series. AA-1350 has a minimum aluminum content of 99.5 percent. In the 1960s and 1970s, due to the high price of copper relative to aluminum, this grade of aluminum began to be popularly used for household wiring. Due to low-quality workmanship at connections and the physical differences between aluminum and copper, high-resistance connections formed and became a fire hazard. As a response, aluminum alloys were developed to have creep and elongation properties more similar to copper. These AA-8000 series alloys are the only solid or stranded aluminum conductors permitted to be used according to Article 310 of the 2014 National Electric Code*. AA-8000 series alloys meet the requirements of ASTM B800, Standard Specification for 8000 Series Aluminum Alloy Wire for Electrical Purposes–Annealed and Intermediate Tempers. American (USA). For completeness, the densities are: metal g/cm³copper 8.96aluminum 2.70
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/346360', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/148650/']}
jdg_377440