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
20923265
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 followed the instructions here yet I couldn't get the linker to work with Jade. If, however I use ejs instead, it does work (exactly the same app, apart from the jade/ejs files of course). Am I missing something? Now provide the response and nothing else.
I'm assuming you have done the following: Created a new project with linker and jade as template sails new <project-name> --template=jade --linker you manually added jade cd <project-name>npm install jade --save (optionally) removed the dependency to ejb in the package.json file. Is that correct? In that case, I've received a warn that says: warn: Automatic asset linking is not implemented for the `jade` view engine at this time. You must modify the Gruntfile yourself for this feature to work. This looks like an old and outdated message, as I looked to the grunt file and everything look like it was prepared for linking to jade. So then, I've changed the layout.jade file in the views folder to: Remove script(src="/js/sails.io.js") and add the placeholders to inject: // SCRIPTS// SCRIPTS END// STYLES// STYLES END Then I made a "sails lift" and the scripts in the javascript files in the public/linker/js folder were injected. BTW: I'm using sails v0.9.9 Hope this helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20923265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1000514/']}
jdg_82541
stackexchange
llm_judgeable_groundtruth_similarity
13207016
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose you have a generic interface: public interface MyInterface<T> { T doSomething();} Is it possible to declare an enum that implements MyInterface<T> , but for which which every enum constant implements it for a different value of T ? That is, given this enum: public enum MyEnum { FOO, BAR, BAZ;} can we change it so that FOO implements MyInterface<Integer> , BAR implements MyInterface<String> , and BAZ implements MyInterface<List<MyOtherType>> , and make it so that MyEnum overall implements MyInterface<?> ? It seems entirely feasible doing this raw, so it may be the case that it can be done in a typesafe manner. Now provide the response and nothing else.
No, as amalloy pointed out , Java doesn't allow enums to be declared with type parameters. It becomes clear why if you think about the way enums are meant to be used, for example in a switch . Also consider how the language would implement generic enums - it isn't trivial. For a generic enum MyEnum<T> , each enum constant would need to resolve T to some specific type, otherwise they wouldn't be constants at all. Consider this: enum MyEnum<T> { FOO; // T is not resolved} What is T for FOO here? The language would need a new syntax just to be able to express it, for example: enum MyEnum<T> { FOO<String>;} So now we're getting into added complexity for the language in order to support semantics that don't have an overly compelling use case. It's easy to see why the language designers would have simply nixed type parameters for enums. The workaround: You can emulate your desired pattern by simply not using an enum. Organize the implementations of your interface into a utility class: public class MyImplementations { public static final MyInterface<Integer> FOO = new MyInterface<Integer>() { ... }; public static final MyInterface<String> BAR = new MyInterface<String>() { ... }; public static final MyInterface<List<MyOtherType>> BAZ = new MyInterface<List<MyOtherType>>() { ... }; private MyImplementations() { }} The only thing inherently missing is a way to iterate over the different implementations, as you could have done with MyEnum.values() - but with a hypothetical MyEnum<T> , the most specific type you could iterate over would be MyEnum<?> .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13207016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1163186/']}
jdg_82542
stackexchange
llm_judgeable_groundtruth_similarity
79360
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have data collected from an experiment organized as follows: Two sites, each with 30 trees. 15 are treated, 15 are control at each site. From each tree, we sample three pieces of the stem, and three pieces of the roots, so 6 level 1 samples per tree which is represented by one of two factor levels (root, stem). Then, from those stem / root samples, we take two samples by dissecting different tissues within the sample, which is represented by one of two factor levels for tissue type (tissue type A, tissue type B). These samples are measured as a continuous variable. Total number of observations is 720; 2 sites * 30 trees * (three stem samples + three root samples) * (one tissue A sample + one tissue B sample). Data looks like this... ï..Site Tree Treatment Organ Sample Tissue Total_Length 1 L LT1 T R 1 Phloem 30 2 L LT1 T R 1 Xylem 28 3 L LT1 T R 2 Phloem 46 4 L LT1 T R 2 Xylem 38 5 L LT1 T R 3 Phloem 103 6 L LT1 T R 3 Xylem 53 7 L LT1 T S 1 Phloem 29 8 L LT1 T S 1 Xylem 21 9 L LT1 T S 2 Phloem 56 10 L LT1 T S 2 Xylem 49 11 L LT1 T S 3 Phloem 41 12 L LT1 T S 3 Xylem 30 I am attempting to fit a mixed effects model using R and lme4, but am new to mixed models. I'd like to model the response as the Treatment + Level 1 Factor (stem, root) + Level 2 Factor (tissue A, tissue B), with random effects for the specific samples nested within the two levels. In R, I am doing this using lmer, as follows fit <- lmer(Response ~ Treatment + Organ + Tissue + (1|Tree/Organ/Sample)) From my understanding (...which is not certain, and why I am posting!) the term: (1|Tree/Organ/Sample) Specifies that 'Sample' is nested within the organ samples, which is nested within the tree. Is this sort of nesting relevant / valid? Sorry if this question is not clear, if so, please specify where I can elaborate. Now provide the response and nothing else.
I think this is correct. (1|Tree/Organ/Sample) expands to/is equivalent to (1|Tree)+(1|Tree:Organ)+(1|Tree:Organ:Sample) (where : denotes an interaction). The fixed factors Treatment , Organ and Tissue automatically get handled at the correct level. You should probably include Site as a fixed effect (conceptually it's a random effect, but it's not practical to try to estimate among-site variance with only two sites); this will reduce the among-tree variance slightly. You should probably include all the data within a data frame, and pass this explicitly to lmer via a data=my.data.frame argument. You may find the glmm FAQ helpful (it's focused on GLMMs but does have stuff relevant to linear mixed models as well).
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/79360', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/36046/']}
jdg_82543
stackexchange
llm_judgeable_groundtruth_similarity
50779
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I can't figure it out what is the problem with my circuit, the segments turning on for sec and then they are turning off for good. I tried to connect to GND instead of the 5 V but then, nothing happened. My code: void setup() { for (int pin = 2 ; pin < 9 ; pin++){ // setup pins 2 – 8 to be output pinMode(pin, OUTPUT); } for (int pin = 2 ; pin < 9 ; pin++){ // turn on pins 2 - 8 digitalWrite(pin, HIGH); }}void loop(){} Working simulation demo Now provide the response and nothing else.
The first thing to understand is how to connect the 7 segment display to your Arduino. The common anode pin connects directly to 5VDC. Each "segment" connects to the Arduino through a current limiting resistor (1k ohm is a good value to start with). To turn a segment on, you supply a ground to it (through the resistor of course). Change: digitalWrite(pin, HIGH) to: digitalWrite(pin, LOW) in your sketch to turn on the segments. I'm sure there are plenty of tutorials on the internet showing one resistor on the common anode input, but that is not the correct way to drive the display. Think about what happens when you display the number 1 VS the number 8. Changing the number of segments drawing power from the single resistor will vary the intensity of the display. The number 1 will be far brighter than the number 8.
{}
{'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/50779', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/43379/']}
jdg_82544
stackexchange
llm_judgeable_groundtruth_similarity
29310688
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't remember where I read this, but either somewhere on here or in the comments of a tutorial I was following, a person said: 'Never never ever use sudo pip install; you could overwrite important stuff without knowing it. Use pip install --user instead!' I see lots of references to sudo pip install everywhere though, so did this person know what they were talking about and I should avoid it, or... ? Now provide the response and nothing else.
$ sudo pip install Installs the package globally in your python installation, i.e. for all users. $ pip install --user Installs to the local user directory, i.e. ~/.local/lib/python -- just you. Example: $ sudo pip install jupyter$ jupyter notebook Will run jupyter, open a web browser, allow you to work with notebooks. $ pip install --user jupyter$ jupyter notebook Will do nothing until your local directory has been added to your PATH. There was recently malicious code included in pypi. Never use sudo to install with pip. This is the same as running a virus as root. Either add your local folder to your PATH or use a virtualenv.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29310688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2917993/']}
jdg_82545
stackexchange
llm_judgeable_groundtruth_similarity
1291792
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The curve $$x^2y^3-3xy^2-9y+9=0$$ is given. I want to determine what points on the curve, for a neighbourhood to said points, $y$ can safely be expressed as a function of $x$. I guess what this means is that I need to find sets $A$ such that for $x_i \in A$ yields one and only one corresponding y-term $y_i$. Furthermore, this means that the y-term in the gradient in every such point is separate from zero, i.e. $$\frac{\partial f}{\partial y} (x_i, y_i) \neq 0$$ where $f$ is the the function $f : x \rightarrow y$. Would this be accurate? Now provide the response and nothing else.
There are 2 behaviours going on here. In your last picture, it's easy to see that all numbers lie on the 6 rays through the origin. Why? This is because there are $2\pi$ radians in a circle, and you are incrementing by $\pi/3$ radians each time (which is 1/6 of the circle). This is why you are getting distinct rays. The other behaviour occurs when you only look at primes. In the second picture (the one consisting of only primes), there is space for 60 rays (since you are incrementing by $\pi/30$ radians, which is 1/60th of a circle each time). So the new question is, why do only 16 rays appear? The answer is that $\varphi(60) = 16$ , meaning that there are only 16 residue classes for primes to fit in mod 60. Stated differently there are only 16 solutions to $p \equiv x \pmod {60}$ in $x$, where $p$ ranges across all the primes. So there are 16 distinguished rays containing primes. Similarly, there are two distinguished rays in the last picture, which is why you can only see primes on 2 of the rays. You might be interested to know that the property of being a ray containing primes will not be origin-symmetric, but mirror-symmetric over the horizontal line $y = 0$. This has to do with how $\gcd(x,n) = \gcd(n-x,n)$, and the order in which you are plotting these rays. To answer your final question, you can plot all primes (except 2) on the same line by using $\pi$ as your increment, or by using $2\pi$ as your increment. The first is equivalent to saying that all primes except $2$ are odd. The second actually puts all numbers on a single line.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1291792', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/233895/']}
jdg_82546
stackexchange
llm_judgeable_groundtruth_similarity
4813914
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 minimize the time needed to retrieve a single unique element from a list.Which one is the fastest method among Find , Single and First ?Note that the searching key is a unique id. Now provide the response and nothing else.
The fastest (for a large set) would be to have them keyed against a Dictionary<TKey,TValue> and use that. Single and First do different things; Single always iterates the entire set, even if it finds it at the start of the list, so First would usually be quicker than Single since it short-circuits.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4813914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397524/']}
jdg_82547
stackexchange
llm_judgeable_groundtruth_similarity
8643276
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently had an interviewer ask to define the difference between objects and primitives. Seemed like an odd question considering that all languages begin with a primitive. How would you have answered this question? I should also note that this interview was for a front-end development position so the language (I assume) he was referring to was JavaScript. Now provide the response and nothing else.
A primitive is a data type that is composed of no other data types and can not be broken down any further. It is like the atoms in the programming scenario. I say atom because atom is a basic unit of matter and there is nothing that can be derived from it. I mean, an int in C can not be broken down into smaller data type. An object, on the other hand can be thought of a molecule, consisting of more than one primitive type. For example, string comes as part of the C++ standard library; however, it is an object and it is composed of smaller data types internally and contains methods. It is important to note that not all object-oriented languages are class based (eg. Javascript) You can not define a class in Javascript, so an object is quite different here. Even though everything in Javascript is an object (Ruby also), the Number object is really a wrapper for an internal primitive.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8643276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/520520/']}
jdg_82548
stackexchange
llm_judgeable_groundtruth_similarity
67122035
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 reading about JWKS and found information about the key rotation concept - https://developer.okta.com/docs/concepts/key-rotation/ Let's assume I use JWKS in my application but I don't fetch them periodically, so just hardcoded.The single key JSON object looks like { "kty": "RSA", "e": "xxx", "use": "sig", "kid": "xxx", "x5t": "xx", "x5c": [ "xxx" ], "n": "xxx} The JWKS provides you the public key so you can validate JWT.Now questions. Is it possible to get information when JWKS expires? For example, can I generate a .cert file using a JWK and open it to check expiration day? Does the JWKS provider expose information when the key rotation is planned or maybe it is sensitive information? And please consider the example above, so I have keys in the application and would like to know when I should replace them. Of course I know that it is bad practice (I should fetched keys directly from JWKS endpoint and feel safe) but this is only an example (if it is a stupid example, please propose a better one just to describe the context). Now provide the response and nothing else.
JSON Web Key Set (JWKS aka JWK Set) is a list of JSON Web Keys (JWKs). Since JWK Set is simply a container, it contains no metadata such as an expiration date/time. It does not expose this for at least two reasons: RFC 7517 is the specification that governs the behavior of JWKs and JWK Set. It does not mention or require the provider to publish an expiration date/time. Perhaps this is so due to reason #2: The provider should be able to remove keys for any reason at any time. Possible reason: key has been compromised. (For a private/public keypair, this would mean the private key has been compromised and the corresponding public key published via JWKS should be removed from circulation). This example is an outlier but it does happen and the provider would have to act immediately to fix it. Emergencies notwithstanding, providers do rotate keys on a regular basis as a matter of good security hygiene. To handle key rotation (be it planned or emergency), your application should adhere to a simple algorithm. It should periodically fetch the keys from JWKS endpoint, build a local replica of all keys and add/remove keys from this replica based on the last fetch. Only keys found in the local replica should be used by your application to perform a cryptographic operation such as verifying a signature on a JWT. Each JWK has a kid (key id) parameter and this parameter is used to match a specific key. RFC 7517 recommends using kid to choose among a set of keys within a JWK Set during key rollover. When your application does a fetch of keys from JWKS, you'll be comparing the set of keys coming from JWKs to the set of keys in your local replica. The comparison is based on kid . If a key with some kid is present in JWKS but not present in your local replica, you should add this key to your replica. Vice versa, if a key with some kid is present in your local replica but not present in JWKS, you should remove this key from your local replica. How frequently should your application fetch the keys from JWKS? This is up to you, it depends on the risk tolerance of your app and/or your organization. Some apps fetch every minute, others do it hourly or daily. Let's say your app never does this fetch, the key is hardcoded in your app. This will work until the key is removed by the provider. (We're assuming that we're talking about a public key here. A JWK could represent a private key...and that you will not want to embed into your app). Some providers don't rotate keys or do so once in a very long while. If you're dealing with a well-known (to you) provider and they guarantee to you that they won't rotate keys, your risk of embedding a key into your app is low. In general, embedding a public key into the app is not a good idea. If you're going to be using a JWKS endpoint, implement a simple fetch + update solution as outlined above.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67122035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12584220/']}
jdg_82549
stackexchange
llm_judgeable_groundtruth_similarity
38692362
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 create action on update and view in controller, but this action does not change on action column in index page public function actionLeadView($id){ $id = $_GET['id']; $model = Leads::findOne($id); return $this->render('viewlead', [ 'model' => $model, ]); } public function actionLeadUpdate($id){ $id = $_GET['id']; $model = Leads::findOne($id); date_default_timezone_set("Asia/Kolkata"); $date = date('Y/m/d H-i-sa'); if ($model->load(Yii::$app->request->post())) { $model->modified = $date; if($model->validate()){ $model->save(); return $this->redirect(['viewlead', 'id' => $model->id]); }else { return $this->render('updatelead', [ 'model' => $model, ]); } } else { return $this->render('updatelead', [ 'model' => $model, ]); }} Now provide the response and nothing else.
[ 'class' => 'yii\grid\ActionColumn', 'header' => 'Actions', 'headerOptions' => ['style' => 'color:#337ab7'], 'template' => '{view}{update}{delete}', 'buttons' => [ 'view' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url, [ 'title' => Yii::t('app', 'lead-view'), ]); }, 'update' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [ 'title' => Yii::t('app', 'lead-update'), ]); }, 'delete' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [ 'title' => Yii::t('app', 'lead-delete'), ]); } ], 'urlCreator' => function ($action, $model, $key, $index) { if ($action === 'view') { $url ='index.php?r=client-login/lead-view&id='.$model->id; return $url; } if ($action === 'update') { $url ='index.php?r=client-login/lead-update&id='.$model->id; return $url; } if ($action === 'delete') { $url ='index.php?r=client-login/lead-delete&id='.$model->id; return $url; } } ],
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38692362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6649838/']}
jdg_82550
stackexchange
llm_judgeable_groundtruth_similarity
32748585
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Normally, you can ssh into a Vagrant-managed VM with vagrant ssh . There are two options: You can use an insecure_private_key generated by Vagrant toauthenticate. Use your own private key - provided that config.ssh.forward_agent is set to true , and the VM isconfigured correctly I use the second option. S when I run vagrant ssh , I ssh into the machine with my custom private key. Now I need to let Ansible SSH into my Vagrant machine and I do not want to use Vagrantfile for it. So I executed: ansible-playbook -i hosts/development --private-key=~/.ssh/id_rsa -u vagrant dev.yml And I have this error returned: fatal: [192.168.50.5] => SSH Error: Permission denied (publickey). while connecting to 192.168.50.5:22 The hosts/inventory file holds just the IP of my Vagrant VM (192.168.50.5). I do not know why Ansible cannot ssh into the VM. It's using exactly the same user ( vagrant ) and key ( id_rsa ) as when executing vagrant ssh . However, there is no problem sshing with vagrant ssh while the above would not run. Any suggestions would be much appreciated. Now provide the response and nothing else.
The problem probably lies within your hosts/inventory file. You need to add the proper connection configuration for Ansible therein, save and re-run. 192.168.50.5 ansible_ssh_port=22 ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.ssh/id_rsa If you are not using port 22 , adjust the ansible_ssh_port in your hosts file accordingly. It is also a possibility that you have not setup your pubkey in Vagrant, hence this would also not work. To test this, run: vagrant ssh-config | grep IdentityFile# result should be your private key and not# .vagrant/machines/default/virtualbox/private_key If you have not put your pubkey in the Vagrant vm, you will need to add that before you can try your private key. Reference: http://docs.ansible.com/ansible/intro_inventory.html#list-of-behavioral-inventory-parameters Reference: https://docs.vagrantup.com/v2/cli/ssh_config.html
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32748585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3785777/']}
jdg_82551
stackexchange
llm_judgeable_groundtruth_similarity
12630567
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 targeting an android app to API 15 and minimum 8. So I use support library to manage fragments. I have a set of fragments that I use in several parts of the app. Now, in an activity I have a ListView in the layout: <ListView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/listOfEvents" android:layout_width="match_parent" android:layout_height="match_parent"></ListView> I would like to add a fragment of mine in the ListView header. I tried this: @Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.event_open); listOfEvents = (ListView) findViewById(R.id.listOfEvents); Fragment fragment = new SortingStandardFragment(); getSupportFragmentManager() .beginTransaction() .add(fragment, null) .commit(); View fragmentView = fragment.getView(); // problem: fragment is null! listOfEvents.addHeaderView(fragmentView); } but i get an error since fragment.getView() returns null (api reference docs say that I have to put a GroupView Id in the add call, but where should I put the GroupView in the layout?Is there another way to hit the mark? Now provide the response and nothing else.
I solved this by creating a new layout containing just the fragment I need in the list header: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/myFragmentEmbedded" android:name=".SortingStandardFragment" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout> and in the activity code: LayoutInflater inflater = getLayoutInflater();header = inflater.inflate(R.layout.myLayout, null);listOfEvents.addHeaderView(header);SortingStandardFragmenttitleFragment = (SortingStandardFragment) getSupportFragmentManager() .findFragmentById(R.id.myFragmentEmbedded);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12630567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274340/']}
jdg_82552
stackexchange
llm_judgeable_groundtruth_similarity
27248559
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was doing some experiments in java, and I've encountered a thing that is bugging me. I have realized that in java, when I use a method instead of direct code, it takes more time to process it. I have the following code: public static void main(String[] args) { long nanoSeconds = System.nanoTime(); int i = foo(); System.out.println(i); System.out.println("Elapsed Nanoseconds = " + (System.nanoTime() - nanoSeconds)); nanoSeconds = System.nanoTime(); int l = 10; i = l; System.out.println(i); System.out.println("Elapsed Nanoseconds = " + (System.nanoTime() - nanoSeconds));}public final static int foo() { int i = 10; return i;} It is a simple code divided in two parts. The first one measures the time of foo() and shows the returned value of foo(), and the second part does the same but without calling foo(). The result was the following: 10 Elapsed Nanoseconds = 601582 10 Elapsed Nanoseconds = 49343 So my question is if is there a way to not loose this performance? Thanks all. Now provide the response and nothing else.
You will not obtain any meaningful benchmark this way. You don't account for the JIT . The compiler will not perform any optimization in this regard, apart from very obvious ones; when it sees a method call in the source code, even if this method call always returns the same value, it will generate bytecode which invokes the method; when it sees a constant, it will generate an ldc (load constant) bytecode instruction. BUT. Then the JIT kicks in at some point. If it determines that a method call always returns the same result, then it will inline the call. At runtime . But this is only done after a certain amount of executions of that code are performed, and it always has a way back if it admits that it has missed at some point (this is backtracking). And that is but one optimization a good JIT implementation can perform. You want to watch this video . Long story short: with Oracle's JVM, optimization will start to kick in only after a piece of code will be executed 10000 times at least — for some definition of "piece of code".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27248559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4315459/']}
jdg_82553
stackexchange
llm_judgeable_groundtruth_similarity
14144573
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following function in C++11: template<class Function, class... Args, typename ReturnType = /*SOMETHING*/> inline ReturnType apply(Function&& f, const Args&... args); I want ReturnType to be equal to the result type of f(args...) What do I have to write instead of /*SOMETHING*/ ? Now provide the response and nothing else.
I think you should rewrite your function template using trailing-return-type as: template<class Function, class... Args> inline auto apply(Function&& f, const Args&... args) -> decltype(f(args...)){ typedef decltype(f(args...)) ReturnType; //your code; you can use the above typedef.} Note that if you pass args as Args&&... instead of const Args&... , then it is better to use std::forward in f as: decltype(f(std::forward<Args>(args)...)) When you use const Args&... , then std::forward doesn't make much sense (at least to me). It is better to pass args as Args&&... called universal-reference and use std::forward with it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14144573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/882932/']}
jdg_82554
stackexchange
llm_judgeable_groundtruth_similarity
25365228
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 added a UIView containing a UITapGestureRecognizer as my key window's subview. It shows properly, however when I tap my view, the target method is not fired. I've even tried to replace the gesture recognizer with a UIButton , still to no avail. Here is my code. NotificationView.h #import <UIKit/UIKit.h>typedef NS_ENUM(int, NotificationKind) { NotificationKindActivity, NotificationKindReply,};@interface NotificationView : UIView { NotificationKind currentNotificationKind;}-(id)initWithMessage:(NSString*)message andColor:(UIColor*)color andKind:(NotificationKind)kind;-(void)show;@end NotificationView.m #import "NotificationView.h"@implementation NotificationView- (id)initWithMessage:(NSString*)message andColor:(UIColor*)color andKind:(NotificationKind)kind{ self = [super initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 60)]; if (self) { // Initialization code [self setAlpha:0]; [self setBackgroundColor:color]; [self setUserInteractionEnabled:YES]; currentNotificationKind = kind; UILabel *label = [[UILabel alloc] initWithFrame:self.bounds]; [label setNumberOfLines:0]; [label setFont:[UIFont fontWithName:@"Roboto-Italic" size:20]]; [label setTextColor:[UIColor whiteColor]]; [label setTextAlignment:NSTextAlignmentCenter]; [label setPreferredMaxLayoutWidth:290]; [label setText:message]; [label setUserInteractionEnabled:YES]; [self addSubview:label]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(notificationTapped)]; [tap setNumberOfTapsRequired:1]; [self addGestureRecognizer:tap]; [[[UIApplication sharedApplication] keyWindow] addSubview:self]; } return self;}-(void)show{ [UIView animateWithDuration:0.3 animations:^{ [self setAlpha:1]; } completion:^(BOOL finished) { [UIView animateWithDuration:0.3 delay:3 options:UIViewAnimationOptionCurveLinear animations:^{ [self setAlpha:0]; } completion:^(BOOL finished) { [self removeFromSuperview]; }]; }];}-(void)notificationTapped{ DDLogDebug(@"Notification tapped!");}@end Now provide the response and nothing else.
When this happens to me it's usually because I screwed up my UIView frame. I see all the content as expected because my UIView isn't clipping to bounds, but I can't interact with anything because my taps are outside the bounds of the UIView . My simple test is to change the background color of the UIView and see if it covers the area I expect or if I screwed up size/placement somehow. I used to pound my head against the wall with this issue, struggling for hours, but I've done it so many times now it's 5min fix of "Oh that again". Edit: Then I'd look at your show code. Your calling code isn't here, but if I'm to assume your are just using your show code and your view is only on screen for 3 seconds, then that's you problem. As Justin mentioned (comment above) and Apple's docs During an animation, user interactions are temporarily disabled for all views involved in the animation, regardless of the value in this property. You can disable this behavior by specifying the UIViewAnimationOptionAllowUserInteraction option when configuring the animation. Since the entire time your view is on the screen it's part of an animation block, all interaction will be disable for the entire time it's visible. I've never quite tested the delay bit and whether animation was disabled during that piece, but it would not surprise me animation is disabled during the delay. The second animation is still inside the primary animation block, so I'd assume animations will be blocked until both are complete.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25365228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/849042/']}
jdg_82555
stackexchange
llm_judgeable_groundtruth_similarity
76280
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have read on the news that the US military and the President have vowed to protect Taiwan if China invades the de facto independent, sovereign nation. China arguably has a stronger claim to Taiwan than Russia does to Ukraine. Unlike Ukraine, Taiwan still calls itself China: its official name is the Republic of China. There is no ethnic Taiwanese population in the way that there is an ethnic Ukrainian population or a Taiwanese language (they speak Mandarin in China). Taiwan is more ethnically Chinese (97% Han Chinese/Taiwanese) than mainland China (92% Han Chinese). Why is the US military and government vowing to protect Taiwan when they won't protect Ukraine? Is there an alliance Taiwan is part of that provides insurance from other countries in the event of an external invasion like NATO that Ukraine is not part of anything similar that would give it American protection? I am not arguing that it is okay for China to invade Taiwan for these reasons. I think such an invasion would be devastating for world peace and the world order of respecting sovereign boundaries which is under attack by Russian imperialism in Ukraine and has the potential of being further attacked by Chinese imperialism. Now provide the response and nothing else.
The main reasons for the difference are likely: Taiwan's economic importance is more obvious. It does a great deal of high-tech manufacturing, and includes the world's leading computer chip manufacturing company, TSMC . Ukraine's grain exports are also important, but less so to the US than to other parts of the world. The US has a long-standing commitment to Taiwan , made when the US was vastly more powerful than the PRC. Nowadays, the military power of the two states is closer to equal, but the US does not want to back down. It's quite practical for the US to intervene in a PRC-Taiwan conflict, because Taiwan is an island, and the US has a powerful navy. In contrast, basing US troops in Ukraine would be seen as menacing Russia in new ways. Having ships near Taiwan is somewhat less threatening, and ships are far easier to move than armoured divisions. If it came to a naval battle in the Taiwan Strait, that doesn't immediately lead to a US invasion of mainland China or a Chinese invasion of the USA, so the risk of nuclear escalation is low. If the US based troops in Ukraine and they defeated the Russian forces there, nothing would prevent the US invading Russia, so the nuclear risk is high.
{}
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/76280', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/29035/']}
jdg_82556
stackexchange
llm_judgeable_groundtruth_similarity
2583
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to compute the spectrum ( all the eigenvalues) of a large sparse matrix (hundreds of thousands of rows). This is hard. I am willing to settle for an approximation. Are there approximation methods to do this? While I hope for a general answer to this question I would also be satisfied with an answer in the following specific case. My matrix is a Normalized Laplacian of a large graph. Eigenvalues will be between 0 and 2 with a large number of them clustered around 1. Now provide the response and nothing else.
If your graph is undirected (as I suspect), the matrix is symmetric, and you cannot do anything better than the Lanczsos algorithm (with selective reorthogonalization if necessary for stability). As the full spectrum consists of 100000 numbers, I giess you are mainly interested in the spectral density. To get an approximate spectral density, take the spectrum of the leading Krylov subspace of dimension 100 or so, and replace its discrete density by a smoothed version. The leading Krylov spectrum will have nearly resolved well-isolated eigenvalues (should these exist), approximates the eigenvalues at the end of the nonisolates spectrum, and is somewhat random in-between, with a distribution whose cumulative distribution function resembles that of the true spectrum. It would converge to it in exact arithmetic if the dimension grows. (If your operator were infinite-dimensional, this would still be the case, and you'd get the integral of the true spectral density function on the continuous spectrum.)
{}
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/2583', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/19/']}
jdg_82557
stackexchange
llm_judgeable_groundtruth_similarity
30351
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I understand the assumptions that have to be true about a property or set of properties in a Turing machine description for Rice's Theorem to apply. But then what? If a set of Turing machines have an undecidable property, is the language itself necessarily undecidable? Or only if you can find a reduction from a known-undecidable machine is the language undecidable? What does it really say about a language if it has an undecidable property? Are machines that recognize that language undecidable? Now provide the response and nothing else.
An undecidable property $\pi$ of Turing machines is the same as an undecidable language consisting of all encodings of Turing machines satisfying $\pi$. We identify the property with the language of encodings of Turing machines satisfying the property. The fact that a language is undecidable just means that no Turing machine decides the language — this is the definition of undecidability. In particular, no machines recognize the language, assuming recognize means decide ; a machine $T$ decides a language $L$ if $T$ terminates on all inputs, on inputs $x \in L$ returns $1$, and on inputs $x \notin L$ returns $0$. A machine cannot be undecidable, only a language can be undecidable.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/30351', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/22152/']}
jdg_82558
stackexchange
llm_judgeable_groundtruth_similarity
69506
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As a part of a controlled power supply for hardware-in-loop testing for a student driven project, I had to develop a current buffer (voltage follower) which could source up to 1 A. I had the (bad) idea of trying to implement this simple circuit: The PMOS inside the feedback loop acts as an inverter (more V_gate, less V_out), and that's why the loop closes in the POSITIVE terminal of the opAmp instead of the negative. In the lab I set VREF = 5V and VIN = 7V. I should get then 5V at VOUT, but I obtain this out-of-control output VOUT: And this is the control signal (output of opAmp, connected to the gate of the MOSFET) I find similar behaviors under different VREF, VIN and Rloads. Also note that the output of the opAmp is not saturated to any of the rails. My assumption is that the gain of the loop is too high for keeping the opAmp in stability. I have some background in control systems and opamps, but I don't know how to apply it to solve this situation... Is it possible to apply some phase shift network to stabilize the loop? I would appreciate both "quick hacks" or educational answers! Now provide the response and nothing else.
This is really simple - use an N channel FET and have it as a source follower. You can even use a BJT. The one below has gain due to the 3k3 feedback and the 1k to ground from -Vin. If you don't want gain connect the output directly to -Vin and omit the 1k. A unity gain buffer on the output of an op-amp is either an emitter follower or a source follower. Simple as that - feedback from the emitter/source back to inverting input of the op-amp. Additionally, because the source/emitter voltage "follows" the op-amps output signal, the gate/base loading effects are minimal hence when using a MOSFET you don't need to worry about gate capacitance. Think about this sensibly - Analog Devices or TI or MAXIM of LT - their marketing team are not going to wake up one morning and say to their designers - why can't you design an op-amp that allows someone to add a gain stage on it and expect it to be stable. If they did, the designers would say that they'd have to reduce the performance of the op-amp for it to be stable - just how would that op-amp compete in the market against all the op-amps that take the sensible road and keep building what they are good at.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/69506', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/10305/']}
jdg_82559
stackexchange
llm_judgeable_groundtruth_similarity
12831667
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 writing a stored procedure in postgres where I need to check if a row exists then act accordingly. something along the line. IF SELECT * FROM foo WHERE x = 'abc' AND y = 'xyz' THEN -- do something hereELSE -- do something elseEND; I have googled a bit but got no good hits. Now provide the response and nothing else.
Use PERFORM and the FOUND automatic variable : PERFORM * FROM foo WHERE x = 'abc' AND y = 'xyz';IF FOUND THEN ....END IF; This will succeed if one or more rows is returned. If you want to constrain the result to exactly one row use GET DIAGNOSTICS to get the row count , or use SELECT INTO to store the count(...) of the rows into a DECLARE d variable you then test. If it's an error to get no results, use SELECT INTO STRICT to require that exactly one row be obtained and stored into the target variable. Beware of concurrency issues when doing anything like this. If you're attempting to write an upsert/merge function this approach will not work . See "why is upsert so complicated" .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12831667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438319/']}
jdg_82560
stackexchange
llm_judgeable_groundtruth_similarity
37038055
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 custom UIView class that renders a gradient in Swift 2. I'm struggling with making an angled gradient so that it draws from the top-left to the bottom-right. Can somebody help me a bit? import UIKitclass GradientView: UIView { let gradientLayer = CAGradientLayer() override func awakeFromNib() { // 1 self.backgroundColor = ColorPalette.White // 2 gradientLayer.frame = self.bounds // 3 let color1 = ColorPalette.GrdTop.CGColor as CGColorRef let color2 = ColorPalette.GrdBottom.CGColor as CGColorRef gradientLayer.colors = [color1, color2] // 4 gradientLayer.locations = [0.0, 1.0] // 5 self.layer.addSublayer(gradientLayer) }} I suspect this should be something else but whatever I input nothing changes. gradientLayer.locations = [0.0, 1.0] Now provide the response and nothing else.
You don't want to use locations to specify the direction of the gradient. Instead use startPoint and endPoint for that. The locations array is used when one wants to specify where, in between startPoint and endPoint , the gradient should to take place. For example, if you want the colors to only take place in the middle 10% of the range from the start and end points, you'd use: locations = [0.45, 0.55] The locations array doesn't dictate the direction. The startPoint and endPoint do. So, for a diagonal gradient from upper left to lower right, you would set startPoint of CGPoint(x: 0, y: 0) and an endPoint to CGPoint(x: 1, y: 1) . For example: @IBDesignableclass GradientView: UIView { override class var layerClass: AnyClass { return CAGradientLayer.self } private var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer } @IBInspectable var color1: UIColor = .white { didSet { updateColors() } } @IBInspectable var color2: UIColor = .blue { didSet { updateColors() } } override init(frame: CGRect = .zero) { super.init(frame: frame) configureGradient() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureGradient() } private func configureGradient() { gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 1) updateColors() } private func updateColors() { gradientLayer.colors = [color1.cgColor, color2.cgColor] }} E.g. Note, unrelated to the immediate issue: If you’re going to add the gradient as a sublayer, you want to update this sublayer’s frame in layoutSubviews so that as the view's bounds changes, so does the frame of the gradientLayer . But, better than that, override the layerClass of the view, and it will not only instantiate the CAGradientLayer for you, but you also enjoy dynamic adjustments of the gradient as the view’s size changes, notably handling animated changes more gracefully. Likewise, I set color1 and color2 such that they'll trigger an updating of the gradient, so that any changes in colors will be immediately reflected in the view. I made this @IBDesignable , so that if I drop this in its own framework, and then add the GradientView in IB, I'll see the effect rendered in IB. For Swift 2 implementation, see previous revision of this answer .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37038055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4108300/']}
jdg_82561
stackexchange
llm_judgeable_groundtruth_similarity
22796164
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 bunch of company data in an ES database. I am looking to pull counts of how many documents each company occurs in, but I'm having some problems with the aggregation query. I am looking to exclude terms such as "Corporation" or "Inc." Thus far I have been able to do this successfully for one term at a time as per the code below. { "aggs" : { "companies" : { "terms" : { "field" : "Companies.name", "exclude" : "corporation" } } }} Which returns "aggregations": { "assignee": { "buckets": [ { "key": "inc", "doc_count": 375 }, { "key": "company", "doc_count": 252 } ] }} Ideally I'd like to be able to do something like { "aggs" : { "companies" : { "terms" : { "field" : "Companies.name", "exclude" : ["corporation", "inc.", "inc", "co", "company", "the", "industries", "incorporated", "international"], } } }} But I haven't been able to find a way that doesn't throw an error I have looked at the "Terms" section of Aggregation in the ES documentation and can only find an example for a single exclude.I'm wondering if it's possible to exclude multiple terms and if so what is the correct syntax for doing so. Note: I know I could set the field to "not_analyzed" and get groupings for full company names rather than the split names. However, I'm hesitant to do this as analyzing allows a bucket to be more tolerant of name variations (ie Microsoft Corp & Microsoft Corporation) Now provide the response and nothing else.
The exclude parameter is a regular expression , so you could use a regular expression that exhaustively lists all choices: "exclude" : "corporation|inc\\.|inc|co|company|the|industries|incorporated|international" Doing this generically, it's important to escape values (e.g., . ). If it is not generically generated, then you could simplify some of these by grouping them (e.g., inc\\.? covers inc\\.|inc , or the more complicated: co(mpany|rporation)? ). If this is going to run a lot, then it's probably worth testing how the added complexity effects performance. There are also optional flags that can be applied, which are the options that exist in Java Pattern . The one that might come in handy is CASE_INSENSITIVE . "exclude" : { "pattern" : "...expression as before...", "flags" : "CASE_INSENSITIVE"}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22796164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2498161/']}
jdg_82562
stackexchange
llm_judgeable_groundtruth_similarity
660170
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose we have a function $f$ defined over $[a,b]$ to the real numbers, i.e. $f: [a, b] \to \mathbb R.$. We can approximate this function as Fourier Series. Suppose $a_n, b_n$ is the Fourier series coefficients, Then $$a_n = \frac{2}{b-a} \int_a^bf(x) \cos(nx)$$ $$b_n = \frac{2}{b-a}\int_a^bf(x)\sin(nx) $$ $$f(x) \approx \frac{a_0}{2}+ \sum^\infty_{n=1} a_n\cos(nx) + b_n\sin(nx)$$ My question is, what is the advantage of using the approximate Fourier Series, rather than the function $f(x)$ itself? When would we use the approximation over the funtion itself? Now provide the response and nothing else.
I think the point is the functions available might be highly irregular, and it is difficult to treat such functions. If we can decompose the function into a series which "converges" globally, then we can substitute the study of the function with its Fourier series. For many analysis purposes like PDE, this helps to translate properties of the original function into properties of the series in a way we can reasonably control. If the original function is unknown (for example only known the boundary values and some decay conditions), then this information translation process can be extremely helpful because it makes a hard problem much easier. You can also decompose the original function into linear combination of other orthogonal sets, but the results may not be as nice.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/660170', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/48863/']}
jdg_82563
stackexchange
llm_judgeable_groundtruth_similarity
42380448
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 create react-router v4 breadcrumbs? I tried asking this question on the react-router V4 website via an issue ticket. They just said to see the recursive paths example. I really want to create it in semantic-ui-react Now provide the response and nothing else.
I was after the same thing and your question pointed me in the right direction. This worked for me: const Breadcrumbs = (props) => ( <div className="breadcrumbs"> <ul className='container'> <Route path='/:path' component={BreadcrumbsItem} /> </ul> </div>)const BreadcrumbsItem = ({ match, ...rest }) => ( <React.Fragment> <li className={match.isExact ? 'breadcrumb-active' : undefined}> <Link to={match.url || ''}> {match.url} </Link> </li> <Route path={`${match.url}/:path`} component={BreadcrumbsItem} /> </React.Fragment>)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42380448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/698890/']}
jdg_82564
stackexchange
llm_judgeable_groundtruth_similarity
28992028
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a situation such as the following library(dplyr)myData <- tbl_df(data.frame( var1 = rnorm(100), var2 = letters[1:3] %>% sample(100, replace = TRUE) %>% factor(), var3 = LETTERS[1:3] %>% sample(100, replace = TRUE) %>% factor(), var4 = month.abb[1:3] %>% sample(100, replace = TRUE) %>% factor())) I would like to group `myData' to eventually find summary data grouping by all possible combinations of var2, var3, and var4. I can create a list with all possible combinations of variables as character values with groupNames <- names(myData)[2:4]myGroups <- Map(combn, list(groupNames), seq_along(groupNames), simplify = FALSE) %>% unlist(recursive = FALSE) My plan was to make separate data sets for each variable combination with a for() loop, something like ### This Does Not Workfor (i in 1:length(myGroups)){ assign( myGroups[i]%>% unlist() %>% paste0(collapse = "")%>% paste0("Data"), myData %>% group_by_(lapply(myGroups[[i]], as.symbol)) %>% summarise( n = length(var1), avgVar2 = var2 %>% mean()))} Admittedly I am not very good with lists, and looking up this issue was a bit challenging since dpyr updates have altered how grouping works a bit. If there is a better way to do this than separate data sets I would love to know. I've gotten a loop similar to above working when I am only grouping by a single variable. Any and all help is greatly appreciated! Thank you! Now provide the response and nothing else.
This seems convulated, and there's probably a way to simplify or fancy it up with a do , but it works. Using your myData and myGroups , results = lapply(myGroups, FUN = function(x) { do.call(what = group_by_, args = c(list(myData), x)) %>% summarise( n = length(var1), avgVar1 = mean(var1)) })> results[[1]]Source: local data frame [3 x 3] var2 n avgVar11 a 31 0.389297382 b 31 -0.074517173 c 38 -0.22522129> results[[4]]Source: local data frame [9 x 4]Groups: var2 var2 var3 n avgVar11 a A 11 -0.11591602 a B 11 0.56633123 a C 9 0.79040564 b A 7 0.08563845 b B 13 0.13097566 b C 11 -0.41928957 c A 15 -0.27830998 c B 10 -0.11108779 c C 13 -0.2517602> results[[7]]# I won't paste them here, but it has all 27 rows, grouped by var2, var3 and var4. I changed your summarise call to average var1 since var2 isn't numeric.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28992028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335897/']}
jdg_82565
stackexchange
llm_judgeable_groundtruth_similarity
53365811
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 go package located on my filesystem (not in the $GOPATH ), called bitbucket.org/me/awesome . ~/awesome> tree.├── main.go├── go.mod├── go.sum├── subpackageA│   └── main.go My go.mod looks like: module bitbucket.org/me/awesomerequire ( ... # lots of external dependencies)replace bitbucket.org/me/awesome => ./ In main.go in my top-level directory, I call a subpackage like follows: import "bitbucket.org/me/awesome/subpackageA" which all seems pretty normal. go get works. However, when I clone this entire repository somewhere else (say in a Docker image) and run go get for the first time, I get errors like: package bitbucket.org/me/awesome/subpackageA: https://api.bitbucket.org/2.0/repositories/me/awesome?fields=scm: 403 Forbidden , which means it's not using the local filesystem version of the packages, even though I told it to with the replace directive in the go.mod file. What am I doing wrong? How do I ensure that subpackages are used from the filesystem instead of attempting to be fetched from the internet? Now provide the response and nothing else.
Go has no (real) notion of "subpackage". All packages are basically treated equal. This means that a replace bitbucket.org/me/awesome does not influence package bitbucket.org/me/awesome/subpackageA as these are two individual, unrelated packages. The folder layout does not introduce a relation of subpackageA to awsome, or the other way around *). So you need to add an individual replace directive for subpackageA replace bitbucket.org/me/awesome/subpackageA => ./subpackageA *) Nitpicking for absolute correctness: Folder layout does have influence for folders named internal (cannot be imported from other projects), for folders named vendor (which may contain vendored packages) and searching for a go.mod file stops at the repo root.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53365811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100208/']}
jdg_82566
stackexchange
llm_judgeable_groundtruth_similarity
240659
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was plotting (standardized) return data with qqplot() in MATLAB against the theoretical quantiles of a normal distribution. However, the line in the QQ-Plot does not have a 45° angle but is rotated a little. Maybe I misunderstand the concept of a QQ plot but isn't it supposed to be exactly a 45° line? I put the plot to illustrate the issue. Now provide the response and nothing else.
Should it be a 45 degree line? It depends! A QQ plot is the parametric curve defined by: \begin{align*}x &= F^{-1}(p)\\y &= G^{-1}(p)\end{align*} for $p \in [0, 1]$. Where $F^{-1}$ and $G^{-1}$ are inverse CDF functions. If $F = G$ then $x(p)=y(p)$ and it would be on a 45 degree line. Another case... Let $\Phi^{-1}(p)$ be the standard normal inverse CDF. Let $F^{-1}(p) = \Phi^{-1}(p)$ Let $G^{-1}(p) = \sigma \Phi^{-1}(p) + \mu$ That is $G$ is the inverse CDF for a normally distributed random variable with mean $\mu$ and standard deviation $\sigma$ while $F$ is the inverse CDF for a standard normal variable (i.e. mean 0, standard deviation 1). Then we see: $$y(p) = \sigma \Phi^{-1}(p) + \mu = \sigma x(p) + \mu$$ That is, the plot is a line $y = \sigma x + \mu$ What's going on in your case? From the Matlab documentation for qqplot Superimposed on the plot is a line joining the first and third quartiles of each distribution (this is a robust linear fit of the order statistics of the two samples). This line is extrapolated out to the ends of the sample to help evaluate the linearity of the data. So even if you standardized your data, the red line MATLAB plots wouldn't be a 45 degree line if the 1st and 3rd quartiles didn't match the normal distribution.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/240659', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/123353/']}
jdg_82567
stackexchange
llm_judgeable_groundtruth_similarity
31568183
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 zoo obj like that colled z. > z["2013-12",1] Allerona 2013-12-01 0.02013-12-02 0.02013-12-03 0.02013-12-04 0.02013-12-05 0.22013-12-06 0.02013-12-07 0.02013-12-08 0.22013-12-09 0.0.... It stores daily value of rainfall. I'm able to compute the 5-days accumulation using rollapply usingi: m=rollapply(z, width=3, FUN=sum, by=1, by.column=TRUE, fill=NA, align="right") It looks ok > m["2013-12",1] Allerona2013-12-01 0.02013-12-02 0.02013-12-03 0.02013-12-04 0.02013-12-05 0.22013-12-06 0.22013-12-07 0.22013-12-08 0.22013-12-09 0.2... How can I calculate for each day themean for 5-years before? Thanks Now provide the response and nothing else.
tl;dr: "owning" types in Rust are not some magic and they are most certainly not hardcoded into the compiler or language. They are just types which written in a certain way (do not implement Copy and likely have a destructor) and have certain semantics which is enforced through non-copyability and the destructor. In its core Rust's ownership mechanism is very simple and has very simple rules. First of all, let's define what move is. It is simple - a value is said to be moved when it becomes available under a new name and stops being available under the old name: struct X(u32);let x1 = X(12);let x2 = x1;// x1 is no longer accessible here, trying to use it will cause a compiler error Same thing happens when you pass a value into a function: fn do_something(x: X) {}let x1 = X(12);do_something(x1);// x1 is no longer accessible here Note that there is absolutely no magic here - it is just that by default every value of every type behaves like in the above examples. Values of each struct or enum you or someone else creates by default will be moved. Another important thing is that you can give every type a destructor , that is, a piece of code which is invoked when the value of this type goes out of scope and destroyed. For example, destructors associated with Vec or Box will free the corresponding piece of memory. Destructors can be declared by implementing Drop trait: struct X(u32);impl Drop for X { fn drop(&mut self) { println!("Dropping {}", x.0); }}{ let x1 = X(12);} // x1 is dropped here, and "Dropping 12" will be printed There is a way to opt-out of non-copyability by implementing Copy trait which marks the type as automatically copyable - its values will no longer be moved but copied: #[derive(Copy, Clone)] struct X(u32);let x1 = X(12);let x2 = x1;// x1 is still available here The copy is done bytewise - x2 will contain a byte-identical copy of x1 . Not every type can be made Copy - only those which have Copy interior and do not implement Drop . All primitive types (except &mut references but including *const and *mut raw pointers) are Copy in Rust, so each struct which contains only primitives can be made Copy . On the other hand, structs like Vec or Box are not Copy - they deliberately do not implement it because bytewise copy of them will lead to double frees because their destructors can be run twice over the same pointer. The Copy bit above is a slight digression on my side, just to give a clearer picture. Ownership in Rust is based on move semantics. When we say that some value own something, like in " Box<T> owns the given T ", we mean semantic connection between them, not something magical or something which is built into the language. It is just most such values like Vec or Box do not implement Copy and thus moved instead of copied, and they also (optionally) have a destructor which cleans up anything these types may have allocated for them (memory, sockets, files, etc.). Given the above, of course you can write your own "owning" types. This is one of the cornerstones of idiomatic Rust, and a lot of code in the standard library and external libraries is written in such way. For example, some C APIs provide functions for creating and destroying objects. Writing an "owning" wrapper around them is very easy in Rust and it is probably very close to what you're asking for: extern { fn create_widget() -> *mut WidgetStruct; fn destroy_widget(w: *mut WidgetStruct); fn use_widget(w: *mut WidgetStruct) -> u32;}struct Widget(*mut WidgetStruct);impl Drop for Widget { fn drop(&mut self) { unsafe { destroy_widget(self.0); } }}impl Widget { fn new() -> Widget { Widget(unsafe { create_widget() }) } fn use_it(&mut self) -> u32 { unsafe { use_widget(self.0) } }} Now you can say that Widget owns some foreign resource represented by *mut WidgetStruct .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31568183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5144421/']}
jdg_82568
stackexchange
llm_judgeable_groundtruth_similarity
41142
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Kai Lai Chung's A course inprobability theory , An atom of any probability measure $\mu$ on $(\mathbb{R}, \mathcal{B})$ is a singleton $\{x\}$ such that $\mu({x}) > 0$. In Wikipedia : Given a measurable space $(X,Σ)$ and a measure $\mu$ on that space, a set A in Σ is called an atom if $\mu (A) >0$ and for any measurable subset B of A with $\mu(A) > \mu (B)$, one has $\mu(B) = 0$. I was wondering if Chung's and Wikipedia's definitions agree with each other? If yes, does Chung'sdefinition mean that in the special probability measure space$(\mathbb{R}, \mathcal{B}, \mu)$, thereis no atom, as defined as inWikipedia, that is not a singleton? Chung says in his book that thenumber of atoms of any$\sigma$-finite measure iscountable. I was wondering if suppose there are uncountably many atoms, howwill it contradicts$\sigma$-finite measure? Is this conclusion also true forgeneral measure space $(X,Σ, \mu)$instead of just for probabilitymeasure space $(\mathbb{R}, \mathcal{B}, \mu)$? Thanks and regards! Now provide the response and nothing else.
The wikipedia definition is more general. Here is a trivial example: on $X = \mathbb{R}$, take the $\sigma$-algebra $\{ \varnothing, \mathbb{R} \}$ and the measure $\mu(\emptyset) = 0$, $\mu(\mathbb{R}) = 1$. Then $\mathbb{R}$ is an atom which is not a singleton set. The above example is totally contrived. I believe that if you have a regular Borel measure on a topological space, the atoms will all be points. This certainly holds for $(\mathbb{R},\mathcal{B},\mu)$ (meaning in this case that there are no atoms at all, since all points have Lebesgue measure zero): if you have a subset $A$ with $\mu(A) = \delta > 0$, partition the real line into a countable union of half open intervals $I_n$ of length less than $\delta$. Since $A = \coprod_{n=1}^{\infty} A \cap I_n$, $\sum_{n=1}^{\infty} \mu(A \cap I_n) = \delta$, so there exists $N$ with $0 < \mu(A \cap I_n) < \delta = \mu(A)$. Finally, suppose you have a measure with uncountably many atoms in Chung's sense, i.e., points of positive measure, and let $\{X_n\}_{n=1}^{\infty}$ be a covering by countably many measurable subsets. Since there are uncountably many atoms, there exist at least one $n$ such that $X_n$ contains uncountably many atoms, so it has infinite measure. Therefore the measure is not $\sigma$-finite.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/41142', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1281/']}
jdg_82569
stackexchange
llm_judgeable_groundtruth_similarity
515726
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I created a program that iterates over a bunch of files and invokes for some of them: scp <file> user@host:<remotefile> However, in my case, there may be thousands of small files that need to transferred, and scp is opening a new ssh connection for each of them, which has quite some overhead. I was wondering if there is no solution where I keep one process running that maintains the connection and I can send it "requests" to copy over single files. Ideally, I'm looking for a combination of some sender and receiver program, such that I can start a single process (1) at the beginning: ssh user@host receiverprogram And for each file, I invoke a command (2): senderprogram <file> <remotefile> and pipe the output of (2) to the input of (1), and this would cause the file to be transferred. In the end, I can just send process (1) some signal to terminate. Preferably the sender and receiver programs are open source C programs for Unix. They may communicate using a socket instead of a pipe, or any other creative solution. However, it is an important constraint that each file gets transferred at the moment I iterate over it: it is not acceptable to collect a list of files and then invoke one instance of scp to transfer all the files at once at the end. Also, I have only simple shell access to the receiving host. Update: I found a solution for the problem of the connection overhead using the multiplexing features of ssh, see my own answer below. Yet, I'm starting a bounty because I'm curious to find if there exists a sender/receiver program as I describe here. It seems there should exist something that can be used, e.g. xmodem/ymodem/zmodem? Now provide the response and nothing else.
I found a solution from another angle. Since version 3.9 , OpenSSH supports session multiplexing : a single connection can carry multiple login or file transfer sessions. This avoids the set-up cost per connection. For the case of the question, I can first open a connection with sets up a control master ( -M ) with a socket ( -S ) in a specific location. I don't need a session ( -N ). ssh user@host -M -S /tmp/%r@%h:%p -N Next, I can invoke scp for each file and instruct it to use the same socket: scp -o 'ControlPath /tmp/%r@%h:%p' <file> user@host:<remotefile> This command starts copying almost instantaneously! You can also use the control socket for normal ssh connections, which will then open immediately: ssh user@host -S /tmp/%r@%h:%p If the control socket is no longer available (e.g. because you killed the master), this falls back to a normal connection. More information is available in this article .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/515726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6918/']}
jdg_82570
stackexchange
llm_judgeable_groundtruth_similarity
228821
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: Is the transverse field Ising model time-reversal invariant? Specifically consider a non-integrable variant: \begin{equation}H = -J \sum_i^{L-1} \sigma_i^z \sigma_{i+1}^z + g \sum_i^L \sigma_i^x + h \sum_i^L \sigma_i^z,\end{equation} so that it has both a transverse and longitudinal field. $\sigma$s are the usual Pauli-matrices. So, is it TRI? Arguments for no: 1) The time-reversal operator is $T = K \prod_{j=1}^L (-i \sigma^y_j)$ where $K$ is complex conjugation in the $\uparrow,\downarrow$ basis. One can check that $[H,T] \neq 0$. 2) Simply recall the action of $T$ on spins. It flips $\vec{S} \to -\vec{S}$. So the transverse fields $\sigma^z$ and $\sigma^x$ flip, and the model is not invariant. Arguments for yes: 1) One must recall that $g, h$ are external magnetic fields which are pseudovectors. So we have to flip them at the same time as flipping $\vec{S}$. So overall, yes, TRI. 2) The level statistics of the model obey well GOE (Gaussian orthogonal ensemble) statistics (see arxiv:1306.4306 for example), a class of random matrices that are supposed to describe time-reversal invariant Hamiltonians. Puzzling issues: 1) If no, how to reconcile with GOE statistics? 2) If yes because of reason 1, that feels like it is cheating; we have to put in the way the constants $g,h$ transform by hand. 3) If yes, Kramers theorem says the spectrum should be doubly-degenerate for a chain of total spin half-integral. Quickly check in Mathematica for $L = 3,5,7\cdots$, this is untrue - the spectrum is not degenerate. Kramer's theorem doesn't hold. So, yes or no? Or yes and no? EDIT Also, I've heard this phrase alot: oh, the Hamiltonian is real so it is time-reversal symmetric. Does that make sense?? I mean, if I had applied my transverse field in the $y$-direction, I don't expect any physical difference. It's just a magnetic field pointing a different way. But in the particular basis I've chosen, the model is now complex. So it has become non-time-reversal symmetric? Oh is the statement "a real Hamiltonian is TRI" too cavalier? Now provide the response and nothing else.
Basically, the answer is yes: $H$ is TRI because it is real. Reality condition really means that the Hamiltonian obeys a certain anti-unitary symmetry. In this case, the time-reversal operation is simply $T=K$ where $K$ is the complex conjugation. It is not the usual one($T=K\prod_i i\sigma^y_i$), and in particular $T^2=1$, so there is no Kramers' theorem and the spectrum is not doubly degenerate. The fact that level statistics follows GOE of course is a consequence of the reality condition. In fact, I think if there was a $T^2=-1$ time-reversal symmetry, the statistics would follow a different ensemble (the symplectic one, I believe). You asked what if one changes the transverse field $g\sum_i \sigma^x_i$ to the $y$ direction. In that case, the two Hamiltonians are unitarily related (i.e. a $\pi/2$ spin rotation $U_z$ around $z$ would bring it back). Let me call the Hamiltonian with $x$ transverse field $H_x(g)$ where $g$ is the transverse field, and with $y$ transverse field $H_y(g)$. Define $U_z=e^{i\pi \sum_i\sigma^z_i/4}$, then it is easy to check that $U_z H_y(g) U_z^{-1}= H_x(g)$. Since we know $H_x^*(g)=H_x(g)$, we can easily find $H_y^*=U_z^2 H_y U_z^{-2}$. Therefore one just has to redefine the time-reversal symmetry to be $T=K U_z^2$. If you really want to break the reality condition, in a way that can not be fixed by additional unitary transformations, then one needs to turn on transverse fields along all three dimensions. Last comment on your "Arguments for yes": the first argument you gave, namely one also flips the external parameters, does not work. In this way, there would be no time-reversal symmetry breaking, except the CP violation in the fundamental processes! When we talk about the symmetry of a Hamiltonian, we should just treat the system on its own, not with all the external devices that generate the various terms -- unless you want to consider the dynamics of these devices, but then it is a different Hamiltonian.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/228821', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/17308/']}
jdg_82571
stackexchange
llm_judgeable_groundtruth_similarity
401423
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 do not have a strong math background, but I'm curious as to what this pattern is from a mathematical standpoint. I was curious how many minutes there were in a day, so I said "24*6=144, add a 0, 1440." Then it immediately struck me that 12*12=144, 6 is half of 12, and 12 is half of 24. So, I checked to make sure it worked in other circumstances: 4*16=648*8=64 11*44=48422*22=484 9*36=32418*18=324 So what exactly is going on here from a logical standpoint to create that pattern? Thanks in advance for satiating my curiosity! Now provide the response and nothing else.
Think about multiplication as having piles of rocks. $6*24$ represents 6 piles of 24 rocks. Now what happens if you split each pile in two halves? The number of rocks in your pile half, but the number of piles double. Thus, you get 12 piles of 12 rocks, or $12*12$. You didn't change the number of rocks, you only rearrange them in a different way.Thus you have $6*24=12*12$ rocks. And the same holds with any numbers. If you split each pile in halves, the number of rocks in piles half, and the number of piles double. But in total you have the same number of rocks... Thus, if you multiply two numbers, half one and double the other, you get the same product. [Note that this intuitive explanation works for whole numbers, but can also be made to work easily for fractions].
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/401423', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74930/']}
jdg_82572
stackexchange
llm_judgeable_groundtruth_similarity
23602181
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 angular js..I am getting follwing error please help me out [ng:areq] Argument 'fn' is not a function, got string var app = angular.module('demo',[]);app.config('$routeProvider',function($routeProvider){ $routeProvider.when('/add',{ templateUrl:'demo/add.html', controller:'addcontroller' }). when('/order',{ templateUrl:'demo/order.html', controller:'ordercontroller' });});app.controller('addcontroller',function($scope){ $scope.message="order";});app.controller('ordercontroller',function($scope){ $scope.message="order";}); Now provide the response and nothing else.
I think the error is in the config block, it should either be: app.config(function($routeProvider){ // routeProvider config}); or better: app.config(['$routeProvider', function($routeProvider){ // routeProvider config, allows minification}]); the annotations are there for minification to work correctly. You can read more about it on AngularJS docs https://docs.angularjs.org/tutorial/step_05 Please note that this practice needs to be done throughout the app to work correctly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23602181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3627233/']}
jdg_82573
stackexchange
llm_judgeable_groundtruth_similarity
606215
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: After running # yum update zfs and restarting my CentOS 6 ZFS on Linux system can no longer see or interact with it's zpools. # zpool statusno pools available# zpool importzpool: ../../lib/libzfs/libzfs_import.c:356: Assertion `nvlist_lookup_uint64(zhp->zpool_config, ZPOOL_CONFIG_POOL_GUID, &theguid) == 0' failed.Aborted# dmesg | grep -i spl SPL: Loaded module v0.6.2-1 SPL: using hostid 0x43a4c8a0 This is a canary system, so I'm not worried about its contents, but I have other machines that I would eventually like to upgrade safely. What did I do wrong, and more importantly how can I do it right for the important systems? Now provide the response and nothing else.
That looks like...a bug. In fact, it is a bug . The ZFS userland is updated, but the kernel modules aren't being updated by DKMS. This assertion is caused by the version mismatch. You can work around it by a process given in a comment to the bug, by removing the old kernel modules and then reinstalling everything. $ find /lib/modules/$(uname -r)/extra -name "splat.ko" -or -name "zcommon.ko" -or -name "zpios.ko" -or -name "spl.ko" -or -name "zavl.ko" -or -name "zfs.ko" -or -name "znvpair.ko" -or -name "zunicode.ko" | xargs rm -f$ find /lib/modules/$(uname -r)/weak-updates -name "splat.ko" -or -name "zcommon.ko" -or -name "zpios.ko" -or -name "spl.ko" -or -name "zavl.ko" -or -name "zfs.ko" -or -name "znvpair.ko" -or -name "zunicode.ko" | xargs rm -f$ yum reinstall zfs-release$ yum reinstall $(rpm -qa | egrep "zfs|spl")
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/606215', 'https://serverfault.com', 'https://serverfault.com/users/84104/']}
jdg_82574
stackexchange
llm_judgeable_groundtruth_similarity
3006617
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: we want to use Unity for IOC.All i've seen is the implementation that there is one global static service (let's call it the the IOCService) which holds a reference to the Unity container, which registers all interface/class combinations and every class asks that object: give me an implementation for Ithis or IThat. Frequently i see a response that this pattern is not good because it leads to a dependency from ALL classes to the IOCService (not to the Unity container because it is only known inside the IOCService). But what i don't see often, is: what is the alternative way? Michel EDIT: found out that the global static service is called the service locator, added that to the title. Now provide the response and nothing else.
The alternative is to have a single instance of your container at the highest application level only , then use that container to resolve every object instance you need to create in that layer. For example, the main method of most executables just looks like this (minus exception handling): private static void main(string[] args) { Container container = new Container(); // Configure the container - by hand or via file IProgramLogic logic = container.Resolve<IProgramLogic>(); logic.Run();} Your program (represented here by the IProgramLogic instance) doesn't have to know anything about your container, because container.Resolve will create all its dependencies - and its dependencies' dependencies, on down to leaf classes with no dependencies of their own. ASP.NET is a harder case, because web forms doesn't support constructor injection. I typically use Model-View-Presenter in my web forms applications, so my Page classes really only have one dependency each - on their presenter. I don't unit test them (everything interesting and testable is in my presenters, which I do test), and I don't ever substitute presenters. So I don't fight the framework - I just expose a container property on my HttpApplication class (in global.asax.cs) and use it directly from my Page files: protected void Page_Load(object sender, EventArgs args) { ICustomerPresenter presenter = Global.Container.Resolve<ICustomerPresenter>(); presenter.Load();} That's service locator of course - though the Page classes are the only thing coupled to the locator: your presenter and all of its dependencies are still fully decoupled from your IoC container implementation. If you have a lot of dependencies in your Page files (that is, if you do not use Model-View-Presenter), or if it's important to you to decouple your Page classes from your Global application class, you should try to find a framework that integrates into the web forms request pipeline and use property injection (as suggested by Nicholas in the comments below) - or write your own IHttpModule and perform the property injection yourself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3006617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/103089/']}
jdg_82575
stackexchange
llm_judgeable_groundtruth_similarity
48024410
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following collection in Firestore: Users (Collection) Users (Collection)-- user1 (Document)-----name: "John"-----age: 23-- user2 (Document)-----name: "Mary"-----age: 25-- user3 (Document)-----name: "John"-----age: 20 Question : How can I query Firestore so that I get all unique names in the collection? Desired result : (John, Mary) Thanks in advance! Now provide the response and nothing else.
There is no specific API to retrieve unique values from Cloud Firestore. You will have to retrieve all relevant documents and determine the unique names in your own code. Alternatively, consider adding a document with unique names and update that with every write. This is a quite common approach in NoSQL databases, butmay take some getting used to if you're new to them.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48024410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8964561/']}
jdg_82576
stackexchange
llm_judgeable_groundtruth_similarity
558014
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: If I want find command to stop after finding a certain number of matches, how do I do that? Background is that I have too many files in a folder, I need to put them into separate folders randomly like: find -max-matches 1000 -exec mv {} /path/to/collection1 \+; find -max-matches 1000 -exec mv {} /path/to/collection2 \+; is this possible to do with find alone? If not, what would be the simplest way to do this? Now provide the response and nothing else.
As you're not using find for very much other than walking the directory tree, I'd suggest instead using the shell directly to do this. See variations for both zsh and bash below. Using the zsh shell mv ./**/*(-.D[1,1000]) /path/to/collection1 # move first 1000 filesmv ./**/*(-.D[1,1000]) /path/to/collection2 # move next 1000 files The globbing pattern ./**/*(-.D[1,1000]) would match all regular files (or symbolic links to such files) in or under the current directory, and then return the 1000 first of these. The -. restricts the match to regular files or symbolic links to these, while D acts like dotglob in bash (matches hidden names). This is assuming that the generated command would not grow too big through expanding the globbing pattern when calling mv . The above is quite inefficient as it would expand the glob for each collection. You may therefore want to store the pathnames in an array and then move slices of that: pathnames=( ./**/*(-.D) )mv $pathnames[1,1000] /path/to/collection1mv $pathnames[1001,2000] /path/to/collection2 To randomise the pathnames array when you create it (you mentioned wanting to move random files): pathnames=( ./**/*(-.Doe['REPLY=$RANDOM']) ) You could do a similar thing in bash (except you can't easily shuffle the result of a glob match in bash , apart for possibly feeding the results through shuf , so I'll skip that bit): shopt -s globstar dotglob nullglobpathnames=()for pathname in ./**/*; do [[ -f $pathname ]] && pathnames+=( "$pathname" )donemv "${pathnames[@]:0:1000}" /path/to/collection1mv "${pathnames[@]:1000:1000}" /path/to/collection2mv "${pathnames[@]:2000:1000}" /path/to/collection3
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/558014', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/27695/']}
jdg_82577
stackexchange
llm_judgeable_groundtruth_similarity
10648772
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am a .Net programmer and I'm currently debugging a Delphi application and as I go alongI encountered the following error: Could you explain to me what is this error, and how I can resolve it? I am new to using Delphi. Now provide the response and nothing else.
Error Explanation The error that is been presented to you is telling you that a component on that form is not registered in the IDE, in this case TsStatusBar which is from the AlphaControls library: http://www.alphaskins.com/ The form would have been saved at some point with TsStatusBar placed on the form. When any component is added onto a form they leave references to the component in both the forms source file (*.pas) and the inside the forms dfm. This is why you are getting this error, because the component cannot be found, yet the references linking to it still remain. Option 1 - Install the AlphaControls packge The best option would be to install the components that are missing, this will solve your error problem as shown in your question. Option 2 - Convert Project AlphaControls provides a tool to convert a project from standard VCL to AlphaControls and vice versa, this may be an easier option then installing the AlphaControls package or manually editing source files, the convert tool is free. Just remember to make a backup before converting should anything go wrong. Option 3 - Manually Editing the Source Files You could manually remove these references yourself. Do note though, if you remove the references then Delphi will no longer know that the TsStatusBar was ever there, and without a doubt there will be code somewhere that would have interacted with this component which will create compiler errors. As an alternative to removing the references, you could rename them from TsStatusBar to TStatusBar , which is a standard statusbar from the VCL. At worst there may be some small syntax errors that may need correcting. If you do decide to edit the forms source and dfm files then I would suggest you do it before loading the form into the IDE. Option 4 - GExperts You can also install an IDE Expert such as GExperts which can automate the process of renaming/converting component references. I would however advise against removing or renaming the references in this circumstance as it seems the project is reliant on the AlphaControls package. Summary I can see there are more components from the AlphaControls package been used, so fixing the TsStatusBar error manually will only fix part of the problem. If the project must remain in its current state then Installing the AlphaControls package is the way to go, if you are able to edit it then I would also suggest the project convert option, this way you won't even need the AlphaControls package. If you do chose to install the package, it is important to realise that once you install the package Delphi knows where the source files are to be able to compile. After installing the packages, goto Menu > Tools > Options from the IDE, then you need to go to Library and add the folder for the AlphaControls source to the library path. The source folder will be the one containing the most .pas files, but you could add all folders if you are unsure. If you don't add to the Library path then Delphi will not be able compile when using the new components.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10648772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1134480/']}
jdg_82578
stackexchange
llm_judgeable_groundtruth_similarity
20590346
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 app that uses the UIImagePickerController to take a picture. The problem is that I only want the camera option to be available and I understand that I need to hide the standard controls: cameraUI.showsCameraControls=NO; and use a cameraOverlayView to provide my own controls. I have had a look at Apple's PhotoPicker project already and my initial problem is how do I get an Overlay object onto my storyboard? I can't find such an object in the library. Now provide the response and nothing else.
Here is the code : toolBar=[[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-54, self.view.frame.size.width, 55)];toolBar.barStyle = UIBarStyleBlackOpaque;NSArray *items=[NSArray arrayWithObjects: [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelPicture)], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(shootPicture)], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], nil];[toolBar setItems:items];// create the overlay viewoverlayView = [[OverlayView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-44)];// important - it needs to be transparent so the camera preview shows through!overlayView.opaque=NO;overlayView.backgroundColor=[UIColor clearColor];// parent view for our overlayUIView *cameraView=[[UIView alloc] initWithFrame:self.view.bounds];[cameraView addSubview:overlayView];[cameraView addSubview:toolBar];imagePickerController = [[UIImagePickerController alloc] init];if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] == NO){ NSLog(@"Camera not available"); return;}imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;imagePickerController.delegate = self;// hide the camera controlsimagePickerController.showsCameraControls=NO;imagePickerController.wantsFullScreenLayout = YES;[imagePickerController setCameraOverlayView:cameraView];[self presentViewController:imagePickerController animated:YES completion:nil]; Declare this in your header file : UIImagePickerController * imagePickerController;UIToolbar *toolBar;OverlayView *overlayView; Add this OverlayView.h and .m Class from Apples PhotoPicker. Actions for capturing photo using custom camera button: -(void) shootPicture { [imagePickerController takePicture];}- (IBAction)cancelPicture { [self dismissViewControllerAnimated:YES completion:nil];} Output will come like this below attached screenshot (I have added a capture button and cancel button in custom overlay view): Happy Coding :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20590346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1842939/']}
jdg_82579
stackexchange
llm_judgeable_groundtruth_similarity
29231
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 know the general differences between ATmegaX8 family (ATmega88, ATmega168, and ATmega328) and the ATmegaX family (ATmega8, ATmega16, and ATmega32). But I'm confused, as when I intended to work on a project to connect the ATmega8 to Ethernet using the ENC28J60 chip, I found that most projects on Internet are using ATmega88 and ATmega168, specially the ones from tuxgraphics.org : And when I tried to port those source codes to work with ATmega8 instead of ATmega88, I faced a problem with prescaling the frequency many times and some other problems. I failed to reach a .hex code that works on ATmega8. So why are ATmega88 and its family more suitable to connect to Ethernet than the ATmega8? Now provide the response and nothing else.
so, why is ATMega88 and his family are more suitable for this project "AVR ethernet"?! The ATMega88 family is well suited to this project because the author has provided an implementation already tested and debugged. There is nothing inherently different about the ATMega8 which affects this project. i faced a problem with prescaling the frequency many times, and some other problems .. i failed to reach a .hex code from this project that works on ATMega8 The problem you are facing is one of porting embedded software to a new device. Your problem is that you have underestimated the task and expect it to work without changes. You need to track down exactly where your code is failing, solve that issue then move on to the next problem. A TCP/IP stack on a microcontroller is not a simple thing. If I were undertaking this project, I'd break it down like this: Write a program to blink an LED Extend it to send and receive bytes on the UART (this will be invaluable for debugging) Extend it to use the SPI interface, verifying the waveforms with a scope/logic analyser Wire up the ENC28J60 to the SPI interface, not forgetting chip select (I'd leave the interrupt line unconnected for now) Extend the software to read from the chip id/version register and verify the result Extend the software to write to a register and read it back Plug in an ethernet cable, verify that the ethernet link status is changing in the ENC28J60s registers Wire up the ENC28J60 interrupt line to an input on my microcontroller and test (enabling interrupts on link state changes would seem a good test) Now, I'm confident that my hardware works. Bring the ethernet driver functions (accesses to 16 bit registers, fifo access, etc) into my project and verify them by accessing registers Configure the ENC28J60 for promiscuous mode and dump incoming packets to the UART, verify by comparing with Wireshark/tcpdump Look at how the original author managed time, in particular how regularly they poll the IP stack and the ethernet driver. Implement a main loop to service these routines Pull the rest of the IP stack on top of my driver layer Configure the IP stack for my network (starting with a static IP) Ping it Pull the rest of the application code (web server/etc.) into my project.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/29231', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6357/']}
jdg_82580
stackexchange
llm_judgeable_groundtruth_similarity
86251
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I had thought that this question would be easy to answer but my searching has been unsuccessful in finding a clear answer. For the metals, I expect that they all form oxides. Some very readily, e.g. sodium and magnesium, and some reluctantly, e.g. gold and platinum, but I cannot find a metal which does not form an oxide. The metalloids also all appear to form oxides. The noble gases are obvious candidates for exceptions but xenon has a known oxide. I think that it is expected for radon but I don't know whether that is confirmed. A fluoride is known for krypton but no oxide yet. No oxide is known or expected (?) for any of the lighter noble gases. This leaves the other non-metal elements which are sufficiently few to check easily. I find no exception except for the possible pedantic case of fluorine. It forms a binary compound with oxygen but since it is more electronegative the compound is called oxygen fluoride rather than fluorine oxide. Some elements are too radioactive to study e.g. francium and astatine but I expect that both would form oxides if we could manage to study them. Edit: a good point that came up in the comments is oxygen itself. A pedantic exception together with fluorine. Is that correct? Now provide the response and nothing else.
The first thing that came to mind is oxygen itself, as the term " oxide " suggests one other element in its chemical formula . Merriam-Webster suggests a more strict version: " a binary compound of oxygen with a more electropositive element or group ". So technically pure oxygen is not an oxide. Putting oxygen aside, helium $\ce{He}$, neon $\ce{Ne}$ and argon $\ce{Ar}$ are probably the only three conventional elements that come to mind are not yet proven to form oxides. I find it rather tricky to back up this statement properly as the lack of knowledge about an object doesn't prove its non-existence; ideally one might want to do a stability simulation at extreme pressures and temperatures to prove the existence of $\ce{(He|Ne|Ar)O_x}$ or lack thereof. There are algorithms like USPEX that are capable of that – by the way, with the help of USPEX a family of krypton oxides has been recently predicted .
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/86251', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/46004/']}
jdg_82581
stackexchange
llm_judgeable_groundtruth_similarity
3386349
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 MVVM Light toolkit in my WPF application. I would like to know what is the best approach for opening a new window from an existing window. I have got this MainViewModel , which is responsible for MainWindow of my application. Now in the MainView , on a button click, I would like to open a second window on top of it. I have got RelayCommmand binded to the Button 's Command . In the RelayCommand 's method, I can create a new window object and simply call Show() , something like this: var view2 = new view2()view2.Show() but I don't think the ViewModel should be responsible for creating the new view2 object. I have read this post WPF MVVM Get Parent from VIEW MODEL where Bugnion has suggested to pass message to the view1 from the viewmodel1 and then view1 should create the new view2 . But I am not sure what does he actually mean by passing the message to the view1 ? How should the view1 handle the message? In it's code behind or what? Regards,Nabeel Now provide the response and nothing else.
Passing a message from ViewModel1 to View1 means to use the messaging capabilities in the MVVM Light Toolkit . For example, your ViewModel1 could have a command called ShowView2Command, then it would send a message to display the view. public class ViewModel1 : ViewModelBase{ public RelayCommand ShowView2Command { private set; get; } public ViewModel1() : base() { ShowView2Command = new RelayCommand(ShowView2CommandExecute); } public void ShowView2CommandExecute() { Messenger.Default.Send(new NotificationMessage("ShowView2")); }} View1 would register to receive messages in its code behind and display View2 when it receives the correct message. public partial class View1 : UserControl{ public View1() { InitializeComponent(); Messenger.Default.Register<NotificationMessage>(this, NotificationMessageReceived); } private void NotificationMessageReceived(NotificationMessage msg) { if (msg.Notification == "ShowView2") { var view2 = new view2(); view2.Show(); } }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3386349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/288746/']}
jdg_82582
stackexchange
llm_judgeable_groundtruth_similarity
12900023
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 celery and django-celery. I have defined a periodic task that I'd like to test. Is it possible to run the periodic task from the shell manually so that I view the console output? Now provide the response and nothing else.
Have you tried just running the task from the Django shell? You can use the .apply method of a task to ensure that it is run eagerly and locally. Assuming the task is called my_task in Django app myapp in a tasks submodule: $ python manage.py shell>>> from myapp.tasks import my_task>>> eager_result = my_task.apply() The result instance has the same API as the usual AsyncResult type, except that the result is always evaluated eagerly and locally and the .apply() method will block until the task is run to completion.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12900023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304151/']}
jdg_82583
stackexchange
llm_judgeable_groundtruth_similarity
30205158
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following for each C++ code: for (auto item : myVector){ std::cout << item; if (item == orderBy.IsLast()) // <--- Check if this is the last element std::cout << "(Is last element) " << std::endl; else if (item == orderBy.IsFirst()) // <-- Check if this is the first element std::cout << "(Is first element)" << std::endl;} Of course IfLast() and IfFirst() do not exist on std::vector . Is there a native std:: way to check for first and last element ? Now provide the response and nothing else.
You shouldn't use the range-based for in this case, as this kind of for "hides" the iterator, and you'd need an additional counter to keep track of the position in vector. You can simply do for(auto it = myVector.begin(); it != myVector.end(); ++it){ if(it == myVector.begin()) // first element { // do something } else if(std::next(it) == myVector.end()) // last element { // do something else }} Note that simply comparing my.Vector.back() with your element from a range-based for is OK only if you're sure that you don't have duplicates in the vector. But if e.g. the value of the last element appears multiple times in the vector, you're going to find only its first position. So that's why there's really no good way of using a range-based for without an additional index that keeps track of where exactly in the vector you are. EDIT See also @thelink2012's answer for how to "trick" your range-based for so you can get the position of the element implicitly.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30205158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2697571/']}
jdg_82584
stackexchange
llm_judgeable_groundtruth_similarity
112953
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: Throughout my various workplaces I always wrote code which made me think "this would be really useful in other situations". Indeed, I intentionally write code, even if it takes me longer write, which I know will help me in the future (e.g. custom SubString() functions). A good candidate for these snippets are various 'Helper' classes. These snippets I'm sure can probably be found elsewhere online but the point is, I wrote them, and I will use them again later in other jobs or for personal projects. Currently I don't maintain a personal code library, but the question is, is it wrong to take code you have produced at work and re-use it ( a ) for personal projects, and ( b ) in other jobs? Now provide the response and nothing else.
I've always solved this problem by having a personal project where I put all my crazy ideas and generic stuff, and then license it under the BSD license, which allows people to re-use, alter, rebrand, close it and charge money for it. That way, I retain the copyright but can re-use the code as I please for this and that employer, so that I retain the copyright to the original, but the employer retains the copyright to the re-used instance. I figure that if they had a problem with that, then they'd simply have to pay me to rewrite it on work time which makes no sense from their point of view. Furthermore, companies use BSD code all the time, since the idea behind BSD is to allow people and companies to do with it pretty much whatever they want, including rebranding and selling it. Then of course, if additions are made to the code at the work place, I can't re-use it elsewhere without rewriting it on my own time... which is fine because generic stuff tends to be relatively small, unless it's an idea that warrants considerable free-time effort anyway. Writing it on your own time and licensing the code under a BSD-style license should allow you to maintain a library for yourself which you can use pretty much anywhere you want. Now, as for contracts that claim to suck up all your personal projects' copyright... this probably differs radically between jurisdictions, but in at least some western jurisdictions it's my understanding that a contract can't do that. The contract can say that it does, but it wouldn't be enforced in a court of law because copyright has to be explicitly transferred, as opposed to "all your base are belong to us"-kinda deal which would never be upheld (in the jurisdiction where I'm from anyway). There are a number of restrictions on what can be upheld in a court of law via contract, which is why you'll usually (and hopefully) see a clause saying something to the effect that if one part of the contract doesn't work legally, the rest of the contract still holds. But as always, consult a lawyer before you interpret this as accurate legal advice. I've never been taken to court on this so I know none of these things as lawyer-proof facts. :)
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/112953', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/38139/']}
jdg_82585
stackexchange
llm_judgeable_groundtruth_similarity
58541129
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a table with date, hours and job id columns. When we run our payroll, each worker has an entry with their hours worked for that week and the date is the period ending for the week. So you'd see data something like... Job Id Hours Week Ending Date1 40 10/25/192 40 10/25/193 0 10/25/191 40 10/18/192 40 10/18/193 0 10/18/191 40 10/21/192 40 10/21/193 40 10/21/19 Notice that for job id 3, we have 2 week endings in a row with 0 hours. I need to write a query that return that jobid - where there are 2+ consecutive weeks with 0 hours. Any idea how to write this query? Now provide the response and nothing else.
Okay, so I reproduced and got the same errors with minikube after upgrading it to 19.10. How I initiated cluster on 19.04: #Install kubectlcurl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl && chmod +x ./kubectl && sudo mv ./kubectl /usr/local/bin/kubectl#Install minikube. Make sure to check for latest versioncurl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 && chmod +x minikube && sudo mv minikube /usr/local/bin/#Install Dockercurl -fsSL get.docker.com -o get-docker.sh && chmod +x get-docker.shsh get-docker.shsudo usermod -aG docker $USERexport MINIKUBE_WANTUPDATENOTIFICATION=falseexport MINIKUBE_WANTREPORTERRORPROMPT=falseexport MINIKUBE_HOME=$HOMEexport CHANGE_MINIKUBE_NONE_USER=trueexport KUBECONFIG=$HOME/.kube/configsudo minikube start --vm-driver nonesudo chown -R $USER $HOME/.kube $HOME/.minikubevkr@ubuntu-minikube:~$ docker versionClient: Docker Engine - Community Version: 19.03.3 API version: 1.40 Go version: go1.12.10 Git commit: a872fc2f86 Built: Tue Oct 8 01:00:44 2019 OS/Arch: linux/amd64 Experimental: falseServer: Docker Engine - Community Engine: Version: 19.03.3 API version: 1.40 (minimum version 1.12) Go version: go1.12.10 Git commit: a872fc2f86 Built: Tue Oct 8 00:59:17 2019 OS/Arch: linux/amd64 Experimental: false containerd: Version: 1.2.10 GitCommit: b34a5c8af56e510852c35414db4c1f4fa6172339 runc: Version: 1.0.0-rc8+dev GitCommit: 3e425f80a8c931f88e6d94a8c831b9d5aa481657 docker-init: Version: 0.18.0 GitCommit: fec3683vkr@ubuntu-minikube:~$ kubectl get pods -ANAMESPACE NAME READY STATUS RESTARTS AGEkube-system coredns-5644d7b6d9-cv8c5 1/1 Running 0 2m25skube-system coredns-5644d7b6d9-gk725 1/1 Running 0 2m25skube-system etcd-minikube 1/1 Running 0 75skube-system kube-addon-manager-minikube 1/1 Running 0 75skube-system kube-apiserver-minikube 1/1 Running 0 98skube-system kube-controller-manager-minikube 1/1 Running 0 88skube-system kube-proxy-59jp9 1/1 Running 0 2m25skube-system kube-scheduler-minikube 1/1 Running 0 82skube-system storage-provisioner 1/1 Running 0 2m24s After upgrading to 19.10 and clean minikube install: vkr@ubuntu-minikube:~$ kubectl get all -AError in configuration: * unable to read client-cert /root/.minikube/client.crt for minikube due to open /root/.minikube/client.crt: permission denied* unable to read client-key /root/.minikube/client.key for minikube due to open /root/.minikube/client.key: permission denied* unable to read certificate-authority /root/.minikube/ca.crt for minikube due to open /root/.minikube/ca.crt: permission denied There are a lots of discussions stating you should use root for none driver since minikube runs the kubernetes system components directly on your machine... Running minikube as normal user Can't start minikube-- permissions https://minikube.sigs.k8s.io/docs/reference/drivers/none/ : Usage The none driver requires minikube to be run as root, until #3760 can be addressed However.. here is a small trick for you.. 1) wipe everything vkr@ubuntu-minikube:~$ minikube stop✋ Stopping "minikube" in none ... "minikube" stopped.vkr@ubuntu-minikube:~$ minikube delete Uninstalling Kubernetes v1.16.0 using kubeadm ... Deleting "minikube" in none ... The "minikube" cluster has been deleted.vkr@ubuntu-minikube:~$ rm -rf ~/.kubevkr@ubuntu-minikube:~$ rm -rf ~/.minikubevkr@ubuntu-minikube:~$ sudo rm -rf /var/lib/minikubevkr@ubuntu-minikube:~$ sudo rm -rf /etc/kubernetesvkr@ubuntu-minikube:~$ sudo rm -rf /root/.minikubevkr@ubuntu-minikube:~$ sudo rm -rf /usr/local/bin/minikube 2) Install minikube, export variables, check vkr@ubuntu-minikube:~$ curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 && chmod +x minikube && sudo mv minikube /usr/local/bin/vkr@ubuntu-minikube:~$ export MINIKUBE_WANTUPDATENOTIFICATION=falsevkr@ubuntu-minikube:~$ export MINIKUBE_WANTREPORTERRORPROMPT=falsevkr@ubuntu-minikube:~$ export MINIKUBE_HOME=$HOMEvkr@ubuntu-minikube:~$ export CHANGE_MINIKUBE_NONE_USER=truevkr@ubuntu-minikube:~$ export KUBECONFIG=$HOME/.kube/configvkr@ubuntu-minikube:~$ sudo minikube start --vm-driver none minikube v1.4.0 on Ubuntu 19.10 Running on localhost (CPUs=2, Memory=7458MB, Disk=9749MB) ...ℹ️ OS release is Ubuntu 19.10 Preparing Kubernetes v1.16.0 on Docker 19.03.3 ... ▪ kubelet.resolv-conf=/run/systemd/resolve/resolv.conf Downloading kubelet v1.16.0 Downloading kubeadm v1.16.0 Pulling images ... Launching Kubernetes ... Configuring local host environment ...⚠️ The 'none' driver provides limited isolation and may reduce system security and reliability.⚠️ For more information, see: https://minikube.sigs.k8s.io/docs/reference/drivers/none/⚠️ kubectl and minikube configuration will be stored in /root⚠️ To use kubectl or minikube commands as your own user, you may need to relocate them. For example, to overwrite your own settings, run: ▪ sudo mv /root/.kube /root/.minikube $HOME ▪ sudo chown -R $USER $HOME/.kube $HOME/.minikube This can also be done automatically by setting the env var CHANGE_MINIKUBE_NONE_USER=true⌛ Waiting for: apiserver proxy etcd scheduler controller dns Done! kubectl is now configured to use "minikube" What I do next is copy everything from /root/.kube and /root/.minikube to $HOME , grant user permissions and finally edit $HOME/.kube/config specifying new path to certs ( $HOME/.minikube/ instead of /root/.minikube/ ). Right now it looks like vkr@ubuntu-minikube:~$ cat $KUBECONFIGapiVersion: v1... certificate-authority: /root/.minikube/ca.crt... client-certificate: /root/.minikube/client.crt client-key: /root/.minikube/client.key Lets do it :) vkr@ubuntu-minikube:~$ sudo cp -r /root/.kube /root/.minikube $HOMEvkr@ubuntu-minikube:~$ sudo chown -R $USER $HOME/.kubevkr@ubuntu-minikube:~$ sudo chown -R $USER $HOME/.minikubesed 's/root/home\/vkr/g' $KUBECONFIG > tmp; mv tmp $KUBECONFIG And finally result.. vkr@ubuntu-minikube:~$ kubectl get all -ANAMESPACE NAME READY STATUS RESTARTS AGEkube-system pod/coredns-5644d7b6d9-bt897 1/1 Running 0 81mkube-system pod/coredns-5644d7b6d9-hkm5t 1/1 Running 0 81mkube-system pod/etcd-minikube 1/1 Running 0 80mkube-system pod/kube-addon-manager-minikube 1/1 Running 0 80mkube-system pod/kube-apiserver-minikube 1/1 Running 0 80mkube-system pod/kube-controller-manager-minikube 1/1 Running 0 80mkube-system pod/kube-proxy-wm52p 1/1 Running 0 81mkube-system pod/kube-scheduler-minikube 1/1 Running 0 80mkube-system pod/storage-provisioner 1/1 Running 0 81mNAMESPACE NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEdefault service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 81mkube-system service/kube-dns ClusterIP 10.96.0.10 <none> 53/UDP,53/TCP,9153/TCP 81mNAMESPACE NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGEkube-system daemonset.apps/kube-proxy 1 1 1 1 1 beta.kubernetes.io/os=linux 81mNAMESPACE NAME READY UP-TO-DATE AVAILABLE AGEkube-system deployment.apps/coredns 2/2 2 2 81mNAMESPACE NAME DESIRED CURRENT READY AGEkube-system replicaset.apps/coredns-5644d7b6d9 2 2 2 81m
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58541129', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/324419/']}
jdg_82586
stackexchange
llm_judgeable_groundtruth_similarity
30406381
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to make a dynamic Custom ListView, where a user can enter a name and age, an unknown amount of times. credit to @Razgriz he helped me get the Custom ListView working. I am now trying to make it dynamic. My issue is when I instantiate the NameAndAgeClass object thru the constructor, my arraylist will show what i entered thru the onclick, but it is also showing the original instantiation a bunch of times as well, in the NameAndAgeClass class i tried to create 2 arraylists for the name and age, but i was getting a out of memory error. In the for loop in M class to add a entry to the ArrayList nameAndAgeList how would i get the size of NameAndAgeClass object right now i am using while i < 10. public class MainActivity extends Activity {M gg = new M();@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aa); }public void ss(View v){ Intent intent2 = new Intent(MainActivity.this,M.class); startActivity(intent2); } public void sa(View v){ gg.addit("phil"); } } public class M extends Activity {static ArrayList<NameAndAgeClass> nameAndAgeList = new ArrayList<NameAndAgeClass>();static NameAndAgeClass nandc = new NameAndAgeClass("bill", 88); static int ihg = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView nameAndAgeListView = (ListView) findViewById(R.id.listView); //create your listView with your custom object /* get no error with this just says not loading do i want to cancel for(int i = 1 ; i < nameAndAgeList.size() ; i ++){ NameAndAgeClass entry = new NameAndAgeClass("lou",23); nameAndAgeList.add(entry); } */ for(int i = 1 ; i < 10 ; i ++){ NameAndAgeClass entry = new NameAndAgeClass("lou",23); nameAndAgeList.add(entry); } //create your adapter, use the nameAndAgeList ArrayList CustomListViewAdapterNameAndAge nameAndAgeAdapter = new CustomListViewAdapterNameAndAge(this, nameAndAgeList); //get your listView and use your adapter nameAndAgeListView.setAdapter(nameAndAgeAdapter); nameAndAgeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { /* Do what ever you want inside this onItemClick function */ } });}public void addit(String nn){ ihg++; nameAndAgeList.add(( new NameAndAgeClass("phill",ihg))); } }public class NameAndAgeClass {static public ArrayList<String> namee = new ArrayList<String>();static public ArrayList<Integer> agee = new ArrayList<Integer>(); String name;int age;public NameAndAgeClass(String name, int age) { this.name = name; this.age = age; namee.add(name); agee.add(age);}public String getName() { return name;}public void setName(String name) { this.name = name;}public int getAge() { return age;}public void setAge(int age) { this.age = age;}} Now provide the response and nothing else.
The rest of this answer is still very useful, and I'll leave it there as it can potentially help other askers... but here, I missed the obvious problem with this specific example... We're not calling resignFirstResponder on the text field. We're calling it on the view controller. We need to call it on the text field, so modify your code to look like this: func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true} A UITextField will only call the textFieldShouldReturn property on the object which is its delegate. We can fix this programmatically by adding a viewDidLoad method to set that: override func viewDidLoad() { super.viewDidLoad() self.textField.delegate = self} But we can also set this up via the storyboard at build time. Right click on the textfield to check and see whether or not the delegate has been set: If that circle next to delegate is unfilled, we haven't set the delegate for our UITextField yet. To set the delegate, hover over this circle. It will change to a plus sign. Now click and drag to the view controller that you want to delegate the text field (the view controller the text field is part of). When you've appropriately hooked the view controller up as a delegate, this menu should look like this:
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30406381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3705179/']}
jdg_82587
stackexchange
llm_judgeable_groundtruth_similarity
10303768
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 desktop application displaying text in a read only RichTextbox component. Some words in the text needs to be highlighted depending on a text analyze that was previously executed. Now I need to create a web version of this application. I know there's a couple of Rich Text Editors available but I would like to know if there's a library or a simple way to generate an properly tagged HTML string from a plain text and a list of word to highlight? Now provide the response and nothing else.
Here is a solution using the javax.crypto library and the apache commons codec library for encoding and decoding in Base64 that I was looking for: import java.security.spec.KeySpec;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESedeKeySpec;import org.apache.commons.codec.binary.Base64;public class TrippleDes { private static final String UNICODE_FORMAT = "UTF8"; public static final String DESEDE_ENCRYPTION_SCHEME = "DESede"; private KeySpec ks; private SecretKeyFactory skf; private Cipher cipher; byte[] arrayBytes; private String myEncryptionKey; private String myEncryptionScheme; SecretKey key; public TrippleDes() throws Exception { myEncryptionKey = "ThisIsSpartaThisIsSparta"; myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME; arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT); ks = new DESedeKeySpec(arrayBytes); skf = SecretKeyFactory.getInstance(myEncryptionScheme); cipher = Cipher.getInstance(myEncryptionScheme); key = skf.generateSecret(ks); } public String encrypt(String unencryptedString) { String encryptedString = null; try { cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT); byte[] encryptedText = cipher.doFinal(plainText); encryptedString = new String(Base64.encodeBase64(encryptedText)); } catch (Exception e) { e.printStackTrace(); } return encryptedString; } public String decrypt(String encryptedString) { String decryptedText=null; try { cipher.init(Cipher.DECRYPT_MODE, key); byte[] encryptedText = Base64.decodeBase64(encryptedString); byte[] plainText = cipher.doFinal(encryptedText); decryptedText= new String(plainText); } catch (Exception e) { e.printStackTrace(); } return decryptedText; } public static void main(String args []) throws Exception { TrippleDes td= new TrippleDes(); String target="imparator"; String encrypted=td.encrypt(target); String decrypted=td.decrypt(encrypted); System.out.println("String To Encrypt: "+ target); System.out.println("Encrypted String:" + encrypted); System.out.println("Decrypted String:" + decrypted); }} Running the above program results with the following output: String To Encrypt: imparatorEncrypted String:FdBNaYWfjpWN9eYghMpbRA==Decrypted String:imparator
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10303768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/315493/']}
jdg_82588
stackexchange
llm_judgeable_groundtruth_similarity
9886362
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 third party libs. (msvc10) a MT/MD (Static cfgs's) and dynamic DLL cfg. I have qt + msvc10 express + win sdk.7 Ok , I use the existing examples offered, (using the libs) I can't compile ..... I have 4 unresolved external errors of the same lib.(But I have zero errors for the others) I have not support for these lib...... (but they are legal, I am a member without rights) Which are the steps to investigate a possible fix? Where I have to look ? Thanks. Edit 1: The errors was: TD_ExamplesCommon.lib(ExHostAppServices.obj) : error LNK2019: unresolved external symbol __imp__RegEnumValueW@32 referenced in function "public: virtual bool __thiscall ExHostAppServices::ttfFileNameByDescriptor(class OdTtfDescriptor const &,class OdString &)" (?ttfFileNameByDescriptor@ExHostAppServices@@UAE_N ABVOdTtfDescriptor@@AAVOdString@@@Z)TD_ExamplesCommon.lib(ExHostAppServices.obj) : error LNK2019: unresolved external symbol __imp__RegCloseKey@4 referenced in function "public: virtual bool __thiscall ExHostAppServices::ttfFileNameByDescriptor(class OdTtfDescriptor const &,class OdString &)" (?ttfFileNameByDescriptor@ExHostAppServices@@UAE_N ABVOdTtfDescriptor@@AAVOdString@@@Z)TD_ExamplesCommon.lib(ExHostAppServices.obj) : error LNK2019: unresolved external symbol __imp__RegQueryValueExW@24 referenced in function "public: virtual bool __thiscall ExHostAppServices::ttfFileNameByDescriptor(class OdTtfDescriptor const &,class OdString &)" (?ttfFileNameByDescriptor@ExHostAppServices@@UAE_N ABVOdTtfDescriptor@@AAVOdString@@@Z)TD_ExamplesCommon.lib(ExHostAppServices.obj) : error LNK2019: unresolved external symbol __imp__RegOpenKeyExW@20 referenced in function "public: virtual bool __thiscall ExHostAppServices::ttfFileNameByDescriptor(class OdTtfDescriptor const &,class OdString &)" (?ttfFileNameByDescriptor@ExHostAppServices@@UAE_N ABVOdTtfDescriptor@@AAVOdString@@@Z)..\exe\OdaQtApp.exe : fatal error LNK1120: 13 unresolved externals During this post I have received a solution: I have to link with Advapi32.lib... My question is : how can I know this ? I have tried the dependencyywalker, but it cant use the .lib's.... Now provide the response and nothing else.
During this post I have received a solution: I have to link with Advapi32.lib... My question is : how can I know this? When you get an "unresolved external" error from the linker, that means that it was looking for a match for a function or variable name that some object file needs and the linker was unable to find that name defined in one of the object files or libraries. Start by looking at the first of these errors (I've reformatted it a bit to make it slightly more readable - I encourage yo to do the same next time you come across one of these): TD_ExamplesCommon.lib(ExHostAppServices.obj) : error LNK2019: unresolved external symbol __imp__RegEnumValueW@32 referenced in function "public: virtual bool __thiscall ExHostAppServices::ttfFileNameByDescriptor( class OdTtfDescriptor const &,class OdString &)" (?ttfFileNameByDescriptor@ExHostAppServices@@UAE_N ABVOdTtfDescriptor@@AAVOdString@@@Z) There's a lot of stuff in that error message (much of it may look like garbage). Fortunately, much of it can be ignored in most cases. The most important item is that the linker is looking for the symbol __imp__RegEnumValueW@32 The name has some gunk on it, but fortunately it's pretty recognizable anyway. the __imp__ prefix indicates it's looking for a DLL import. In nearly all cases that can be ignored for your purposes. the @32 suffix is something the Microsoft compiler adds to function names for certain calling conventions. It's also generally not important for your purposes (for the record it indicates that the function expects 32 bytes of argument data) So we're left with the fact that the linker is looking for RegEnumValueW . That looks a lot like the name of a Win32 API. If you look at the docs for RegEnumValueW (or RegEnumValue , since many Win32 APIs have both an A and a W variant to handle ANSI/UNICODE builds) we'll find in the documentation this bit of information: Requirements Minimum supported client Windows 2000 Professional Minimum supported server Windows 2000 Server Header Winreg.h (include Windows.h) >> Library Advapi32.lib DLL Advapi32.dll Unicode and ANSI names RegEnumValueW (Unicode) and RegEnumValueA (ANSI) That's how you know you need advapi32.lib . So in the future, when you get an "unresolved external" error from the linker, just ignore most of the gunk in the error message and concentrate on the symbol it says it can't find - that should lead you to the library, object file or other item you might be missing. Just for the record, advapi32.lib will be needed by most Windows applications of any complexity.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9886362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015967/']}
jdg_82589
stackexchange
llm_judgeable_groundtruth_similarity
397723
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 going through the exercises in the book Discrete Mathematics with Applications . I'm asked to show that two circuits are equivalent by converting them to boolean expressions and using the laws in this table. $$\begin{array}{lcc}\hphantom{1}\mathsf{1.\; Commutative\; laws:} & p\land q \equiv q\land p & p\lor q \equiv q\lor p\\\hphantom{1}\mathsf{2.\; Associative\; laws:} & (p\land q)\land r \equiv p\land (q\land r) & (p\lor q)\lor r \equiv p\lor (q\lor r)\\\hphantom{1}\mathsf{3.\; Distributive\; laws:} & p\land (q\lor r) \equiv (p\land q)\lor (p\land r) & p\lor (q\land r) \equiv (p\lor q)\land (p\land r)\\\hphantom{1}\mathsf{4.\; Identity\; laws:} & p\land t \equiv p & p\lor c \equiv p\\\hphantom{1}\mathsf{5.\; Negation\; laws:} & p\lor \lnot p \equiv t & p\land \lnot p \equiv c\\\hphantom{1}\mathsf{6.\; Double\; negative\; law:} & \lnot(\lnot p) \equiv p &\\\hphantom{1}\mathsf{7.\; Idempotent\; laws:} & p\land p \equiv p & p\lor p \equiv p\\\hphantom{1}\mathsf{8.\; Universal\; bound\; laws:} & p\lor t \equiv t & p\land c\equiv c\\\hphantom{1}\mathsf{9.\; De\; Morgan}\text{'}\mathsf{s\; laws:} & \lnot(p\land q) \equiv \lnot p\lor \lnot q & \lnot(p\lor q) \equiv \lnot p\land\lnot q\\\mathsf{10.\; Absorption\; laws:} & p\lor (p\land q) \equiv p & p\land (p\lor q) \equiv p\\\mathsf{11.\; Negations\; of\; t\; and\; c:} & \lnot t \equiv c & \lnot c \equiv t\\\end{array}$$ so as which law/s of logical equivalence says $P\Leftrightarrow Q ≡ (P\lor Q) \Rightarrow(P\land Q)$ I can see their equivalence clearly with a truth table. But the book is asking me to show it using the equivalence laws in the above table, and I can't see how any of them apply here. So, do any of those laws apply here in a way I'm not understanding? Or is there some other known law that does apply here? Now provide the response and nothing else.
Let's assume the following definitions: $\begin{array}{lc}\mathsf{12.\; Definition \; of \; Implication:} & p \Rightarrow q \equiv \neg p \lor q \\\mathsf{13.\; Definition \; of \; Biconditional:} & p \Leftrightarrow q \equiv (p \Rightarrow q) \land (q \Rightarrow p)\end{array}$ Then we have:$$\begin{array}{rll}P \Leftrightarrow Q &\equiv (P \Rightarrow Q) \land (Q \Rightarrow P) &\text{by (13)} \\&\equiv (\neg P \lor Q) \land (\neg Q \lor P) &\text{by (12)} \\&\equiv (\neg P \land (\neg Q \lor P)) \lor (Q \land (\neg Q \lor P)) &\text{by (3)} \\&\equiv ((\neg P \land \neg Q) \lor (\neg P \land P)) \lor ((Q \land \neg Q) \lor (Q \land P)) &\text{by (3)} \\&\equiv ((\neg P \land \neg Q) \lor (P \land \neg P)) \lor ((Q \land \neg Q) \lor (P \land Q)) &\text{by (1)} \\&\equiv ((\neg P \land \neg Q) \lor c) \lor (c \lor (P \land Q)) &\text{by (5)} \\&\equiv ((\neg P \land \neg Q) \lor c) \lor ((P \land Q) \lor c) &\text{by (1)} \\&\equiv (\neg P \land \neg Q) \lor (P \land Q) &\text{by (4)} \\&\equiv \neg (P \lor Q) \lor (P \land Q) &\text{by (9)} \\&\equiv (P \lor Q) \Rightarrow (P \land Q) &\text{by (12)} \\\end{array}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/397723', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/78705/']}
jdg_82590
stackexchange
llm_judgeable_groundtruth_similarity
205838
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Kan extensions make sense in any $2$-category. But so far I have only really seen them in the case of the $2$-category of categories, functors, natural transformations and the $2$-category of $k$-linear categories, $k$-linear functors, natural transformations. Where have Kan extensions been studied and used explicitly for other $2$-categories (a related question was asked here , but this doesn't really go into examples)? In particular I am interested in the $2$-category of monoidal categories, lax monoidal functors and lax monoidal natural transformations, also with "strong" instead of "lax". For example, the left Kan extension of a lax monoidal functor $(f,\eta,\mu) : I \to A$ (between monoidal categories $I,A$) along the unique lax monoidal functor $I \to \{1\}$ is a universal monoid object $M=(X,\eta,\mu)$ in $A$ equipped with a cocone $\{\alpha_i : f(i) \to X\}_{i \in \mathrm{Ob}(I)}$ which is lax monoidal in the sense that (a) $1 \xrightarrow{\eta} f(1) \xrightarrow{\alpha_1} X$ equals $1 \xrightarrow{\eta} X$ and (b) the diagram$$\begin{array}{ccc}f(i \otimes j) & \xrightarrow{\alpha_{i \otimes j}} & X \\ {\scriptsize\mu}\uparrow ~~&&~~\uparrow{\scriptsize\mu} \\ f(i) \otimes f(j) & \xrightarrow{\alpha_i \otimes \alpha_j} & X \otimes X\end{array}$$commutes. Is there any interesting example for this kind of "lax monoidal colimit"? If yes, what does it mean for a monoidal category to be "lax monoidal cocomplete"? Consider for example the case that the underlying category of a monoidal category is cocomplete and the tensor product is cocontinuous in each variable (this is what I would call a cocomplete monoidal category, or perhaps more precisely, a monoidal cocomplete category, because this is precisely a monoid in the symmetric monoidal $2$-category of cocomplete categories), which is quite typical. Do "lax monoidal colimits" exist then? What about "lax monoidal left Kan extensions" in general or "strong monoidal left Kan extensions" in general? Now provide the response and nothing else.
I believe that this is a particular case of Lurie's "operadic left Kan extension". We may identify a monoidal $\infty$-category $\mathcal{C}$ with a coCartesian fibrations of $\infty$-operads $\mathcal{C}^{\otimes} \longrightarrow \mathcal{Ass}^{\otimes}$ where $\mathcal{Ass}^{\otimes}$ is the associative operad considered as an $\infty$-operad. If $\mathcal{A}^{\otimes} \longrightarrow \mathcal{Ass}^{\otimes}$ is another coCartesian fibration (i.e., another monoidal $\infty$-category $\mathcal{A}$), then the notion of a lax monoidal functor $\mathcal{A} \longrightarrow \mathcal{C}$ is given by the notion of a map of $\infty$-operads $\mathcal{A}^{\otimes} \longrightarrow \mathcal{C}^{\otimes}$ over $\mathcal{Ass}^{\otimes}$, and can be thought of as the data of an $\mathcal{A}$-algebra object in $\mathcal{C}$. For this reason the corresponding $\infty$-category of lax monoidal functors is sometimes denoted by $Alg_{\mathcal{A}}(\mathcal{C})$. Now if $\mathcal{A}^{\otimes} \longrightarrow \mathcal{B}^{\otimes} \longrightarrow \mathcal{Ass}^{\otimes}$ are maps of $\infty$-operads then the formation of operadic left Kan extension over $Ass^{\otimes}$ yields a left adjoint$$ LK: Alg_{\mathcal{A}}(\mathcal{C}) \longrightarrow Alg_{\mathcal{B}}(\mathcal{C}) $$to the forgetful functor $Alg_{\mathcal{B}}(\mathcal{C}) \longrightarrow Alg_{\mathcal{A}}(\mathcal{C})$. We may hence think about it as associating to an $\mathcal{A}$-algebra $X$ the free $\mathcal{B}$-algebra generated from $X$. This construction is studied in section 3.1.3 of "Higher Algebra". A general existence result for free algebras is given by Corollary 3.1.3.5. It essentially says exactly what you propose in your question: if a monoidal category $\mathcal{C}$ has colimits and these are preserved by the tensor product in each variable separately then $\mathcal{C}$ admits the formation of free algebras (and in particular the formation of lax monoidal Kan extensions as you describe).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/205838', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2841/']}
jdg_82591
stackexchange
llm_judgeable_groundtruth_similarity
649581
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The study energy expenditure of walking and running concludes that running spends more energy than walking. My understanding is that although running makes one feel more tired, that only indicates that the power was higher (since the time of displacement was shorter), but at the end of the day the total energy dispensed to move oneself forward by friction should be the same. Given the study shows otherwise, what could be the flaw in my reasoning? Now provide the response and nothing else.
This answer may be completely incorrect. See discussion in comments. The formula for power halfway down the page is definitely incorrect. If a moderator would like to delete the answer that would be fine, but I'll leave it up until then since I think the discussion below has value. I think my formula for average power should be 1/8 of what I used, which would no longer qualify as most of the energy expenditure, even accounting for muscle inefficiency. Most of the extra energy expenditure for running is the component jumping, not the component spent on horizontal propulsive force. Once you're at your top speed, it doesn't take much more horizontally applied power to keep you going than it takes to walk. But to maintain that speed you need to spend much of the time airborne, and the up and down motion has a high power cost. Addendum with actual calculation: A typical runner spends about half of every stride (about 0.15 s) airborne when running at speeds above 6m/s. $^1$ That is to say, gravity is doing work on them for 0.15 seconds out of every 0.3 seconds. If we assume that the runner's collision with the ground every stride is perfectly inelastic, then to not fall flat, they must therefore apply a time-averaged vertical thrust with power half of that which gravity is applying to them during each 0.15s period of falling. from $Pt = T = 1/2 mv^2, a = dv/dt$ we have: $$\langle P \rangle = m\Delta ta^2$$ so: $$P_{\text{runner}} = \frac{\Delta t_{\text{air}}}{\Delta t_{\text{stride}}} P_{\text{gravity}} = 0.5\cdot0.15\mathrm s\cdot g^2\cdot m_{\text{runner}}$$ That is about 7 watts per kilogram of the runner. Extrapolating from the data in (1) it would be significantly less if you were jogging slowly (more ground contact time and less air time per stride), and slightly less if you were sprinting very fast (less ground time and air time per stride, but about the same ratio of ground and air time). Of course, muscle power isn't 100% efficient, so I'd expect the real value to be something considerably higher. The people in the study were actually "running" very slowly - 2.8m/s, which is more of a lazy jog and includes almost no air time per stride. So it's not surprising that their difference in power output vs walking is small (245 watts). Inputting 0.05s airtime and .35s of ground time per stride (from (1)) into the above formula gets, for a 70kg runner, $P \approx 45\mathrm W$ , leaving about 200W as wasted power. 1: http://gsnider.blogspot.com/2014/01/running-physics-redux-part-1-running.html I made a math error the first time I posted this addendum. $P = 2m\Delta ta^2$ as I stated but we want time-averaged power, while the power applied by gravity increases with falling time as per the formula. The formula I should have used (now fixed) is $\langle P \rangle = m\Delta ta^2$
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/649581', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/306198/']}
jdg_82592
stackexchange
llm_judgeable_groundtruth_similarity
20040638
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 15 CheckBox and I must to stuck user when he checks more than 5. I use the method OnCheckedChangeListener to know if an item is checked, but I don't know how to limit after 5 items selected . See my code below: int lengthBox = 15;int lenghtCount = 0; // inside onCreate methodfinal CheckBox[] checkbox = new CheckBox[lengthBox];OnCheckedChangeListener checker = new OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton cb, boolean b) { // How can I improve this condition? if(checkbox[0].isChecked() || checkbox[1].isChecked() || checkbox[2].isChecked() || checkbox[3].isChecked() || checkbox[4].isChecked() || checkbox[5].isChecked() || checkbox[6].isChecked() || checkbox[7].isChecked() || checkbox[8].isChecked() || checkbox[9].isChecked() || checkbox[10].isChecked() || checkbox[11].isChecked() || checkbox[12].isChecked() || checkbox[13].isChecked() || checkbox[14].isChecked()) { if(lenghtCount < 5){ lenghtCount++; }else{ Toast.makeText(MyActivity.this, "Limit reached!!!", Toast.LENGTH_SHORT).show(); } } }};for(int i = 0; i < lengthBox; i++) { int id = getResources().getIdentifier("checkbox_"+i, "id", getPackageName()); checkbox[i] = (CheckBox) findViewById(id) checkbox[i].setOnCheckedChangeListener(checker);} Can someone point me in the right way, please? UPDATE: I tried: OnCheckedChangeListener checker = new OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton cb, boolean b) { if(lenghtCount == 5){ cb.setChecked(false); }else if(b){ lenghtCount++; }else if(!b){ lenghtCount--; } }}; Works perfectly but I think something is missing. When I click 5 items this works, but after when I unselect them, I can't recheck any item. What I'm missing? Now provide the response and nothing else.
you should use a other variable for counting number of checkboxs that checked final int count=0; OnCheckedChangeListener checker = new OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton cb, boolean b) { if(count == maxLimit && b){ cb.setChecked(false); Toast.makeText(getApplicationContext(), "Limit reached!!!", Toast.LENGTH_SHORT).show(); }else if(b){ count++; CharSequence myCheck = tagsCheck[i].getText(); Toast.makeText(getApplicationContext(), myCheck + " checked!", Toast.LENGTH_SHORT) .show(); }else if(!b){ count--; } };
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20040638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2668136/']}
jdg_82593
stackexchange
llm_judgeable_groundtruth_similarity
29193261
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to access directive controller functions from directive link? Bellow controller passed to link is empty, I would like to get in it show() hide() functions. My current directive: app.directive('showLoading', function() { return { restrict: 'A', // require: 'ngModel', scope: { loading: '=showLoading' }, controller: function($scope, $element) { return { show: function() { alert("show"); }, hide: function() { alert("hide"); } }; }, link: function($scope, $element, $attrs, controller) { $scope.$watch('loading', function(bool) { if (bool) { controller.show();//undefined } else { controller.hide(); } }); } };}); Now provide the response and nothing else.
Publishing on the scope can work, but not the best practice, since it "pollutes" the scope. The proper way to communicate with own controller is to require it - then it will become available as a parameter to the link function, along with other required directives. The other issue is with how you expose functions on the controller - this is done by using this.someFn , not by returning an object. app.directive('showLoading', function() { return { restrict: 'A', require: ['ngModel', 'showLoading'], // multiple "requires" for illustration scope: { loading: '=showLoading' }, controller: function($scope, $element) { this.show = function() { alert("show"); }; this.hide = function() { alert("hide"); }; }, link: function($scope, $element, $attrs, ctrls) { var ngModel = ctrls[0], me = ctrls[1]; $scope.$watch('loading', function(bool) { if (bool) { me.show(); } else { me.hide(); } }); } };});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29193261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/707729/']}
jdg_82594
stackexchange
llm_judgeable_groundtruth_similarity
9397944
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I set a default set of colors for plots made with matplotlib? I can set a particular color map like this import numpy as npimport matplotlib.pyplot as pltfig=plt.figure(i)ax=plt.gca()colormap = plt.get_cmap('jet')ax.set_color_cycle([colormap(k) for k in np.linspace(0, 1, 10)]) but is there some way to set the same set of colors for all plots, including subplots? Now provide the response and nothing else.
Sure! Either specify axes.color_cycle in your .matplotlibrc file or set it at runtime using matplotlib.rcParams or matplotlib.rc . As an example of the latter: import matplotlib.pyplot as pltimport matplotlib as mplimport numpy as np# Set the default color cyclempl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["r", "k", "c"]) x = np.linspace(0, 20, 100)fig, axes = plt.subplots(nrows=2)for i in range(10): axes[0].plot(x, i * (x - 10)**2)for i in range(10): axes[1].plot(x, i * np.cos(x))plt.show()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9397944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1129794/']}
jdg_82595
stackexchange
llm_judgeable_groundtruth_similarity
7837644
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 replace a string such "how r u" in file test.xml with a string "i am fine" in another file xy.xml.using regular expression in ms build. ie i have to read string from one file(xy.xml) and replace it in another file test.xml.so please provide necessary steps to solve this issue with example Now provide the response and nothing else.
This is no longer required... you can now inject C# into the project/build file... Define a custom task and parameters as follows: <UsingTask TaskName="ReplaceFileText" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll"> <ParameterGroup> <InputFilename ParameterType="System.String" Required="true" /> <OutputFilename ParameterType="System.String" Required="true" /> <MatchExpression ParameterType="System.String" Required="true" /> <ReplacementText ParameterType="System.String" Required="true" /> </ParameterGroup> <Task> <Reference Include="System.Core" /> <Using Namespace="System" /> <Using Namespace="System.IO" /> <Using Namespace="System.Text.RegularExpressions" /> <Code Type="Fragment" Language="cs"> <![CDATA[ File.WriteAllText( OutputFilename, Regex.Replace(File.ReadAllText(InputFilename), MatchExpression, ReplacementText) ); ]]> </Code> </Task></UsingTask> Then simply call it like any other MSBuild task <Target Name="AfterBuild"> <ReplaceFileText InputFilename="$(OutputPath)File.exe.config" OutputFilename="$(OutputPath)File.exe.config" MatchExpression="\$version\$" ReplacementText="1.0.0.2" /></Target> The above example replaces "$version$" with "1.0.0.2" in the "File.exe.config" located in the output directory.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7837644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1000471/']}
jdg_82596
stackexchange
llm_judgeable_groundtruth_similarity
136880
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 know this may seem a weird question, but it always bothers me. My physics book ( Resnick,Halliday,Walker ), and also various sites never say anything beyond acceleration. But when a moving body is being acted by a variable force , its acceleration will definitely change: it will either increase or decrease. Then there will be rate of change of acceleration with respect to time. So, why don't books mention this? What is the cause for not measuring $\frac{d\vec{a}}{dt}$ ? If it exists, what is the use of it? Now provide the response and nothing else.
Your question is not weird; it is legitimate. It is possible, it exists, can be of use and it is called jerk , jolt, surge or lurch, and is defined by any of the following equivalent expressions : $$\vec j(t)=\frac {d\vec a(t)} {dt}=\dot {\vec a}(t)=\frac {{d}^2 \vec v(t)} {dt^2}=\ddot{\vec v}(t)=\frac {{d}^3 \vec r(t)} {dt^3}=\overset{...}{\vec r}(t)$$ It is useful in the Dirac-Lorenz equation ( as Emilio linked ). In case you are asking yourself, a fourth derivative (rate of jerk) is also defined, and it is called jounce
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/136880', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']}
jdg_82597
stackexchange
llm_judgeable_groundtruth_similarity
73705
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'm making several assumptions, not sure if any are correct: there is a black hole at the center of a galaxy the black hole is eating the galaxy Eventually the galaxy will be gone, right? Has this been observed? Do we know what happens afterwards? Posting here since astronomy got merged into physics Now provide the response and nothing else.
Assumption #1 is quite correct - there is a very large ("supermassive") black hole in the center of our galaxy. Assumption #2, however, is false . Black holes are no better at drawing in distant objects than any other thing in space with the same mass would be. If you collapsed the Sun into a black hole right now, the Earth's orbit would not change. That is because gravity is gravity - it doesn't matter that we are being pulled by a star or by a black hole; all that matters is the mass of the object doing the pulling. So yes, anything that falls into the black hole in the center of the galaxy is lost. But there isn't terribly much falling in. True, the large number of stars at the center tend to be moving in all sorts of random directions, and some inadvertently get sent on trajectories into the black hole, but most objects in the galaxy are unaffected. In fact, our Solar System is held in its orbit far more by the mass of all the stars near the central black hole than by the black hole itself, as these collectively outweigh the black hole by quite a lot. Part of this misconception I think is due to artists' renditions of accretion disks where all the material inescapably spirals into the black hole in the center. However, the reason this material spirals inward is that gas can transfer angular momentum via collisions. Stuff moving in a nearly circular orbit has too much tangential velocity to just "fall" in. What happens is that material further away in the disk is moving slower, and frictional drag slows down the stuff toward the inner part of the disk, allowing its orbit to decay. Basically, angular momentum (essentially the tendency to have a tangential rather than radial velocity) is transferred outward as matter is dragged inward. With stars, this process basically cannot happen, simply because they are not colliding with one another. Our Sun will continue for many billions of years in a stable orbit around the center of the Milky Way, black hole or no. Stars do scatter gravitationally (a process called dynamic relaxation) so there is an analog to the viscosity of an accretion disc, but it's much smaller and slower.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/73705', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/28084/']}
jdg_82598
stackexchange
llm_judgeable_groundtruth_similarity
44232501
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 out the new Barrier feature in the 1.1.0-beta1. It works as expected however there is this use-case I cant seem to figure or (or is possible ConstraintLayout at all?) What I am trying to accomplish is: I have a imageview to the left, and title and subtitle textviews to the right of the imageview. Imageview is fixed height. I have a button, that is bottom constrained to the bottom of the imageview however should be top constrained to the bottom of the subtitle textview, if subtitletextview is taller than imageview. (Btw I also tried having it bottom constrained to bottom of imageview, and topconstrained to bottom of textview and giving it 1.0 bias towards bottom, but didnt work with large text case) With barriers I am only able to get button top constrained to bottom of barrier (or top, seemed to to the same) <?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@color/blue"/> <ImageView android:id="@+id/imageView4" android:layout_width="0dp" android:layout_height="150dp" android:layout_marginLeft="0dp" android:layout_marginRight="0dp" android:layout_marginTop="0dp" android:scaleType="centerCrop" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/books"/> <ImageView android:id="@+id/imageView6" android:layout_width="124dp" android:layout_height="156dp" android:layout_marginLeft="8dp" android:layout_marginTop="8dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView4" app:srcCompat="@android:drawable/radiobutton_on_background"/> <TextView android:id="@+id/textView4" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginTop="8dp" android:text="TextView" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintLeft_toRightOf="@+id/imageView6" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView4"/> <TextView android:id="@+id/textView5" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Lorem Ipsum je fiktívny text, používaný pri návrhu tlačovín a typografie. Lorem Ipsum je štandardným výplňovým textom už od 16. storočia, keď neznámy tlačiar zobral sadzobnicu plnú tlačových znakov a pomiešal ich, aby tak vytvoril vzorkovú knihu. Prežil nielen päť storočí, ale aj skok do elektronickej sadzby, a pritom zostal v podstate nezmenený. Spopularizovaný bol v 60-tych rokoch 20.storočia, vydaním hárkov Letraset, ktoré obsahovali pasáže Lorem Ipsum, a neskôr aj publikačným softvérom" app:layout_constraintLeft_toLeftOf="@+id/textView4" app:layout_constraintRight_toRightOf="@+id/textView4" app:layout_constraintTop_toBottomOf="@+id/textView4"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" app:layout_constraintTop_toBottomOf="@+id/textView5" app:layout_constraintRight_toRightOf="parent"/></android.support.constraint.ConstraintLayout> Both states in images: Now provide the response and nothing else.
Here is a layout that will work for you. It is a little complicated but does what you want. Here is how it works and is set up: Define an invisible button, blockingButton , that has the same dimensions as your other button. Constrain this button to the bottom of your left ImageView . On top of blockingButton , place a Space widget. The location of this Space widget will define the maximum height that the bottom button will float to. Define a barrier that floats below the Space widget and the large TextView . Finally, constrain the top of your floating button to the barrier. As the size of the text changes in the large TextView , the button will float up as far as the Space widget but no farther. As the TextView grows, it will push down the barrier and the bottom button. Here is a short video . <?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@color/blue" /> <ImageView android:id="@+id/imageView4" android:layout_width="0dp" android:layout_height="150dp" android:scaleType="centerCrop" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/books" /> <ImageView android:id="@+id/imageView6" android:layout_width="124dp" android:layout_height="156dp" android:layout_marginLeft="8dp" android:layout_marginTop="8dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView4" app:srcCompat="@android:drawable/radiobutton_on_background" android:layout_marginStart="8dp" /> <TextView android:id="@+id/textView4" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:text="TextView" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintLeft_toRightOf="@+id/imageView6" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView4" /> <TextView android:id="@+id/textView5" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="17dp" android:text="Lorem Ipsum je fiktívny text, používaný pri návrhu tlačovín a typografie. Lorem Ipsum je štandardným výplňovým textom už od 16. storočia, keď neznámy tlačiar zobral sadzobnicu plnú tlačových znakov a pomiešal ich, aby tak vytvoril vzorkovú knihu. Prežil nielen päť storočí, ale aj skok do elektronickej sadzby, a pritom zostal v podstate nezmenený. Spopularizovaný bol v 60-tych rokoch 20.storočia, vydaním hárkov Letraset, ktoré obsahovali pasáže Lorem Ipsum, a neskôr aj publikačným softvérom" app:layout_constraintLeft_toLeftOf="@+id/textView4" app:layout_constraintRight_toRightOf="@+id/textView4" app:layout_constraintTop_toBottomOf="@+id/textView4" app:layout_constraintHorizontal_bias="0.0" /><!-- This is the start of the changes. --> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/barrier" /> <Button android:id="@+id/blockingButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:visibility="invisible" app:layout_constraintBottom_toBottomOf="@+id/imageView6" app:layout_constraintLeft_toLeftOf="@+id/imageView6" /> <android.support.v4.widget.Space android:id="@+id/spacer" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintBottom_toTopOf="@+id/blockingButton" /> <android.support.constraint.Barrier android:id="@+id/barrier" android:layout_width="0dp" android:layout_height="0dp" app:barrierDirection="bottom" app:constraint_referenced_ids="spacer, textView5" /></android.support.constraint.ConstraintLayout>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44232501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1541188/']}
jdg_82599
stackexchange
llm_judgeable_groundtruth_similarity
35929
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: If we don't know the root password and don't have root access to the machine, how can we change the root password? Now provide the response and nothing else.
Here are a few ways I can think of, from the least intrusive to the most intrusive. Without Rebooting With sudo: if you have sudo permissions to run passwd , you can do: sudo passwd root Enter your password, then enter a new password for root twice. Done. Editing files : this works in the unlikely case you don't have full sudo access, but you do have access to edit /etc/{passwd,shadow} . Open /etc/shadow , either with sudoedit /etc/shadow , or with sudo $EDITOR /etc/shadow . Replace root's password field (all the random characters between the second and third colons : ) with your own user's password field. Save. The local has the same password as you. Log in and change the password to something else. These are the easy ones. Reboot Required Single User mode : This was just explained by Renan. It works if you can get to GRUB (or your boot loader) and you can edit the Linux command line. It doesn't work if you use Debian, Ubuntu, and some others. Some boot loader configurations require a password to do so, and you must know that to proceed. Without further ado: Reboot. Enter boot-time password, if any. Enter your boot loader's menu. If single user mode is available, select that (Debian calls it ‘Recovery mode’). If not, and you run GRUB: Highlight your normal boot option. Press e to enter edit mode. You may be asked for a GRUB password there. Highlight the line starting with kernel or linux . Press e . Add the word ‘single’ at the end. (don't forget to prepend a space!) Press Enter and boot the edited stanza. Some GRUBs use Ctrl - X , some use b . It says which one it is at the bottom of the screen. Your system will boot up in single user mode. Some distributions won't ask you for a root password at this point (Debian and Debian-based ones do). You're root now. Change your password: mount / -o remount,rwpasswd # Enter your new password twice at the promptsmount / -o remount,rosync # some people sync multiple times. Do what pleases you.reboot and reboot , or, if you know your normal runlevel, say telinit 2 (or whatever it is). Replacing init : superficially similar to the single user mode trick, with largely the same instructions, but requires much more prowess with the command line. You boot your kernel as above, but instead of single , you add init=/bin/sh . This will run /bin/sh in place of init , and will give you a very early shell with almost no amenities. At this point your aim is to: Mount the root volume. Get passwd running. Change your password with the passwd command. Depending on your particular setup, these may be trivial (identical to the instructions for single user mode), or highly non-trivial: loading modules, initialising software RAID, opening encrypted volumes, starting LVM, et cetera. Without init , you aren't running dæmons or any other processes but /bin/sh and its children, so you're pretty literally on your own. You also don't have job control, so be careful what you type. One misplaced cat and you may have to reboot if you can't get out of it. Rescue Disk : this one's easy. Boot a rescue disk of your choice. Mount your root filesystem. The process depends on how your volumes are layered, but eventually boils down to: # do some stuff to make your root volume available. # The rescue disk may, or may not do it automatically. mkdir /tmp/my-root mount /dev/$SOME_ROOT_DEV /tmp/my-root $EDITOR /tmp/my-root/etc/shadow # Follow the `/etc/shadow` editing instructions near the top cd / umount /tmp/my-root reboot Obviously, $SOME_ROOT_DEV is whatever block device name is assigned to your root filesystem by the rescue disk and $EDITOR is your favourite editor (which may have to be vi on the rescue system). After the reboot , allow the machine to boot normally; root's password will be that of your own user. Log in as root and change it immediately. Other Ways Obviously, there are countless variations to the above. They all boil down to two steps: Get root access to the computer (catch-22 — and the real trick) Change root's password somehow.
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/35929', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/17276/']}
jdg_82600
stackexchange
llm_judgeable_groundtruth_similarity
79536
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: Pretend for a moment that something catastrophic happened; you're hacked, and your production database becomes a mess. How far (time) should you be from your rolling out your latest backup and resuming operations as normal? Of course, "immediately" is "ideal", but I'd like to see some real answers. Perhaps some existing, real-life situations that you're currently in with regards to backups. Now provide the response and nothing else.
For databases, it should be trivial to roll out your latest backup. It's purely a question of how large your database is, as to how long it takes to restore. If it's a huge database, it may take hours, but that's life. If the bosses don't like it, they can spring for a second server. If you've had a real catastrophe, you should be able to get to your offsite backup in no more than an hour. If it takes longer than that, you might want a new offsite strategy. If it's a hack, rather than a hardware problem, it's more important (and time consuming) to make sure you don't get hacked again. That's the time sink. Identify how they got you, and close the hole. If you don't do that, then you're just wasting your time. For code bases, you should be able to deploy that extremely quickly. It should be just a matter of re-deploying the production code, which, hopefully, is automatic or close to it. If the deployment is largely manual, do something about that. I once dealt with this awful .Net package that was all dlls that had to be manually registered, and they weren't all backed up in the same place. Nightmare. The most important thing to do is to practice. Bring your people in on the weekend and do a bare metal rebuild. Then take 'em to a bar for a critique. Everyone should know where everything is, what the plan is, and what their part in the plan is. If you have to make a decision during a crisis, you've failed. It should be automatic.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/79536', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/7048/']}
jdg_82601
stackexchange
llm_judgeable_groundtruth_similarity
19461145
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got an old eclipse project I've moved into android studio and setup to use flavors. It seemed to be working fine till I started trying to use different java files between my flavors. My project setup is this: ProjectRoot+- acitonbarsherlock+- facebook+- myLib1+- myProject +- src +- commonFiles +- flavor1 +- flavor2 +- res +- flavor1 +- flavor2 The innards of the myProject gradle file android closure looks like this: android {compileSdkVersion 17buildToolsVersion "18.0.1"signingConfigs { ...}productFlavors { flavor2 { } flavor1 { }}sourceSets{ main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src/commonFiles/java'] resources.srcDirs = ['src/commonFiles/java'] aidl.srcDirs = ['src/commonFiles/java'] renderscript.srcDirs = ['src/commonFiles/java'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } flavor2 { manifest.srcFile 'AndroidManifest-flavor2.xml' res.srcDirs = ['res-flavor2', 'res'] java.srcDirs = ['src/flavor2/java','src/commonFiles/java'] resources.srcDirs = ['src/flavor2/java','src/commonFiles/java'] aidl.srcDirs = ['src/flavor2/java','src/commonFiles/java'] renderscript.srcDirs = ['src/flavor2/java','src/commonFiles/java'] } flavor1 { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src/flavor1/java','src/commonFiles/java'] resources.srcDirs = ['src/flavor1/java','src/commonFiles/java'] aidl.srcDirs = ['src/flavor1/java','src/commonFiles/java'] renderscript.srcDirs = ['src/flavor1/java','src/commonFiles/java'] res.srcDirs = ['res-flavor1','res'] assets.srcDirs = ['assets'] } // Move the tests to tests/java, tests/res, etc... instrumentTest.setRoot('tests') // Move the build types to build-types/<type> // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ... // This moves them out of them default location under src/<type>/... which would // conflict with src/ being used by the main source set. // Adding new build types or product flavors should be accompanied // by a similar customization. debug.setRoot('build-types/debug') release.setRoot('build-types/release')}buildTypes { release { signingConfig signingConfigs.release }} } With my setup like this gradle complains about not being able to find classes I'm trying to inherit from commonFiles in flavor1 or flavor2. From the various other topics I've looked at on here I see others not even defining source sets, and I feel like what I'm doing in them is perhaps too much. Has anyone experimented with this before and know how this should properly be configured? Now provide the response and nothing else.
I think you'd be better off not defining custom sourceSets but using the default gradle configuration. I used to do custom sourcesets until I realized the conventions are, well, convenient. You'll want something like this: + src + main // this is your common code + java + res + flavor1 + java + res + flavor2 + java + res Then you can just go ahead and remove the sourcesets closure from your build.gradle NOTE: For the gradle configuration, resources are merged or overridden whereas all java code is put on the same class-path. For example, the AndroidManifest.xml files for each flavor need only have the differences from main 's manifest file. Having an asset, for example, ic_launcher in a flavor overrides the ic_launcher from main if such file exists. However, having a file HomeActivity.java in both main and the flavor is not possible and will give a duplicate file error.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19461145', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1301630/']}
jdg_82602
stackexchange
llm_judgeable_groundtruth_similarity
112791
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm designing a totem-pole by BJTs in order to drive a MOSFET. I studied on several online examples and built up my circuit according to what I understood from them. However, there is a detail which got stuck in my mind. I would like to know why doesn't shoot-through occur in this circuit during the transition time of the clock pulse (e.g.; when \$V_{clk} \tilde= 6V\$)? In other words, why doesn't the two BJTs become turned on at the same time during the transition? simulate this circuit – Schematic created using CircuitLab Simulation result: ( V tp and V gs overlap. ) Now provide the response and nothing else.
These transistors don't conduct unless Vbe>0.6V for the NPN, Vbe<-0.6V for the PNP. And as the bases and emitters are tied together, it is impossible for both these conditions to be true at the same time. So when one transistor is turned on, the other is turned off. HOWEVER if R2 is too low, the transistor being turned on will "saturate". And when saturated, it will take a significant time to turn off after the base current is removed. This question and answers discuss one famous solution to that problem. However the present value of R2 limits the base current, because the voltage across R2 will be relatively low, so the transistors will not saturate hard and will turn off relatively fast.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/112791', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/5542/']}
jdg_82603
stackexchange
llm_judgeable_groundtruth_similarity
13604655
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 use case is simple: I have two controllers sharing the same dependency MyService . This service is holding some state, lets sat myVariable . If I set it from ControllerOne , then it will be also spotted by ControllerTwo . What I want is for each controller to have it's own instance of MyService , so that myVariable can be changed by each Controller without affecting the other. To put it in another words - I want new instance to be returned by Dependency Injection, rather than singleton . Now provide the response and nothing else.
Not as directly has you might hope. Service instances are created the first time they're retrieved by the injector and maintained by the injector... in other words, they're always singletons. The magic happens in here , particularly look at the provider function, which puts the provider instance in the providerCache object. But don't lose hope, you could just as easily add constructors for whatever it is you want to share in a Service, if you so chose: app.factory('myService', [function() { var i = 1; function Foo() { this.bar = "I'm Foo " + i++; }; return { Foo: Foo };}]);app.controller('Ctrl1', function($scope, myService) { $scope.foo = new myService.Foo(); console.log($scope.foo.bar) //I'm Foo 1});app.controller('Ctrl2', function($scope, myService) { $scope.foo = new myService.Foo(); console.log($scope.foo.bar) //I'm Foo 2}); EDIT: as the OP pointed out, there is also the $injector.instantiate , which you can use to call JavaScript constructors outside of your controller. I'm not sure what the implications are of the testability here, but it does give you another way to inject code that will construct a new object for you.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13604655', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218592/']}
jdg_82604
stackexchange
llm_judgeable_groundtruth_similarity
8038726
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 pretty much a novice when it comes to js so I'm sorry if I'm missing something really simple. Basically, I've done some research into using the history.pustate and popstate and I've made it so a query string is added to the end of the url ( ?v=images ) or ( ?v=profile )...( v meaning 'view') by using this: var url = "?v=profile"var stateObj = { path: url };history.pushState(stateObj, "page 2", url); I want to make it so I can load content into a div but without reloading the page which I have done using the .load() function. I then used this code: $(window).bind('popstate', function(event) { var state = event.originalEvent.state; in $(document).ready() section and later tried within just <script> tags and neither worked. I don't know how to make it so the content changes when I use the back button or at least makes it so I can trigger my own function to do so; and I'm assuming it has something to do with the state object?! I just can't seem to find anything online that explains the process clearly. If someone could help me out it would be amazing and thank you in advance to anyone who does! Now provide the response and nothing else.
The popstate only contains a state when there is one. When it goes like this: initial page loaded new page loaded, with state added via pushState back button pressed then there is no state, because the initial page was loaded regularly, not with pushState . As a result, the onpopstate event is fired with a state of null . So when it is null , it means the original page should be loaded. You could implement it such that history.pushState will be called consistently and you only need to provide a state change function like this: Click here for jsFiddle link function change(state) { if(state === null) { // initial page $("div").text("Original"); } else { // page added with pushState $("div").text(state.url); }}$(window).on("popstate", function(e) { change(e.originalEvent.state);});$("a").click(function(e) { e.preventDefault(); history.pushState({ url: "/page2" }, "/page2", "page 2");});(function(original) { // overwrite history.pushState so that it also calls // the change function when called history.pushState = function(state) { change(state); return original.apply(this, arguments); };})(history.pushState);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8038726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1033654/']}
jdg_82605
stackexchange
llm_judgeable_groundtruth_similarity
1256562
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I'm trying to grab the current URL of the page using Java's request object. I've been using request.getRequestURI() to preform this, but I noticed that when a java class reroutes me to a different page off a servlet request getRequestURI gives that that address as opposed to the orginal URL that was typed in the browser and which still shows in the browser. Ex: \AdvancedSearch: getRequestURI() returns "\subdir\search\search.jsp" I'm looking for a way to grab what the browser sees as the URL and not what that page knows is only a servlet wrapper. Now provide the response and nothing else.
If your current request is coming from an "inside the app-server" forward or include, the app-server is expected to preserve request information as request attributes. The specific attributes, and what they contain, depends on whether you're doing a forward or an include. For <jsp:include> , the original parent URL will be returned by request.getRequestURL() , and information about the included page will be found in the following request attributes: javax.servlet.include.request_uri javax.servlet.include.context_path javax.servlet.include.servlet_path javax.servlet.include.path_info javax.servlet.include.query_string For <jsp:forward> , the new URL will be returned by request.getRequestURL() , and the original request's information will be found in the following request attributes: javax.servlet.forward.request_uri javax.servlet.forward.context_path javax.servlet.forward.servlet_path javax.servlet.forward.path_info javax.servlet.forward.query_string These are set out in section 8.3 and 8.4 of the Servlet 2.4 specification. However, be aware that this information is only preserved for internally-dispatched requests. If you have a front-end web-server, or dispatch outside of the current container, these values will be null. In other words, you may have no way to find the original request URL.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1256562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100658/']}
jdg_82606
stackexchange
llm_judgeable_groundtruth_similarity
8674831
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I have an assigned variable in smarty: {assign var=number value=0} Now I can increment it using {$number++} or {++$number} Which is exactly what I need, only problem is, it displays the value of $number on the page.Is there a way I can increment the value but not display it? This is not used inside of a loop otherwise I would use something like iteration or index. Now provide the response and nothing else.
You could do this: {assign var=val value=1}{assign var=val value=$val+1}{$val} // displays 2 The above will be compiled to: $this->assign('val', 1);$this->assign('val', $this->_tpl_vars['val']+1);echo $this->_tpl_vars['val']; or {assign var=var value=1}{capture assign=var}{$var+1}{/capture}{$var} // displays 2 Which in turn will be compiled as: $this->assign('var', 1);ob_start();echo $this->_tpl_vars['var']+1;$this->_smarty_vars['capture']['default'] = ob_get_contents();$this->assign('var', ob_get_contents());ob_end_clean();echo $this->_tpl_vars['var']; another approach would be to write a small plugin: // plugins/function.inc.phpfunction smarty_function_inc($params, Smarty &$smarty){ $params['step'] = empty($params['step']) ? 1 : intval($params['step']); if (empty($params['var'])) { trigger_error("inc: missing 'var' parameter"); return; } if (!in_array($params['var'], array_keys($smarty->_tpl_vars))) { trigger_error("inc: trying to increment unassigned variable " . $params['var']); return; } if (isset($smarty->_tpl_vars[$params['var']])) { $smarty->assign($params['var'], $smarty->_tpl_vars[$params['var']] + $params['step']); }} The function would then be called like this, notice that step is optional and if not given the variable will be incremented by one: {assign var=var value=0}{inc var=var step=2}{$var} // displays 2 Reference Smarty {assign} Smarty {capture} Extending Smarty With Plugins
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8674831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/572014/']}
jdg_82607
stackexchange
llm_judgeable_groundtruth_similarity
2045197
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to call the following bash command in MATLAB: grep "Up to" ~/test_linux/vision1.1/log | awk '{print $7}' I use system() in MATLAB, but it turns out to have errors: >> [status string]=system('grep "Up to" ~/test_linux/vision1.1/log | awk '{print $7}' '); ??? [status string]=system('grep "Up to" ~/test_linux/vision1.1/log | awk '{print $7}' '); Error: Unbalanced or unexpected parenthesis or bracket. Do I need to escape some special characters in the bash command as a string in MATLAB? Now provide the response and nothing else.
This should work: [status string]=system('grep "Up to" ~/test_linux/vision1.1/log | awk ''{print $7}'' '); You have to escape ' with another ' if you want it to appear as a character in a string. With respect to handling strings in MATLAB , ' is the only character with special meaning (it starts and ends the string), so it is the only one that needs escaping. Caveat: Some functions may interpret their string arguments in different ways, and thus require certain characters to be escaped in different ways. These requirements will appear in the documentation for each function. A couple of these types of functions off the top of my head: FPRINTF / SPRINTF : % and \ characters appearing in the format argument have to be escaped as %% and \\ , respectively. REGEXP/REGEXPI : Characters with special meaning in a regular expression must be preceded with a \ .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2045197', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156458/']}
jdg_82608
stackexchange
llm_judgeable_groundtruth_similarity
17291
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a nested list: list = {1, 2, {3, 4}, f[a], {2, h[b]}} I would like to apply a function g to all elements of the nested list (starting from top to bottom) that are not lists themselves. That is, I would like to obtain: {g[1], g[2], {g[3], g[4]}, g[f[a]], {g[2], g[h[b]]}} (Using Map[g, list, {-1}] does not work, as it maps g inside f and h ) The alternative I have ended up using is the following function: mapAtLeavesOfList[g_, x_List] := Map[mapAtLeavesOfList[g, #] &, x]mapAtLeavesOfList[g_, x_] := g[x]mapAtLeavesOfList[g, list]=> {g[1], g[2], {g[3], g[4]}, g[f[a]], {g[2], g[h[b]]}} Any better suggestions? Now provide the response and nothing else.
Contrary to what the title claims, your example shows that do not want to map at the "maximum depth" of the list, but rather, merely onto the elements of a List that are not lists themselves. I think you're over complicating things with your definition of mapAtLeavesOfList . The solution is as simple as: Clear@gg[a_List] := g /@ ag@list(* {g[1], g[2], {g[3], g[4]}, g[f[a]], {g[2], g[h[b]]}} *) If you want to use g as a blackbox function, the following should work: Block[{mapg}, mapg[a_List] := mapg /@ a; mapg@list /. mapg -> g] or even: Block[{g}, g[a_List] := g /@ a; g@list] The above solution temporarily modifies g to make it listable using Block and once outside the Block , the original definition of g kicks in. You can also set the Listable attribute for g as in Leonid's answer.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/17291', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/209/']}
jdg_82609
stackexchange
llm_judgeable_groundtruth_similarity
88365
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: At the top of my arduino sketch, I have the following : // softApconst char *softApSsid = "abcdefg";const char *softApPassword = "123456"; Those are the DEFAULT ssid and password to connect to the soft AP. The soft AP is start in the setup() such as : WiFi.softAP(softApSsid, softApPassword); according to the github repo, that function indeed requires "const char*" as parameters (source: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiAP.cpp#L97 ) Further in my sketch, I want to let the user edit the ssid and password. I wrote a function that reads the first byte of the eeprom. If it equals 255, we use the default credentials, if it equals to 1, it means the user set custom credentials, so we will use those to spawn the soft AP. I wrote this : void getSoftApAuth() { bool isDefaultSoftApAuth = 255 == EEPROM.read(0); if (! isDefaultSoftApAuth) { softApSsid = ""; softApPassword = ""; int i = 1; while ('\0' != EEPROM.read(i)) { softApSsid += char(EEPROM.read(i)); i++; } i = 65; while ('\0' != EEPROM.read(i)) { softApPassword += char(EEPROM.read(i)); i++; } }}void setSoftApAuth(const char* ssid, const char* passphrase) { EEPROM.write(0, 1); // ssid int positionOfSsid = 1; int lengthOfSsid = strlen(ssid); for (int i = 0; i < lengthOfSsid; i++) { EEPROM.write(positionOfSsid + i, ssid[i]); } EEPROM.write(positionOfSsid + lengthOfSsid, '\0'); // passphrase int positionOfPassphrase = 65; int lengthOfPassphrase = strlen(passphrase); for (int i = 0; i < lengthOfPassphrase; i++) { EEPROM.write(positionOfPassphrase + i, passphrase[i]); } EEPROM.write(positionOfPassphrase + lengthOfPassphrase, '\0'); if (EEPROM.commit()) { Serial.println("Successful EEPROM write"); } else { Serial.println("Failed EEPROM write"); }}void resetSoftApAuth() { EEPROM.write(0, 255); if (EEPROM.commit()) { Serial.println("Successful EEPROM reset"); } else { Serial.println("Failed EEPROM reset"); }} this does compile but crashes and throws exceptions when I run the chip. I believe the issue is in getSoftApAuth() where i try to concatenate the string such as softApSsid += char(EEPROM.read(i)); . I print the value of softApSsid in the Serial Monitor and it outputs garbage. I replaced everything with "String" type, and this time it outputs correct username/password stored in the eeprom, but it wont start the soft AP, I believe because I am now trying to pass String instead of const char* to the WiFi.softAP() function as I said earlier (it starts the soft AP with factory default SSID like ESP-AABBCCDDEE appending the MAC address and without any password). So, basically, how can I modify my softApSsid down in my code, while i declared it at the top as a const char* , knowing it feeds a function that takes (exclusively?) a const char* (WiFi.softAP()) Or is there an other approach / design pattern to achieve this? That is to say: having default credentials hard-coded, but allowing the user to define custom credentials (and storing/retrieving them from the eeprom). Thanks. Please be indulgent as I am mostly a webdev and not yet comfortable with the strongly typed languages (let alone pointers / references ...) Now provide the response and nothing else.
that function indeed requires "const char*" as parameters There seems to be a misunderstanding here. The method signature is: bool ESP8266WiFiAPClass::softAP(const char* ssid, const char* psk, int channel, int ssid_hidden, int max_connection); Within this signature, the word const means the method makes thepromise not to modify the ssid nor the psk strings. If you wereimplementing the method, you would indeed be required to honor theconstness of these strings. As a user of the method, however, you areperfectly allowed to provide a modifiable string. You are not bound byany constness requirement. And indeed, you have to use modifiablestrings if you want your user to be able to change them. The simplest way to handle this situation is: char softApSsid[MAX_SSID_LENGTH] = "abcdefg";char softApPassword[MAX_PWD_LENGTH] = "123456"; Note that you have to allocate enough room to store the longest stringsyou may need. Whereas 8 bytes would be enough to store "abcdefg" ,it may not suffice for other ssids. Also note that C strings cannot be grown with the += operator. Theyare just arrays of characters and should be written to as such: i = 0;do { char c = EEPROM.read(1+i); softApSsid[i++] = c;} while (c != '\0'); Edit : answering this comment: Some research on SO also suggested the following: const char *password = myString.c_str(); where myString is of String type. Indeed. The c_str() method of the String class lets you directlyaccess the C string buried within a String object, if you promise notto modify it (hence the const ). Growing a String is easy, as the += operator takes care of handling the memory. I would, however, advice against any unnecessary use of the String class, as it involves lots of heap memory allocation, especially if youbuild a string one character at a time with += . This is not reallyfriendly to your device's memory. See The Evils of ArduinoStrings for details.
{}
{'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/88365', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/82014/']}
jdg_82610
stackexchange
llm_judgeable_groundtruth_similarity
497670
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: These instructions are a little intimidating and confusing: http://svnbook.red-bean.com/en/1.0/ch04s04.html#svn-ch-4-sect-4.3 .And also they don't seem to mention that it's much simpler if you haven't yet checked in after doing the " svn rm " [1]. So I thought this would be a good place to record a simpler answer for those googling for this. [1] To an svn newbie, it might appear that " svn rm " immediately destroys the file. I recall doing svn rm thinking that would just remove it from source control and freaking out when the file itself actually disappeared. So a sub-question is, what's the right way to remove a file from version control without actually removing your local copy? Now provide the response and nothing else.
If you just did svn rm foo.txt then you can undo that with simply svn revert foo.txt If you already checked in after doing the " svn rm " then you can look at the log ( svn log ), find the last revision where the file existed, and grab it from that version. One way to do that is to merge in the old revision that has the file. Assuming the current revision is 123 and the last version with that file is 120, then do this: svn merge -r123:120 Maybe first do a dry run to make sure it won't do anything you don't want: svn --dry-run merge -r123:120 For the sub-question, how to remove a file from svn without removing the local copy: svn rm foo.txt --keep-local Or, of course, you could just copy to a temp file before svn rm'ing and then copy back: cp foo.txt foo.txt-tmpsvn rm foo.txt(svn ci -m "just removed foo.txt from the repository")cp foo.txt-tmp foo.txt
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/497670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4234/']}
jdg_82611
stackexchange
llm_judgeable_groundtruth_similarity
3099497
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 currently working on the following exercise: Show that for every prime number $p$ and every integer $m$ , the number $m^p + (p − 1)! m$ is divisible by $p$ . What I'm doing is the following: $$m(m^{p-1}+(p-1)!)\equiv 0\mod p$$ $$m((1)+(-1))\equiv 0\mod p$$ $$m(0)\equiv 0 \mod p$$ $$0 \equiv 0 \mod p.$$ Is a valid proof? Am I missing something? Any hint or help will be really appreciated. Now provide the response and nothing else.
Show that for every prime number $p$ and every integer $m$ , the number $mp+(p−1)!m$ is divisible by $p$ . This can be proved via two theorems: Fermat's Little Theorem and Wilson's Theorem. $\,m^p+(p-1)!m \;=\; m^p-m+(p-1)!m+m \;=\; m^p-m+m((p-1)!+1)$ By Fermat's little theorem , $\,m^p-m\,$ is an integer multiple of $p$ , since $p$ is prime. By Wilson's Theorem , $\, (p-1)!+1\,$ is an integer multiple of $\,p\,$ , since $\,p\,$ is prime. So, for some $\, k,\,l \in \mathbb{Z}\text{,}\,$ we have $$m^p-m+m((p-1)!+1) \;=\; kp + m(lp) \;=\; p(k+ml)\text{.}$$ Thus $\,m^p+(p−1)!m\,$ is divisible by $p$ . I believe the error in your proof came from assuming that $\,m^{p-1}\equiv1\,(\text{mod}\; p)\text{.}\,$ This is only true if we assume $m$ is not divisible by $p$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3099497', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/537502/']}
jdg_82612
stackexchange
llm_judgeable_groundtruth_similarity
2199279
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: There are some similar questions, but not exactly this one. First: As, Zero is a rational number. So, by using the counterexample $a=0$ and $b=x$ ($x$ being an irrational number) we get $ab = 0$. Thus it is not true that $ab$ necessarily has to be irrational . Second: However, I have learned a technique that I have used to proof similar but slightly different combination ($a$ is rational and $b$ is irrational, is $a+b$ irrational?) of questions. With this technique (Proof by contradiction): Given $a$ is rational and $b$ is irrational. Let, $ab$ be rational. Suppose, $a= \frac{m}{n}$ and $ab= z =\frac{p}{q}$ , where $m,n,p,q$ are intgers and $n,q \neq 0$ $b=x$ where $x$ is an irrational number. $$a \cdot b=z$$ $$\frac{m}{n} \cdot x=\frac{p}{q}$$ $$x=\frac{p}{q} \cdot \frac{n}{m}$$ Now, as $p,q,m,n$ are all integers, therefore $x$ is an integer, therefore rational , which contradicts our starting assumption that $x$ is an irrational number. Therefore, $ab$ is irrational. Now, I think the First conclusion that $ab$ is not necessarily irrational is correct. The second proof is definitely wrong (I think), but I am new to proofs and don't know where it is wrong. What did I miss and not consider in the second approach? Now provide the response and nothing else.
The denominator clearly $\to\infty$ Now for the numerator using $\log a/b=\log a-\log b$ for all the logarithm remain defined, $$\lim_{x\to\infty}(\ln(1+x)-\ln x)=\lim_{x\to\infty}\ln\left(1+\dfrac1x\right)=?$$ Alternatively, Set $1/x=h$ to get $$\lim_{h\to0}h\cdot\ln(1+h)$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2199279', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/407650/']}
jdg_82613
stackexchange
llm_judgeable_groundtruth_similarity
28282371
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 newcomer to programming and I am attempting to create an Android app using Android Studio. I've tried searching but my findings do not appear to be what I am looking for, because they seem to be overly complex. What I've written below is just an example. I want to be able to return a string from string.xml when user types "whale". The string in this case is information about the whale. This is my java file, animal is already a string entered from a form. TextView textview = new TextView(this);String animalType = "water_" + animal; // This become water_whale if user typed whaleString animalInfo = getString(R.string.animalType); // This doesn't worktextView.setText(animalInfo); This is my string.xml <string name="water_fish">Fish is a small bla...</string><string name="water_whale">A whale is an enourmous blabla...</string><string name="land_giraffe">Africa.</string> I have probably tunneled on this particular way and I have probably miss something obvious or is there another way to do this? Now provide the response and nothing else.
The correct way to limit the size of the request body is to do as you suggested: r.Body = http.MaxBytesReader(w, r.Body, MaxFileSize) err := r.ParseForm()if err != nil { // redirect or set error status code. return} MaxBytesReader sets a flag on the response when the limit is reached. When this flag is set, the server does not read the remainder of the request body and the server closes the connection on return from the handler. If you are concerned about malicious clients, then you should also set Server.ReadTimeout , Server.WriteTimeout and possibly Server.MaxHeaderBytes . If you want to set the request body limit for all of your handlers, then wrap root handler with a handler that sets the limit before delegating to the root handler: type maxBytesHandler struct { h http.Handler n int64 } func (h *maxBytesHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, h.n) h.h.ServeHTTP(w, r) } Wrap the root handler when calling ListenAndServe: log.Fatal(http.ListenAndServe(":8080", &maxBytesHandler{h:mux, n:4096)) or when configuring a server: s := http.Server{ Addr: ":8080", Handler: &maxBytesReader{h:mux, n:4096},}log.Fatal(s.ListenAndServe()) There's no need for a patch as suggested in another answer. MaxBytesReader is the official way to limit the size of the request body.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28282371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4520438/']}
jdg_82614
stackexchange
llm_judgeable_groundtruth_similarity
94362
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to calculate an impedance value from voltage and current functions. The calculation method is based on how an actual measurement device performs it. I have two different current function, where one is slightly more complex. iBV[t_, freq_] = i0*(-Exp[(alpha - 1)*bvVor*(U[t, freq] - E0)] + Exp[alpha*bvVor*(U[t, freq] - E0)]) + Cdl*DU[t, freq];i[t_, freq_] = iBV[t, freq]*iLimit/(Abs[iBV[t, freq]] + iLimit); If i use iBV directly, the calculations finish very rapidly. When I however use i I am still waiting for the results after half an hour and I don't understand why. Granted, it has to calculate iBV twice for each round but shouldn't that lead to twice the time and not 1000 times? As you'll see I need to integrate. Is maybe the complexity of performing the integration much more complicated in the latter case for some reason? The rest of the computation is as follows: ClearAll[t, freq, U0, Harmonic, bvVor, i0, alpha, E0, T, z, cBulk, Cdl, iLimit];ClearAll[U, DU, iVoigt, i, iL, Rea, Ima, tmax, ReZ, ImZ, Impe];(* Current parameters *)i0 = 0.0001; alpha = 0.5; E0 = 0; T = 293; z = 1; cBulk = 25; Cdl = \0.000001; iLimit = 0.0005;(* Voltage parameters and Misc *)U0 = 0.1;Harmonic = 0;bvVor = z*96485/8.314/T;(* Voltage Functions *)U[t_, freq_] = U0*Sin[2*\[Pi]*freq*t];DU[t_, freq_] = 2*freq*\[Pi]*U0*Cos[2*freq*\[Pi]*t];(*iVoigt[t_,freq_]=Cdl*DU[t,freq]+U[t,freq]/100;*)(* Current Function *)iBV[t_, freq_] = i0*(-Exp[(alpha - 1)*bvVor*(U[t, freq] - E0)] + Exp[alpha*bvVor*(U[t, freq] - E0)]) + Cdl*DU[t, freq];i[t_, freq_] = iBV[t, freq]*iLimit/(Abs[iBV[t, freq]] + iLimit);(* Functions to calculate the real and imaginary part of the current \by integration *)ReaF[t_, freq_] = i[t, freq]*Sin[(Harmonic + 1)*2*\[Pi]*freq*t];ImaF[t_, freq_] = i[t, freq]*Cos[(Harmonic + 1)*2*\[Pi]*freq*t];(* Integration bound, 1 period *)tmax[freq_] = 2/freq;(* Real and Imaginary part of the current *)ReI[freq_] = 2/tmax[freq]*Integrate[ReaF[t, freq], {t, 0, tmax[freq]}];ImI[freq_] = 2/tmax[freq]*Integrate[ImaF[t, freq], {t, 0, tmax[freq]}];(* The Impedance *)Impe[freq_] = U0/(ReI[freq] + I*ImI[freq]);(* Calculation of results *)Freqs = 10^Range[-2,5,0.1];Results = Impe[Freqs];(* Output *)Res = Re[Results];Ims = Im[Results];marker = Graphics[{Red, Disk[]}];ListPlot[Transpose[{Res, -Ims}], {Joined -> True, PlotMarkers -> {marker, .03}, PlotStyle -> {Orange, Thick}}]TraditionalForm[TableForm[Transpose[{Freqs, Res, Ims}]]] If you want to test the difference, just rename i[t_, freq_] to something, and rename iBV[t_, freq_] to i[t_, freq_] . I also tried rewriting the whole stuff in Function/Module nomenclature, getting rid of doubled calculations in the process, but that just made everything slower (i guess due to overhead<->actual evaluation time bias). Edit I tried to do some benchmarks: Timing[Do[iBV[0.1, 100], {10000}]]Timing[Do[i[0.1, 110], {10000}]] This does indeed report what I thought: {0.328, Null} , {0.657, Null} . So each function evaluation takes twice as long for the more complex function. I also further narrowed it down: Everything is fast up to the integration. I changed - as Edmund suggested in the comments - all definitions to SetDelayed , which did not improve the speed though. Now provide the response and nothing else.
Consider the solutions to the following equation: yoursolutions = {x, y} /. NSolve[{x^3 - y^3 == 2, x y == 3} , {x, y}] {{-0.923042 + 1.59876 I, -0.812531 - 1.40734 I}, {-0.923042 - 1.59876 I, -0.812531 + 1.40734 I}, {0.812531 + 1.40734 I, 0.923042 - 1.59876 I}, {0.812531 - 1.40734 I, 0.923042 + 1.59876 I}, {1.84608, 1.62506}, {-1.62506, -1.84608}} Now let's use Cases to extract only the real solutions: onlyrealsols = Cases[yoursolutions, {__Real}] {{1.84608, 1.62506}, {-1.62506, -1.84608}} UPDATE: Here is a second version that retains the Rule structure : solutionrules = NSolve[{x^3 - y^3 == 2, x y == 3} , {x, y}] {{x -> -0.923042 + 1.59876 I, y -> -0.812531 - 1.40734 I}, {x -> -0.923042 - 1.59876 I, y -> -0.812531 + 1.40734 I}, {x -> 0.812531 + 1.40734 I, y -> 0.923042 - 1.59876 I}, {x -> 0.812531 - 1.40734 I, y -> 0.923042 + 1.59876 I}, {x -> 1.84608, y -> 1.62506}, {x -> -1.62506, y -> -1.84608}} Again, we can use a modified pattern in Cases to select those rules corresponding to real solutions: realsolutionrules = Cases[ solutionrules, {_ -> solx_, _ -> soly_} /; {solx, soly} \[Element] Reals ] {{x -> 1.84608, y -> 1.62506}, {x -> -1.62506, y -> -1.84608}}
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/94362', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/29305/']}
jdg_82615
stackexchange
llm_judgeable_groundtruth_similarity
5741038
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 ArrayList of custom objects. I want to remove duplicate entries. The objects have three fields: title, subtitle , and id . If a subtitle occurs multiple times, I only need the first item with thats subtitle (ignore the remaining object with that subtitle). Now provide the response and nothing else.
You can put the content of the ArrayList in a TreeSet using a custom Comparator which should return 0 if the two subtitles are the same.After that you can convert the Set in a List and have the List without "duplicates".Here is an example for Object, of course you should use the correct class and logic. public void removeDuplicates(List<Object> l) { // ... the list is already populated Set<Object> s = new TreeSet<Object>(new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { // ... compare the two object according to your requirements return 0; } }); s.addAll(l); List<Object> res = Arrays.asList(s.toArray());}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5741038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/487219/']}
jdg_82616
stackexchange
llm_judgeable_groundtruth_similarity
9511462
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 WebForm we could write a method in MasterPage.cs and it ran in each request . e.g: MasterPage.cs--------------protected void Page_Load(object sender, EventArgs e){ CheckCookie();} How can we do something like this in MVC ? Now provide the response and nothing else.
In ASP.NET MVC you could write a custom global action filter . UPDATE: As requested in the comments section here's an example of how such filter might look like: public class MyActionFilterAttribute : ActionFilterAttribute{ public override void OnActionExecuting(ActionExecutingContext filterContext) { var fooCookie = filterContext.HttpContext.Request.Cookies["foo"]; // TODO: do something with the foo cookie }} If you want to perform authorization based on the value of the cookie, it would be more correct to implement the IAuthorizationFilter interface: public class MyActionFilterAttribute : FilterAttribute, IAuthorizationFilter{ public void OnAuthorization(AuthorizationContext filterContext) { var fooCookie = filterContext.HttpContext.Request.Cookies["foo"]; if (fooCookie == null || fooCookie.Value != "foo bar") { filterContext.Result = new HttpUnauthorizedResult(); } }} If you want this action filter to run on each request for each controller action you could register it as a global action filter in your global.asax in the RegisterGlobalFilters method: public static void RegisterGlobalFilters(GlobalFilterCollection filters){ filters.Add(new HandleErrorAttribute()); filters.Add(new MyActionFilterAttribute());} And if you need this to execute only for particular actions or controllers simply decorate them with this attribute: [MyActionFilter]public ActionResult SomeAction(){ ...}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9511462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191647/']}
jdg_82617
stackexchange
llm_judgeable_groundtruth_similarity
6299950
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 SQL 2008 database table like this name score-----------------------steve 207steve 205steve 200steve 139 I want to get the difference between the rows. eqn = [row - (row + 1)]so I would ideally want it to be, steve 2 //207 - 205steve 5 //205 - 200steve 61 //200 - 139steve 139 //139 - 0 What is the best way to do this? Thanks! Now provide the response and nothing else.
This is one way to do it with cte as(SELECT ROW_NUMBER() OVER (PARTITION BY table.name ORDER BY id) row, name, score FROM table)SELECT a.name , a.score - ISNULL(b.score,0)FROM cte a LEFT JOIN cte b on a.name = b.name and a.row = b.row+1
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6299950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/791794/']}
jdg_82618
stackexchange
llm_judgeable_groundtruth_similarity
47859273
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I want to add padding in the bootsector. Let's say, there is currently just an endless loop in there: jmp . . The sector needs to be 512 bytes long. Also, the magic num 0xaa55 is needed which is added at the end. jmp ..skip 508, 0.word 0xaa55 But what if I want to print something but don't want to count all the bytes to pad it into the right size? In Intel/NASM syntax would it be: ; print somethingtimes 510-($-$$) db 0dw 0xaa55 But in AT&T syntax? Well a loop ( .rept ) doesn't work here because . doesn't give an absolute value which is needed here. We have the same problem with .skip / .space , they need an absolute value too. Is there a method to add padding using some sort of loop/ .align / .skip /etc? EDIT:I use as to build and for linking ld -Ttext 0x7c00 --oformat binary until yasm is stable enough for AT&T syntax. Now provide the response and nothing else.
With AT&T syntax you can put a label at the start of your bootloader and then use something like this: .global _start.text.code16_start: jmp ..space 510-(.-_start).word 0xaa55 Period . is the current location counter relative to the beginning of the current section. The difference between period . and _start is an absolute value so should work in this expression. You can use GCC (that will invoke LD ) to assemble this to a bootloader with a command like: gcc -Wl,--oformat=binary -Wl,-Ttext=0x7c00 -Wl,--build-id=none \ -nostartfiles -nostdlib -m32 -o boot.bin boot.s The option -Wl,--oformat=binary passes this option to the linker which will force it to output to a flat binary file. -Wl,-Ttext=0x7c00 will pass this option to the linker that will effectively set the origin point to 0x07c00. -Wl,--build-id=none tell the linker not to use the build id that GCC may generate. 0x7c00 is the offset the code is expected to be loaded at. Since we can't use a standard library or C runtime we exclude them with -nostartfiles -nostdlib You won't be able to use this method if you intend to link multiple files together. In that case you will need to leave the boot signature out of the code and let the linker take care of it with a specially crafted linker script. The method above will work if you contain your bootloader to a single assembly file. I have some general bootloader tips for writing bootloader code. One big issue people usually have is not setting the segment registers up. If you use an origin point of 0x7c00 then you need to make sure at a minimum that the DS register us set to 0. That will be important if you write code that uses memory operands that reference a label within your code. When assembling with GNU assembler ensure that you set the proper instruction encoding you want. .code16 will make the assembler assume the target processor is running in 16-bit mode. .code32 for 32-bit encoding, .code64 assumes 64-bit encoding. The default for as is generally never .code16 . Bootloader with Multiple Object Files As I mentioned above using multiple object files to create your bootloader presents challenges that can't be overcome with assembly directives. In order to do this you can create a special linker script that sets the Origin point to 0x7c00 and lets the linker place the boot signature in the output file. Using this method you don't need to do any padding, the linker will do it for you. A basic linker script that deals with traditional sections like .text , .data , .rodata is shown below. You may never use some of the section, but I added them as an example: File bootloader.ld OUTPUT_FORMAT("elf32-i386");ENTRY(_start);SECTIONS{ . = 0x7C00; /* Code section, .text.bootentry code before other code */ .text : SUBALIGN(0) { *(.text.bootentry); *(.text) } /* Read only data section with no alignment */ .rodata : SUBALIGN(0) { *(.rodata) } /* Data section with no alignment */ .data : SUBALIGN(0) { *(.data) } /* Boot signature at 510th byte from 0x7c00 */ .sig : AT(0x7DFE) { SHORT(0xaa55); } /DISCARD/ : { *(.eh_frame); *(.comment); *(.note*); }} File boot.s containing main entry point of bootloader: # Section .text.bootentry is always placed before all other code and data# in the linker script. If using multiple object files only specify# one .text.bootentry as that will be the code that will start executing# at 0x7c00.section .text.bootentry.code16.global _start_start: # Initialize the segments especially DS and set the stack to grow down from # start of bootloader at _start. SS:SP=0x0000:0x7c00 xor %ax, %ax mov %ax, %ds mov %ax, %ss mov $_start, %sp cld # Set direction flag forward for string instructions mov $0x20, %al # 1st param: Attribute black on green xor %cx, %cx # 2nd param: Screen cell index to write to. (0, 0) = upper left mov $boot_msg, %dx # 3rd param: String pointer call print_str # Infinite loop to end bootloader cli.endloop: hlt jmp .endloop.section .rodataboot_msg: .asciz "My bootloader is running" File aux.s with a simple function to display a string directly to screen: .global print_str # Make this available to other modules.section .text.code16# print_str (uint8_t attribute, char *str, uint16_t cellindex)## Print a NUL terminated string directly to video memory at specified screen cell# using a specified attribute (foreground/background)## Calling convention:# Watcom# Inputs:# AL = Attribute of characters to print# CX = Pointer to NUL terminated string to print# DX = Screen cell index to start printing at (cells are 2 bytes wide)# Clobbers:# AX, ES# Returns:# Nothingprint_str: push %di push %si mov $0xb800, %di # Segment b800 = text video memory mov %di, %es mov %cx, %di # DI = screen cell index (0 = upper left corner) mov %dx, %si # SI = pointer to string (2nd parameter) mov %al, %ah # AH = attribute (3rd parameter) jmp .testchar# Print each character until NUL terminator found.nextchar: stosw # Store current attrib(AH) and char(AL) to screen # Advances DI by 2. Each text mode cell is 2 bytes.testchar: lodsb # Load current char from string into AL(advances SI by 1) test %al, %al jne .nextchar # If we haven't reach NUL terminator display character # and advance to the next one pop %si pop %di ret To build this bootloader to a file called boot.bin we could do something like: as --32 aux.s -o aux.oas --32 boot.s -o boot.old -melf_i386 --oformat=binary -Tlink.ld -nostartfiles -nostdlib \ aux.o boot.o -o boot.bin The special .text.bootentry is placed as the first code by the linker script. This section should only be defined in one object file as it will be the code that appears right at the beginning of the bootloader at 0x7c00. The linker script adjusts the VMA (origin) to 0x7dfe and writes the boot signature(0xaa55). 0x7dfe is 2 bytes below the end of the first 512 bytes. We no longer do any padding in the assembly code nor do we emit the boot signature there. When run this sample bootloader should print a string to the upper left of the display with black on a green background.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47859273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6490150/']}
jdg_82619
stackexchange
llm_judgeable_groundtruth_similarity
3411106
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: Of course “several” in the title means $n$ strictly greater than 1 and the function is defined on some open subset of $\mathbb{C}^n$ . I tried to use the Weierstrass preparation theorem because it’s the only result on analysis of several variables I know but I couldn’t find a contradiction (I believe the answer is “no”). Now provide the response and nothing else.
The answer is indeed no, which might be surprising since the real analogue of this question has a different outcome ( $f(x) = \|x\|^2$ is smooth and only has one zero). The crucial result in this proof is Hartog's Theorem : Let $n \geq 2$ and $\Omega \subset \mathbb C^n$ be open.Suppose $K \subset \Omega$ is compact and $\Omega \setminus K$ is connected. Then any holomorphic function on $\Omega \setminus K$ can be extended to all of $\Omega$ . Remark: This is not true in one variable: The function $z \mapsto e^{1/z}$ cannot be extended to all of $\mathbb C$ because it has an essential singularity at zero. We are now going to prove that no holomorphic function of several variables has just one zero. Toward a contradiction, let $\Omega \subset \mathbb C^n$ be a (connected) domain and let $f: \mathbb{\Omega} \rightarrow \mathbb C$ be holomorphic with $f(z) = 0$ if and only if $z = z_0$ . Then the function $1/f$ is holomorphic in $\Omega \setminus \{z_0\}$ . By Hartog's Theorem, $1/f$ admits a holomorphic extension to $\Omega$ . But then, $f(z_0) \cdot 1/f(z_0) = 1$ by continuity of the product of continuous functions, which is a contradiction to $f(z_0) = 0$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3411106', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/375772/']}
jdg_82620
stackexchange
llm_judgeable_groundtruth_similarity
20959805
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to add delay without using Thread.sleep() or a while loop doing nothing.The game im editing(Minecraft) clock runs on "Ticks" but they can fluctuate depending on your FPS. public void onTick() {//Called every "Tick" if(variable){ //If my variable is true boolean = true; //Setting my boolean to true /** *Doing a bunch of things. **/ //I need a delay for about one second here. boolean = false; //Setting my boolean to false; }} The reason why i need a delay is because if i dont have one the code runs too fast and misses it and does not toggle. Now provide the response and nothing else.
Something like the following should give you the delay you need without holding up the game thread: private final long PERIOD = 1000L; // Adjust to suit timingprivate long lastTime = System.currentTimeMillis() - PERIOD;public void onTick() {//Called every "Tick" long thisTime = System.currentTimeMillis(); if ((thisTime - lastTime) >= PERIOD) { lastTime = thisTime; if(variable) { //If my variable is true boolean = true; //Setting my boolean to true /** *Doing a bunch of things. **/ //I need a delay for about one second here. boolean = false; //Setting my boolean to false; } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20959805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3166950/']}
jdg_82621
stackexchange
llm_judgeable_groundtruth_similarity
1558590
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 done some programming in Scala, and I know that, e.g., xs map f is the same thing as xs.map(f) but I have no idea how to generalize this syntax to something like ScalaTest's syntax, e.g., it should "throw NoSuchElementException if an empty stack is popped" in { val emptyStack = new Stack[String] evaluating { emptyStack.pop() } should produce [NoSuchElementException]} I'm mainly wondering about the things that look like multi-word constructs, namely should produce . It's neat. Now provide the response and nothing else.
That kind of syntax is method calls in operator notation, but carried forward more than just three tokens. As you already mentioned: xs map f means: xs.map(f) But you could go further and say: xs map f map g which means: xs.map(f).map(g) In ScalaTest matchers, for example, you could say: result should not be null That gets desugared by the compiler to: result.should(not).be(null) This: it should "throw an exception" in { ... } gets desugared into: it.should("throw an exception").in { ... } The curly braces at the end is really just a way to pass the code in between the curly braces (the test code) into the in method, wrapped as a no-arg function. So all of these are the same idea. Operator notation used twice in a row. The last one you asked about is a tad different: evaluating { ... } should produce [IllegalArgumentException] This gets transformed into: evaluating { ... } is, well, evaluated first, because the curly braces give it precedence. So that is a method call, you are calling a method named "evaluating", passing in the code in between the curly braces as a no-arg function. That returns an object, on which should is invoked. So should is a method on the object returned by invoking evaluating . What should actually takes is the result of invoking produce . Here produce is actually a method, which has a type parameter such as [IllegalArgumentException] . It must be done this way so the Scala compiler can "poor-man's-reify" that type parameter. It passes an implicit "Manifest" parameter into produce that can provide the java.lang.Class instance for IllegalArgumentException . When that should method is invoked, therefore, it has a function containing the code passed to evaluating , and a way to find the java.lang.Class of the exception type put in the square brackets. So it executes the block of code wrapped in a try , catches the exception, compares it with what's expected. If no exception is thrown, or the wrong one, the should method throws a TestFailedException . Otherwise the should method just returns silently. So, the answer is that line gets desugared into: (evaluating { ... }).should(produce[IllegalArgumentException] (compilerSuppliedManifest)) And the moral of the story is that high level code like this makes it easier to see the programmer's intent, but often harder to understand how the code actually works. Most of the time in practice all you care about is the intent, but now and then you need to know how something works. In such cases in Scala you can pass -Xprint:typer as a command line arg to the Scala compiler and it will print out a version of your file after all the desugaring has happened. So you can see what's what when you need to.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1558590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/43118/']}
jdg_82622
stackexchange
llm_judgeable_groundtruth_similarity
25811017
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 delete an enum type value that I created in postgresql? create type admin_level1 as enum('classifier', 'moderator', 'god'); E.g. I want to remove moderator from the list. I can't seem to find anything on the docs. I'm using Postgresql 9.3.4. Now provide the response and nothing else.
You delete (drop) enum types like any other type, with DROP TYPE : DROP TYPE admin_level1; Is it possible you're actually asking about how to remove an individual value from an enum type ? If so, you can't. It's not supported : Although enum types are primarily intended for static sets of values, there is support for adding new values to an existing enum type, and for renaming values (see ALTER TYPE ). Existing values cannot be removed from an enum type, nor can the sort ordering of such values be changed, short of dropping and re-creating the enum type. You must create a new type without the value, convert all existing uses of the old type to use the new type, then drop the old type. E.g. CREATE TYPE admin_level1 AS ENUM ('classifier', 'moderator');CREATE TABLE blah ( user_id integer primary key, power admin_level1 not null);INSERT INTO blah(user_id, power) VALUES (1, 'moderator'), (10, 'classifier');ALTER TYPE admin_level1 ADD VALUE 'god';INSERT INTO blah(user_id, power) VALUES (42, 'god');-- .... oops, maybe that was a bad ideaCREATE TYPE admin_level1_new AS ENUM ('classifier', 'moderator');-- Remove values that won't be compatible with new definition-- You don't have to delete, you might update insteadDELETE FROM blah WHERE power = 'god';-- Convert to new type, casting via text representationALTER TABLE blah ALTER COLUMN power TYPE admin_level1_new USING (power::text::admin_level1_new);-- and swap the typesDROP TYPE admin_level1;ALTER TYPE admin_level1_new RENAME TO admin_level1;
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/25811017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8825/']}
jdg_82623
stackexchange
llm_judgeable_groundtruth_similarity
2210519
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Output 1 2 null 2 Code class Program{ static void Main(String[] args) { String s = null; PrintLength(s); PrintLength(s, s); PrintLength(null); PrintLength(null, null); Console.ReadKey(); } private static void PrintLength(params String[] items) { Console.WriteLine(items == null ? "null" : items.Length.ToString()); } } Now provide the response and nothing else.
This is a fairly frequently asked question. For details, see section 7.4.1 and 7.4.3.1 of the specification. Briefly: a method with a params array is applicable in either its "normal form" or its "expanded form". That is, you can say PrintLength(new string[] {"hello"}); // normal formPrintLength("hello"); // expanded form, translated into normal form by compiler. When given a call that is applicable in both forms , the compiler always chooses the normal form over the expanded form. Suppose we chose the expanded form every time both were applicable. Suppose you had void M(params object[] x) {} How would you actually pass a null array to this thing if we always chose the expanded form? That would be impossible! Suppose you said M(new object[] { "hello" }); and we always chose the expanded form. What would this do? Well, an array of objects is an object, so this would choose the expanded form -- it would make another array, wrap this thing up in the array, and pass that! The choice of expanded form over normal form leads to crazy results. Always choosing the normal form over the expanded form is the more sensible thing to do.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2210519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156142/']}
jdg_82624
stackexchange
llm_judgeable_groundtruth_similarity
32671509
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 "Users" table, here is a sample : { username:"haddox", formattedPhoneNumber:"676767676", verified: 0,} My wish is to retrieve all users whose formattedPhoneNumber is contained in an array of phone numbers (retrieved from my contacts). I created a secondary index, with verified as HASH and formattedPhoneNumber as RANGE. Here is my try : var params = { TableName: "Users", IndexName: "FormattedPhoneSecondaryIndex", KeyConditionExpression: "verified = :v AND formattedPhone IN :n", ExpressionAttributeValues: { ":v":1, ":n": ["672053916", "642117296"] }, ProjectionExpression: "username, formattedPhoneNumber"};dynamodb.query(params, function(err, data) { if (err) console.log(JSON.stringify(err, null, 2)); else console.log(JSON.stringify(data, null, 2));}); But I get the following error : Invalid KeyConditionExpression: Syntax error; token: \":n\", near: \"IN :n\"", Is there something wrong with the IN keyword ? Maybe there is another way to achieve this ? Now provide the response and nothing else.
KeyConditionExpression's cannot use the "IN" operator (see http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#FilteringResults ). The idea with KeyConditions/KeyConditionExpression in a query operation is to more efficiently read pages of items from DynamoDB, since items with the same hash key but different range keys are stored contiguously and in sorted order. The IN operator would require extracting small portions of certain pages, which makes the Query operation less efficient, so it is not allowed in KeyConditions. You would want to add that as a FilterExpression instead, which is a convenience parameter to reduce the number of items returned from DynamoDB, but does not impact how the data is read from DynamoDB.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32671509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4609567/']}
jdg_82625
stackexchange
llm_judgeable_groundtruth_similarity
308311
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I created my own service for jekyll and when I start the service it seems like it doesn't run as a background process because I am forced to ctrl + c out of it. It just stays in the foreground because of the --watch. I am not sure how to go around it and make it so that it runs in the background. Any thoughts? # /etc/systemd/system/jekyll-blog.service[Unit]Description=Start blog jekyll[Service]Type=forkingWorkingDirectory=/home/blogExecStart=/usr/local/bin/jekyll build --watch --incremental -s /home/blog -d /var/www/html/blog &ExecReload=/bin/kill -HUP $MAINPIDKillMode=processRestart=on-failureUser=rootGroup=root[Install]WantedBy=multi-user.target Now provide the response and nothing else.
Systemd is able to handle various different service types specifically one of the following simple - A long-running process that does not background its self and stays attached to the shell. forking - A typical daemon that forks itself detaching it from the process that ran it, effectively backgrounding itself. oneshot - A short-lived process that is expected to exit. dbus - Like simple, but notification of processes startup finishing is sent over dbus. notify - Like simple, but notification of processes startup finishing is sent over inotify. idle - Like simple, but the binary is started after the job has been dispatched. In your case you have picked Type=forking which means systemd is waiting for the process to fork itself and for the parent process to end, which it takes as an indication that the process has started successfully. However, your process is not doing this - it remains in the foreground and so systemctl start will hang indefinitely or until the processes crashes. Instead, you want Type=simple , which is the default so you can remove the line entirely to get the same effect. In this mode systemd does not wait for the processes to finish starting up (as it has no way of know when this has happened) and so continues executing and dependent services straight away. In your case there are none so this does not matter. A small note on security: You are running the service as root, this is discouraged as it is less secure than running it as an unprivileged user. The reason for this is that if there is a vulnerability in jekyll that somehow allows execution of commands (possibly via the code it is parsing) then the attacker needs to do nothing else to completely own your system. If, on the other hand, it is run as a non-privileged user, the attacker is only able to do as much damage as that user and must now attempt to gain root privileges to completely own your system. It simply adds an extra layer attackers must go though. You can simply run it as the same user that is running your web server, but this leaves you open to another potential attack. If there is a vulnerability in your web server that allows the user to manipulate files on your system they can modify the generated html files, or worst the source files and cause your server to serve anything they want. However, if the generated files and source files are only readable by the webserver and writable be another non-privileged user they will not be able to, as easily, modify them by attacking the web server. However, if you are simply serving static files from this server and keep the server up to date these attacks are very very unlikely - but still possible. It is your responsibility to weigh the risks vs the overhead of setting it up based on how critical your system is but both of these tips are very simple to set up and next to no maintenance overhead.
{}
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/308311', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/188594/']}
jdg_82626
stackexchange
llm_judgeable_groundtruth_similarity
8275883
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: With the DatePickerDialog we can have a fancy interface to set the date as this (source: androidpeople.com ) I like it but it can only be used to set date so how could I build a "DatePickerDialog-like" AlertDialog ? I mean users could click on the "plus" and "minus" button as well as put in the number with keyboard. Instead of only being able to select a single date, I'd be able to select three different numbers using the three up/down/scroll controls. Now provide the response and nothing else.
A rotation of angle a around the point (x,y) corresponds to the affine transformation: CGAffineTransform transform = CGAffineTransformMake(cos(a),sin(a),-sin(a),cos(a),x-x*cos(a)+y*sin(a),y-x*sin(a)-y*cos(a)); You may need to plug in -a instead of a depending on whether you want the rotation to be clockwise or counterclockwise. Also, you may need to plug in -y instead of y depending on whether or not your coordinate system is upside down. Also, you can accomplish precisely the same thing in three lines of code using: CGAffineTransform transform = CGAffineTransformMakeTranslation(x, y);transform = CGAffineTransformRotate(transform, a);transform = CGAffineTransformTranslate(transform,-x,-y); If you were applying this to a view, you could also simply use a rotation transform via CGAffineTransformMakeRotation(a), provided you set the view's layer's anchorPoint property to reflect the point you want to rotate around. However, is sounds like you aren't interested in applying this to a view. Finally, if you are applying this to a non-Euclidean 2D space, you may not want an affine transformation at all. Affine transformations are isometries of Euclidean space, meaning that they preserve the standard Euclidean distance, as well as angles. If your space is not Euclidean, then the transformation you want may not actually be affine, or if it is affine, the matrix for the rotation might not be as simple as what I wrote above with sin and cos. For instance, if you were in a hyperbolic space, you might need to use the hyperbolic trig functions sinh and cosh, along with different + and - signs in the formula. P.S. I also wanted to remind anyone reading this far that "affine" is pronounced with a short "a" as in "ask", not a long "a" as in "able". I have even heard Apple employees mispronouncing it in their WWDC talks.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8275883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/792668/']}
jdg_82627
stackexchange
llm_judgeable_groundtruth_similarity
63449
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So, I acquired some images by scanning a radiation source with a square detector like in the following gif. Where the dashed grid represents reality, the 3x3 square my detector, and the 4x4 my acquired data.Obviously, because I'm moving the detector in steps smaller than its size, my image is convoluted. Assuming my detector has uniform sensitivity, how do I go about deconvolving it? The point spread function should be simple, but I can't seem to find examples anywhere. (I can work with Python or Matlab, so feel free to give any examples you want) The data I'm working with consists of gaussian-ish peaks surrounded by noise like so: Now provide the response and nothing else.
Your model is exactly a Convolution with Uniform Kernel where the output is what is called the Valid Part of the Convolution . In MATLAB lingo it will be using conv2(mA, mK, 'valid') . So the way to solve it will be using a matrix form of the convolution and solving the linear system of equations. Let's use the Lenna Image as input (Size was reduced for faster calculations): We have a uniform kernel for the sensor model. The output of the convolution with uniform kernel is given by: The output from the sensor is both blurred and smaller (Less 2 rows and 2 columns as it is 3x3 kernel) just as in your model. This is the model of Valid Convolution . In Matrix form what we have is: $$ \boldsymbol{b} = K \boldsymbol{a} $$ Where $ \boldsymbol{b} $ is the column stack vector of the output image, $ \boldsymbol{a} $ is the column stack vector of the input image and $ K $ is the convolution operator ( Valid Convolution ) in matrix form. In the code it is done in the function CreateConvMtx2D() . So, now all we need is to restore the image by solving the Matrix Equation. Yet the issue is the equation is Underdetermined System and the matrix has high condition number which suggest not to solve this equation directly. The solution is to use some kind of regularization of the least squares form of the problem: $$ \arg \min_{\boldsymbol{a}} \frac{1}{2} {\left\| K \boldsymbol{a} - \boldsymbol{b} \right\|}_{2}^{2} + \lambda r \left( \boldsymbol{a} \right) $$ Where $ r \left( \boldsymbol{a} \right) $ is the regularization term. In the optimal case the regularization should match the prior knowledge on the problem. For instance, in Image Processing we can assume a Piece Wise Smooth / Constant Model which matches the Total Variation regularization. Since we have no knowledge here, we will use the classic regularization to handle the Condition Number - Tikhonov Regularization : $$ \arg \min_{\boldsymbol{a}} \frac{1}{2} {\left\| K \boldsymbol{a} - \boldsymbol{b} \right\|}_{2}^{2} + \frac{\lambda}{2} {\left\| \boldsymbol{a} \right\|}_{2}^{2} = {\left( {K}^{T} K + \lambda I \right)}^{-1} {K}^{T} \boldsymbol{b} $$ The output is given by (For $ \lambda = 0.005 $ ): We can see that near the edge we have some artifacts which are due to the fact the system is Underdetermined and we have less equations to describe those pixels. One can use the $ \lambda $ parameter to balance between how sharp the output is (Yet with artifacts) to how smooth it is, basically governing the level inversion of the system. I advise playing with the parameter to find the best balance for your case but more than that, find a better regularization. Since the information you're after looks smooth you can use something in that direction. The full MATLAB code is available on my StackExchange Signal Processing Q63449 GitHub Repository (Look at the SignalProcessing\Q63449 folder). Enjoy...
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/63449', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/47325/']}
jdg_82628
stackexchange
llm_judgeable_groundtruth_similarity
47688358
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 make regex that can match all of them: word word-hyphen word-hyphen-again that is -\w+ could be many depends on words in a term. How can I make it optional Thing I made so far is given here:- https://regex101.com/r/Atpwze/1 Now provide the response and nothing else.
You need to add runtime permission for OS Marshmallow or above.Add this code for permission to allow run time operation in splash activity in onCreate or before download process of image. if (!checkPermission()) { openActivity();} else { if (checkPermission()) { requestPermissionAndContinue(); } else { openActivity(); }} Add this method outside onCreate private static final int PERMISSION_REQUEST_CODE = 200;private boolean checkPermission() { return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ; }private void requestPermissionAndContinue() { if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE) && ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.setCancelable(true); alertBuilder.setTitle(getString(R.string.permission_necessary)); alertBuilder.setMessage(R.string.storage_permission_is_encessary_to_wrote_event); alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE , READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); } }); AlertDialog alert = alertBuilder.create(); alert.show(); Log.e("", "permission denied, show dialog"); } else { ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE); } } else { openActivity(); }}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PERMISSION_REQUEST_CODE) { if (permissions.length > 0 && grantResults.length > 0) { boolean flag = true; for (int i = 0; i < grantResults.length; i++) { if (grantResults[i] != PackageManager.PERMISSION_GRANTED) { flag = false; } } if (flag) { openActivity(); } else { finish(); } } else { finish(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); }}private void openActivity() { //add your further process after giving permission or to download images from remote server.}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47688358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275002/']}
jdg_82629
stackexchange
llm_judgeable_groundtruth_similarity
8050264
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 have a global dict in my code which is something like the following: group = { 'vowel' : ['aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o'], 'consonant' : ['b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng', 'p', 'r', 's', 'sh', 't', 'th', 'v', 'w', 'y', 'z', 'zh'] } It has a single key and multiple values. I need this dict because I have to make sure a phoneme is either a vowel or consonant to proceed further in the code. Later in the code I have to do something like, if phoneme == vowel : do thiselse : do that (for consonants) Thank you. Now provide the response and nothing else.
It's more effective to use sets (you can group them in dict if you want): vowels = set(['aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o'])consonants = set(['b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng', 'p', 'r', 's', 'sh', 't', 'th', 'v', 'w', 'y', 'z', 'zh'])if phoneme in vowels: do thiselse : do that (for consonants)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8050264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/824742/']}
jdg_82630
stackexchange
llm_judgeable_groundtruth_similarity
287255
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider an interface: interface IWaveGenerator{ SoundWave GenerateWave(double frequency, double lengthInSeconds);} This interface is implemented by a number of classes which generate waves of different shapes (for example, SineWaveGenerator and SquareWaveGenerator ). I want to implement a class that generates a SoundWave based on musical data, not raw sound data. It would receive the name of a note and a length in terms of beats (not seconds), and internally use the IWaveGenerator functionality to create a SoundWave accordingly. Question is, should the NoteGenerator contain an IWaveGenerator or should it inherit from an IWaveGenerator implementation? I'm leaning towards composition because of two reasons: 1- It allows me to inject any IWaveGenerator to the NoteGenerator dynamically. Also, I only need one NoteGenerator class, instead of SineNoteGenerator , SquareNoteGenerator , etc. 2- There's no need for NoteGenerator to expose the lower-level interface defined by IWaveGenerator . However I'm posting this question to hear other opinions regarding this, maybe points I haven't thought of. BTW: I would say NoteGenerator is conceptually an IWaveGenerator because it generates SoundWave s. Now provide the response and nothing else.
It allows me to inject any IWaveGenerator to the NoteGenerator dynamically. Also, I only need one NoteGenerator class, instead of SineNoteGenerator , SquareNoteGenerator , etc. That is a clear sign it would be better to use composition here, and not inherit from SineGenerator or SquareGenerator or (worse) both. Nethertheless, it will make sense to inherit a NoteGenerator directly from an IWaveGenerator if you change the latter a little bit. The real problem here is, it is probably meaningful to have NoteGenerator with a method like SoundWave GenerateWave(string noteName, double noOfBeats, IWaveGenerator waveGenerator); but not with a method SoundWave GenerateWave(double frequency, double lengthInSeconds); because this interface is too specific. You want IWaveGenerator s to be objects which generate SoundWave s, but currently your interface expresses IWaveGenerator s are objects which generate SoundWave s from frequency and length exclusively . So better design such an interface this way interface IWaveGenerator{ SoundWave GenerateWave();} and pass parameters like frequency or lengthInSeconds , or a completely different set of parameters through the constructors of a SineWaveGenerator , a SquareGenerator , or whatever other generator you have in mind. This will allow you to create other kind of IWaveGenerator s with completely different construction parameters. Maybe you want to add a rectangle wave generator which needs a frequency and two length parameters, or something like that, maybe you want to add a triangle wave generator next, also with at least three parameters. Or, a NoteGenerator , with constructor parameters noteName , noOfBeats , and waveGenerator . So the general solution here is to decouple the input parameters from the output function, and make only the output function part of the interface.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/287255', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/121368/']}
jdg_82631
stackexchange
llm_judgeable_groundtruth_similarity
3747730
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Which one is the best practice and Why ? a) Type Table, Surrogate/Artificial Key Foreign key is from user.type to type.id : b) Type Table, Natural Key Foreign key is from user.type to type.typeName : Now provide the response and nothing else.
I believe that in practice, using a natural key is rarely the best option. I would probably go for the surrogate key approach as in your first example. The following are the main disadvantages of the natural key approach: You might have an incorrect type name, or you may simply want to rename the type. To edit it, you would have to update all the tables that would be using it as a foreign key. An index on an int field will be much more compact than one on a varchar field. In some cases, it might be difficult to have a unique natural key, and this is necessary since it will be used as a primary key. This might not apply in your case.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3747730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/242769/']}
jdg_82632
stackexchange
llm_judgeable_groundtruth_similarity
17866735
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From what I saw in this post I decided to start reading the book Effective C++ . But now that there are many new features because of C++11 and that a few of the good practices changed, I'm not sure whether or not it is actually a good idea. Has the advent of C++11 deprecated any of the advice contained in Effective C++? If so, which topics should I avoid? Now provide the response and nothing else.
This what Scott Meyers himself had to say about it on his own blog Which may lead you to wonder whether the information and advice in this pre-C++0x edition of Effective C++ remains relevant. I'm pleased to report that it does. Surprisingly so, in fact. Having spent nearly two years steeped in the details of C++0x, I expected to groan a bit as I reviewed this book's table of contents with C++0x in mind. Surely some Items would be inappropriate. But the advice I found proved sound. Should C++0x developers prefer consts, enums, and inlines to #defines (Item 2)? They should. Should they prevent exceptions from leaving destructors (Item 8)? Certainly. Should they use objects to manage resources? Declare data members private? Consider alternatives to virtual functions? Factor parameter-independent code out of templates? (Items 13, 22, 35, and 44.) Yes, yes, yes, yes! My goal has always been for Effective C++'s table of contents to summarize the advice in the book, and that summary remains just as applicable to C++0x development as to “traditional” C++ development. C++0x is a bigger language, and in some ways it's a different one, but the core techniques for making effective use of “old” C++ are core for the effective use of C++0x, too. This doesn't mean that this Effective C++ is a perfect match for C++0x. The book doesn't discuss features new to C++0x, so Items about making effective use of those features are missing. A C++0xified Effective C++ would certainly have Items devoted to move operations, to uniform initialization, and to lambda expressions, and it'd probably have an entire chapter on making effective use of the concurrency API. Such a book would also contain different examples, e.g., ones making use of auto variables, range-based for loops, in-class default initializers, as well as the occasional variadic template. To the extent that this book falls short in its support for C++0x, the errors are those of omission, not commission. UPDATE : the new title Effective Modern C++ has been for sale since November 2014 from O'Reilly and Amazon (and many others that you can google for).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17866735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2340918/']}
jdg_82633
stackexchange
llm_judgeable_groundtruth_similarity
45311
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: My school uses the website WebAssign for online math and science homework. One of WebAssign's features is a "My Notes" section that allows you to input notes for a problem and come back to it later without actually submitting the answer. The "My Notes" dialog has an <input> button to edit the text, and a <div> whose innerHTML is the raw contents of the notes. This means that, for example, writing &pi; in the notes box will cause π to appear in the rendered view. Another interesting side effect is that it's the rendered HTML that's copied into the box for further editing. For example, writing &amp;gt; and then pressing "Edit" and "Save" repeatedly would result in the sequence &amp;gt; → &gt; → > showing up in the editor. You can also break the page by writing something like </div></body></html> , which is injected into the HTML raw. My question is whether there's anything inherently dangerous to the server or any other users of the website here. It would seem to me that there isn't—I have no indication that the server is actually executing any scripts, etc. that I might put in there, only storing the text and feeding it back later. However, there also seems to be something just wrong about this lack of sanitization in a production website. So is this a problem? Now provide the response and nothing else.
Looking at your description, the application seems to be vulnerable to Cross-Site Scripting (XSS) . Such attack can lead to the compromise of student accounts and even accounts with higher privileges. This can be demonstrated by: The victim clicks a shortened link leading to http://evil.com . The page http://evil.com contains a hidden 'My Notes' form that is pre-filled with malicious <script> (a script that sends the user's cookie to the attacker). The form is automatically submitted to the legitimate WebAssign URL (not that the request is sent from the victim's browser, meaning that it is sent with the victim's cookie). The legitimate WebAssign page is rendered with the malicious <script> which is executed and the victim's cookie is sent to the attacker. This can be mitigated by properly sanitizing the user-supplied HTML content before sending it to the browser and by setting the HttpOnly flag with the cookies.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/45311', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/23966/']}
jdg_82634
stackexchange
llm_judgeable_groundtruth_similarity
2137415
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a function that takes some bitmap data and returns a UIImage * from it. It looks something like so: UIImage * makeAnImage() { unsigned char * pixels = malloc(...); // ... CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, pixels, pixelBufferSize, NULL); CGImageRef imageRef = CGImageCreate(..., provider, ...); UIImage * image = [[UIImage alloc] initWithCGImage:imageRef]; return [image autorelease];} Can anyone explain exactly who owns what memory here? I want to clean up properly, but I'm not sure how to do it safely. Docs are fuzzy on these. If I free pixels at the end of this function after creating the UIImage, and then use the UIImage, I crash. If I Release the provider or the imageRef after creating the UIImage, I don't see a crash, but they're apparently passing the pixels all the way through, so I'm skittish about releasing these intermediate states. (I know per CF docs that I should need to call release on both of the latter because they come from Create functions, but can I do that before the UIImage is used?) Presumably I can use the provider's dealloc callback to cleanup the pixels buffer, but what else? Thanks! Now provide the response and nothing else.
The thumb rule here is " -release * it if you don't need it". Because you no longer need provider and imageRef afterwards, you should -release all of them, i.e. UIImage * image = [[UIImage alloc] initWithCGImage:imageRef];CGDataProviderRelease(provider);CGImageRelease(imageRef);return [image autorelease]; pixel is not managed by ref-counting, so you need to tell the CG API to free them for you when necessary. Do this: void releasePixels(void *info, const void *data, size_t size) { free((void*)data);}....CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, pixels, pixelBufferSize, releasePixels); By the way, you can use +imageWithCGImage: instead of [[[* alloc] initWithCGImage:] autorelease] . Even better, there is +imageWithData: so you don't need to mess with the CG and malloc stuff. (*: Except when the retainCount is already supposedly zero from the beginning.)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2137415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73297/']}
jdg_82635
stackexchange
llm_judgeable_groundtruth_similarity
394182
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: So let's say I have a view model, representing a student. The view model is corresponding to a student model, from which the data comes. What I am struggling with, is how to populate the fields in the view model. Do I simply forward reference the fields from the model (where possible) or do I have actual fields in the view model, which I then populate? Example A - Forward referencing public class StudentViewModel{ public StudentModel Student { get; set; } public string FirstName { get { return Student.FirstName; } } public string LastName { get { return Student.LastName; } } // ...and so on} Example B - Using actual fields public class StudentViewModel { public string FirstName { get; private set; } public string LastName { get; private set; } public void SetStudentProperties(StudentModel student) { FirstName = student.FirstName; LastName = student.LastName; }} So obviously both of these examples are overly simplified and I have left out stuff like INotifyPropertyChanged , but I think you get the point. Are any of my approaches viable, or have I completely misunderstood the intend of view models? I also considered using the constructor for input, but this makes me struggle with the depency injection framework (I am using Caliburn.Micro). Now provide the response and nothing else.
In General When do you have enough automatic testing to be confident in your continuous integration pipeline? The answer probably becomes clear if you think about what you want to be confident about. Ultimately, it maps 1-1; every test makes you confident about the one thing it tests: Unit testing gives you confidence that a class (or module) does what it is tested for. Integration testing gives you confidence that several units work together in the way that is tested for. End-to-end testing gives you confidence that the whole application does a certain thing, the way it is described in the test. From the way you formulated your question, you're probably thinking in a big-picture business sense right now, for example: I want to be confident that my app can do X . So you write an end-to-end test that tries to do X and checks if it does that correctly. More concrete That's all very self-referential, but that's because that's what it comes down to. There simply is not more to it. For example, imagine you write an app to create cooking recipes. One feature is that, if you add different amounts of several different kinds of cheese, it gives you the correct temperature and time so that they all melt. So you can write a unit test for your CheeseMeltCalculator , where you give it 100g Gouda and 200g Emmental cheese, and then you check that the temperature and time turn out right. That means you can now be confident that CheeseMeltCalculator works for 100g Gouda and 200g cheese. Now if you repeat this test with 300g Gouda instead of 200g, you can be pretty confident that it works correctly for different values. You can add tests for 0 , -1 and int.MaxValue g of Gouda to be confident that the code does not trip up (or trips up correctly as intended) for weird input. You can write an integration test to check that CheeseMeltCalculator is incorporated correctly into the whole food temperature and time calculation process. If this goes wrong, but the CheeseMeltCalculator tests above are fine, you can be confident that the bug is in other calculators or in the way the data from different calculators is combined. And finally you can write an end-to-end test for creating a whole recipe, and one of the things you check for is the result temperature and time. If the previous 2 levels of tests are fine, but it goes wrong for this, then you can again be confident that those parts are correct and the mistake is something about how temperature calculation is integrated into the application. For example, maybe the user input is not transferred correctly. And finally , if all of those test are fine, then you can be confident that " if you add different amounts of several different kinds of cheese, it gives you the correct temperature and time so that they all melt " Long Story Short The point is you can't have a test "it works correctly". You can only test "If I do X, Y happens". However, this is exactly the stuff that should be in technical specifications for the project. A statement like " if you add different amounts of several different kinds of cheese, it gives you the correct temperature and time so that they all melt " not only gives the client clear expectations about what the finished product will do, but also can be turned into automated tests. Additional info User Richard added this info in an edit: Martin Fowler has a very nice summary on his website about the most common strategies: https://martinfowler.com/articles/microservice-testing/ I don't want to remove this, but I want to say this: Compared to this answer, it is not a "summary", but rather a much more in-depth explanation, with nice graphics and everything. My advice would be: If everything makes sense to you after reading my answer, you're done. If things still seem unclear, set a little time aside and read through the linked article.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/394182', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/271714/']}
jdg_82636
stackexchange
llm_judgeable_groundtruth_similarity
40579879
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 display a simple SnackBar inside Flutter 's Stateful widget. My application creates new instance of MaterialApp with a stateful widget called MyHomePage . I try to show the SnackBar in showSnackBar() method. But it fails with The method showSnackBar was called on null . What's wrong with this code? class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(), ); }}class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key); @override _MyHomePageState createState() => new _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(); @override void initState() { super.initState(); showInSnackBar("Some text"); } @override Widget build(BuildContext context) { return new Padding( key: _scaffoldKey, padding: const EdgeInsets.all(16.0), child: new Text("Simple Text") ); } void showInSnackBar(String value) { _scaffoldKey.currentState.showSnackBar(new SnackBar( content: new Text(value) )); }} SOLUTION: class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new Scaffold(body: new MyHomePage()), ); }}class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key); @override _MyHomePageState createState() => new _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { showInSnackBar("Some text"); return new Padding( padding: const EdgeInsets.all(16.0), child: new Scaffold( body: new Text("Simple Text") ) ); } void showInSnackBar(String value) { Scaffold.of(context).showSnackBar(new SnackBar( content: new Text(value) )); }} Now provide the response and nothing else.
There's three problems. The first is that you don't have a Scaffold anywhere, and the Scaffold widget is the one that knows how to show snack bars. The second is that you have a key for getting a hold of the scaffold, but you've put it on a Padding instead (and Paddings don't have any knowledge of snack bars). The third is that you've used the key before the widget that it's associated with has had a chance to be initialised, since initState is called before build. The simplest solution is to change the home line in your MyApp widget to: home: new Scaffold(body: new MyHomePage()), ...and then remove all mention of _scaffoldKey and instead use Scaffold.of(context) where you currently have _scaffoldKey.currentState .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40579879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/706387/']}
jdg_82637
stackexchange
llm_judgeable_groundtruth_similarity
30373
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the light source in the black hole images? I've searched the site before asking, as well as tried to google it. But perhaps the answer is buried due to the recent news. My understanding, is that the ring in the images is an illuminated accretion disc. What I could not find explained is the light source, and by extension, why is a bright accretion disc – which is round by definition – a proof for light bending? (I'm not disputing the fact.) Now provide the response and nothing else.
The radiation being detected in this case is mostly synchroton radiation, caused by energetic electrons spiralling around magnetic field line, rather than thermal radiation, but it comes from the same place (the disk). The actual evidence for light bending is, I believe the dark area in the middle, which is several times larger than the actual event horizon and is caused because the light that would have been coming to us from that direction has been bent away.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/30373', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/26579/']}
jdg_82638
stackexchange
llm_judgeable_groundtruth_similarity
21746750
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to wait until a file is created then read it in. I have the below code, but sure it does not work: import os.pathif os.path.isfile(file_path): read file inelse: wait Any ideas please? Now provide the response and nothing else.
A simple implementation could be: import os.pathimport timewhile not os.path.exists(file_path): time.sleep(1)if os.path.isfile(file_path): # read fileelse: raise ValueError("%s isn't a file!" % file_path) You wait a certain amount of time after each check, and then read the file when the path exists. The script can be stopped with the KeyboardInterruption exception if the file is never created. You should also check if the path is a file after, to avoid some unwanted exceptions.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21746750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2446702/']}
jdg_82639
stackexchange
llm_judgeable_groundtruth_similarity
22188514
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 compare the current row with a value in the next row. SQL has LEAD and LAG functions to get the next and previous values but I can not use them because I am using SQL Server 2008. So how do I get this? I have table with output +----+-------+-----------+-------------------------+| Id | ActId | StatusId | MinStartTime |+----+-------+-----------+-------------------------+| 1 | 42 | 1 | 2014-02-14 11:17:21.203 || 2 | 42 | 1 | 2014-02-14 11:50:19.367 || 3 | 42 | 1 | 2014-02-14 11:50:19.380 || 4 | 42 | 6 | 2014-02-17 05:25:57.280 || 5 | 42 | 6 | 2014-02-19 06:09:33.150 || 6 | 42 | 1 | 2014-02-19 06:11:24.393 || 7 | 42 | 6 | 2014-02-19 06:11:24.410 || 8 | 42 | 8 | 2014-02-19 06:44:47.070 |+----+-------+-----------+-------------------------+ What I want to do is if the current row status is 1 and the next row status is 6 and both times are the same (up to minutes) then I want to get the row where the status is 1. Eg: Id 6 row has status 1 and Id 7 row has status 6 but both times are the same ie. 2014-02-19 06:11 So I want to get this row or id for status 1 ie. id 6 Now provide the response and nothing else.
In your case, the id s appear to be numeric, you can just do a self-join: select t.*from table t join table tnext on t.id = tnext.id - 1 and t.StatusId = 1 and tnext.StatusId = 6 and datediff(second, t.MinStartTime, tnext.MinStartTime) < 60; This isn't quite the same minute. It is within 60 seconds. Do you actually need the same calendar time minute? If so, you can do: select t.*from table t join table tnext on t.id = tnext.id - 1 and t.StatusId = 1 and tnext.StatusId = 6 and datediff(second, t.MinStartTime, tnext.MinStartTime) < 60 and datepart(minute, t.MinStartTime) = datepart(minute, tnext.MinStartTime);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22188514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2589895/']}
jdg_82640