qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
1,674,980 | I really can't believe I couldn't find a clear answer to this...
How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.:
```
class Blah
{
public:
Blah()
{
throw "oops";
}
};
void main()
{
Blah* b = NULL;
try
{
b = new Blah();
}
catch (...)
{
// What now?
}
}
```
When I tried this out, `b` is NULL in the catch block (which makes sense).
When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor.
This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx):
>
> When new is used to allocate memory
> for a C++ class object, the object's
> constructor is called after the memory
> is allocated.
>
>
>
So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory?
It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say?
CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case). | 2009/11/04 | [
"https://Stackoverflow.com/questions/1674980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31760/"
]
| You should refer to the similar questions [here](https://stackoverflow.com/questions/1230423/c-handle-resources-if-constructors-may-throw-exceptions-reference-to-faq-17) and [here](https://stackoverflow.com/questions/1197566/is-it-ever-not-safe-to-throw-an-exception-in-a-constructor).
Basically if the constructor throws an exception you're safe that the memory of the object itself is freed again. Although, if other memory has been claimed during the constructor, you're on your own to have it freed before leaving the constructor with the exception.
For your question WHO deletes the memory the answer is the code behind the new-operator (which is generated by the compiler). If it recognizes an exception leaving the constructor it has to call all the destructors of the classes members (as those have already been constructed successfully prior calling the constructor code) and free their memory (could be done recursively together with destructor-calling, most probably by calling a proper *delete* on them) as well as free the memory allocated for this class itself. Then it has to rethrow the catched exception from the constructor to the caller of *new*.
Of course there may be more work which has to be done but I cannot pull out all the details from my head because they are up to each compiler's implementation. | If an object cannot complete destruction because the constructor throws an exception, the first thing to happen (this happens as part of the constructor's special handling) is that all member variables to have been constructed are destroyed - if an exception is thrown in the initializer list, this means that only elements for which the initializer has completed are destroyed.
Then, if the object was being allocated with `new`, the appropriate deallocation function (`operator delete`) is called with the same additional arguments that were passed to `operator new`. For instance, `new (std::nothrow) SomethingThatThrows()` will allocate memory with `operator new (size_of_ob, nothrow)`, attempt to construct `SomethingThatThrows`, destroy any members that were successfully constructed, then call `operator delete (ptr_to_obj, nothrow)` when an exception is propagated - it won't leak memory.
What you have to be careful is allocating several objects in succession - if one of the later ones throws, the previous ones will not be automatically be deallocated. The best way around this is with smart pointers, because as local objects their destructors will be called during stack unwinding, and their destructors will properly deallocate memory. |
1,674,980 | I really can't believe I couldn't find a clear answer to this...
How do you free the memory allocated after a C++ class constructor throws an exception, in the case where it's initialised using the `new` operator. E.g.:
```
class Blah
{
public:
Blah()
{
throw "oops";
}
};
void main()
{
Blah* b = NULL;
try
{
b = new Blah();
}
catch (...)
{
// What now?
}
}
```
When I tried this out, `b` is NULL in the catch block (which makes sense).
When debugging, I noticed that the conrol enters the memory allocation routine BEFORE it hits the constructor.
This on the MSDN website [seems to confirm this](http://msdn.microsoft.com/en-us/library/kewsb8ba.aspx):
>
> When new is used to allocate memory
> for a C++ class object, the object's
> constructor is called after the memory
> is allocated.
>
>
>
So, bearing in mind that the local variable `b` is never assigned (i.e. is NULL in the catch block) how do you delete the allocated memory?
It would also be nice to get a cross platform answer on this. i.e., what does the C++ spec say?
CLARIFICATION: I'm not talking about the case where the class has allocated memory itself in the c'tor and then throws. I appreciate that in those cases the d'tor won't be called. I'm talking about the memory used to allocate *THE* object (`Blah` in my case). | 2009/11/04 | [
"https://Stackoverflow.com/questions/1674980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31760/"
]
| You should refer to the similar questions [here](https://stackoverflow.com/questions/1230423/c-handle-resources-if-constructors-may-throw-exceptions-reference-to-faq-17) and [here](https://stackoverflow.com/questions/1197566/is-it-ever-not-safe-to-throw-an-exception-in-a-constructor).
Basically if the constructor throws an exception you're safe that the memory of the object itself is freed again. Although, if other memory has been claimed during the constructor, you're on your own to have it freed before leaving the constructor with the exception.
For your question WHO deletes the memory the answer is the code behind the new-operator (which is generated by the compiler). If it recognizes an exception leaving the constructor it has to call all the destructors of the classes members (as those have already been constructed successfully prior calling the constructor code) and free their memory (could be done recursively together with destructor-calling, most probably by calling a proper *delete* on them) as well as free the memory allocated for this class itself. Then it has to rethrow the catched exception from the constructor to the caller of *new*.
Of course there may be more work which has to be done but I cannot pull out all the details from my head because they are up to each compiler's implementation. | Quoted from C++ FAQ ([parashift.com](http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.10)):
>
> [17.4] How should I handle resources if my constructors may throw
> exceptions?
> ------------------------------------------------------------------------------
>
>
> Every data member inside your object should clean up its own mess.
>
>
> If a constructor throws an exception, the object's destructor is not
> run. If your object has already done something that needs to be undone
> (such as allocating some memory, opening a file, or locking a
> semaphore), this "stuff that needs to be undone" *must* be remembered
> by a data member inside the object.
>
>
> For example, rather than allocating memory into a raw `Fred*` data
> member, put the allocated memory into a "smart pointer" member object,
> and the destructor of this smart pointer will `delete` the `Fred`
> object when the smart pointer dies. The template `std::auto_ptr` is an
> example of such as "smart pointer." You can also [write your own
> reference counting smart pointer](http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.22). You can also [use smart pointers
> to "point" to disk records or objects on other machines](http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.3).
>
>
> By the way, if you think your `Fred` class is going to be allocated
> into a smart pointer, be nice to your users and create a `typedef`
> within your `Fred` class:
>
>
>
> ```
> #include <memory>
>
> class Fred {
> public:
> typedef std::auto_ptr<Fred> Ptr;
> ...
> };
>
> ```
>
> That typedef simplifies the syntax of all the code that uses your
> objects: your users can say `Fred::Ptr` instead of
> `std::auto_ptr<Fred>`:
>
>
>
> ```
> #include "Fred.h"
>
> void f(std::auto_ptr<Fred> p); // explicit but verbose
> void f(Fred::Ptr p); // simpler
>
> void g()
> {
> std::auto_ptr<Fred> p1( new Fred() ); // explicit but verbose
> Fred::Ptr p2( new Fred() ); // simpler
> ...
> }
>
> ```
>
> |
409,088 | What is the proof of the theorem which says: there is a root of the equation $x^{2}+x=1$ in $\mathbb{Z}\_{p}$ if and only if $p=5$ or $p\equiv -1\bmod 5$ or $p\equiv 1\bmod 5$. | 2013/06/02 | [
"https://math.stackexchange.com/questions/409088",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/80632/"
]
| There are no solutions in $\mathbb{Z}\_2$ by inspection. For any prime $p$ other than $2$, we have that $2$ is a unit in $\mathbb{Z}\_p$, so that
$$x^2+x\equiv 1\bmod p\iff 4x^2+4x\equiv 4\bmod p\iff (2x+1)^2=4x^2+4x+1\equiv 5\bmod p.$$
Thus, we see that there the equation has solutions in $\mathbb{Z}\_p$ if and only if $5$ is a quadratic residue (or $0$) modulo $p$. By quadratic reciprocity $5$ is a quadratic residue modulo $p$ if and only if $p\equiv1\bmod 5$ or $p\equiv 4\equiv-1\bmod 5$, and $5$ is $0$ modulo $p$ if and only if $p=5$. | Exactly like in $\mathbb R$, quadratic equations in $\mathbb Z\_p$ have a solution if and only if the discriminant is a square un $\mathbb Z\_p$.
Here we have $\Delta = 5$ so the question now is : does $5$ have a square root in $\mathbb Z\_p$ ?
This is answered by quadratic reciprocity. |
60,984,111 | I know this question has been asked before. I checked through multiple answers on this site,
for example:
[Wordpress loop with different bootstrap columns](https://stackoverflow.com/questions/54568904/wordpress-loop-with-different-bootstrap-columns)
<https://wordpress.stackexchange.com/questions/222278/how-to-separate-posts-loop-in-to-two-columns/222281>
... but I cannot work out how to integrate answers with my code (assuming that is possible).
I want to display a list of Categories and their related posts on a page.
The code I'm using works fine BUT displays the results in a single column down the page:
[](https://i.stack.imgur.com/ukuUZ.jpg)
I want to split the display into 2 columns, like in the image below, if possible:
[](https://i.stack.imgur.com/dRfHK.jpg)
The code I'm using (currently placed in a new page template) is as follows:
```
<?php
/*
* Template Name: Alphabetical List
*/
get_header();
// Grab all the categories from the database that have posts.
$categories = get_terms( 'category', 'orderby=name&order=ASC');
// Loop through categories
foreach ( $categories as $category ) {
// Display category name
echo '<h2 class="post-title">' . $category->name . '</h2>';
echo '<div class="post-list">';
// WP_Query arguments
$args = array(
'cat' => $category->term_id,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
?>
<p><a href="<?php the_permalink();?>"><?php the_title(); ?></a></p>
<?php
} // End while
} // End if
echo '</div>';
// Restore original Post Data
wp_reset_postdata();
} // End foreach
get_footer();
?>
```
Wondering if anyone can help me to get this code to display loop results in 2 columns.
Many thanks.
**UPDATE TO QUESTION**
Karl, thanks for your answer. Your script works, but with a small problem:
The Categories/Related Posts display in 2 columns but a 'gap/space' appears in the middle of the display of data (see image below):
[](https://i.stack.imgur.com/BWjin.jpg)
I added to your code slightly so I could display a custom field I inserted into each post. I'm not sure if this has caused the problem.
Altered code (changes are immediately after $query->the\_post();):
```
<?php
/*
* Template Name: Alphabetical List
*/
get_header();
?>
<div style="height:100px"></div>
<?php
// Grab all the categories from the database that have posts.
$categories = get_terms( 'category', 'orderby=name&order=ASC');
// Loop through categories
echo "<div class='new-column'>";
$counter = 0;
foreach ( $categories as $category ) {
if($counter % 4 == 0 && $counter !=0){
echo "<div class='new-column'>";
}
// Display category name
echo '<h2 class="post-title">' . $category->name . '</h2>';
echo '<div class="post-list">';
// WP_Query arguments
$args = array(
'cat' => $category->term_id,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$customfieldvalue = get_post_meta($post->ID, "PDF", true);
?>
<p><a href="<?php echo $customfieldvalue; ?>" target="_blank"><?php
the_title(); ?></a></p>
<?php
} // End while
} // End if
echo '</div>';
// Restore original Post Data
wp_reset_postdata();
$counter++;
if($counter % 4 == 0){
echo "</div>";
}
} // End foreach
if($counter % 4 != 0){
echo "</div>";
}
get_footer();
?>
``` | 2020/04/02 | [
"https://Stackoverflow.com/questions/60984111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536102/"
]
| I've used bootstrap classes (row, col-6). Checked the size of categories array and used 2 variables - one as a counter and the other one to check if the column is first or second.
```
<?php
/*
* Template Name: Alphabetical List
*/
get_header();
// Grab all the categories from the database that have posts.
$categories = get_terms( 'category', 'orderby=name&order=ASC');
//get size of category
$catSize = sizeof($categories);
$j = 1;
$n = 1;
// Loop through categories
foreach ( $categories as $category ) {
if($n == 1){
echo '<div class="row">';
}
echo'<div class="col-6">';
// Display category name
echo '<h2 class="post-title">' . $category->name . '</h2>';
echo '<div class="post-list">';
// WP_Query arguments
$args = array(
'cat' => $category->term_id,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
?>
<p><a href="<?php the_permalink();?>"><?php the_title(); ?></a></p>
<?php
} // End while
} // End if
echo '</div></div>';
if($n == 1){
if($j == $catSize){
echo '<div class="col-6"></div>
</div>';
}
else{
$n = 2;
}
}
else{
echo '</div>';
$n =1;
}
$j++;
}
// Restore original Post Data
wp_reset_postdata();
} // End foreach
get_footer();
?>
``` | Try this, I used a modulos operator "%" to group loops into 4, it will create new column every 4 loops. MAKE SURE YOU ADD CSS TO class new-column to arrange it like columns.
```
<?php
/*
* Template Name: Alphabetical List
*/
get_header();
// Grab all the categories from the database that have posts.
$categories = get_terms( 'category', 'orderby=name&order=ASC');
// Loop through categories
echo "<div class='new-column'">;
$counter = 0;
foreach ( $categories as $category ) {
if($counter % 4 == 0 && $counter !=0){
echo "<div class='new-column'">;
}
// Display category name
echo '<h2 class="post-title">' . $category->name . '</h2>';
echo '<div class="post-list">';
// WP_Query arguments
$args = array(
'cat' => $category->term_id,
'order' => 'ASC',
'orderby' => 'title',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
?>
<p><a href="<?php the_permalink();?>"><?php the_title(); ?></a></p>
<?php
} // End while
} // End if
echo '</div>';
// Restore original Post Data
wp_reset_postdata();
$counter++;
if($counter % 4 == 0){
echo "</div>";
}
} // End foreach
if($counter % 4 != 0){
echo "</div>";`enter code here`
}
get_footer();
?>
``` |
36,123,581 | I have the following code
```
import java.util.*;
public class Sorts {
public static void sort(ArrayList objects, Comparator<Car>) {
Comparator compareThing = new CarNameComparator();
int min;
Car temp;
for(int i = 0; i < objects.size() - 1; i++){
min = i;
for(int j = min+1; j < objects.size(); j++){
if(compareThing.compare(objects.get(i), objects.get(j))> 0){
min = j;
}
}
temp = (Car)objects.get(i);
objects.set(i, objects.get(min));
objects.set(min, temp);
}
}
}
```
and my IDE highlights the close parenthesis at the end of line 3, saying "expected identifier."
I can't tell what it means. This is a static method so it won't have a type, and it's not referring to the comparator because that has an identifier. What should I do? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1776000/"
]
| ```
public static void sort(ArrayList objects, Comparator<Car> identifier)
```
You missed the argument name in the function parameters. | I'm not sure what you are trying to do. But you have to specify an identifier for the passed parameter of the type Comparator. I guess what you want to do is:
```
public static void sort(ArrayList objects, CarNameComparator compareThing) {
int min;
Object temp;
for(int i = 0; i < objects.size() - 1; i++){
min = i;
for(int j = min+1; j < objects.size(); j++){
if(compareThing.compare(objects.get(i), objects.get(j))> 0){
min = j;
}
}
temp = (Object)objects.get(i);
objects.set(i, objects.get(min));
objects.set(min, temp);
}
}
```
Or you might just want to remove the parameter at all and do something like:
```
public static void sort(ArrayList objects) {
Comparator compareThing = new CarNameComparator();
int min;
Object temp;
for(int i = 0; i < objects.size() - 1; i++){
min = i;
for(int j = min+1; j < objects.size(); j++){
if(compareThing.compare(objects.get(i), objects.get(j))> 0){
min = j;
}
}
temp = (Object)objects.get(i);
objects.set(i, objects.get(min));
objects.set(min, temp);
}
}
```
If you could specify your problem more specific, a better answer may be possible. |
1,482,300 | Is there any method in .net that wraps phrases given a maximum length for each line?
Example:
```
Phrase: The quick red fox jumps over the lazy cat
Length: 20
```
Result:
```
The quick red fox
jumps over the lazy
cat
``` | 2009/09/26 | [
"https://Stackoverflow.com/questions/1482300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/129495/"
]
| There is no built in method for that. You can use a regular expression:
```
string text = "The quick brown fox jumps over the lazy dog.";
int minLength = 1;
int maxLength = 20;
MatchCollection lines = Regex.Matches(text, "(.{"+minLength.ToString()+","+maxLength.ToString()+"})(?: |$)|([^ ]{"+maxLength.ToString()+"})");
StringBuilder builder = new StringBuilder();
foreach (Match line in lines) builder.AppendLine(line.Value);
text = builder.ToString();
```
Note: I corrected [the pangram](http://en.wikipedia.org/wiki/The_quick_brown_fox_jumps_over_the_lazy_dog). | The code in this article returns a list of lines, but you should be able to easily adapt it.
**C# Wrapping text using split and List<>**
<http://bryan.reynoldslive.com/post/Wrapping-string-data.aspx> |
2,556,041 | We currently have rings and groups in school and I'm fine proving the group axioms except the proof for an operator to be well defined. I tried to solve two exercises I found in the internet, but I don't have a clue at what to do.
1) Proof that the matrix multiplication is well defined for $\begin{pmatrix} a & -b \\ b & a \end{pmatrix} \in \mathbb{R}^{2 \times 2} ~$for$~ a,b \in \mathbb{R} ~$and$~ a^2 + b^2 = 1$. 2) Proof that $\phi:\mathbb{Z}\_{mn}\rightarrow \mathbb{Z}\_{m} \times \mathbb{Z}\_{n}, z \rightarrow ([z]\_m,[z]\_n)$ is well defined. I tried the first one like that: $\begin{pmatrix} a & -b \\ b & a \end{pmatrix} \cdot \begin{pmatrix} a' & -b' \\ b' & a' \end{pmatrix} = \begin{pmatrix} aa' -bb' & a(-b')-ba' \\ ba' + ab' & b(-b') + aa' \end{pmatrix}$ but I don't know how what to do now. On the second one I don't even know how to start. Any help or hints are appreciated. | 2017/12/07 | [
"https://math.stackexchange.com/questions/2556041",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/462981/"
]
| There are basically two cases where a given 'human-understandable' operation might not be well-defined:
* The first is a question of domain and codomain. It may be possible that an function is not defined because it fails to land in the given co-domain, or because it is a composite of functions where the range of one fails to fall into the domain of the second. Your first example is of this sort. To show that it is well defined, show that the resulting matrix from your multiplication lands within the set of matrices you are considering: i.e. its '$a$' and its '$b$' have a sum of squares equalling $1$. (It may help to consider other invariants of matrices you know, like the determinant, but if that fails you can fall back on brute calculation to prove it)
* The second case is where equivalence relations are concerned. A function $f(a)$ may not be well defined because $a$ was a representative of a class of elements, and the result would have been different if a different representative had been chosen (It should have been the same for the entire class of equivalent elements). The classic example is that the operation on fractions $\frac{a}{b}\ \oplus \frac{c}{d}= \frac{a+c}{b+d}$ isn't well defined, because $\frac{1}{2} \oplus \frac{1}{1} = \frac{2}{3}$ but $\frac{1}{2}=\frac{2}{4}$ and $\frac{2}{4} \oplus \frac{1}{1} = \frac{3}{5} \neq \frac{2}{3}$. Your second example is of this form. The elements of $\mathbb{Z}\_{nm}$ are classes of integers all differing by multiples of $nm$. You must prove that even if a different representative $z'$ was chosen, differing from the original by a multiple of $nm$, the resulting $f(z')$ will still be the same.
*More info about the second case*: So, *in* $\mathbb{Z}\_{nm}$ *and only in* $\mathbb{Z}\_{nm}$ we know that $z + kmn$ and $z$ are equal. This is exactly why we expect them to be equal under the function. But we are only capable of representing them by integers from $\mathbb{Z}$, and if they aren't equal in $\mathbb{Z}$ then the formula we've given might not give equal answers for both. This is why it might not be well defined.
Consider the 'function' $f: \mathbb{Z}\_3 \rightarrow \{0,1\}$ with $f(z)=0$ if it is even and $f(z) = 1$ if it is odd. When you understand why this isn't well-defined, you'll understand what you need to prove in the second case. | **Hints:**
For 1), it is of course well defined as a matrix multiplication. All you have to do is to check the product satisfies the defining conditions of this set of matrices.
For 2), you have to prove that, if
$[z]\_{mn}=[z]\_{mn}$, then $[z]\_{m}=[z]\_{m}$ and $[z]\_{n}=[z]\_{n}$. |
2,556,041 | We currently have rings and groups in school and I'm fine proving the group axioms except the proof for an operator to be well defined. I tried to solve two exercises I found in the internet, but I don't have a clue at what to do.
1) Proof that the matrix multiplication is well defined for $\begin{pmatrix} a & -b \\ b & a \end{pmatrix} \in \mathbb{R}^{2 \times 2} ~$for$~ a,b \in \mathbb{R} ~$and$~ a^2 + b^2 = 1$. 2) Proof that $\phi:\mathbb{Z}\_{mn}\rightarrow \mathbb{Z}\_{m} \times \mathbb{Z}\_{n}, z \rightarrow ([z]\_m,[z]\_n)$ is well defined. I tried the first one like that: $\begin{pmatrix} a & -b \\ b & a \end{pmatrix} \cdot \begin{pmatrix} a' & -b' \\ b' & a' \end{pmatrix} = \begin{pmatrix} aa' -bb' & a(-b')-ba' \\ ba' + ab' & b(-b') + aa' \end{pmatrix}$ but I don't know how what to do now. On the second one I don't even know how to start. Any help or hints are appreciated. | 2017/12/07 | [
"https://math.stackexchange.com/questions/2556041",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/462981/"
]
| There are basically two cases where a given 'human-understandable' operation might not be well-defined:
* The first is a question of domain and codomain. It may be possible that an function is not defined because it fails to land in the given co-domain, or because it is a composite of functions where the range of one fails to fall into the domain of the second. Your first example is of this sort. To show that it is well defined, show that the resulting matrix from your multiplication lands within the set of matrices you are considering: i.e. its '$a$' and its '$b$' have a sum of squares equalling $1$. (It may help to consider other invariants of matrices you know, like the determinant, but if that fails you can fall back on brute calculation to prove it)
* The second case is where equivalence relations are concerned. A function $f(a)$ may not be well defined because $a$ was a representative of a class of elements, and the result would have been different if a different representative had been chosen (It should have been the same for the entire class of equivalent elements). The classic example is that the operation on fractions $\frac{a}{b}\ \oplus \frac{c}{d}= \frac{a+c}{b+d}$ isn't well defined, because $\frac{1}{2} \oplus \frac{1}{1} = \frac{2}{3}$ but $\frac{1}{2}=\frac{2}{4}$ and $\frac{2}{4} \oplus \frac{1}{1} = \frac{3}{5} \neq \frac{2}{3}$. Your second example is of this form. The elements of $\mathbb{Z}\_{nm}$ are classes of integers all differing by multiples of $nm$. You must prove that even if a different representative $z'$ was chosen, differing from the original by a multiple of $nm$, the resulting $f(z')$ will still be the same.
*More info about the second case*: So, *in* $\mathbb{Z}\_{nm}$ *and only in* $\mathbb{Z}\_{nm}$ we know that $z + kmn$ and $z$ are equal. This is exactly why we expect them to be equal under the function. But we are only capable of representing them by integers from $\mathbb{Z}$, and if they aren't equal in $\mathbb{Z}$ then the formula we've given might not give equal answers for both. This is why it might not be well defined.
Consider the 'function' $f: \mathbb{Z}\_3 \rightarrow \{0,1\}$ with $f(z)=0$ if it is even and $f(z) = 1$ if it is odd. When you understand why this isn't well-defined, you'll understand what you need to prove in the second case. | 1) Multiply two matrices of this form, and verify that the product again satisfies the condition, i.e., that it is again of this form with $a',b'$ satisfying $a'^2+b'^2=1$. Then 2) comes automatically in the same spirit.
Edit: For 1), use that such matrices correspond to complex numbers $z=a+bi$ with $|z|=a^2+b^2=1$:
[Why is the complex number $z=a+bi$ equivalent to the matrix form $\left(\begin{smallmatrix}a &-b\\b&a\end{smallmatrix}\right)$](https://math.stackexchange.com/questions/180849/why-is-the-complex-number-z-abi-equivalent-to-the-matrix-form-left-begins?noredirect=1&lq=1)
Then the multiplication of such matrices corresponds to multiplication of $z$ and $w$, and of course
$$
|zw|=|z|\cdot |w|=1\cdot 1=1.
$$ |
50,818,182 | I'm working on a very uncritical project. Therefore I want to have the best possible user experience while authentication meaning: log in once and stay logged in forever.
I managed to get firebase authentication working. However the token expires after one hour.
I read that the refresh token never expires. (see [here](https://stackoverflow.com/questions/37907096/firebase-authentication-duration-is-too-persistent/37908468#37908468) ) Therefore I thought of putting it in the local storage and use it to retrieve a new access token. Is that correct?
If this was the case: why is there no
```
this.afAuth.auth.getTokenWithRefreshToken()
```
Do I need to use
```
this.afAuth.auth.signInWithCustomToken(MyRefreshTokenFromLocalStorage)
```
this function?
What does setting the persistence to LOCAL actually do? In the [docs](https://firebase.google.com/docs/auth/web/auth-state-persistence) it says you will be logged in forever (even if browser is closed and reopened) but thats not true? "This includes the ability to specify whether a signed in user should be indefinitely persisted until explicit sign out, cleared when the window is closed or cleared on page reload." (firebase docs)
I tried quite a few things including a third-party auth-provider but I never know if its not working or if I'm not smart enough. So if someone could give me a direction what might work and where I could focus my tries and errors I'd be super happy. | 2018/06/12 | [
"https://Stackoverflow.com/questions/50818182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9659620/"
]
| This thread says the problem is configuration in GCP <https://groups.google.com/g/firebase-talk/c/9q6jQKtZyEg> but does not elaborate
>
> It turned out to be a GCP API configuration issue.
> The Token Service API must not be restricted, to allow the token to be refreshed.
>
>
>
After more search, I got this <https://github.com/firebase/firebase-js-sdk/issues/497#issuecomment-375500476>
You need to add "Token Service API" to the list of restrictions for your API KEY in `APIs & Servicers/Credentials` at GCP console. | You do need to retrieve the refresh token yourself. [User.prototype.getIdToken](https://firebase.google.com/docs/reference/js/firebase.User#getIdToken) will check if the token expires, if no, it returns the token, otherwise, it uses the refresh token to exchange a new id token for you.
For persistence, there is a doc here: <https://firebase.google.com/docs/auth/web/auth-state-persistence>
Local basically means the sign in states persist until you explicitly sign out and also the the states persist across tabs. |
50,818,182 | I'm working on a very uncritical project. Therefore I want to have the best possible user experience while authentication meaning: log in once and stay logged in forever.
I managed to get firebase authentication working. However the token expires after one hour.
I read that the refresh token never expires. (see [here](https://stackoverflow.com/questions/37907096/firebase-authentication-duration-is-too-persistent/37908468#37908468) ) Therefore I thought of putting it in the local storage and use it to retrieve a new access token. Is that correct?
If this was the case: why is there no
```
this.afAuth.auth.getTokenWithRefreshToken()
```
Do I need to use
```
this.afAuth.auth.signInWithCustomToken(MyRefreshTokenFromLocalStorage)
```
this function?
What does setting the persistence to LOCAL actually do? In the [docs](https://firebase.google.com/docs/auth/web/auth-state-persistence) it says you will be logged in forever (even if browser is closed and reopened) but thats not true? "This includes the ability to specify whether a signed in user should be indefinitely persisted until explicit sign out, cleared when the window is closed or cleared on page reload." (firebase docs)
I tried quite a few things including a third-party auth-provider but I never know if its not working or if I'm not smart enough. So if someone could give me a direction what might work and where I could focus my tries and errors I'd be super happy. | 2018/06/12 | [
"https://Stackoverflow.com/questions/50818182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9659620/"
]
| This thread says the problem is configuration in GCP <https://groups.google.com/g/firebase-talk/c/9q6jQKtZyEg> but does not elaborate
>
> It turned out to be a GCP API configuration issue.
> The Token Service API must not be restricted, to allow the token to be refreshed.
>
>
>
After more search, I got this <https://github.com/firebase/firebase-js-sdk/issues/497#issuecomment-375500476>
You need to add "Token Service API" to the list of restrictions for your API KEY in `APIs & Servicers/Credentials` at GCP console. | ```
firebase.auth.Auth.Persistence.LOCAL
```
'local' Indicates that the state will be persisted even when the browser window is closed or the activity is destroyed in React Native. An explicit sign out is needed to clear that state. Note that Firebase Auth web sessions are single host origin and will be persisted for a single domain only.
```
firebase.auth.Auth.Persistence.SESSION
```
'session' Indicates that the state will only persist in the current session or tab, and will be cleared when the tab or window in which the user authenticated is closed. Applies only to web apps.
```
firebase.auth.Auth.Persistence.NONE
```
'none' Indicates that the state will only be stored in memory and will be cleared when the window or activity is refreshed. |
39,396,047 | This is a question about OWL (Web Ontology Language). There might be some mistakes of terms as I am a very beginner.
I want to represent a painting activity as a **Painting** class.
* **Painting** has a property **TargetSurface** whose range is a **Surface** class:
+ **Surface** has properties **SurfaceColor** (range: **Color**), etc.
* **Painting** has a property **TargetColor** whose range is a **Color** class.
Now I want to represent the objective of painting as a property of **Painting**. It would be something like: a property **Painting.Objective** has a range that is an instance of **Change** class (let's say, **Change1**), which involves properties **Change1.What** = **TargetSurface.SurfaceColor** and **Change1.ToWhat** = **TargetColor**.
My question is that **Objective** is referring to properties of **Painting** (**Painting** is a holder of **Objective**; referred properties are **Painting.TargetSurface.SurfaceColor** and **Painting.TargetColor**). How can we represent this in OWL? An ugly solution would be representing the properties of **Change1** as xsd:string; **Change1.What** = "parent.TargetSurface.SurfaceColor" and **Change1.ToWhat** = "parent.TargetColor". Are there better solutions?
Note that **Painting.TargetSurface** and **Painting.TargetColor** will be referred to in other properties of **Painting**. So making an instance **Change2** which directly refers to **Painting.TargetSurface.SurfaceColor** and **Painting.TargetColor** would not be a good idea.
Many thanks! | 2016/09/08 | [
"https://Stackoverflow.com/questions/39396047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4236833/"
]
| This is a typical use case of **Apache Storm** in case you've continuous items coming in to F1. You can implement this in Storm in matter of minutes and you'll have fast and perfectly parallel system in place. Your F1, F2 and F3 will become bolts and your Items producer will become spout.
Since you asked how to do it using BlockingCollections here is an implementation. You'll need 3 threads in total.
**ItemsProducer:** It is producing 5 items at a time and feeding it to F1.
**F2ExecutorThread:** It is consuming 20 items at a time and feeding it to F2.
**F3ExecutorThread:** It is consuming 20 items at a time and feeding it to F3.
You also have 2 blocking queues one is used to transfer data from F1->F2 and one from F2->F3. You can also have a queue to feed data to F1 in similar fashion if required. It depends upon how you are getting the items. I've used Thread.sleep to simulate the time required to execute the function.
Each function will keep looking for items in their assigned queue, irrespective of what other functions are doing and wait until the queue has items. Once they've processed the item they'll put it in another queue for another function. They'll wait until the other queue has space if it is full.
Since all your functions are running in different threads, F1 won't be waiting for F2 or F3 to finish. If your F2 and F3 are significantly faster then F1 you can assign more threads to F1 and keep pushing to same f2Queue.
```
public class App {
final BlockingQueue<Item> f2Queue = new ArrayBlockingQueue<>(100);
final BlockingQueue<Item> f3Queue = new ArrayBlockingQueue<>(100);
public static void main(String[] args) throws InterruptedException {
App app = new App();
app.start();
}
public void start() throws InterruptedException {
Thread t1 = new ItemsProducer(f2Queue);
Thread t2 = new F2ExecutorThread(f2Queue, f3Queue);
Thread t3 = new F3ExecutorThread(f3Queue);
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
}
}
/**
* Thread producing 5 items at a time and feeding it to f1()
*/
class ItemsProducer extends Thread {
private BlockingQueue<Item> f2Queue;
private static final int F1_BATCH_SIZE = 5;
public ItemsProducer(BlockingQueue<Item> f2Queue) {
this.f2Queue = f2Queue;
}
public void run() {
Random random = new Random();
while (true) {
try {
List<Item> items = new ArrayList<>();
for (int i = 0; i < F1_BATCH_SIZE; i++) {
Item item = new Item(String.valueOf(random.nextInt(100)));
Thread.sleep(20);
items.add(item);
System.out.println("Item produced: " + item);
}
// Feed items to f1
f1(items);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
void f1(List<Item> items) throws InterruptedException {
Random random = new Random();
for (Item item : items) {
Thread.sleep(100);
item.upc = String.valueOf(random.nextInt(100));
f2Queue.put(item);
}
}
}
/**
* Thread consuming items produced by f1(). It takes 20 items at a time, but if they are not
* available it waits and starts processesing as soon as one gets available
*/
class F2ExecutorThread extends Thread {
static final int F2_BATCH_SIZE = 20;
private BlockingQueue<Item> f2Queue;
private BlockingQueue<Item> f3Queue;
public F2ExecutorThread(BlockingQueue<Item> f2Queue, BlockingQueue<Item> f3Queue) {
this.f2Queue = f2Queue;
this.f3Queue = f3Queue;
}
public void run() {
try {
List<Item> items = new ArrayList<>();
while (true) {
items.clear();
if (f2Queue.drainTo(items, F2_BATCH_SIZE) == 0) {
items.add(f2Queue.take());
}
f2(items);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void f2(List<Item> items) throws InterruptedException {
Random random = new Random();
for (Item item : items) {
Thread.sleep(100);
item.price = random.nextInt(100);
f3Queue.put(item);
}
}
}
/**
* Thread consuming items produced by f2(). It takes 20 items at a time, but if they are not
* available it waits and starts processesing as soon as one gets available.
*/
class F3ExecutorThread extends Thread {
static final int F3_BATCH_SIZE = 20;
private BlockingQueue<Item> f3Queue;
public F3ExecutorThread(BlockingQueue<Item> f3Queue) {
this.f3Queue = f3Queue;
}
public void run() {
try {
List<Item> items = new ArrayList<>();
while (true) {
items.clear();
if (f3Queue.drainTo(items, F3_BATCH_SIZE) == 0) {
items.add(f3Queue.take());
}
f3(items);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void f3(List<Item> items) throws InterruptedException {
Random random = new Random();
for (Item item : items) {
Thread.sleep(100);
item.competitorName = String.valueOf(random.nextInt(100));
System.out.println("Item done: " + item);
}
}
}
class Item {
String sku, upc, competitorName;
double price;
public Item(String sku) {
this.sku = sku;
}
public String toString() {
return "sku: " + sku + " upc: " + upc + " price: " + price + " compName: " + competitorName;
}
}
```
I guess you can follow the exact same approach in .Net as well. For better understanding I suggest you to go through basic architecture of <http://storm.apache.org/releases/current/Tutorial.html> | I tried to do same thing in .NET and i think it is working.
```html
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace BlockingCollectionExample
{
class Program
{
static void Main(string[] args)
{
BlockingCollection<Listing> needUPCJobs = new BlockingCollection<Listing>();
BlockingCollection<Listing> needPricingJobs = new BlockingCollection<Listing>();
// This will have final output
List<Listing> output = new List<Listing>();
// start executor 1 which waits for data until available
var executor1 = Task.Factory.StartNew(() =>
{
int maxSimutenousLimit = 5;
int gg = 0;
while (true)
{
while (needUPCJobs.Count >= maxSimutenousLimit)
{
List<Listing> tempListings = new List<Listing>();
for (int i = 0; i < maxSimutenousLimit; i++)
{
Listing listing = new Listing();
if (needUPCJobs.TryTake(out listing))
tempListings.Add(listing);
}
// Simulating some delay for first executor
Thread.Sleep(1000);
foreach (var eachId in tempListings)
{
eachId.UPC = gg.ToString();
gg++;
needPricingJobs.Add(eachId);
}
}
if (needUPCJobs.IsAddingCompleted)
{
if (needUPCJobs.Count == 0)
break;
else
maxSimutenousLimit = needUPCJobs.Count;
}
}
needPricingJobs.CompleteAdding();
});
// start executor 2 which waits for data until available
var executor2 = Task.Factory.StartNew(() =>
{
int maxSimutenousLimit = 10;
int gg = 10;
while (true)
{
while (needPricingJobs.Count >= maxSimutenousLimit)
{
List<Listing> tempListings = new List<Listing>();
for (int i = 0; i < maxSimutenousLimit; i++)
{
Listing listing = new Listing();
if (needPricingJobs.TryTake(out listing))
tempListings.Add(listing);
}
// Simulating more delay for second executor
Thread.Sleep(10000);
foreach (var eachId in tempListings)
{
eachId.Price = gg;
gg++;
output.Add(eachId);
}
}
if (needPricingJobs.IsAddingCompleted)
{
if(needPricingJobs.Count==0)
break;
else
maxSimutenousLimit = needPricingJobs.Count;
}
}
});
// producer thread
var producer = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 100; i++)
{
needUPCJobs.Add(new Listing() { ID = i });
}
needUPCJobs.CompleteAdding();
});
// wait for producer to finish producing
producer.Wait();
// wait for all executors to finish executing
Task.WaitAll(executor1, executor2);
Console.WriteLine();
Console.WriteLine();
}
}
public class Listing
{
public int ID;
public string UPC;
public double Price;
public Listing() { }
}
}
``` |
36,474,002 | I am trying to count result from multiple tables. I have picture and picture has comments, likes and dislikes. I want to merge all that in one table query where i will show all photos and count likes, comments, dislikes for that photo.
**My photo table looks like this:**
```
photo_id owner_id album_id image_type photo_name photo_ext photo_size photo_type photo_description date_uploaded date_midified photo_guid bg_x_position bg_y_position
-------- -------- -------- ---------- ------------------------------------ --------- ---------- ---------- ----------------- ------------------- ------------------- ------------------------------------ ------------- ---------------
2 1 5 0 27bda14cb0e30efb0eeef5688e6c0ef9.jpg .jpg 42.6 jpeg (NULL) 2016-02-09 15:45:20 2016-02-09 15:45:20 E8CFF5F0-F8FA-8AD7-E3B5-63EAFE81E1B6 (NULL) (NULL)
3 1 5 0 8077f0d2104c35c8e612e24834f82ace.jpg .jpg 34.52 jpeg (NULL) 2016-02-09 15:49:44 2016-02-09 15:49:44 09B25F5C-0A9D-0EBC-DCE9-EE24E8ED4B6D (NULL) (NULL)
4 1 5 0 6c28b264470e7a7f2829ea5b7290cbba.jpg .jpg 85.65 jpeg (NULL) 2016-02-09 15:49:56 2016-02-09 15:49:56 9A5EF85E-F691-F42E-C20C-BCDC765BFA1B (NULL) (NULL)
```
**Like table:**
```
like_id item_id account_id rate time host
------- ------- ---------- ------ ------------------- --------
308 2 1 1 2016-03-18 13:45:16 (NULL)
309 3 1 2 2016-03-18 13:45:33 (NULL)
310 2 7 1 2016-03-18 14:23:49 (NULL)
```
**Comment table:**
```
comment_id item_id content account_id time
------- ------- ---------- ------------ -------------------
308 262 Test comment 1 2016-03-18 13:45:16
```
So result what i want to have is like this:
```
photo_id owner_id album_id image_type photo_name photo_ext photo_size photo_type photo_description date_uploaded date_midified photo_guid bg_x_position bg_y_position likes dislikes comments
-------- -------- -------- ---------- ------------------------------- --------- ---------- ---------- ----------------- ------------------- ------------------- ---- ------ ------ ------------------------------------ ------------- --------------
```
So on existing table i want to add 3 new cells (likes, dislikes and comments) count. My query work good but count of comments is not correct becouse he show all picure has `1` comment but there is no comment.
```
SELECT * FROM (SELECT p.photo_id, p.photo_name,
IFNULL(SUM(l.rate = 1), 0) AS likes,
IFNULL(SUM(l.rate = 2), 0) AS dislikes
FROM pb_account_photos AS p
LEFT JOIN pb_account_likes AS l ON l.item_id = p.photo_id
WHERE p.owner_id = 1 GROUP BY p.photo_id) AS LIKES,
(SELECT COUNT(*) AS comments, p.photo_id
FROM pb_account_photos AS p
LEFT JOIN pb_account_comments AS c ON c.item_id = p.photo_id
WHERE p.owner_id = 1 GROUP BY p.photo_id) AS COMM WHERE COMM.photo_id=LIKES.photo_id;
``` | 2016/04/07 | [
"https://Stackoverflow.com/questions/36474002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2040496/"
]
| The problem is your counting after the `LEFT JOIN`. In this case, `COUNT(*)` always returns a value of at least 1, because it is counting rows. You need to count matches, so count a column in the second table:
```
SELECT likes.*, comm.comments
FROM (SELECT p.photo_id, p.photo_name,
COALESCE(SUM(l.rate = 1), 0) AS likes,
COALESCE(SUM(l.rate = 2), 0) AS dislikes
FROM pb_account_photos p LEFT JOIN
pb_account_likes l
ON l.item_id = p.photo_id
WHERE p.owner_id = 1
GROUP BY p.photo_id
) likes JOIN
(SELECT COUNT(C.item_id) AS comments, p.photo_id
FROM pb_account_photos p LEFT JOIN
pb_account_comments c
ON c.item_id = p.photo_id
WHERE p.owner_id = 1
GROUP BY p.photo_id
) comm
ON comm.photo_id = likes.photo_id;
``` | ```
SELECT p.*,
SUM(l.rate = 1) AS likes
SUM(l.rate = 2) AS dislikes
SUM(IF(ISNULL(c.item_id), 0, 1)) AS comments
FROM pb_account_photos p
LEFT JOIN pb_account_likes AS l ON l.item_id = p.photo_id
LEFT JOIN pb_account_comments AS c ON c.item_id = p.photo_id
GROUP BY p.photo_id
``` |
10,109,808 | How to register `DependencyProperty` on `Rectangle` fill, so i can change the color
dynamically?
```
<UserControl.Resources>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF48B6E4" Offset="0.013"/>
<GradientStop Color="#FF091D8D" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True"/>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<Button Style="{DynamicResource ButtonStyle1}"/>
<TextBlock
x:Name="NodeName"
x:FieldModifier="public"
Text="Property"
Margin="8"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextWrapping="Wrap"
TextAlignment="Center"
FontFamily="Segoe Print"
FontWeight="Bold"
Foreground="White"
FontSize="40"/>
</Grid>
``` | 2012/04/11 | [
"https://Stackoverflow.com/questions/10109808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1076067/"
]
| Why don't you bind `Fill` to the `Background` property of the Button:
```
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black" Fill="{TemplateBinding Background}" />
...
</Grid>
...
</ControlTemplate>
```
and then set `Background` like this:
```
<Button Style="{DynamicResource ButtonStyle1}">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF48B6E4" Offset="0.013"/>
<GradientStop Color="#FF091D8D" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
``` | If you have your own dependency property called `MyProperty` registered in your `UserControl`, you can bind it this way:
```
...
<Rectangle Stroke="Black" Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Parent.Parent.MyProperty}" />
...
```
No other changes are needed.
This binds the `Fill` property to parent of parent of the control to which the style is assigned, in your case the `UserControl` itself.
Using this method you can not only bind it to properties of a `UserControl`, but also to other controls' properties. |
10,109,808 | How to register `DependencyProperty` on `Rectangle` fill, so i can change the color
dynamically?
```
<UserControl.Resources>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF48B6E4" Offset="0.013"/>
<GradientStop Color="#FF091D8D" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True"/>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<Button Style="{DynamicResource ButtonStyle1}"/>
<TextBlock
x:Name="NodeName"
x:FieldModifier="public"
Text="Property"
Margin="8"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextWrapping="Wrap"
TextAlignment="Center"
FontFamily="Segoe Print"
FontWeight="Bold"
Foreground="White"
FontSize="40"/>
</Grid>
``` | 2012/04/11 | [
"https://Stackoverflow.com/questions/10109808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1076067/"
]
| If you have your own dependency property called `MyProperty` registered in your `UserControl`, you can bind it this way:
```
...
<Rectangle Stroke="Black" Fill="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Parent.Parent.MyProperty}" />
...
```
No other changes are needed.
This binds the `Fill` property to parent of parent of the control to which the style is assigned, in your case the `UserControl` itself.
Using this method you can not only bind it to properties of a `UserControl`, but also to other controls' properties. | I would create a dependency property on your YourUserControl view, something like this (I removed some of your markup for brevity):
```
<UserControl.Resources>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black" Fill="{TemplateBinding Background}">
</Rectangle>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
```
<Grid x:Name="LayoutRoot">
<Button Style="{DynamicResource ButtonStyle1}" Background="{Binding DynamicColor}"/>
</Grid>
```
Then in YourUserControl.xaml.cs you could create your dependency property:
```
private My_ViewModel _viewModel
{
get { return this.DataContext as My_ViewModel; }
}
public LinearGradientBrush DynamicColor
{
get { return (string)GetValue(DynamicColorProperty); }
set { SetValue(DynamicColorProperty, value); }
}
public static readonly DependencyProperty DynamicColorProperty =
DependencyProperty.Register("DynamicColor", typeof(LinearGradientBrush), typeof(YourUserControl),
new PropertyMetadata(new PropertyChangedCallback(OnDynamicColorPropertyChanged)));
private static void OnDynamicColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((YourUserControl)d).OnTrackerInstanceChanged(e);
}
protected virtual void OnDynamicColorPropertyChanged(DependencyPropertyChangedEventArgs e)
{
this._viewModel.DynamicColor = e.NewValue;
}
public class My_ViewModel : INotifyPropertyChanged
{
public LinearGradientBrush DynamicColor
{
get { return dynamicColor; }
set
{
if(dynamicColor != value)
{
dynamicColor = value;
OnPropertyChanged("DynamicColor");
}
}
}
private LinearGradientBrush dynamicColor;
}
```
This approach gives you complete control over the DynamicColor property's value as well as allows you to be able to unit test the behavior effectively. |
10,109,808 | How to register `DependencyProperty` on `Rectangle` fill, so i can change the color
dynamically?
```
<UserControl.Resources>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF48B6E4" Offset="0.013"/>
<GradientStop Color="#FF091D8D" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True"/>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<Button Style="{DynamicResource ButtonStyle1}"/>
<TextBlock
x:Name="NodeName"
x:FieldModifier="public"
Text="Property"
Margin="8"
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextWrapping="Wrap"
TextAlignment="Center"
FontFamily="Segoe Print"
FontWeight="Bold"
Foreground="White"
FontSize="40"/>
</Grid>
``` | 2012/04/11 | [
"https://Stackoverflow.com/questions/10109808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1076067/"
]
| Why don't you bind `Fill` to the `Background` property of the Button:
```
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black" Fill="{TemplateBinding Background}" />
...
</Grid>
...
</ControlTemplate>
```
and then set `Background` like this:
```
<Button Style="{DynamicResource ButtonStyle1}">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF48B6E4" Offset="0.013"/>
<GradientStop Color="#FF091D8D" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
``` | I would create a dependency property on your YourUserControl view, something like this (I removed some of your markup for brevity):
```
<UserControl.Resources>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Rectangle Stroke="Black" Fill="{TemplateBinding Background}">
</Rectangle>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
```
<Grid x:Name="LayoutRoot">
<Button Style="{DynamicResource ButtonStyle1}" Background="{Binding DynamicColor}"/>
</Grid>
```
Then in YourUserControl.xaml.cs you could create your dependency property:
```
private My_ViewModel _viewModel
{
get { return this.DataContext as My_ViewModel; }
}
public LinearGradientBrush DynamicColor
{
get { return (string)GetValue(DynamicColorProperty); }
set { SetValue(DynamicColorProperty, value); }
}
public static readonly DependencyProperty DynamicColorProperty =
DependencyProperty.Register("DynamicColor", typeof(LinearGradientBrush), typeof(YourUserControl),
new PropertyMetadata(new PropertyChangedCallback(OnDynamicColorPropertyChanged)));
private static void OnDynamicColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((YourUserControl)d).OnTrackerInstanceChanged(e);
}
protected virtual void OnDynamicColorPropertyChanged(DependencyPropertyChangedEventArgs e)
{
this._viewModel.DynamicColor = e.NewValue;
}
public class My_ViewModel : INotifyPropertyChanged
{
public LinearGradientBrush DynamicColor
{
get { return dynamicColor; }
set
{
if(dynamicColor != value)
{
dynamicColor = value;
OnPropertyChanged("DynamicColor");
}
}
}
private LinearGradientBrush dynamicColor;
}
```
This approach gives you complete control over the DynamicColor property's value as well as allows you to be able to unit test the behavior effectively. |
69,642,843 | Apologies if this has already been asked and answered but I couldn't find a satisfactory answer.
I have a list of thousands of chemical formulas that could include symbols for any element and I would like to determine the total number of atoms of any element in each formula. Examples include:
* CH3NO3
* CSe2
* C2Cl2
* C2Cl2O2
* C2Cl3F
* C2H2BrF3
* C2H2Br2
* C2H3Cl3Si
I just want the total number of atoms in a single formula, so for the first example (CH3NO3), the answer would be 8 (1 carbon + 3 hydrogens + 1 nitrogen + 3 oxygens).
I have found some useful code by PEH ([Extract numbers from chemical formula](https://stackoverflow.com/questions/46091219/extract-numbers-from-chemical-formula)) that uses regular expression to extract the number of instances of a specific element in a chemical formula, and I was wondering if this could be adapted to give the total atoms:
```
Public Function ChemRegex(ChemFormula As String, Element As String) As Long
Dim regEx As New RegExp
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
End With
'first pattern matches every element once
regEx.Pattern = "([A][cglmrstu]|[B][aehikr]?|[C][adeflmnorsu]?|[D][bsy]|[E][rsu]|[F][elmr]?|[G][ade]|[H][efgos]?|[I][nr]?|[K][r]?|[L][airuv]|[M][cdgnot]|[N][abdehiop]?|[O][gs]?|[P][abdmortu]?|[R][abefghnu]|[S][bcegimnr]?|[T][abcehilms]|[U]|[V]|[W]|[X][e]|[Y][b]?|[Z][nr])([0-9]*)"
Dim Matches As MatchCollection
Set Matches = regEx.Execute(ChemFormula)
Dim m As Match
For Each m In Matches
If m.SubMatches(0) = Element Then
ChemRegex = ChemRegex + IIf(Not m.SubMatches(1) = vbNullString, m.SubMatches(1), 1)
End If
Next m
'second patternd finds parenthesis and multiplies elements within
regEx.Pattern = "(\((.+?)\)([0-9])+)+?"
Set Matches = regEx.Execute(ChemFormula)
For Each m In Matches
ChemRegex = ChemRegex + ChemRegex(m.SubMatches(1), Element) * (m.SubMatches(2) - 1) '-1 because all elements were already counted once in the first pattern
Next m
End Function
``` | 2021/10/20 | [
"https://Stackoverflow.com/questions/69642843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17194644/"
]
| You could do that by looping through all characters. Count all capital characters and add all numbers subtracted by 1. That is the total count of elements.
```
Option Explicit
Public Function ChemCountTotalElements(ByVal ChemFormula As String) As Long
Dim RetVal As Long
Dim c As Long
For c = 1 To Len(ChemFormula)
Dim Char As String
Char = Mid$(ChemFormula, c, 1)
If IsNumeric(Char) Then
RetVal = RetVal + CLng(Char) - 1
ElseIf Char = UCase(Char) Then
RetVal = RetVal + 1
End If
Next c
ChemCountTotalElements = RetVal
End Function
```
Note that this does not handle parenthesis! And it does not check if the element actually exists. So `XYZ2` will be counted as `4`.
Also this only can handle numbers below `10`. In case you have numbers with `10` and above use the RegEx solution below (which can handle that).
[](https://i.stack.imgur.com/48v1k.png)
### Recognize also chemical formulas with prenthesis like Ca(OH)₂
If you need a more precise way (checking the existance of the Elements) and recognizing parenthesis you need to do it with RegEx again.
Because VBA doesn't support regular expressions out of the box we need to reference a Windows library first.
1. Add reference to regex under *Tools* then *References*
[](https://i.stack.imgur.com/sKCdA.png)
2. and selecting *Microsoft VBScript Regular Expression 5.5*
[](https://i.stack.imgur.com/nmSgP.png)
3. Add this function to a module
```
Public Function ChemRegexCountTotalElements(ByVal ChemFormula As String) As Long
Dim RetVal As Long
Dim regEx As New RegExp
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
End With
'first pattern matches every element once
regEx.Pattern = "([A][cglmrstu]|[B][aehikr]?|[C][adeflmnorsu]?|[D][bsy]|[E][rsu]|[F][elmr]?|[G][ade]|[H][efgos]?|[I][nr]?|[K][r]?|[L][airuv]|[M][cdgnot]|[N][abdehiop]?|[O][gs]?|[P][abdmortu]?|[R][abefghnu]|[S][bcegimnr]?|[T][abcehilms]|[U]|[V]|[W]|[X][e]|[Y][b]?|[Z][nr])([0-9]*)"
Dim Matches As MatchCollection
Set Matches = regEx.Execute(ChemFormula)
Dim m As Match
For Each m In Matches
RetVal = RetVal + IIf(Not m.SubMatches(1) = vbNullString, m.SubMatches(1), 1)
Next m
'second patternd finds parenthesis and multiplies elements within
regEx.Pattern = "(\((.+?)\)([0-9]+)+)+?"
Set Matches = regEx.Execute(ChemFormula)
For Each m In Matches
RetVal = RetVal + ChemRegexCountTotalElements(m.SubMatches(1)) * (m.SubMatches(2) - 1) '-1 because all elements were already counted once in the first pattern
Next m
ChemRegexCountTotalElements = RetVal
End Function
```
While this code will also recognize parenthesis, note that it does not recognize nested parenthesis.
[](https://i.stack.imgur.com/hAgd2.png) | Here's my two cent's
[](https://i.stack.imgur.com/Ve3lX.png)
Formula in `C1`:
```
=ChemRegex(A1)
```
Where `ChemRegex()` calls:
```
Public Function ChemRegex(ChemFormula As String) As Long
With CreateObject("vbscript.regexp")
.Global = True
.Pattern = "[A-Z][a-z]*(\d*)"
If .Test(ChemFormula) Then
Set matches = .Execute(ChemFormula)
For Each Match In matches
ChemRegex = ChemRegex + IIf(Match.Submatches(0) = "", 1, Match.Submatches(0))
Next
Else
ChemRegex = 0
End If
End With
End Function
```
Or in a (shorter) 2-step regex-solution:
```
Public Function ChemRegex(ChemFormula As String) As Long
With CreateObject("vbscript.regexp")
.Global = True
.Pattern = "([A-Za-z])(?=[A-Z]|$)"
ChemFormula = .Replace(ChemFormula, "$1-1")
.Pattern = "\D+"
ChemFormula = .Replace(ChemFormula, "+")
ChemRegex = Evaluate(ChemFormula)
End With
End Function
``` |
345,036 | I want to express a situation to a friend saying the following:
>
> I have received two offers. The first one is of a good salary, but I did not
> like the city, while regarding the 2nd offer, it is of a lower salary but
> the city is awesome. I do not know whether or not I should sacrifice the
> salary for living in a nice city.
>
>
>
I would like to find an alternative word for the word "sacrifice" in the last sentence, and I do not know if my attempt is right or wrong.
My attempt to re-write the last sentence is:
>
> I do not know whether or not I should forgo the salary
> for living in a nice city.
>
>
>
Please help me to find the best alternative for the word "sacrifice" in the last sentence. | 2016/08/26 | [
"https://english.stackexchange.com/questions/345036",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/185732/"
]
| **Sacrifice** and **forgo** both seem like perfectly good choices.
**Trade-off** (or **tradeoff**) would be a good possibility, but the dictionaries I've checked define it only as a noun. See <http://www.merriam-webster.com/dictionary/trade-off>, <http://www.thefreedictionary.com/tradeoff>, <http://www.dictionary.com/browse/tradeoff?s=t>>, <http://www.oxforddictionaries.com/us/definition/american_english/trade-off?q=tradeoff>. Given that, you could use **trade off** as two separate words:
>
> I don't know if I should **trade off** the higher salary for living in
> a nicer city.
>
>
> I don't know if I should **trade off** living in a nicer city for the
> higher salary.
>
>
>
You could also use **compromise** or **exchange**:
>
> I don't know if I should **compromise** the higher salary for living
> in a nicer city.
>
>
> I don't know if I should **exchange** the higher salary for living in a nicer city.
>
>
>
Of these options, I would go with **trade off** (which is a slight twist on the suggestion of @KristinaLopez -- noun versus verb issue). | *Sacrifice* often has the connotation of giving up something you already had:
>
> **To surrender or give up (something)** for the attainment of some higher advantage or dearer object.
>
>
>
If I had a well-paying job in a crummy city, and I was offered a worse-paying job in a preferable city, I might consider sacrificing my high salary for the better living conditions.
*Forgo*, on the other hand, has the connotation of not partaking in something that you do not yet have:
>
> To abstain from, go without, deny to oneself; **to let go or pass, omit to take or use;** to give up, part with, relinquish, renounce, resign.
>
>
>
I think that "forgo" is a better choice here, since you do not yet have either job. That said, both options would be perfectly understandable.
(Both definitions are from the OED.) |
345,036 | I want to express a situation to a friend saying the following:
>
> I have received two offers. The first one is of a good salary, but I did not
> like the city, while regarding the 2nd offer, it is of a lower salary but
> the city is awesome. I do not know whether or not I should sacrifice the
> salary for living in a nice city.
>
>
>
I would like to find an alternative word for the word "sacrifice" in the last sentence, and I do not know if my attempt is right or wrong.
My attempt to re-write the last sentence is:
>
> I do not know whether or not I should forgo the salary
> for living in a nice city.
>
>
>
Please help me to find the best alternative for the word "sacrifice" in the last sentence. | 2016/08/26 | [
"https://english.stackexchange.com/questions/345036",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/185732/"
]
| *Sacrifice* often has the connotation of giving up something you already had:
>
> **To surrender or give up (something)** for the attainment of some higher advantage or dearer object.
>
>
>
If I had a well-paying job in a crummy city, and I was offered a worse-paying job in a preferable city, I might consider sacrificing my high salary for the better living conditions.
*Forgo*, on the other hand, has the connotation of not partaking in something that you do not yet have:
>
> To abstain from, go without, deny to oneself; **to let go or pass, omit to take or use;** to give up, part with, relinquish, renounce, resign.
>
>
>
I think that "forgo" is a better choice here, since you do not yet have either job. That said, both options would be perfectly understandable.
(Both definitions are from the OED.) | I agree with Michael Seifert on this one.
You are comparing the pros and cons of these two job opportunities.
And you can't really sacrifice something you don't have.
So your sentence could look something like:
"I have received two offers. The first one is of a good salary, but I did not like the city, while regarding the 2nd offer, it is of a lower salary but the city is awesome. I do not know whether or not if I should [settle for a lower salary, so I can live] in a nice city."
I say settle, because when you settle for something, you are accepting or agreeing to something that is less than satisfactory. |
345,036 | I want to express a situation to a friend saying the following:
>
> I have received two offers. The first one is of a good salary, but I did not
> like the city, while regarding the 2nd offer, it is of a lower salary but
> the city is awesome. I do not know whether or not I should sacrifice the
> salary for living in a nice city.
>
>
>
I would like to find an alternative word for the word "sacrifice" in the last sentence, and I do not know if my attempt is right or wrong.
My attempt to re-write the last sentence is:
>
> I do not know whether or not I should forgo the salary
> for living in a nice city.
>
>
>
Please help me to find the best alternative for the word "sacrifice" in the last sentence. | 2016/08/26 | [
"https://english.stackexchange.com/questions/345036",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/185732/"
]
| **Sacrifice** and **forgo** both seem like perfectly good choices.
**Trade-off** (or **tradeoff**) would be a good possibility, but the dictionaries I've checked define it only as a noun. See <http://www.merriam-webster.com/dictionary/trade-off>, <http://www.thefreedictionary.com/tradeoff>, <http://www.dictionary.com/browse/tradeoff?s=t>>, <http://www.oxforddictionaries.com/us/definition/american_english/trade-off?q=tradeoff>. Given that, you could use **trade off** as two separate words:
>
> I don't know if I should **trade off** the higher salary for living in
> a nicer city.
>
>
> I don't know if I should **trade off** living in a nicer city for the
> higher salary.
>
>
>
You could also use **compromise** or **exchange**:
>
> I don't know if I should **compromise** the higher salary for living
> in a nicer city.
>
>
> I don't know if I should **exchange** the higher salary for living in a nicer city.
>
>
>
Of these options, I would go with **trade off** (which is a slight twist on the suggestion of @KristinaLopez -- noun versus verb issue). | I agree with Michael Seifert on this one.
You are comparing the pros and cons of these two job opportunities.
And you can't really sacrifice something you don't have.
So your sentence could look something like:
"I have received two offers. The first one is of a good salary, but I did not like the city, while regarding the 2nd offer, it is of a lower salary but the city is awesome. I do not know whether or not if I should [settle for a lower salary, so I can live] in a nice city."
I say settle, because when you settle for something, you are accepting or agreeing to something that is less than satisfactory. |
43,100,285 | I have temp table that I've populated with a running total. I used SQL Server windowing functions. The data in my temp table is in the following format:
```
|Day | Sku Nbr | CMQTY |
| 1 | f45 | 0 |
| 2 | f45 | 2 |
| 3 | f45 | 0 |
| 4 | f45 | 7 |
| 5 | f45 | 0 |
| 6 | f45 | 0 |
| 7 | f45 | 0 |
| 8 | f45 | 13 |
| 9 | f45 | 15 |
| 10 | f45 | 21 |
```
I would like to manipulate the data so that it displays like this:
```
|Day| Sku Nbr | CMQTY |
| 1 | f45 | 0 |
| 2 | f45 | 2 |
| 3 | f45 | 2 |
| 4 | f45 | 7 |
| 5 | f45 | 7 |
| 6 | f45 | 7 |
| 7 | f45 | 7 |
| 8 | f45 | 13 |
| 9 | f45 | 15 |
| 10 | f45 | 21 |
```
I've tried using a lag function but there are issues when I have multiple days, in a row, with a 0 CMQTY. I've also tried using CASE WHEN logic but am failing. | 2017/03/29 | [
"https://Stackoverflow.com/questions/43100285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6780741/"
]
| You can use row\_number as below
```
;with cte as (
select *, sm = sum(case when cmqty>0 then 1 else 0 end) over (order by [day]) from #yoursum
)
select *, sum(cmqty) over(partition by sm order by [day]) from cte
```
Your table structure
```
create table #yoursum ([day] int, sku_nbr varchar(10), CMQTY int)
insert into #yoursum
([Day] , Sku_Nbr , CMQTY ) values
( 1 ,'f45', 0 )
,( 2 ,'f45', 2 )
,( 3 ,'f45', 0 )
,( 4 ,'f45', 7 )
,( 5 ,'f45', 0 )
,( 6 ,'f45', 0 )
,( 7 ,'f45', 0 )
,( 8 ,'f45', 13 )
,( 9 ,'f45', 15 )
,( 10 ,'f45', 21 )
``` | For fun, another approach. First for some sample data:
```
IF OBJECT_ID('tempdb..#t1') IS NOT NULL DROP TABLE #t1;
CREATE TABLE #t1
(
[day] int NOT NULL,
[Sku Nbr] varchar(5) NOT NULL,
CMQTY int NOT NULL,
CONSTRAINT pk_t1 PRIMARY KEY CLUSTERED([day] ASC)
);
INSERT #t1 VALUES
(1 , 'f45', 0),
(2 , 'f45', 2),
(3 , 'f45', 0),
(4 , 'f45', 7),
(5 , 'f45', 0),
(6 , 'f45', 0),
(7 , 'f45', 0),
(8 , 'f45', 13),
(9 , 'f45', 15),
(10, 'f45', 21);
```
And the solution:
```
DECLARE @RunningTotal int = 0;
UPDATE #t1
SET @RunningTotal = CMQTY = IIF(CMQTY = 0, @RunningTotal, CMQTY)
FROM #t1 WITH (TABLOCKX)
OPTION (MAXDOP 1);
```
Results:
```
day Sku Nbr CMQTY
---- ------- ------
1 f45 0
2 f45 2
3 f45 2
4 f45 7
5 f45 7
6 f45 7
7 f45 7
8 f45 13
9 f45 15
10 f45 21
```
This approach is referred to the local updateable variable or Quirky Update. You can read more about it here: <http://www.sqlservercentral.com/articles/T-SQL/68467/> |
43,196,588 | Hi I have the JSON like this:
```
[
"supplier" : "Apple",
"features" : {
"0": [
{
"feature_id": "58d1b42ec2ef165bbfca0873",
"symbol": "tick"
},
{
"feature_id": "58d4b843bd966f52093ce32f",
"symbol": "cross"
}
],
"1":[
{
"feature_id": "58d1b42ec2ef165bb33422087",
"symbol": "tick"
},
{
"feature_id": "58d4b843bd91ads2jfloice32",
"symbol": "cross"
}
]
},
"supplier" : "Orange",
"features" : {
"0": [
{
"feature_id": "58d1b42ec2ef165bbfca0873",
"symbol": "tick"
},
{
"feature_id": "58d4b843bd966f52093ce32f",
"symbol": "cross"
}
],
"1":[
{
"feature_id": "58d1b42ec2ef165bb33422087",
"symbol": "tick"
},
{
"feature_id": "58d4b843bd91ads2jfloice32",
"symbol": "cross"
}
]
}
]
```
How can I use jQuery/javascript to move the features object key '0' to the end after the key '0'? I have tried to use the array.push(array.shift()); but it throws error saying "array.shift()" is not a function. I guess the .features is not array, so how can I move the object to the end? | 2017/04/04 | [
"https://Stackoverflow.com/questions/43196588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5222129/"
]
| Ideally, this, for example:
```
<input type="date" lang="en-AU" />
```
will configure the input to show dates in the way it is acceptable in Australia. Which is different from, say, Canada that also uses English.
And that's the answer. | W3C spec on language and locale identifiers: <https://www.w3.org/TR/ltli/>
IETF spec on the make up of the attribute: <http://www.ietf.org/rfc/rfc3066.txt>
It's system / platform / OS / user specific and based on what technology / language you're using, there are ways to determine it and it's usage.
For e.g.
apple / iOS: <https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPInternational/InternationalizingLocaleData/InternationalizingLocaleData.html>
Oracle:
<https://docs.oracle.com/cd/E23824_01/html/E26033/glmbx.html> |
3,959,996 | My question is closely related to this [question](https://stackoverflow.com/questions/3933407/error-page-in-iis7-has-text-added-to-it).
Here is a quick synopsis: My app is running in Classic Mode.
I have the following code in Global.asax
```
protected void Application_Error(Object sender, EventArgs e)
{
// ... boring stuff...
HttpContext.Current.Server.Transfer("~/MyErrorPage.aspx", true);
}
```
Everything works OK (i.e. I see MyErrorPage.aspx) when an error occurs if
```
<httpErrors errorMode="Detailed" />
```
but when `errorMode="Custom"` (or `errorMode="DetailedLocalOnly"` and the request is from a remote machine), I see the IIS custom error page followed by my error page (MyErrorPage.aspx).
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- The contents of the default 500 page as configured in IIS
Which for me is the default %SystemDrive%\inetpub\custerr\<LANGUAGE-TAG>\500.htm
-->
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<!-- The contents of MyErrorPage.aspx -->
</html>
```
If I remove the default 500 error page from the IIS error pages section then I get the following output (note that I get "The page cannot be displayed..." instead of the custom 500 page)
```
The page cannot be displayed because an internal server error has occurred.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<!-- The contents of MyErrorPage.aspx -->
</html>
```
If I step through the code using the debugger, then I see that the IIS 500 page gets flushed to the client when I step over the `Server.Transfer` statement.
My error page then gets sent to the browser after the normal page lifecycle of the MyErrorPage.aspx (as you would expect).
I have tried (in desperation) clearing the content of the response (`HttpContext.Current.Response.Clear()`) prior to the Server.Transfer but that has no effect.
I have also tried calling `Server.ClearError()` prior to the transfer but that has no effect either.
Now as per the linked question, the "fix" is to set `errormode="Detailed"` but I do not want to see the detailed error pages for errors that are not handled in ASP.Net - for example I would prefer to see the IIS custom 404 page instead of the detailed page if I enter the url `myApp/DoesNotExist.html`. [Some of our customers absolutely insist that users never see the detailed error page because it is deemed a potential security weakness.]
Another "fix" is to redirect instead doing a server transfer but I would prefer to do a transfer if possible: doing a transfer means that the browser's URL is unchanged, meaning that, for example, if the error occurred because the app.was just starting up, they can hit F5 to retry the request. Redirecting obviously changes the browser's address to the error page.
Does anyone have an explaination as to why I am seeing this behaviour? Does anyone have a solution?
Thanks in advance.
**Edit**
I have knocked together a little app that demonstrates the behaviour :
<http://rapidshare.com/files/427244682/Err.zip>
[Make sure that the app is running in Classic mode.]
If you click on a link that has both transfer and setstatus args set then you see the problem.
[BANG](http://img836.imageshack.us/img836/93/2errors.png) | 2010/10/18 | [
"https://Stackoverflow.com/questions/3959996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132648/"
]
| You can use a [UILongPressGestureRecognizer](https://developer.apple.com/documentation/uikit/uilongpressgesturerecognizer) for this. Wherever you create or initialize the mapview, first attach the recognizer to it:
```
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //user needs to press for 2 seconds
[self.mapView addGestureRecognizer:lpgr];
[lpgr release];
```
Then in the gesture handler:
```
- (void)handleLongPress:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
return;
CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
CLLocationCoordinate2D touchMapCoordinate =
[self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
YourMKAnnotationClass *annot = [[YourMKAnnotationClass alloc] init];
annot.coordinate = touchMapCoordinate;
[self.mapView addAnnotation:annot];
[annot release];
}
```
YourMKAnnotationClass is a class you define that conforms to the [MKAnnotation](https://developer.apple.com/documentation/mapkit/mkannotation) protocol. If your app will only be running on iOS 4.0 or later, you can use the pre-defined [MKPointAnnotation](https://developer.apple.com/documentation/mapkit/mkpointannotation) class instead.
For examples on creating your own MKAnnotation class, see the sample app [MapCallouts](https://developer.apple.com/documentation/mapkit/mapkit_annotations/annotating_a_map_with_custom_data). | Thanks to Anna for providing such a great answer! Here is a Swift version if anybody is interested (the answer has been updated to Swift 4.1 syntax).
Creating UILongPressGestureRecognizer:
```
let longPressRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(MapViewController.handleLongPress(_:)))
longPressRecogniser.minimumPressDuration = 1.0
mapView.addGestureRecognizer(longPressRecogniser)
```
Handling the gesture:
```
@objc func handleLongPress(_ gestureRecognizer : UIGestureRecognizer){
if gestureRecognizer.state != .began { return }
let touchPoint = gestureRecognizer.location(in: mapView)
let touchMapCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
let album = Album(coordinate: touchMapCoordinate, context: sharedContext)
mapView.addAnnotation(album)
}
``` |
7,789,359 | I have a question regarding the local variables for my jQuery plugin. I am pretty sure if I declare them outside the main jQuery function register, then every time the plugin is called it will redefine the variables.
Example:
```
(function($){
jQuery.fn.test = function(options){
if ( options ) {
$.extend( settings, options );
}
this.each(function(i,item){
// do whatever i am going to do
});
};
var settings = {
value1: "hello",
value2: "word"
};
})(jQuery);
```
Say that `$(object).test({value1:'newterm'});` is called multiple times.. Am I correct in thinking that every time that method is called, that it will override the settings with the most recently declared settings?
If i want multiple instances of my plugin, do I need to declare everything within the scope of the main `jQuery.fn.test = function(){//here}` method? | 2011/10/17 | [
"https://Stackoverflow.com/questions/7789359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557836/"
]
| Yes, that is correct, because `$.extend` will modify `settings` which is in the closure scope exposed when the jQuery initialization function sets up `.test` on the global object jQuery. That closure scope is the same everytime you execute `.test`; therefore, all objects will retain changes. | It depends on the order you pass objects to $.extend. The first (target) object passed will be modified, in your case the settings object. If you want to keep the defaults:
```
$.extend(options, settings);
```
Or to get a brand new object:
```
var newoptions = $.extend({}, options, settings);
``` |
47,783,406 | I'm using Atom to write LaTeX and C++. When I use for example a snippet:
Prefix 'fr' expands to '\frac{$1}{$2} $3' meaning that typing 'f r TAB' creates the sentence '/frac{}{}' and places the cursor at position '$1', pressing TAB again moves the cursor to '$2', TAB again moves the cursor outside of the expression in position '$3'.
However, support that I have a snippet 'sq' which expands to '\sqrt($1)'. This means that typing 's q TAB' creates the text '\sqrt()' and places the cursor in position '$1'.
Now suppose I want to combine both snippets.
'f r TAB' expands to '\frac{$1}{$2}', I then type '2' to insert the number '2' in the position of '$1', I press TAB to jump to position '$2' and now I want to insert 'sqrt(2)'. Then I type 's q TAB' and it expands to the following total expression:
'\frac{2}{sqrt($1)}'
The cursor is in '$1' I then type '2' and the expression now is:
'\frac{2}{sqrt(2)}'
Now if I press TAB again it will indent right after 2, like this:
'\frac{2}{sqrt(2...........)}'
What I would like it to do is go to the next position of '\frac{$1}{$2} $3', that is, position '$3' outside of the frac expression so I can continue typing without having to press right arrow, right arrow, etc.
Is there any text editor that can do this, even if it uses plugins to achieve it? It would be great for me. | 2017/12/12 | [
"https://Stackoverflow.com/questions/47783406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6157300/"
]
| `in` checks membership: `a in b` is true if and only if `a` is a member *contained by* `b`.
Since `availableNums` is a tuple of ints, `selectedNumbers`, which is a list, isn't a member. You seem to be wanting to check whether `selectedNumbers` is a *subset* of `availableNums`.
You can either check each item in a loop:
```
for s in selectedNumbers:
if s not in availableNums
....
```
Or you can convert them to sets, if you're okay with checking all at once and failing completely if *any* of the selected numbers are invalid:
```
if not set(selectedNumbers) < set(availableNums):
....
```
Note that `<` here, applied to sets, is the subset operator.
---
Also, as noted in a comment, `raw_input` returns a string, but you're attempting to treat it as an integer. You can use `int()` to parse the input string. | `selectedNumbers` is a list. You are checking if the whole list is in `availableNums`, not if each number in `selectedNumbers` is in `availableNums`.
It sounds like you want something like:
```
for selectedNumber in selectedNumbers:
if selectedNumber not in availableNums:
# selectedNumber from selectedNumbers is not in availableNums
```
Edit: As [hatshepsut](https://stackoverflow.com/users/3346095/hatshepsut) pointed out, your code places strings in `selectedNumbers`, not integers. Use [`input`](https://docs.python.org/2/library/functions.html#input) instead of `raw_input`1 or convert to [`int`](https://docs.python.org/3/library/functions.html#int).
1 For Python 2. For Python 3, see [What's the difference between raw\_input() and input() in python3.x?](https://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python3-x) |
13,714,966 | I'm trying to create a different `actionPerformed` when `Shift` is held down while pressing a JButton, but when I use:
`event.isShiftDown;`
my program does not compile because it does't recognise it. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13714966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1877561/"
]
| Basically you need to bitwise-and the `ActionEvent#getModifiers` result
```
if ((e.getModifiers() & InputEvent.SHIFT_MASK) != 0) {
// Shift is down...
}
``` | As an alternative to checking the event modifiers directly, consider using a different [`Action`](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) for each state of the shift key. You can supply the desired mask to the `KeyStroke` used in your [*key binding*](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html), as outlined [here](https://stackoverflow.com/a/12521353/230513). A related example using `getMenuShortcutKeyMask()` is shown [here](https://stackoverflow.com/a/5129757/230513). |
1,581,832 | Let $$v\_i=(v\_{i1},v\_{i2},v\_{i3},v\_{i4}),\ \ for\ \ i=1,2,3,4$$ be four vectors in$\mathbb R^4$ such that $$\sum\_{i=1}^4v\_{ij}=0\ \ for\ \ each\ \ j=1,2,3,4.$$ $W$ be the subspace generated by $\{v\_1,v\_2,v\_3,v\_4\}.$ Then the dimension $d$ of $W$ over $\mathbb R$ is
$A.\ d=1\ \ or\ \ d=4$
$B.\ d\le 3$
$C.\ d\ge 2$
$D.\ d=0\ \ or\ \ d=4$
Now writing them vectors as follows **:**
$$v\_1=\ \ v\_{11}\ \ \ v\_{12}\ \ \ v\_{13}\ \ \ v\_{14}\\v\_2=\ \ v\_{21}\ \ \ v\_{22}\ \ \ v\_{23}\ \ \ v\_{24}\\v\_3=\ \ v\_{31}\ \ \ v\_{32}\ \ \ v\_{33}\ \ \ v\_{34}\\v\_4=\ \ v\_{41}\ \ \ v\_{42}\ \ \ v\_{43}\ \ \ v\_{44}$$
$\sum\_{i=1}^4 v\_{ij}=0$ gives $$v\_{i1}+v\_{i2}+v\_{i3}+v\_{i4}=0\ \ for\ \ i=1,2,3,4.$$ i.e. \*sum of $i$-th co-ordinate of all the $4$ vectors is $0$. So,if we know any $3$ of them then the co-ordinates of the $4$-th can be found and so dimension can never be $4.$ So , strike off options $A$ and $D.$
Now , we are left with the options $B$ and $C.$ Now , my question is how do I know if the dimension can be reduced to $2$ or not i.e. whether $B$ or $C$ is correct $?$
Thanks. | 2015/12/19 | [
"https://math.stackexchange.com/questions/1581832",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/118494/"
]
| Note that very little has been said about the vectors $v\_1,v\_2,v\_3,v\_4$. In particular they could all be the zero vector. This rules out Option C. You have done the rest.
Even if we interpret the wording to mean that the $v\_i$ are different, the following four vectors rule out Option C: $(1,0,0,0)$, $(-1,0,0,0)$, $(2,0,0,0)$, $(-2,0,0,0)$. | Take the four vectors $(1,0,0,0), (0,1,0,0), (0,0,1,0)$ and $(-1,-1,-1,0) .$ These four satisfy the given conditions and the first three are linearly independent . Hence the answer will be $B.$ |
1,581,832 | Let $$v\_i=(v\_{i1},v\_{i2},v\_{i3},v\_{i4}),\ \ for\ \ i=1,2,3,4$$ be four vectors in$\mathbb R^4$ such that $$\sum\_{i=1}^4v\_{ij}=0\ \ for\ \ each\ \ j=1,2,3,4.$$ $W$ be the subspace generated by $\{v\_1,v\_2,v\_3,v\_4\}.$ Then the dimension $d$ of $W$ over $\mathbb R$ is
$A.\ d=1\ \ or\ \ d=4$
$B.\ d\le 3$
$C.\ d\ge 2$
$D.\ d=0\ \ or\ \ d=4$
Now writing them vectors as follows **:**
$$v\_1=\ \ v\_{11}\ \ \ v\_{12}\ \ \ v\_{13}\ \ \ v\_{14}\\v\_2=\ \ v\_{21}\ \ \ v\_{22}\ \ \ v\_{23}\ \ \ v\_{24}\\v\_3=\ \ v\_{31}\ \ \ v\_{32}\ \ \ v\_{33}\ \ \ v\_{34}\\v\_4=\ \ v\_{41}\ \ \ v\_{42}\ \ \ v\_{43}\ \ \ v\_{44}$$
$\sum\_{i=1}^4 v\_{ij}=0$ gives $$v\_{i1}+v\_{i2}+v\_{i3}+v\_{i4}=0\ \ for\ \ i=1,2,3,4.$$ i.e. \*sum of $i$-th co-ordinate of all the $4$ vectors is $0$. So,if we know any $3$ of them then the co-ordinates of the $4$-th can be found and so dimension can never be $4.$ So , strike off options $A$ and $D.$
Now , we are left with the options $B$ and $C.$ Now , my question is how do I know if the dimension can be reduced to $2$ or not i.e. whether $B$ or $C$ is correct $?$
Thanks. | 2015/12/19 | [
"https://math.stackexchange.com/questions/1581832",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/118494/"
]
| Note that very little has been said about the vectors $v\_1,v\_2,v\_3,v\_4$. In particular they could all be the zero vector. This rules out Option C. You have done the rest.
Even if we interpret the wording to mean that the $v\_i$ are different, the following four vectors rule out Option C: $(1,0,0,0)$, $(-1,0,0,0)$, $(2,0,0,0)$, $(-2,0,0,0)$. | You have only concluded that dimension of W can,t be 4, from this information you can't strike off option A and D because dimension can be 0 or 1, but then you will realize that option B is most appropriate answer as it covers all the options, that's why answer will be B. |
1,581,832 | Let $$v\_i=(v\_{i1},v\_{i2},v\_{i3},v\_{i4}),\ \ for\ \ i=1,2,3,4$$ be four vectors in$\mathbb R^4$ such that $$\sum\_{i=1}^4v\_{ij}=0\ \ for\ \ each\ \ j=1,2,3,4.$$ $W$ be the subspace generated by $\{v\_1,v\_2,v\_3,v\_4\}.$ Then the dimension $d$ of $W$ over $\mathbb R$ is
$A.\ d=1\ \ or\ \ d=4$
$B.\ d\le 3$
$C.\ d\ge 2$
$D.\ d=0\ \ or\ \ d=4$
Now writing them vectors as follows **:**
$$v\_1=\ \ v\_{11}\ \ \ v\_{12}\ \ \ v\_{13}\ \ \ v\_{14}\\v\_2=\ \ v\_{21}\ \ \ v\_{22}\ \ \ v\_{23}\ \ \ v\_{24}\\v\_3=\ \ v\_{31}\ \ \ v\_{32}\ \ \ v\_{33}\ \ \ v\_{34}\\v\_4=\ \ v\_{41}\ \ \ v\_{42}\ \ \ v\_{43}\ \ \ v\_{44}$$
$\sum\_{i=1}^4 v\_{ij}=0$ gives $$v\_{i1}+v\_{i2}+v\_{i3}+v\_{i4}=0\ \ for\ \ i=1,2,3,4.$$ i.e. \*sum of $i$-th co-ordinate of all the $4$ vectors is $0$. So,if we know any $3$ of them then the co-ordinates of the $4$-th can be found and so dimension can never be $4.$ So , strike off options $A$ and $D.$
Now , we are left with the options $B$ and $C.$ Now , my question is how do I know if the dimension can be reduced to $2$ or not i.e. whether $B$ or $C$ is correct $?$
Thanks. | 2015/12/19 | [
"https://math.stackexchange.com/questions/1581832",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/118494/"
]
| Take the four vectors $(1,0,0,0), (0,1,0,0), (0,0,1,0)$ and $(-1,-1,-1,0) .$ These four satisfy the given conditions and the first three are linearly independent . Hence the answer will be $B.$ | You have only concluded that dimension of W can,t be 4, from this information you can't strike off option A and D because dimension can be 0 or 1, but then you will realize that option B is most appropriate answer as it covers all the options, that's why answer will be B. |
109,013 | [](https://i.stack.imgur.com/HNN7W.jpg)
The photographer said it was done by using the built in flash, that's it and he never explained the process. Does anyone know how it was done?
<https://imgur.com/a/Zx1Zz3z> | 2019/06/18 | [
"https://photo.stackexchange.com/questions/109013",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/83170/"
]
| The subject is in complete darkness, so a long exposure (1 or 2 seconds) combined with a bit of camera wobble makes the lights in the picture leave trails like that but you don't get a blurry subject.
Combine that with a camera flash (1/1000s maybe?) which illuminates the subject and there you have it. (the flash also dimly illuminates the objects in the bottom-right of the picture).
Edit - the flash will either fire at the start or at the end of the exposure, controlled by the first/second curtain sync setting. I don't think it would matter too much for this exposure, but for an effect like car light trails appearing to streak away BEHIND the car ([Car light trails, Google images](https://www.google.com/search?q=car%20light%20trail%20rear-curtain&rlz=1C1GCEA_enGB807GB808&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiViM-8jfPiAhXCsKQKHaqpCzwQ_AUIECgB&biw=1619&bih=897)), you'd use second curtain. so with the shutter open for a second or two you capture the light trails, and then the flash fires as the shutter close (2nd curtain) to illuminate the car, frozen in the frame with the light trails behind it.
Default for curtain sync is usually first, which would illuminate the car as the shutter opens and THEN capture the light trails, which would then appear to streak AHEAD of the car. | Since all the "jiggles" have the same shape, I'd say that it was done with a double exposure.
One with a flash to (slightly under) expose the subject.
Another exposure was made on some lights with an extended exposure time while the camera was moved.
The two can be made in any order.
Some people do this on purpose with some effort and planning to position the image elements for effect.
It used to be done in error by older roll film cameras that did not require the shutter to be cocked before firing; and, the film was not manually turned to the next unexposed position on a roll of film automatically. |
143,651 | I am a junior at a large state university. Lately, as you all have probably heard, the coronavirus is spreading like a wildfire and we all should be scared.
My instructor is from China, and my school is also filled with Asian students. How do I ask for excused absences so that I can stay at home for the lectures so that I won't get the virus from my instructor or my Asian classmates? Do I contact the chair of the department that's offering the course or the dean of the school? Would it be better if I ask to switch to an online class instead (it's already after the add/drop period)
Some suggestion would be helpful. | 2020/01/31 | [
"https://academia.stackexchange.com/questions/143651",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/118937/"
]
| You should do none of these things and we should not all be scared. This would be panic reaction.
You have not said in which country you are studying, but the Health authorities of most governments have issued official advice to their citizens which you should follow. Most institutions, such as universities, will also have issued official advice which you should also read and follow.
If you are in the UK the Department of Health has provided advice to UK universities.
If you wanted personal action, using hand cleansing gel dispensers provided by the university will reduce incidents of cross contamination and ensure regular hand-washing is your best defence. | "We should all be scared" [citation needed]
However, some concern is reasonable. For this reason it is likely that your university has developed policies around this topic. Ask your contact point at the university (e.g. a student service centre or similar). Please be careful to avoid racism against people who look Asian. |
143,651 | I am a junior at a large state university. Lately, as you all have probably heard, the coronavirus is spreading like a wildfire and we all should be scared.
My instructor is from China, and my school is also filled with Asian students. How do I ask for excused absences so that I can stay at home for the lectures so that I won't get the virus from my instructor or my Asian classmates? Do I contact the chair of the department that's offering the course or the dean of the school? Would it be better if I ask to switch to an online class instead (it's already after the add/drop period)
Some suggestion would be helpful. | 2020/01/31 | [
"https://academia.stackexchange.com/questions/143651",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/118937/"
]
| You should do none of these things and we should not all be scared. This would be panic reaction.
You have not said in which country you are studying, but the Health authorities of most governments have issued official advice to their citizens which you should follow. Most institutions, such as universities, will also have issued official advice which you should also read and follow.
If you are in the UK the Department of Health has provided advice to UK universities.
If you wanted personal action, using hand cleansing gel dispensers provided by the university will reduce incidents of cross contamination and ensure regular hand-washing is your best defence. | If you have a special need, such as an immune deficiency, and must avoid all potential sources of infection, then your university will probably have some procedures to accommodate you. If you have deep psychological fears of disease then your university may have a counseling office to help you deal with your fears.
Otherwise, the other answers here, counseling you to relax should be considered as good advice.
Note, of course, that authorities are dealing with the problems of international travel by isolating travelers who might have become infected so that the problem is contained. It isn't Asians you need to be concerned with in any case. It is those frequent international travelers who don't comply with quarantine guidelines. |
143,651 | I am a junior at a large state university. Lately, as you all have probably heard, the coronavirus is spreading like a wildfire and we all should be scared.
My instructor is from China, and my school is also filled with Asian students. How do I ask for excused absences so that I can stay at home for the lectures so that I won't get the virus from my instructor or my Asian classmates? Do I contact the chair of the department that's offering the course or the dean of the school? Would it be better if I ask to switch to an online class instead (it's already after the add/drop period)
Some suggestion would be helpful. | 2020/01/31 | [
"https://academia.stackexchange.com/questions/143651",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/118937/"
]
| If you have a special need, such as an immune deficiency, and must avoid all potential sources of infection, then your university will probably have some procedures to accommodate you. If you have deep psychological fears of disease then your university may have a counseling office to help you deal with your fears.
Otherwise, the other answers here, counseling you to relax should be considered as good advice.
Note, of course, that authorities are dealing with the problems of international travel by isolating travelers who might have become infected so that the problem is contained. It isn't Asians you need to be concerned with in any case. It is those frequent international travelers who don't comply with quarantine guidelines. | "We should all be scared" [citation needed]
However, some concern is reasonable. For this reason it is likely that your university has developed policies around this topic. Ask your contact point at the university (e.g. a student service centre or similar). Please be careful to avoid racism against people who look Asian. |
50,066,340 | I have the following problem when inserting the info in the databases
```
public void Insertar()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=BD-DLLO-SP2016;Initial Catalog=GobernacionCesar;Integrated Security=True";
con.Open();
string query = "INSERT INTO Liquidacion (IdLiquidacion, IdPeriodo, FechaGeneracion, Usuario) VALUES(@IdLiquidacion, @IdPeriodo, @FechaGeneracion, @Usuario)";
SqlCommand com1 = new SqlCommand(query, con);
foreach (GridViewRow gridRow in GridView4.Rows)
{
Iniciar();
com1.Parameters.AddWithValue("@IdLiquidacion", A);
com1.Parameters.AddWithValue("@IdPeriodo", cell);
com1.Parameters.AddWithValue("@FechaGeneracion", DateTime.Now.ToString());
com1.Parameters.AddWithValue("@Usuario", gridRow.Cells[0].Text);
com1.ExecuteNonQuery();
}
con.Close();
return;
}
``` | 2018/04/27 | [
"https://Stackoverflow.com/questions/50066340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9206372/"
]
| Move the command
```
SqlCommand com1 = new SqlCommand(query, con);
```
to the beginning of the loop:
```
foreach (GridViewRow gridRow in GridView4.Rows)
{
SqlCommand com1 = new SqlCommand(query, con);
....
}
``` | You're adding the parameters in the loop. If you clear them before adding, this should work. |
50,066,340 | I have the following problem when inserting the info in the databases
```
public void Insertar()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=BD-DLLO-SP2016;Initial Catalog=GobernacionCesar;Integrated Security=True";
con.Open();
string query = "INSERT INTO Liquidacion (IdLiquidacion, IdPeriodo, FechaGeneracion, Usuario) VALUES(@IdLiquidacion, @IdPeriodo, @FechaGeneracion, @Usuario)";
SqlCommand com1 = new SqlCommand(query, con);
foreach (GridViewRow gridRow in GridView4.Rows)
{
Iniciar();
com1.Parameters.AddWithValue("@IdLiquidacion", A);
com1.Parameters.AddWithValue("@IdPeriodo", cell);
com1.Parameters.AddWithValue("@FechaGeneracion", DateTime.Now.ToString());
com1.Parameters.AddWithValue("@Usuario", gridRow.Cells[0].Text);
com1.ExecuteNonQuery();
}
con.Close();
return;
}
``` | 2018/04/27 | [
"https://Stackoverflow.com/questions/50066340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9206372/"
]
| You should
* **define** the parameters **outside** of the loop
* only **set** the values for the parameters inside the loop
Like this:
```
SqlCommand com1 = new SqlCommand(query, con);
// define parameters - you need to adapt the datatypes - I was only guessing
com1.Parameters.Add("@IdLiquidacion", SqlDbType.Int);
com1.Parameters.Add("@IdPeriodo", SqlDbType.VarChar, 50);
com1.Parameters.Add("@FechaGeneracion", SqlDbType.DateTime);
com1.Parameters.Add("@Usuario", SqlDbType.VarChar, 100);
foreach (GridViewRow gridRow in GridView4.Rows)
{
Iniciar();
// inside the loop, only SET the values
com1.Parameters["@IdLiquidacion"].Value = A;
com1.Parameters["@IdPeriodo"].Value = cell;
com1.Parameters["@FechaGeneracion"].Value = DateTime.Now;
com1.Parameters["@Usuario"].Value = gridRow.Cells[0].Text;
com1.ExecuteNonQuery();
}
``` | You're adding the parameters in the loop. If you clear them before adding, this should work. |
95,741 | I have an application with a SQL Server-hosted database. I do not have access to the application code, but I do have full access to the database. I have added my own custom auditing to a table to assist in debugging.
I'm using `after` triggers. Below are simplified versions of my triggers.
**Question**: I am seeing `update` audit records that precede the corresponding `insert` audit records. How is this possible? The difference is only a few miliseconds and doesn't matter for my current purposes, but I can imagine much worse scenarios where program logic depends on the correct chronology.
I know about the ways to control trigger execution order among triggers of the same kind (all `insert` or all `update`). What assumptions can I make about heterogeneous trigger execution order?
```
create trigger dbo.MyTrigger_i on dbo.theTable
after insert
as
begin
set nocount on
declare @Date datetime, @User sysname
set @Date = GETDATE()
set @User = SUSER_SNAME()
insert into MyAudit (RowID, [Date], UserName, Comment)
select i.ID, @Date, @User, 'Insert'
from
inserted as i
end
go
create trigger dbo.MyTrigger_u on dbo.theTable
after update
as
begin
set nocount on
declare @Date datetime, @User sysname
set @Date = GETDATE()
set @User = SUSER_SNAME()
insert into MyAudit (RowID, [Date], UserName, Comment)
select
i.ID, @Date, @User, 'Update'
from
inserted as i
inner join deleted as d
on i.ID = d.ID
end
go
``` | 2015/03/19 | [
"https://dba.stackexchange.com/questions/95741",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/11511/"
]
| Considering that a) Triggers are naturally part of the Transaction that is the DML statement that fired the Trigger, and b) an UPDATE cannot happen on a row until the row exists, it is impossible for the actual UPDATE to show up before the actual INSERT. Hence, something else is going on.
Things to consider:
1. Are the Trigger definitions shown in the question the *actual* and *current* definitions? Is it possible that the `Comment` values of "Insert" and "Update" are switched in the Triggers such that the INSERT Trigger has the comment of "Update" and vice-versa?
2. Is it possible that the `UPDATE` Trigger is somehow defined as being `AFTER INSERT, UPDATE` ? If so, an `INSERT` operation would fire both triggers making it look like both an `INSERT` and an `UPDATE` happened when in fact there was no `UPDATE` operation (which might also explain why the times are only a few milliseconds apart for the audit entries).
3. Is it possible that your query to determine "corresponding" records is flawed and that the results are misleading? | If I understand your issue, it's that the 'after trigger' in SQL Server will pass the immediate current datetime which is a few ms after the actual event took place. How do you make the them match.
You could try getting the datetime as a variable in the beginning of 1 transaction and passing that value to the auditing table. Would that work for you? That way it's what it was when the transaction started.
You could have a last updated column enforced with a trigger any the applicable columns on the row. Then you get the 'last updated' value and finally, your 2nd trigger would copy both values to the auditing table. This would require [nested triggers](https://msdn.microsoft.com/en-us/library/ms178101.aspx) however which is often a no no. I personally would go with getting the datetime as a variable and passing that along using transactions where needed. |
95,741 | I have an application with a SQL Server-hosted database. I do not have access to the application code, but I do have full access to the database. I have added my own custom auditing to a table to assist in debugging.
I'm using `after` triggers. Below are simplified versions of my triggers.
**Question**: I am seeing `update` audit records that precede the corresponding `insert` audit records. How is this possible? The difference is only a few miliseconds and doesn't matter for my current purposes, but I can imagine much worse scenarios where program logic depends on the correct chronology.
I know about the ways to control trigger execution order among triggers of the same kind (all `insert` or all `update`). What assumptions can I make about heterogeneous trigger execution order?
```
create trigger dbo.MyTrigger_i on dbo.theTable
after insert
as
begin
set nocount on
declare @Date datetime, @User sysname
set @Date = GETDATE()
set @User = SUSER_SNAME()
insert into MyAudit (RowID, [Date], UserName, Comment)
select i.ID, @Date, @User, 'Insert'
from
inserted as i
end
go
create trigger dbo.MyTrigger_u on dbo.theTable
after update
as
begin
set nocount on
declare @Date datetime, @User sysname
set @Date = GETDATE()
set @User = SUSER_SNAME()
insert into MyAudit (RowID, [Date], UserName, Comment)
select
i.ID, @Date, @User, 'Update'
from
inserted as i
inner join deleted as d
on i.ID = d.ID
end
go
``` | 2015/03/19 | [
"https://dba.stackexchange.com/questions/95741",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/11511/"
]
| I just had this exact scenario happen and figured out what was going on (at least for my situation). I had an old, third trigger on my table that was something like this:
```
CREATE TRIGGER [dbo].[MyTrigger_fi] ON [dbo].[theTable]
FOR INSERT
AS
UPDATE theTable
SET ReportingDate = ot.ReportingDate
FROM Inserted i
JOIN theTable tb ON tb.ID = i.ID
JOIN OtherTable ot on ot.ID = tb.OtherTableID
```
That FOR INSERT was happening before my AFTER INSERT, performing the update, which then fired my AFTER UPDATE trigger. The end result was an Update message being logged before my Insert message on every insert. It all went down like this:
```
Record Inserted
FOR INSERT trigger fires
Record is Updated
AFTER UPDATE trigger fires
Update Event is recorded
AFTER INSERT trigger fires
Insert Event is recorded
``` | If I understand your issue, it's that the 'after trigger' in SQL Server will pass the immediate current datetime which is a few ms after the actual event took place. How do you make the them match.
You could try getting the datetime as a variable in the beginning of 1 transaction and passing that value to the auditing table. Would that work for you? That way it's what it was when the transaction started.
You could have a last updated column enforced with a trigger any the applicable columns on the row. Then you get the 'last updated' value and finally, your 2nd trigger would copy both values to the auditing table. This would require [nested triggers](https://msdn.microsoft.com/en-us/library/ms178101.aspx) however which is often a no no. I personally would go with getting the datetime as a variable and passing that along using transactions where needed. |
62,131,704 | it possible to sort and rearrange an array that looks like this:
```
items:[{
id: '5',
name: 'wa'
},{
id: '3',
name: 'ads'
},{
id: '1',
name: 'fdf'
}]
```
to match the arrangement of this object:
```
Item_sequence: {
"5": {index: 1},
"1": { index: 0 }
}
```
Here is the output I’m looking for:
```
items:[{
id: '1',
name: 'fdf'
},{
id: '5',
name: 'wa'
},{
id: '3',
name: 'ads'
}]
``` | 2020/06/01 | [
"https://Stackoverflow.com/questions/62131704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8627536/"
]
| You could check if the index is supplied and if not take a lage value for sorting by delta of two items.
```js
var data = { items: [{ id: '5', name: 'wa' }, { id: '3', name: 'ads' }, { id: '1', name: 'fdf' }] },
sequence = { 5: { index: 1 }, 1: { index: 0 } };
data.items.sort(({ id: a }, { id: b }) =>
(a in sequence ? sequence[a].index : Number.MAX_VALUE) -
(b in sequence ? sequence[b].index : Number.MAX_VALUE)
);
console.log(data.items);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
``` | JavaScript specifically, First you have to apply loop to your array "items":
```
`
let newArr = [];
items.map(obj=>{
//obj will be the element of items array, here it is an object.
if(Item_sequence.obj[id] !== undefined) {
/*this condition will be satisfied when id from items array will be present as a
key in Item_sequence array*/
insertAt(newArr, Item_sequence.obj[id] , obj)
}
else{
newArr.push(obj);
}
})
//After checking on whole array here you assign a newArr value to items array.
items=newArr;
```
Hope that it will help you. |
8,084,793 | The jQuery UI Draggable interaction has a nice property for [setting the containment](http://jqueryui.com/demos/draggable/#option-containment) as the parent.
```
$( ".selector" ).draggable({ containment: 'parent' });
```
I wish to set the containment as the parent's parent. There is no string value to accomplish this, as string the options are
>
> 'parent', 'document', 'window', [x1, y1, x2, y2]
>
>
>
I could calculate x1,y1,x2,y2 of the parent's parent at page load and use those values to set boundaries for a container relative to the document. But the container position can change relative to the parent's parent position if the window is resized after page load. The native 'parent' option keeps the draggable element within the parent element regardless of window resizing.
Is there a way to accomplish this draggable containment using the parent's parent?
. | 2011/11/10 | [
"https://Stackoverflow.com/questions/8084793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404699/"
]
| As per the [documentation](http://jqueryui.com/demos/draggable/#option-containment), the `containment` option can also be a jquery selector or an actual element. So you can do this:
```
$('.selector').draggable({
containment: $('.selector').parent().parent()
});
```
Or even better yet:
```
$('.selector').each(function(){
$(this).draggable({
containment: $(this).parent().parent()
});
});
``` | According to the docs, you do not *have to* pass in a string for the `containment` property. You can pass in any of:
```
Selector, Element, String, Array
```
So, just select the parent's parent with jQuery (i.e. `$( ".selector" ).parent().parent()`), and pass in instead of `'parent'`. |
8,084,793 | The jQuery UI Draggable interaction has a nice property for [setting the containment](http://jqueryui.com/demos/draggable/#option-containment) as the parent.
```
$( ".selector" ).draggable({ containment: 'parent' });
```
I wish to set the containment as the parent's parent. There is no string value to accomplish this, as string the options are
>
> 'parent', 'document', 'window', [x1, y1, x2, y2]
>
>
>
I could calculate x1,y1,x2,y2 of the parent's parent at page load and use those values to set boundaries for a container relative to the document. But the container position can change relative to the parent's parent position if the window is resized after page load. The native 'parent' option keeps the draggable element within the parent element regardless of window resizing.
Is there a way to accomplish this draggable containment using the parent's parent?
. | 2011/11/10 | [
"https://Stackoverflow.com/questions/8084793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404699/"
]
| As per the [documentation](http://jqueryui.com/demos/draggable/#option-containment), the `containment` option can also be a jquery selector or an actual element. So you can do this:
```
$('.selector').draggable({
containment: $('.selector').parent().parent()
});
```
Or even better yet:
```
$('.selector').each(function(){
$(this).draggable({
containment: $(this).parent().parent()
});
});
``` | This works fine as well:
```
$('.selector').draggable({
containment: "#parent",
scroll: false
});
``` |
8,084,793 | The jQuery UI Draggable interaction has a nice property for [setting the containment](http://jqueryui.com/demos/draggable/#option-containment) as the parent.
```
$( ".selector" ).draggable({ containment: 'parent' });
```
I wish to set the containment as the parent's parent. There is no string value to accomplish this, as string the options are
>
> 'parent', 'document', 'window', [x1, y1, x2, y2]
>
>
>
I could calculate x1,y1,x2,y2 of the parent's parent at page load and use those values to set boundaries for a container relative to the document. But the container position can change relative to the parent's parent position if the window is resized after page load. The native 'parent' option keeps the draggable element within the parent element regardless of window resizing.
Is there a way to accomplish this draggable containment using the parent's parent?
. | 2011/11/10 | [
"https://Stackoverflow.com/questions/8084793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404699/"
]
| As per the [documentation](http://jqueryui.com/demos/draggable/#option-containment), the `containment` option can also be a jquery selector or an actual element. So you can do this:
```
$('.selector').draggable({
containment: $('.selector').parent().parent()
});
```
Or even better yet:
```
$('.selector').each(function(){
$(this).draggable({
containment: $(this).parent().parent()
});
});
``` | If i use `$(this).parent()` my element go over the parent element.
```
$('.selector').draggable({
containment: $(this).parent()
});
```
But with `parent` it works fine.
```
$('.selector').draggable({
containment: "parent"
});
``` |
8,084,793 | The jQuery UI Draggable interaction has a nice property for [setting the containment](http://jqueryui.com/demos/draggable/#option-containment) as the parent.
```
$( ".selector" ).draggable({ containment: 'parent' });
```
I wish to set the containment as the parent's parent. There is no string value to accomplish this, as string the options are
>
> 'parent', 'document', 'window', [x1, y1, x2, y2]
>
>
>
I could calculate x1,y1,x2,y2 of the parent's parent at page load and use those values to set boundaries for a container relative to the document. But the container position can change relative to the parent's parent position if the window is resized after page load. The native 'parent' option keeps the draggable element within the parent element regardless of window resizing.
Is there a way to accomplish this draggable containment using the parent's parent?
. | 2011/11/10 | [
"https://Stackoverflow.com/questions/8084793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404699/"
]
| According to the docs, you do not *have to* pass in a string for the `containment` property. You can pass in any of:
```
Selector, Element, String, Array
```
So, just select the parent's parent with jQuery (i.e. `$( ".selector" ).parent().parent()`), and pass in instead of `'parent'`. | This works fine as well:
```
$('.selector').draggable({
containment: "#parent",
scroll: false
});
``` |
8,084,793 | The jQuery UI Draggable interaction has a nice property for [setting the containment](http://jqueryui.com/demos/draggable/#option-containment) as the parent.
```
$( ".selector" ).draggable({ containment: 'parent' });
```
I wish to set the containment as the parent's parent. There is no string value to accomplish this, as string the options are
>
> 'parent', 'document', 'window', [x1, y1, x2, y2]
>
>
>
I could calculate x1,y1,x2,y2 of the parent's parent at page load and use those values to set boundaries for a container relative to the document. But the container position can change relative to the parent's parent position if the window is resized after page load. The native 'parent' option keeps the draggable element within the parent element regardless of window resizing.
Is there a way to accomplish this draggable containment using the parent's parent?
. | 2011/11/10 | [
"https://Stackoverflow.com/questions/8084793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404699/"
]
| According to the docs, you do not *have to* pass in a string for the `containment` property. You can pass in any of:
```
Selector, Element, String, Array
```
So, just select the parent's parent with jQuery (i.e. `$( ".selector" ).parent().parent()`), and pass in instead of `'parent'`. | If i use `$(this).parent()` my element go over the parent element.
```
$('.selector').draggable({
containment: $(this).parent()
});
```
But with `parent` it works fine.
```
$('.selector').draggable({
containment: "parent"
});
``` |
8,084,793 | The jQuery UI Draggable interaction has a nice property for [setting the containment](http://jqueryui.com/demos/draggable/#option-containment) as the parent.
```
$( ".selector" ).draggable({ containment: 'parent' });
```
I wish to set the containment as the parent's parent. There is no string value to accomplish this, as string the options are
>
> 'parent', 'document', 'window', [x1, y1, x2, y2]
>
>
>
I could calculate x1,y1,x2,y2 of the parent's parent at page load and use those values to set boundaries for a container relative to the document. But the container position can change relative to the parent's parent position if the window is resized after page load. The native 'parent' option keeps the draggable element within the parent element regardless of window resizing.
Is there a way to accomplish this draggable containment using the parent's parent?
. | 2011/11/10 | [
"https://Stackoverflow.com/questions/8084793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404699/"
]
| If i use `$(this).parent()` my element go over the parent element.
```
$('.selector').draggable({
containment: $(this).parent()
});
```
But with `parent` it works fine.
```
$('.selector').draggable({
containment: "parent"
});
``` | This works fine as well:
```
$('.selector').draggable({
containment: "#parent",
scroll: false
});
``` |
32,284,092 | Utilizing express.Router() for API calls to/from our application:
```
var express = require('express');
var app = express();
var router = express.Router();
```
`router.use` console.logs before every API call:
```
router.use(function(req, res, next) { // run for any & all requests
console.log("Connection to the API.."); // set up logging for every API call
next(); // ..to the next routes from here..
});
```
How do we export our routes to `folder/routes.js` and access them from our main **app.js**, where they are currently located:
```
router.route('/This') // on routes for /This
// post a new This (accessed by POST @ http://localhost:8888/api/v1/This)
.post(function(req, res) {
// do stuff
});
router.route('/That') // on routes for /That
// post a new That (accessed by POST @ http://localhost:8888/api/v1/That)
.post(function(req, res) {
// do stuff
});
```
...when we prefix every route with:
```
app.use('/api/v1', router); // all of the API routes are prefixed with '/api' version '/v1'
``` | 2015/08/29 | [
"https://Stackoverflow.com/questions/32284092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4441520/"
]
| In your new routes module (eg in `api/myroutes.js`), export the module.
```
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
console.log('Connection to the API..');
next();
});
router.route('/example')
.get(function(req, res) { });
.post(function(req, res) { });
module.exports = router;
```
Then you can require the module in your main server/app file:
```
var express = require('express');
var app = express();
var myRoutes = require('./api/myRoutes');
app.use('/api', myRoutes); //register the routes
``` | In your app.js file you can have the following:
```
//api
app.use('/', require('./api'));
```
In the folder `api` you can have 'index.js` file, where you can write something like this:
```
var express = require('express');
var router = express.Router();
//API version 1
router.use('/api/v1', require('./v1'));
module.exports = router;
```
In the folder `v1` file `index.js` something like this:
```
var express = require('express');
var router = express.Router();
router.use('/route1', require('./route1'));
router.use('/route2', require('./route2'));
module.exports = router;
```
File `route1.js` can have the following structure:
```
var express = require('express');
var router = express.Router();
router.route('/')
.get(getRouteHandler)
.post(postRouteHandler);
function getRouteHandler(req, res) {
//handle GET route here
}
function postRouteHandler(req, res) {
//handle POST route here
}
module.exports = router;
```
`route2.js` file can have the same structure.
I think this is very comfortable for developing the node project. |
17,207,281 | I have this function:
```
$(document).on('scroll', function(e)
{
if (processing)
return false;
if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.9)
{
processing = true;
var resource = $('#lazyLoad').attr('href');
$.get(resource, '', function(data)
{
$('#lazyLoad').remove();
$('#content').append(data);
step++;
processing = false;
});
}
});
```
I add some html code to my page every time this function is called. But other Javascript functions are not triggered when I click on a newly added html button. So I guess the DOM-element was not porper updated. But how do I proper update the DOM-element?
My Handler looks like this:
```
$('.article_action.un_read').on('click', function(event)
{
event.preventDefault();
var resource = $(this).attr('href');
var elElemente = $(this);
$.get(resource, '', function(data)
{
var obj = $.parseJSON(data);
if(obj.status == 1)
elElemente.html('📕');
else
elElemente.html('📖');
});
});
```
So it also uses the `on` function. | 2013/06/20 | [
"https://Stackoverflow.com/questions/17207281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912227/"
]
| Try it like this :
```
$('#content').on('click', '.article_action.un_read', function(event) {
event.preventDefault();
var resource = $(this).attr('href');
var elElemente = $(this);
$.getJSON(resource, '', function(obj) {
elElemente.html(obj.status == 1 ? '📕' : '📖');
});
});
``` | You have to bind the button clicks with delegate-events.
```
$('#parentElement').on('click', 'button', function () {});
``` |
17,207,281 | I have this function:
```
$(document).on('scroll', function(e)
{
if (processing)
return false;
if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.9)
{
processing = true;
var resource = $('#lazyLoad').attr('href');
$.get(resource, '', function(data)
{
$('#lazyLoad').remove();
$('#content').append(data);
step++;
processing = false;
});
}
});
```
I add some html code to my page every time this function is called. But other Javascript functions are not triggered when I click on a newly added html button. So I guess the DOM-element was not porper updated. But how do I proper update the DOM-element?
My Handler looks like this:
```
$('.article_action.un_read').on('click', function(event)
{
event.preventDefault();
var resource = $(this).attr('href');
var elElemente = $(this);
$.get(resource, '', function(data)
{
var obj = $.parseJSON(data);
if(obj.status == 1)
elElemente.html('📕');
else
elElemente.html('📖');
});
});
```
So it also uses the `on` function. | 2013/06/20 | [
"https://Stackoverflow.com/questions/17207281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1912227/"
]
| Try it like this :
```
$('#content').on('click', '.article_action.un_read', function(event) {
event.preventDefault();
var resource = $(this).attr('href');
var elElemente = $(this);
$.getJSON(resource, '', function(obj) {
elElemente.html(obj.status == 1 ? '📕' : '📖');
});
});
``` | you need to mention the event binder declaration
```
$(<selector>).on('click', <handler>);
```
again inside the function which appends the html.
check the sample [fiddle](http://jsfiddle.net/seelan/UzXuf/)
edit:
but first you should unbind old events inside the function which appends the html to prevent callback from multiple call.
```
$(<selector>).off();
``` |
26,670,501 | This is the code I have written so far:
```
foreach ($link_body as $key => $unfinished_link)
{
#further Remove non ad links
if (stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
{
unset($link_body[$key]);
}
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
}
```
I'm not getting any error messages but I keep getting results that look like this:
```
/cars/" />
/cars/">
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" rel="nofollow">(not what I wanted)
/cars/?layout=gallery" rel="nofollow">(not what I wanted)
/cars/2001-ford-escort-great-condition/1235588">(IS what I wanted)
```
Where am I messing up here guys? Thx | 2014/10/31 | [
"https://Stackoverflow.com/questions/26670501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4179805/"
]
| If you're trying to find a string inside that, maybe you indend to use `stripos` instead:
```
foreach ($link_body as $key => $unfinished_link) {
// further Remove non ad links
if(
stripos($unfinished_link, 'inactive') !== false ||
stripos($unfinished_link, 'nofollow') !== false
) {
unset($link_body[$key]);
} else {
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
// make sure your background is not white, or else your text will not be seen, at least on the white screen
}
}
```
If this is an HTML markup, consider using an HTML parser instead, `DOMDocument` in particular, and search for that attributes:
```
$rel = $node->getAttribute('rel'); // or
$class = $node->getAttribute('class');
``` | To my knowledge, you cannot combine parameters in the way you try here :
```
if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
```
Instead, you can replace with
```
if(stristr($unfinished_link, "nofollow") === TRUE) || stristr($unfinished_link, "inactive") === TRUE)
``` |
26,670,501 | This is the code I have written so far:
```
foreach ($link_body as $key => $unfinished_link)
{
#further Remove non ad links
if (stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
{
unset($link_body[$key]);
}
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
}
```
I'm not getting any error messages but I keep getting results that look like this:
```
/cars/" />
/cars/">
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" rel="nofollow">(not what I wanted)
/cars/?layout=gallery" rel="nofollow">(not what I wanted)
/cars/2001-ford-escort-great-condition/1235588">(IS what I wanted)
```
Where am I messing up here guys? Thx | 2014/10/31 | [
"https://Stackoverflow.com/questions/26670501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4179805/"
]
| You echo the variable $unfinished\_link that it's different that $link\_body[$key]. OK, the values are the same before you unset $link\_body[$key] but it's like you are doing:
```
$a=1;
$b=1;
unset($a);
echo $b;
```
Of course, this code will echo the number one because I have unset a variable and echo other one. Also the condition of the If is incorrect. | To my knowledge, you cannot combine parameters in the way you try here :
```
if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
```
Instead, you can replace with
```
if(stristr($unfinished_link, "nofollow") === TRUE) || stristr($unfinished_link, "inactive") === TRUE)
``` |
26,670,501 | This is the code I have written so far:
```
foreach ($link_body as $key => $unfinished_link)
{
#further Remove non ad links
if (stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
{
unset($link_body[$key]);
}
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
}
```
I'm not getting any error messages but I keep getting results that look like this:
```
/cars/" />
/cars/">
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" rel="nofollow">(not what I wanted)
/cars/?layout=gallery" rel="nofollow">(not what I wanted)
/cars/2001-ford-escort-great-condition/1235588">(IS what I wanted)
```
Where am I messing up here guys? Thx | 2014/10/31 | [
"https://Stackoverflow.com/questions/26670501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4179805/"
]
| Do not remove array's element *inside* foreach statement
Remember elements to delete in foreach, delete them after foreach:
```
$elements_to_delete = {};
foreach ($link_body as $key => $unfinished_link)
{
if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE) {
$elements_to_delete.push($key);
}
}
// removing elements after foreach complete
foreach($key in $elements_to_delete){
$link_body[$key];
}
``` | To my knowledge, you cannot combine parameters in the way you try here :
```
if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
```
Instead, you can replace with
```
if(stristr($unfinished_link, "nofollow") === TRUE) || stristr($unfinished_link, "inactive") === TRUE)
``` |
26,670,501 | This is the code I have written so far:
```
foreach ($link_body as $key => $unfinished_link)
{
#further Remove non ad links
if (stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
{
unset($link_body[$key]);
}
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
}
```
I'm not getting any error messages but I keep getting results that look like this:
```
/cars/" />
/cars/">
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" rel="nofollow">(not what I wanted)
/cars/?layout=gallery" rel="nofollow">(not what I wanted)
/cars/2001-ford-escort-great-condition/1235588">(IS what I wanted)
```
Where am I messing up here guys? Thx | 2014/10/31 | [
"https://Stackoverflow.com/questions/26670501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4179805/"
]
| Using [array\_filter](http://php.net/manual/en/function.array-filter.php) :
```
function filterLink($link) {
return stripos($unfinished_link, 'inactive') === false &&
stripos($unfinished_link, 'nofollow') === false
}
$unfinished_link = array_filter($unfinished_link, "filterLInk")
``` | To my knowledge, you cannot combine parameters in the way you try here :
```
if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
```
Instead, you can replace with
```
if(stristr($unfinished_link, "nofollow") === TRUE) || stristr($unfinished_link, "inactive") === TRUE)
``` |
26,670,501 | This is the code I have written so far:
```
foreach ($link_body as $key => $unfinished_link)
{
#further Remove non ad links
if (stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
{
unset($link_body[$key]);
}
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
}
```
I'm not getting any error messages but I keep getting results that look like this:
```
/cars/" />
/cars/">
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" rel="nofollow">(not what I wanted)
/cars/?layout=gallery" rel="nofollow">(not what I wanted)
/cars/2001-ford-escort-great-condition/1235588">(IS what I wanted)
```
Where am I messing up here guys? Thx | 2014/10/31 | [
"https://Stackoverflow.com/questions/26670501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4179805/"
]
| If you're trying to find a string inside that, maybe you indend to use `stripos` instead:
```
foreach ($link_body as $key => $unfinished_link) {
// further Remove non ad links
if(
stripos($unfinished_link, 'inactive') !== false ||
stripos($unfinished_link, 'nofollow') !== false
) {
unset($link_body[$key]);
} else {
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
// make sure your background is not white, or else your text will not be seen, at least on the white screen
}
}
```
If this is an HTML markup, consider using an HTML parser instead, `DOMDocument` in particular, and search for that attributes:
```
$rel = $node->getAttribute('rel'); // or
$class = $node->getAttribute('class');
``` | You echo the variable $unfinished\_link that it's different that $link\_body[$key]. OK, the values are the same before you unset $link\_body[$key] but it's like you are doing:
```
$a=1;
$b=1;
unset($a);
echo $b;
```
Of course, this code will echo the number one because I have unset a variable and echo other one. Also the condition of the If is incorrect. |
26,670,501 | This is the code I have written so far:
```
foreach ($link_body as $key => $unfinished_link)
{
#further Remove non ad links
if (stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
{
unset($link_body[$key]);
}
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
}
```
I'm not getting any error messages but I keep getting results that look like this:
```
/cars/" />
/cars/">
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" rel="nofollow">(not what I wanted)
/cars/?layout=gallery" rel="nofollow">(not what I wanted)
/cars/2001-ford-escort-great-condition/1235588">(IS what I wanted)
```
Where am I messing up here guys? Thx | 2014/10/31 | [
"https://Stackoverflow.com/questions/26670501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4179805/"
]
| If you're trying to find a string inside that, maybe you indend to use `stripos` instead:
```
foreach ($link_body as $key => $unfinished_link) {
// further Remove non ad links
if(
stripos($unfinished_link, 'inactive') !== false ||
stripos($unfinished_link, 'nofollow') !== false
) {
unset($link_body[$key]);
} else {
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
// make sure your background is not white, or else your text will not be seen, at least on the white screen
}
}
```
If this is an HTML markup, consider using an HTML parser instead, `DOMDocument` in particular, and search for that attributes:
```
$rel = $node->getAttribute('rel'); // or
$class = $node->getAttribute('class');
``` | Do not remove array's element *inside* foreach statement
Remember elements to delete in foreach, delete them after foreach:
```
$elements_to_delete = {};
foreach ($link_body as $key => $unfinished_link)
{
if(stristr($unfinished_link, "inactive" OR "nofollow") === TRUE) {
$elements_to_delete.push($key);
}
}
// removing elements after foreach complete
foreach($key in $elements_to_delete){
$link_body[$key];
}
``` |
26,670,501 | This is the code I have written so far:
```
foreach ($link_body as $key => $unfinished_link)
{
#further Remove non ad links
if (stristr($unfinished_link, "inactive" OR "nofollow") === TRUE)
{
unset($link_body[$key]);
}
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
}
```
I'm not getting any error messages but I keep getting results that look like this:
```
/cars/" />
/cars/">
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" class="inactive">(not what I wanted)
/cars/" rel="nofollow">(not what I wanted)
/cars/?layout=gallery" rel="nofollow">(not what I wanted)
/cars/2001-ford-escort-great-condition/1235588">(IS what I wanted)
```
Where am I messing up here guys? Thx | 2014/10/31 | [
"https://Stackoverflow.com/questions/26670501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4179805/"
]
| If you're trying to find a string inside that, maybe you indend to use `stripos` instead:
```
foreach ($link_body as $key => $unfinished_link) {
// further Remove non ad links
if(
stripos($unfinished_link, 'inactive') !== false ||
stripos($unfinished_link, 'nofollow') !== false
) {
unset($link_body[$key]);
} else {
echo "<font color='#FFFFFF' size='16'>$unfinished_link</font><br>";
// make sure your background is not white, or else your text will not be seen, at least on the white screen
}
}
```
If this is an HTML markup, consider using an HTML parser instead, `DOMDocument` in particular, and search for that attributes:
```
$rel = $node->getAttribute('rel'); // or
$class = $node->getAttribute('class');
``` | Using [array\_filter](http://php.net/manual/en/function.array-filter.php) :
```
function filterLink($link) {
return stripos($unfinished_link, 'inactive') === false &&
stripos($unfinished_link, 'nofollow') === false
}
$unfinished_link = array_filter($unfinished_link, "filterLInk")
``` |
57,858,144 | I use `pyenv` to manage my Python environments and I get the following when simply running `bash`.
```
$ bash
pyenv: bash: command not found
```
I was trying to troubleshoot why `pipenv shell` failed with the above error, which is how I found out even `bash` wasn't working. I tried updating `pipenv` via `brew` and ran `pyenv rehash` to regenerate the shims. And `bash` is definitely present.
```
$ which bash
/bin/bash
```
I expected that if `pyenv` doesn't find a command, the subsequent paths specified by the `PATH` environment variable will be searched. Interestingly if I execute some non-existant command I don't get a `pyenv` error.
```
$ someboguscommand
-bash: someboguscommand: command not found
```
This suggests to me that `pyenv` doesn't even search for a matching command in this case and the subsequent paths in `PATH` are searched, so there must be some special handling with `bash`. | 2019/09/09 | [
"https://Stackoverflow.com/questions/57858144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4396801/"
]
| I had this issue when setting up **Python 3.8** on **CentOS** using **Pyenv**.
I was running into the error below when I run `pyenv install 3.8.2`:
```
pyenv: bash: command not found
```
**Here's how I solved it**:
The issue was pyenv was not added to the load path for my profile.
All I had to do was to do the following:
Open the `.bashrc` file in the home directory of my user:
```
sudo nano ~/.bashrc
```
Next, add the following add the bottom of the file and save:
```
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
```
Finally, restart your terminal or run the command below to load the newly added paths into your current shell/terminal session:
```
exec "$SHELL"
```
Now when you run the command `pyenv install 3.8.2` it should work fine.
**Resources**: [Managing Multiple Python Versions With pyenv](https://realpython.com/intro-to-pyenv/)
That's all.
**I hope this helps** | The issue was that I had the following line in my `.bashrc`, which was being invoked when running `bash`. It's a line that I no longer need:
```
. virtualenvwrapper.sh
```
This was in turn invoking pyenv's virtualwrapper shim:
```
$ which virtualenvwrapper.sh
/Users/greg/.pyenv/shims/virtualenvwrapper.sh
```
That's what caused the failure. I was able to identify this by running a debug trace with `bash`:
```
$ bash -x
+ . virtualenvwrapper.sh
++ set -e
++ '[' -n '' ']'
++ program=bash
++ [[ bash = \p\y\t\h\o\n* ]]
++ export PYENV_ROOT=/Users/greg/.pyenv
++ PYENV_ROOT=/Users/greg/.pyenv
++ exec /usr/local/Cellar/pyenv/1.2.13_1/libexec/pyenv exec bash
pyenv: bash: command not found
```
Thank you for the useful comments "that other guy", Charles Duffy, and rje! |
10,203,554 | There is 7Gb available but...
```
~ # dpkg --configure -a
Setting up linux-image-2.6.32-31-generic-pae (2.6.32-31.61) ...
Running depmod.
update-initramfs: Generating /boot/initrd.img-2.6.32-31-generic-pae
gzip: stdout: No space left on device
update-initramfs: failed for /boot/initrd.img-2.6.32-31-generic-pae
Failed to create initrd image.
dpkg: error processing linux-image-2.6.32-31-generic-pae (--configure):
subprocess installed post-installation script returned error exit status 2
dpkg: dependency problems prevent configuration of linux-image-generic-pae:
linux-image-generic-pae depends on linux-image-2.6.32-31-generic-pae; however:
Package linux-image-2.6.32-31-generic-pae is not configured yet.
dpkg: error processing linux-image-generic-pae (--configure):
dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of linux-generic-pae:
linux-generic-pae depends on linux-image-generic-pae (= 2.6.32.31.37); however:
Package linux-image-generic-pae is not configured yet.
dpkg: error processing linux-generic-pae (--configure):
dependency problems - leaving unconfigured
Errors were encountered while processing:
linux-image-2.6.32-31-generic-pae
linux-image-generic-pae
linux-generic-pae
~ # df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda3 18577148 10255512 7377972 59% /
none 1026416 164 1026252 1% /dev
none 1030624 0 1030624 0% /dev/shm
none 1030624 100 1030524 1% /var/run
none 1030624 4 1030620 1% /var/lock
none 1030624 0 1030624 0% /lib/init/rw
/dev/sda1 93207 87960 435 100% /boot
~ # cat /etc/redhat-release
cat: /etc/redhat-release: No such file or directory
~ # cat /proc/version
Linux version 2.6.32-30-generic-pae (buildd@vernadsky) (gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) ) #59-Ubuntu SMP Tue Mar 1 23:01:33 UTC 2011
~ # uname -a
Linux ws1.naturapet.com.au 2.6.32-30-generic-pae #59-Ubuntu SMP Tue Mar 1 23:01:33 UTC 2011 i686 GNU/Linux
~ # lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 10.04.2 LTS
Release: 10.04
Codename: lucid
``` | 2012/04/18 | [
"https://Stackoverflow.com/questions/10203554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1035279/"
]
| The problem is your /boot partition is 100% full. New linux kernels will be installed there, but they obviously cannot be if that partition is full.
Check whether you have old kernels installed and uninstall them.
```
dpkg -l | grep linux-image
```
will tell you which linux kernels you have installed.
```
uname -a
```
will tell you what kernel you are currently using. | cause you have no space left on /boot |
28,001,292 | What are the necessary dll files to deploy an application using Qt? By necessary I mean those who are common to all applications, not the entire dll folder. Are msvr120.dll and msvc120.dll necessary too? Thanks to further answers. | 2015/01/17 | [
"https://Stackoverflow.com/questions/28001292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I edited the shebang on the iPython executable from `#!/usr/bin/python` to `#/usr/local/bin/python3`, but I am not sure if this is a hacky or bad solution. | what work for me is changing #!/usr/bin/python to #! /usr/bin/python3 in file /usr/local/bin/ipython3
Just make sure that above address in all files coming out from '`whereis ipython3`' should be same. |
41,050,202 | I am quite new to python and I am trying to write a simple implementation of REST api calls. My goal is to be able to create methods of a class at run time and to be able to use method names as basis for API calls. For example list\_virtual\_networks will turn into GET to <http://localhost:8080/virtual-networks>, etc. I'd also want to practice at some more advanced object oriented techniques. Here's my approach:
```
def _api_call_wrapper(wrapped_function):
def wrapper_function(*args, **kwargs):
handler_name = wrapped_function.__name__
agent_logger.info('Got function name {}'.format(handler_name))
<do something>
return res
return wrapper_function
class API(HTTPConnection):
def __init__(self, host, port):
<do something>
def __getattr__(self, name):
@_api_call_wrapper
def handler(self, *args, **kwargs):
self.request('GET', self.last_url)
return self.getresponse()
handler.__name__ = name
setattr(self, name, handler)
agent_logger.info('Returning method with name {}'.format(self.name))
if __name__ == '__main__':
api = API(127.0.0.1, 8080)
api.list_virtual_networks()
```
Here's what I see in logs:
2016-12-08 23:05:03,034 - AgentLogger - INFO - Returning method with name function wrapper\_function at 0x1073c8d70>
2016-12-08 23:05:03,034 - AgentLogger - INFO - Returning method with name None
I hope I made myself clear enough to explain what I wanted to achieve. Is there a way to solve it at least roughly in a way I am trying to do it? | 2016/12/08 | [
"https://Stackoverflow.com/questions/41050202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802567/"
]
| Your synchronization is broken, so you can't deduce much by your experiment. Each time you do `sum += i`, you assign a new Integer to `sum`. So the threads synchronize on two different Integers.
Also, you're binding an instance of Sommatore, but you're showing the code of Adder.
But to answer your question, you're binding an instance, and RMI won't magically create copies of that instance. It won't synchronize all calls to this instance either. So you need to make sure the code is thread-safe. Just because a quick test produces a correct result despite the absence of proper synchronization doesn't mean that it will always be that way. You can cross a road with your eyes shut 10 times and never die. That doesn't mean it's safe. | >
> Is RMI automatically "thread-safe"?
>
>
>
No.
>
> Extra question: when I bind an object in RMI, what exactly am I binding? The specific instance of the object I call Naming.rebind() on, or the class(and then when I look it up I just get a new instance?)?
>
>
>
Actually neither. You are binding a *stub*, which is irretrievably associated with the remote object instance you supplied to the `bind()` method. |
61,442,869 | I'm learning Clojure and working on a simple file parsing script.
I have a file in the form of:
```
pattern1
pattern2
pattern3
pattern1
pattern2
...
```
where each line has a few values (numbers) that I extract.
If I was to write this in Java for example, I would do something similar to:
```
Map<String, Integer> parse(String line) {
//using Optional in this toy example, but could be an empty map or something else to
//signal if first one was actually matched and the values are there
Optional<Map<String, Integer>> firstMatched = matchFirst(line);
if (firstMatched.isPresent()) {
return firstMatched.get();
}
//...do the same for 2 remaining patterns
//...
}
```
Now **what would be a an elegant or idiomatic way** to do something similar **in Clojure**?
I guess I can use [cond](https://clojuredocs.org/clojure.core/cond), but since there's no binding in the test expression, I'll have to parse the line twice:
```
(defn parse
[line]
(cond
(re-find #"pattern-1-regex" line) (re-find...)
(re-find #"pattern-2-regex" line) (re-find...
```
I could also use [if-let](https://clojuredocs.org/clojure.core/if-let), but that will be a lot of nesting since there are 3 different options. Imagine with 7 different pattern how that would look like.
Any suggestions? Obviously Java solution is an imperative one and I can do a "return" whenever I want, so what would be the *Clojure/FP way* of dealing with this simple branching. | 2020/04/26 | [
"https://Stackoverflow.com/questions/61442869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/967510/"
]
| You do not need to deserialise inner `JSON Object` one more time. It is already deserialised to `Map` instance. So, all you need is casting.
1. Deserialise payload to `Map<String, Object>` which is safe using `com.fasterxml.jackson.core.type.TypeReference` class.
2. Cast inner object to `Map<String, String>` only if `JSON` payload is validated. In other case problem with casting will appear again.
3. To iterate over `Map` do not create `Iterator` object. Use `Java 8` `Stream API` or regular `for` loop.
How code could look like after above changes:
```
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws IOException {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper objectMapper = new ObjectMapper();
// read as Map
Map<String, Object> busObjMap = objectMapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() {});
// Inner object is already deserialised as well into Map
Map<String, String> attributeList = (Map<String, String>) busObjMap.get("attributeList");
System.out.println("Business Object values:");
for (Map.Entry<String, Object> entry : busObjMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("Attribute values:");
for (Map.Entry<String, String> entry : attributeList.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
``` | Create a class matching your json structure, use that instead , it's better in terms of readability. |
1,683,902 | Is it possible to wait for all processes launched by a child process in Windows? I can't modify the child or grandchild processes.
Specifically, here's what I want to do. My process launches uninstallA.exe. The process uninistallA.exe launches uninstallB.exe and immediately exits, and uninstallB.exe runs for a while. I'd like to wait for uninstallB.exe to exit so that I can know when the uninstall is finished. | 2009/11/05 | [
"https://Stackoverflow.com/questions/1683902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11661/"
]
| There is not a generic way to wait for all grandchildren but for your specific case you may be able to hack something together. You know you are looking for a specific process instance. I would first wait for uninstallA.exe to exit (using WaitForSingleObject) because at that point you know that uninstallB.exe has been started. Then use EnumProcesses and GetProcessImageFileName from PSAPI to find the running uninstallB.exe instance. If you don't find it you know it has already finished, otherwise you can wait for it.
An additional complication is that if you need to support versions of Windows older than XP you can't use GetProcessImageFileName, and for Windows NT you can't use PSAPI at all. For Windows 2000 you can use GetModuleFileNameEx but it has some caveats that mean it might fail sometimes (check docs). If you have to support NT then look up Toolhelp32.
Yes this is super ugly. | Use a [named mutex](http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx). |
1,683,902 | Is it possible to wait for all processes launched by a child process in Windows? I can't modify the child or grandchild processes.
Specifically, here's what I want to do. My process launches uninstallA.exe. The process uninistallA.exe launches uninstallB.exe and immediately exits, and uninstallB.exe runs for a while. I'd like to wait for uninstallB.exe to exit so that I can know when the uninstall is finished. | 2009/11/05 | [
"https://Stackoverflow.com/questions/1683902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11661/"
]
| Create a Job Object with `CreateJobObject`. Use `CreateProcess` to start `UninstallA.exe` in a suspended state. Assign that new process to your job object with `AssignProcessToJobObject`. Start UninstallA.exe running by calling `ResumeThread` on the handle of the thread you got back from `CreateProcess`.
Then the hard part: wait for the job object to complete its execution. Unfortunately, this is quite a bit more complex than anybody would reasonably hope for. The basic idea is that you create an I/O completion port, then you create the object object, associate it with the I/O completion port, and finally wait on the I/O completion port (getting its status with `GetQueuedCompletionStatus`). Raymond Chen has a demonstration (and explanation of how this came about) on his [blog](https://devblogs.microsoft.com/oldnewthing/20130405-00/?p=4743). | Use a [named mutex](http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx). |
1,683,902 | Is it possible to wait for all processes launched by a child process in Windows? I can't modify the child or grandchild processes.
Specifically, here's what I want to do. My process launches uninstallA.exe. The process uninistallA.exe launches uninstallB.exe and immediately exits, and uninstallB.exe runs for a while. I'd like to wait for uninstallB.exe to exit so that I can know when the uninstall is finished. | 2009/11/05 | [
"https://Stackoverflow.com/questions/1683902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11661/"
]
| Here's a technique that, while not infallible, can be useful if for some reason you can't use a job object. The idea is to create an anonymous pipe and let the child process inherit the handle to the write end of the pipe.
Typically, grandchild processes will also inherit the write end of the pipe. In particular, processes launched by `cmd.exe` (e.g., from a batch file) will inherit handles.
Once the child process has exited, the parent process closes its handle to the write end of the pipe, and then attempts to read from the pipe. Since nobody is writing to the pipe, the read operation will block indefinitely. (Of course you can use threads or asynchronous I/O if you want to keep doing stuff while waiting for the grandchildren.)
When (and only when) the last handle to the write end of the pipe is closed, the write end of the pipe is automatically destroyed. This breaks the pipe and the read operation completes and reports an ERROR\_BROKEN\_PIPE failure.
I've been using this code (and earlier versions of the same code) in production for a number of years.
```
// pwatch.c
//
// Written in 2011 by Harry Johnston, University of Waikato, New Zealand.
// This code has been placed in the public domain. It may be freely
// used, modified, and distributed. However it is provided with no
// warranty, either express or implied.
//
// Launches a process with an inherited pipe handle,
// and doesn't exit until (a) the process has exited
// and (b) all instances of the pipe handle have been closed.
//
// This effectively waits for any child processes to exit,
// PROVIDED the child processes were created with handle
// inheritance enabled. This is usually but not always
// true.
//
// In particular if you launch a command shell (cmd.exe)
// any commands launched from that command shell will be
// waited on.
#include <windows.h>
#include <stdio.h>
void error(const wchar_t * message, DWORD err) {
wchar_t msg[512];
swprintf_s(msg, sizeof(msg)/sizeof(*msg), message, err);
printf("pwatch: %ws\n", msg);
MessageBox(NULL, msg, L"Error in pwatch utility", MB_OK | MB_ICONEXCLAMATION | MB_SYSTEMMODAL);
ExitProcess(err);
}
int main(int argc, char ** argv) {
LPWSTR lpCmdLine = GetCommandLine();
wchar_t ch;
DWORD dw, returncode;
HANDLE piperead, pipewrite;
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
char buffer[1];
while (ch = *(lpCmdLine++)) {
if (ch == '"') while (ch = *(lpCmdLine++)) if (ch == '"') break;
if (ch == ' ') break;
}
while (*lpCmdLine == ' ') lpCmdLine++;
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe(&piperead, &pipewrite, &sa, 1)) error(L"Unable to create pipes: %u", GetLastError());
GetStartupInfo(&si);
if (!CreateProcess(NULL, lpCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
error(L"Error %u creating process.", GetLastError());
if (WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_FAILED) error(L"Error %u waiting for process.", GetLastError());
if (!GetExitCodeProcess(pi.hProcess, &returncode)) error(L"Error %u getting exit code.", GetLastError());
CloseHandle(pipewrite);
if (ReadFile(piperead, buffer, 1, &dw, NULL)) {
error(L"Unexpected data received from pipe; bug in application being watched?", ERROR_INVALID_HANDLE);
}
dw = GetLastError();
if (dw != ERROR_BROKEN_PIPE) error(L"Unexpected error %u reading from pipe.", dw);
return returncode;
}
``` | Use a [named mutex](http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx). |
1,683,902 | Is it possible to wait for all processes launched by a child process in Windows? I can't modify the child or grandchild processes.
Specifically, here's what I want to do. My process launches uninstallA.exe. The process uninistallA.exe launches uninstallB.exe and immediately exits, and uninstallB.exe runs for a while. I'd like to wait for uninstallB.exe to exit so that I can know when the uninstall is finished. | 2009/11/05 | [
"https://Stackoverflow.com/questions/1683902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11661/"
]
| There is not a generic way to wait for all grandchildren but for your specific case you may be able to hack something together. You know you are looking for a specific process instance. I would first wait for uninstallA.exe to exit (using WaitForSingleObject) because at that point you know that uninstallB.exe has been started. Then use EnumProcesses and GetProcessImageFileName from PSAPI to find the running uninstallB.exe instance. If you don't find it you know it has already finished, otherwise you can wait for it.
An additional complication is that if you need to support versions of Windows older than XP you can't use GetProcessImageFileName, and for Windows NT you can't use PSAPI at all. For Windows 2000 you can use GetModuleFileNameEx but it has some caveats that mean it might fail sometimes (check docs). If you have to support NT then look up Toolhelp32.
Yes this is super ugly. | One possibility is to install Cygwin and then use the ps command to watch for the grandchild to exit |
1,683,902 | Is it possible to wait for all processes launched by a child process in Windows? I can't modify the child or grandchild processes.
Specifically, here's what I want to do. My process launches uninstallA.exe. The process uninistallA.exe launches uninstallB.exe and immediately exits, and uninstallB.exe runs for a while. I'd like to wait for uninstallB.exe to exit so that I can know when the uninstall is finished. | 2009/11/05 | [
"https://Stackoverflow.com/questions/1683902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11661/"
]
| Create a Job Object with `CreateJobObject`. Use `CreateProcess` to start `UninstallA.exe` in a suspended state. Assign that new process to your job object with `AssignProcessToJobObject`. Start UninstallA.exe running by calling `ResumeThread` on the handle of the thread you got back from `CreateProcess`.
Then the hard part: wait for the job object to complete its execution. Unfortunately, this is quite a bit more complex than anybody would reasonably hope for. The basic idea is that you create an I/O completion port, then you create the object object, associate it with the I/O completion port, and finally wait on the I/O completion port (getting its status with `GetQueuedCompletionStatus`). Raymond Chen has a demonstration (and explanation of how this came about) on his [blog](https://devblogs.microsoft.com/oldnewthing/20130405-00/?p=4743). | One possibility is to install Cygwin and then use the ps command to watch for the grandchild to exit |
1,683,902 | Is it possible to wait for all processes launched by a child process in Windows? I can't modify the child or grandchild processes.
Specifically, here's what I want to do. My process launches uninstallA.exe. The process uninistallA.exe launches uninstallB.exe and immediately exits, and uninstallB.exe runs for a while. I'd like to wait for uninstallB.exe to exit so that I can know when the uninstall is finished. | 2009/11/05 | [
"https://Stackoverflow.com/questions/1683902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11661/"
]
| Here's a technique that, while not infallible, can be useful if for some reason you can't use a job object. The idea is to create an anonymous pipe and let the child process inherit the handle to the write end of the pipe.
Typically, grandchild processes will also inherit the write end of the pipe. In particular, processes launched by `cmd.exe` (e.g., from a batch file) will inherit handles.
Once the child process has exited, the parent process closes its handle to the write end of the pipe, and then attempts to read from the pipe. Since nobody is writing to the pipe, the read operation will block indefinitely. (Of course you can use threads or asynchronous I/O if you want to keep doing stuff while waiting for the grandchildren.)
When (and only when) the last handle to the write end of the pipe is closed, the write end of the pipe is automatically destroyed. This breaks the pipe and the read operation completes and reports an ERROR\_BROKEN\_PIPE failure.
I've been using this code (and earlier versions of the same code) in production for a number of years.
```
// pwatch.c
//
// Written in 2011 by Harry Johnston, University of Waikato, New Zealand.
// This code has been placed in the public domain. It may be freely
// used, modified, and distributed. However it is provided with no
// warranty, either express or implied.
//
// Launches a process with an inherited pipe handle,
// and doesn't exit until (a) the process has exited
// and (b) all instances of the pipe handle have been closed.
//
// This effectively waits for any child processes to exit,
// PROVIDED the child processes were created with handle
// inheritance enabled. This is usually but not always
// true.
//
// In particular if you launch a command shell (cmd.exe)
// any commands launched from that command shell will be
// waited on.
#include <windows.h>
#include <stdio.h>
void error(const wchar_t * message, DWORD err) {
wchar_t msg[512];
swprintf_s(msg, sizeof(msg)/sizeof(*msg), message, err);
printf("pwatch: %ws\n", msg);
MessageBox(NULL, msg, L"Error in pwatch utility", MB_OK | MB_ICONEXCLAMATION | MB_SYSTEMMODAL);
ExitProcess(err);
}
int main(int argc, char ** argv) {
LPWSTR lpCmdLine = GetCommandLine();
wchar_t ch;
DWORD dw, returncode;
HANDLE piperead, pipewrite;
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
char buffer[1];
while (ch = *(lpCmdLine++)) {
if (ch == '"') while (ch = *(lpCmdLine++)) if (ch == '"') break;
if (ch == ' ') break;
}
while (*lpCmdLine == ' ') lpCmdLine++;
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe(&piperead, &pipewrite, &sa, 1)) error(L"Unable to create pipes: %u", GetLastError());
GetStartupInfo(&si);
if (!CreateProcess(NULL, lpCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
error(L"Error %u creating process.", GetLastError());
if (WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_FAILED) error(L"Error %u waiting for process.", GetLastError());
if (!GetExitCodeProcess(pi.hProcess, &returncode)) error(L"Error %u getting exit code.", GetLastError());
CloseHandle(pipewrite);
if (ReadFile(piperead, buffer, 1, &dw, NULL)) {
error(L"Unexpected data received from pipe; bug in application being watched?", ERROR_INVALID_HANDLE);
}
dw = GetLastError();
if (dw != ERROR_BROKEN_PIPE) error(L"Unexpected error %u reading from pipe.", dw);
return returncode;
}
``` | One possibility is to install Cygwin and then use the ps command to watch for the grandchild to exit |
1,683,902 | Is it possible to wait for all processes launched by a child process in Windows? I can't modify the child or grandchild processes.
Specifically, here's what I want to do. My process launches uninstallA.exe. The process uninistallA.exe launches uninstallB.exe and immediately exits, and uninstallB.exe runs for a while. I'd like to wait for uninstallB.exe to exit so that I can know when the uninstall is finished. | 2009/11/05 | [
"https://Stackoverflow.com/questions/1683902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11661/"
]
| Create a Job Object with `CreateJobObject`. Use `CreateProcess` to start `UninstallA.exe` in a suspended state. Assign that new process to your job object with `AssignProcessToJobObject`. Start UninstallA.exe running by calling `ResumeThread` on the handle of the thread you got back from `CreateProcess`.
Then the hard part: wait for the job object to complete its execution. Unfortunately, this is quite a bit more complex than anybody would reasonably hope for. The basic idea is that you create an I/O completion port, then you create the object object, associate it with the I/O completion port, and finally wait on the I/O completion port (getting its status with `GetQueuedCompletionStatus`). Raymond Chen has a demonstration (and explanation of how this came about) on his [blog](https://devblogs.microsoft.com/oldnewthing/20130405-00/?p=4743). | There is not a generic way to wait for all grandchildren but for your specific case you may be able to hack something together. You know you are looking for a specific process instance. I would first wait for uninstallA.exe to exit (using WaitForSingleObject) because at that point you know that uninstallB.exe has been started. Then use EnumProcesses and GetProcessImageFileName from PSAPI to find the running uninstallB.exe instance. If you don't find it you know it has already finished, otherwise you can wait for it.
An additional complication is that if you need to support versions of Windows older than XP you can't use GetProcessImageFileName, and for Windows NT you can't use PSAPI at all. For Windows 2000 you can use GetModuleFileNameEx but it has some caveats that mean it might fail sometimes (check docs). If you have to support NT then look up Toolhelp32.
Yes this is super ugly. |
1,683,902 | Is it possible to wait for all processes launched by a child process in Windows? I can't modify the child or grandchild processes.
Specifically, here's what I want to do. My process launches uninstallA.exe. The process uninistallA.exe launches uninstallB.exe and immediately exits, and uninstallB.exe runs for a while. I'd like to wait for uninstallB.exe to exit so that I can know when the uninstall is finished. | 2009/11/05 | [
"https://Stackoverflow.com/questions/1683902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11661/"
]
| Here's a technique that, while not infallible, can be useful if for some reason you can't use a job object. The idea is to create an anonymous pipe and let the child process inherit the handle to the write end of the pipe.
Typically, grandchild processes will also inherit the write end of the pipe. In particular, processes launched by `cmd.exe` (e.g., from a batch file) will inherit handles.
Once the child process has exited, the parent process closes its handle to the write end of the pipe, and then attempts to read from the pipe. Since nobody is writing to the pipe, the read operation will block indefinitely. (Of course you can use threads or asynchronous I/O if you want to keep doing stuff while waiting for the grandchildren.)
When (and only when) the last handle to the write end of the pipe is closed, the write end of the pipe is automatically destroyed. This breaks the pipe and the read operation completes and reports an ERROR\_BROKEN\_PIPE failure.
I've been using this code (and earlier versions of the same code) in production for a number of years.
```
// pwatch.c
//
// Written in 2011 by Harry Johnston, University of Waikato, New Zealand.
// This code has been placed in the public domain. It may be freely
// used, modified, and distributed. However it is provided with no
// warranty, either express or implied.
//
// Launches a process with an inherited pipe handle,
// and doesn't exit until (a) the process has exited
// and (b) all instances of the pipe handle have been closed.
//
// This effectively waits for any child processes to exit,
// PROVIDED the child processes were created with handle
// inheritance enabled. This is usually but not always
// true.
//
// In particular if you launch a command shell (cmd.exe)
// any commands launched from that command shell will be
// waited on.
#include <windows.h>
#include <stdio.h>
void error(const wchar_t * message, DWORD err) {
wchar_t msg[512];
swprintf_s(msg, sizeof(msg)/sizeof(*msg), message, err);
printf("pwatch: %ws\n", msg);
MessageBox(NULL, msg, L"Error in pwatch utility", MB_OK | MB_ICONEXCLAMATION | MB_SYSTEMMODAL);
ExitProcess(err);
}
int main(int argc, char ** argv) {
LPWSTR lpCmdLine = GetCommandLine();
wchar_t ch;
DWORD dw, returncode;
HANDLE piperead, pipewrite;
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
char buffer[1];
while (ch = *(lpCmdLine++)) {
if (ch == '"') while (ch = *(lpCmdLine++)) if (ch == '"') break;
if (ch == ' ') break;
}
while (*lpCmdLine == ' ') lpCmdLine++;
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe(&piperead, &pipewrite, &sa, 1)) error(L"Unable to create pipes: %u", GetLastError());
GetStartupInfo(&si);
if (!CreateProcess(NULL, lpCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
error(L"Error %u creating process.", GetLastError());
if (WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_FAILED) error(L"Error %u waiting for process.", GetLastError());
if (!GetExitCodeProcess(pi.hProcess, &returncode)) error(L"Error %u getting exit code.", GetLastError());
CloseHandle(pipewrite);
if (ReadFile(piperead, buffer, 1, &dw, NULL)) {
error(L"Unexpected data received from pipe; bug in application being watched?", ERROR_INVALID_HANDLE);
}
dw = GetLastError();
if (dw != ERROR_BROKEN_PIPE) error(L"Unexpected error %u reading from pipe.", dw);
return returncode;
}
``` | There is not a generic way to wait for all grandchildren but for your specific case you may be able to hack something together. You know you are looking for a specific process instance. I would first wait for uninstallA.exe to exit (using WaitForSingleObject) because at that point you know that uninstallB.exe has been started. Then use EnumProcesses and GetProcessImageFileName from PSAPI to find the running uninstallB.exe instance. If you don't find it you know it has already finished, otherwise you can wait for it.
An additional complication is that if you need to support versions of Windows older than XP you can't use GetProcessImageFileName, and for Windows NT you can't use PSAPI at all. For Windows 2000 you can use GetModuleFileNameEx but it has some caveats that mean it might fail sometimes (check docs). If you have to support NT then look up Toolhelp32.
Yes this is super ugly. |
1,683,902 | Is it possible to wait for all processes launched by a child process in Windows? I can't modify the child or grandchild processes.
Specifically, here's what I want to do. My process launches uninstallA.exe. The process uninistallA.exe launches uninstallB.exe and immediately exits, and uninstallB.exe runs for a while. I'd like to wait for uninstallB.exe to exit so that I can know when the uninstall is finished. | 2009/11/05 | [
"https://Stackoverflow.com/questions/1683902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11661/"
]
| Create a Job Object with `CreateJobObject`. Use `CreateProcess` to start `UninstallA.exe` in a suspended state. Assign that new process to your job object with `AssignProcessToJobObject`. Start UninstallA.exe running by calling `ResumeThread` on the handle of the thread you got back from `CreateProcess`.
Then the hard part: wait for the job object to complete its execution. Unfortunately, this is quite a bit more complex than anybody would reasonably hope for. The basic idea is that you create an I/O completion port, then you create the object object, associate it with the I/O completion port, and finally wait on the I/O completion port (getting its status with `GetQueuedCompletionStatus`). Raymond Chen has a demonstration (and explanation of how this came about) on his [blog](https://devblogs.microsoft.com/oldnewthing/20130405-00/?p=4743). | Here's a technique that, while not infallible, can be useful if for some reason you can't use a job object. The idea is to create an anonymous pipe and let the child process inherit the handle to the write end of the pipe.
Typically, grandchild processes will also inherit the write end of the pipe. In particular, processes launched by `cmd.exe` (e.g., from a batch file) will inherit handles.
Once the child process has exited, the parent process closes its handle to the write end of the pipe, and then attempts to read from the pipe. Since nobody is writing to the pipe, the read operation will block indefinitely. (Of course you can use threads or asynchronous I/O if you want to keep doing stuff while waiting for the grandchildren.)
When (and only when) the last handle to the write end of the pipe is closed, the write end of the pipe is automatically destroyed. This breaks the pipe and the read operation completes and reports an ERROR\_BROKEN\_PIPE failure.
I've been using this code (and earlier versions of the same code) in production for a number of years.
```
// pwatch.c
//
// Written in 2011 by Harry Johnston, University of Waikato, New Zealand.
// This code has been placed in the public domain. It may be freely
// used, modified, and distributed. However it is provided with no
// warranty, either express or implied.
//
// Launches a process with an inherited pipe handle,
// and doesn't exit until (a) the process has exited
// and (b) all instances of the pipe handle have been closed.
//
// This effectively waits for any child processes to exit,
// PROVIDED the child processes were created with handle
// inheritance enabled. This is usually but not always
// true.
//
// In particular if you launch a command shell (cmd.exe)
// any commands launched from that command shell will be
// waited on.
#include <windows.h>
#include <stdio.h>
void error(const wchar_t * message, DWORD err) {
wchar_t msg[512];
swprintf_s(msg, sizeof(msg)/sizeof(*msg), message, err);
printf("pwatch: %ws\n", msg);
MessageBox(NULL, msg, L"Error in pwatch utility", MB_OK | MB_ICONEXCLAMATION | MB_SYSTEMMODAL);
ExitProcess(err);
}
int main(int argc, char ** argv) {
LPWSTR lpCmdLine = GetCommandLine();
wchar_t ch;
DWORD dw, returncode;
HANDLE piperead, pipewrite;
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
char buffer[1];
while (ch = *(lpCmdLine++)) {
if (ch == '"') while (ch = *(lpCmdLine++)) if (ch == '"') break;
if (ch == ' ') break;
}
while (*lpCmdLine == ' ') lpCmdLine++;
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe(&piperead, &pipewrite, &sa, 1)) error(L"Unable to create pipes: %u", GetLastError());
GetStartupInfo(&si);
if (!CreateProcess(NULL, lpCmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
error(L"Error %u creating process.", GetLastError());
if (WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_FAILED) error(L"Error %u waiting for process.", GetLastError());
if (!GetExitCodeProcess(pi.hProcess, &returncode)) error(L"Error %u getting exit code.", GetLastError());
CloseHandle(pipewrite);
if (ReadFile(piperead, buffer, 1, &dw, NULL)) {
error(L"Unexpected data received from pipe; bug in application being watched?", ERROR_INVALID_HANDLE);
}
dw = GetLastError();
if (dw != ERROR_BROKEN_PIPE) error(L"Unexpected error %u reading from pipe.", dw);
return returncode;
}
``` |
21,706,747 | i try to add the option to my application to drag file into my `Listbox` instead of navigate into the file folder and this is what i have try:
```
private void Form1_Load(object sender, EventArgs e)
{
listBoxFiles.AllowDrop = true;
listBoxFiles.DragDrop += listBoxFiles_DragDrop;
listBoxFiles.DragEnter += listBoxFiles_DragEnter;
}
private void listBoxFiles_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
listBoxFiles.Items.Add(e.Data.ToString());
}
```
but instead of the full file path `e.Data.ToString()` `return System.Windows.Forms.DataObject` | 2014/02/11 | [
"https://Stackoverflow.com/questions/21706747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3271698/"
]
| This code I found [here](https://stackoverflow.com/questions/8550937/c-sharp-drag-and-drop-files-to-form):
```
private void Form1_Load(object sender, EventArgs e)
{
listBoxFiles.AllowDrop = true;
listBoxFiles.DragDrop += listBoxFiles_DragDrop;
listBoxFiles.DragEnter += listBoxFiles_DragEnter;
}
private void listBoxFiles_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
listBoxFiles.Items.Add(file);
}
``` | I tried using @AsfK's answer in WPF, had to delete
```
listBoxFiles.DragDrop += listBoxFiles_DragDrop;
```
from `public MainWindow()` else I got the dragged files duplicated.
Thanks! |
2,387,258 | I'm writing a CMS in ASP.NET/C#, and I need to process things like that, every page request:
```
<html>
<head>
<title>[Title]</title>
</head>
<body>
<form action="[Action]" method="get">
[TextBox Name="Email", Background=Red]
[Button Type="Submit"]
</form>
</body>
</html>
```
and replace the [...] of course.
My question is how should I implement it, with ANTLR or with Regex? What will be faster? Note, that if I'm implementing it with ANTLR I think that I will need to implement XML, in addon to the [..].
I will need to implement parameters, etc.
**EDIT:** Please note that my regex can even look like something like that:
```
public override string ToString()
{
return Regex.Replace(Input, @"\[
\s*(?<name>\w+)\s*
(?<parameter>
[\s,]*
(?<paramName>\w+)
\s*
=
\s*
(
(?<paramValue>\w+)
|
(""(?<paramValue>[^""]*)"")
)
)*
\]", (match) =>
{
...
}, RegexOptions.IgnorePatternWhitespace);
}
``` | 2010/03/05 | [
"https://Stackoverflow.com/questions/2387258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140937/"
]
| Whether the correct tool is RegEx or ANTLR or even something else entirely should be heavily dependent on your **requirements**. The best answer to a "what tool to use" question shouldn't be primarily based on *performance*, but on *the right tool for the job*.
RegEx is a text search tool. If all you need to do is pull strings out of strings then it's often the hammer of choice. You'll likely want a tool to help you build your RegEx. I'd recommend [Expresso](http://www.ultrapico.com/ExpressoDownload.htm), but there are lots of options out there.
ANTLR is a compiler generator. If you need error messages and parse actions or any of the complicated things that come with a compiler then it's a good option.
What it looks like you're doing is XML search/replace, have you considered XPath? That would be my suggestion.
Choosing the right tool for the job is definitely important, something that should be researched and thought out before development begins. In all cases, it's important to fully understand the program requirements before making any decisions. Do you have a specification for the project? If not, spending the time to come up with one will save you all the time that a poor tool choice can cost you.
Hope that helps! | About the performance of ANTLR vs. RegEx depends on the implementation of RegEx in C#. I know, from experience, that ANTLR is fast enough.
In ANTLR you can ignore certain content, like the XML. You can also seek for the `[` and `]` and go further with processing.
Both RegEx and ANTLR are supporting your kind of parameters (the "etc." I'm not sure about).
In terms of development speed: RegEx is slightly faster for such a case like this. You can use an online tool to develop the RegEx and see the capture-groups while you edit the RegEx. (Google @ `regex gskinner`)
Then ANTLR has perfect support for "error-messages": they show line/column numbers and what was wrong. RegEx doesn't have this support.
A general approach for RegEx would be: create a "global scan" RegEx which will find correct `[`...`]` groups in your content. Then let the "..." be captuerd by a group, and then apply another RegEx for this smaller content (which splits content based on the equal-sign and commas). This way you have the best runtime performance and it's easy to develop. |
2,387,258 | I'm writing a CMS in ASP.NET/C#, and I need to process things like that, every page request:
```
<html>
<head>
<title>[Title]</title>
</head>
<body>
<form action="[Action]" method="get">
[TextBox Name="Email", Background=Red]
[Button Type="Submit"]
</form>
</body>
</html>
```
and replace the [...] of course.
My question is how should I implement it, with ANTLR or with Regex? What will be faster? Note, that if I'm implementing it with ANTLR I think that I will need to implement XML, in addon to the [..].
I will need to implement parameters, etc.
**EDIT:** Please note that my regex can even look like something like that:
```
public override string ToString()
{
return Regex.Replace(Input, @"\[
\s*(?<name>\w+)\s*
(?<parameter>
[\s,]*
(?<paramName>\w+)
\s*
=
\s*
(
(?<paramValue>\w+)
|
(""(?<paramValue>[^""]*)"")
)
)*
\]", (match) =>
{
...
}, RegexOptions.IgnorePatternWhitespace);
}
``` | 2010/03/05 | [
"https://Stackoverflow.com/questions/2387258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140937/"
]
| About the performance of ANTLR vs. RegEx depends on the implementation of RegEx in C#. I know, from experience, that ANTLR is fast enough.
In ANTLR you can ignore certain content, like the XML. You can also seek for the `[` and `]` and go further with processing.
Both RegEx and ANTLR are supporting your kind of parameters (the "etc." I'm not sure about).
In terms of development speed: RegEx is slightly faster for such a case like this. You can use an online tool to develop the RegEx and see the capture-groups while you edit the RegEx. (Google @ `regex gskinner`)
Then ANTLR has perfect support for "error-messages": they show line/column numbers and what was wrong. RegEx doesn't have this support.
A general approach for RegEx would be: create a "global scan" RegEx which will find correct `[`...`]` groups in your content. Then let the "..." be captuerd by a group, and then apply another RegEx for this smaller content (which splits content based on the equal-sign and commas). This way you have the best runtime performance and it's easy to develop. | If the language you are parsing is **regular** then **regular expressions** are certainly an option. If it is not then ANTLR may be your only choice. If I understand these matters correctly XML is not regular. |
2,387,258 | I'm writing a CMS in ASP.NET/C#, and I need to process things like that, every page request:
```
<html>
<head>
<title>[Title]</title>
</head>
<body>
<form action="[Action]" method="get">
[TextBox Name="Email", Background=Red]
[Button Type="Submit"]
</form>
</body>
</html>
```
and replace the [...] of course.
My question is how should I implement it, with ANTLR or with Regex? What will be faster? Note, that if I'm implementing it with ANTLR I think that I will need to implement XML, in addon to the [..].
I will need to implement parameters, etc.
**EDIT:** Please note that my regex can even look like something like that:
```
public override string ToString()
{
return Regex.Replace(Input, @"\[
\s*(?<name>\w+)\s*
(?<parameter>
[\s,]*
(?<paramName>\w+)
\s*
=
\s*
(
(?<paramValue>\w+)
|
(""(?<paramValue>[^""]*)"")
)
)*
\]", (match) =>
{
...
}, RegexOptions.IgnorePatternWhitespace);
}
``` | 2010/03/05 | [
"https://Stackoverflow.com/questions/2387258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140937/"
]
| Whether the correct tool is RegEx or ANTLR or even something else entirely should be heavily dependent on your **requirements**. The best answer to a "what tool to use" question shouldn't be primarily based on *performance*, but on *the right tool for the job*.
RegEx is a text search tool. If all you need to do is pull strings out of strings then it's often the hammer of choice. You'll likely want a tool to help you build your RegEx. I'd recommend [Expresso](http://www.ultrapico.com/ExpressoDownload.htm), but there are lots of options out there.
ANTLR is a compiler generator. If you need error messages and parse actions or any of the complicated things that come with a compiler then it's a good option.
What it looks like you're doing is XML search/replace, have you considered XPath? That would be my suggestion.
Choosing the right tool for the job is definitely important, something that should be researched and thought out before development begins. In all cases, it's important to fully understand the program requirements before making any decisions. Do you have a specification for the project? If not, spending the time to come up with one will save you all the time that a poor tool choice can cost you.
Hope that helps! | If the language you are parsing is **regular** then **regular expressions** are certainly an option. If it is not then ANTLR may be your only choice. If I understand these matters correctly XML is not regular. |
34,958 | As per the title, what hardware do I need to be able to run various versions of Android? | 2012/12/07 | [
"https://android.stackexchange.com/questions/34958",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/1465/"
]
| Start with [the Android compatibility page](http://source.android.com/compatibility/index.html). This outlines goals for Android's compatibility and links to the current Compatibility Definition Document which has the technical requirements. All versions of the CDD to date are below.
* [Android 12](https://source.android.com/compatibility/12/android-12-cdd.pdf)
* [Android 11](https://source.android.com/compatibility/11/android-11-cdd.pdf)
* [Android 10](https://source.android.com/compatibility/10/android-10-cdd.pdf)
* [Android 9.0](https://source.android.com/compatibility/9/android-9-cdd.pdf) "Pie"
* [Android 8.0](https://source.android.com/compatibility/8.0/android-8.0-cdd.pdf) and [Android 8.1](https://source.android.com/compatibility/8.1/android-8.1-cdd.pdf) "Oreo"
* [Android 7.0](https://source.android.com/compatibility/7.0/android-7.0-cdd.pdf) and [Android 7.1](https://source.android.com/compatibility/7.1/android-7.1-cdd.pdf) "Nougat"
* [Android 6.0](https://source.android.com/compatibility/6.0/android-6.0-cdd.pdf) "Marshmallow"
* [Android 5.0](https://source.android.com/compatibility/5.0/android-5.0-cdd.pdf) and [Android 5.1](https://source.android.com/compatibility/5.1/android-5.1-cdd.pdf) "Lollipop"
* [Android 4.4](https://source.android.com/compatibility/4.4/android-4.4-cdd.pdf) "KitKat"
* [Android 4.3](http://source.android.com/compatibility/4.3/android-4.3-cdd.pdf), [Android 4.2](http://source.android.com/compatibility/4.2/android-4.2-cdd.pdf) and [Android 4.1](http://source.android.com/compatibility/4.1/android-4.1-cdd.pdf) "Jelly Bean"
* [Android 4.0](http://source.android.com/compatibility/4.0/android-4.0-cdd.pdf) "Ice Cream Sandwich"
* Android 3.0 "Honeycomb" not available (since it was not a public open-source release)
* [Android 2.3](http://source.android.com/compatibility/2.3/android-2.3-cdd.pdf) "Gingerbread"
* [Android 2.2](http://source.android.com/compatibility/2.2/android-2.2-cdd.pdf) "Froyo"
* [Android 2.1](http://source.android.com/compatibility/2.1/android-2.1-cdd.pdf) "Eclair"
* [Android 1.6](http://source.android.com/compatibility/1.6/android-1.6-cdd.pdf) "Donut"
These are also linked to from [the Android Compatibility Downloads page](http://source.android.com/compatibility/downloads.html) which also includes test suites.
>
> There is no Compatibility Program for older versions of Android, such as Android 1.5 (known in development as Cupcake). New devices intended to be Android compatible must ship with Android 1.6 or later.
>
>
>
Notable points:
* The absolute minimum requirements for Android were originally [a 200 MHz processor, 32 MB of RAM, and 32 MB of storage](https://android.stackexchange.com/a/14663/1465).
* Out of the box, [Android is incompatible with ARMv4 or lower](https://android.stackexchange.com/q/686/1465#comment9905_5353); ARMv5 or higher is needed to run native code without modifications.
* Android 4.4+ requires an ARMv7 processor. Custom versions have been made for ARMv6, however.
The requirements in these documents must be met for a device to be "Google Approved" and ship with the official Google apps such as the Play Store and Google Talk. However, they are not necessarily hard requirements. Since Android is open-source it can be modified to run on lesser hardware, and the opposite is possible as well — modifications necessary to run the OS on a device may make the firmware image too large to fit on it, just for example. | Here follows a somewhat simpler answer regarding the **RAM memory requirements**. According to the above mentioned docs, all versions from "Lollipop" (Android 5.0) up to Android 11 need at least **416 MB** memory. This is true if the default display uses "framebuffer resolutions up to qHD (e.g. FWVGA)". Higher resolutions need more memory.
For Android 7.1. "Nougat" and earlier, handhelds with 512MB RAM or less must have `ActivityManager#isLowRamDevice` set to `true`. [[1]](https://source.android.com/compatibility/7.1/android-7.1-cdd.pdf#page=70&zoom=100,80,580)
From Android 8.0 "Oreo" onwards, this flag must be set for handhelds that have 1GB RAM or less. [[2]](https://source.android.com/compatibility/8.0/android-8.0-cdd.pdf#page=8&zoom=100,80,780)
* [1] — [Android 7.1 CDD; §7.6.1 Minimum Memory and Storage; paragraph 3](https://source.android.com/compatibility/7.1/android-7.1-cdd.pdf#page=70&zoom=100,80,580)
* [2] — [Android 8.0 CDD; §2.2.1 Handheld requirements, Hardware; requirement [7.6.1/H-0-2]](https://source.android.com/compatibility/8.0/android-8.0-cdd.pdf#page=8&zoom=100,80,780) |
54,683,476 | I am dispatching data from one component to use in other components.
When i am dispatching subscribe is calling multiple times.
On click of button i am dispatching
```
appStore.dispatch(new SetSearch(value));
```
I am listing in other component
```
appStore.select<ISearch>(AppState.Search)
.pipe(
takeUntil(this.unsubscribe$), skip(1)
)
.subscribe(SearchState => {
if (SearchState.account !== '')
```
calling one for method here to save.In that method i am dispatching to save that value,on subscribe i am calling other method to load data and dispatching. | 2019/02/14 | [
"https://Stackoverflow.com/questions/54683476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6164719/"
]
| Your nested subscriptions must be creating a cycle execution due to changes in state that are introduced, perhaps repeated, and then the cycle ends due to no changes in value. If you are dispatching additional actions inside of that subscription, those actions might affect the state of the appStore and therefore retrigger the current subscription to execute once more. In this case, then you'll observe multiple subscriptions until your store is no longer reacting to additional changes to state. The type of operation occuring in the reducer determines how long this cycle can last. If you are setting a field and changing it's value, then you might see two dispatches, as the appStore changes from an initial value to a new value, and due to a dispatch nested in a subscription, you are seeing multiple subscription events. If you are using some other form of mutation on the reducer during dispatches you may have longer cycles of execution. The way to mitigate this is to compare your state and do not fire additional dispatches if your state is already in the right format. This is something you can add another conditional control structure as a remedy.
Also as an addendum, if you have effects that are reacting to the dispatch then that can also trigger additional subscription events, thus leading to further cycles of execution inside of your subscription. Especially if you use the traditional subscription execution dispatches REQUEST -> effect dispatches {SUCCESS | ERROR} actions that also modify your state, such as a loading field, or an error flag. | Read this issue
<https://github.com/ngxs/store/issues/477>
and see the example from here <https://stackblitz.com/edit/angular-gxh1sr> |
21,963,284 | I want to create a chat system, which has a free and a paid chats. Paid chat differs from a free one only with one property ("Price"). So paid chat inherits a free chat and adds one property to it. Also I don't want to have Paid chats with unset price. So I create a custom public constructor and leave private default constructor (so EF will be able to materialize paid chat instance).
Here is the code:
```
namespace EfTest
{
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Data.Entity.Migrations;
using System.Diagnostics;
public class User
{
public string Id { get; set; }
public virtual List<Chat> Chats { get; set; }
}
public class Chat
{
public string Id { get; set; }
public virtual List<User> Users { get; set; }
public Chat()
{
this.Users = new List<User>();
}
}
public class PaidChat : Chat
{
public int Price { get; set; }
/* PRIVATE MODIFICATOR CAUSES THE ISSUE */
private PaidChat() { }
public PaidChat(int price)
{
Price = price;
}
}
public class TestContext : DbContext
{
public DbSet<Chat> Chats { get; set; }
public DbSet<User> Members { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<PaidChat>().ToTable("PaidChat");
base.OnModelCreating(modelBuilder);
}
}
class Program
{
static void Main()
{
const string ChatId = "1";
using (var dbContext = new TestContext())
{
var user1 = new User { Id = "1" };
var user2 = new User { Id = "2" };
dbContext.Members.AddOrUpdate(m => m.Id, user1, user2);
var paidChat = new PaidChat(50) { Id = ChatId };
paidChat.Users.AddRange(new[] { user1, user2 });
dbContext.Chats.AddOrUpdate(c => c.Id, paidChat);
dbContext.SaveChanges();
}
using (var dbContext = new TestContext())
{
var queryResult = (from chat in dbContext.Chats
where chat.Id == ChatId
select new
{
Chat = chat,
Users = chat.Users
}).Single();
Debug.Assert(queryResult.Users.Count == 2);
Debug.Assert(queryResult.Chat.Users.Count == 2); // !!! HERE WE HAVE A PROBLEM !!!
}
}
}
}
```
And private default ctor of PaidChat prevents EF to pick-up Users refecences.
Even though a proper amount of users is retrieved from DB:
```
Debug.Assert(queryResult.Users.Count == 2);
```
I can't access them from a chat instance:
```
Debug.Assert(queryResult.Chat.Users.Count == 2); // !!! HERE WE HAVE A PROBLEM !!!
```
The issue I have with EF 5.0 and EF 6.0.2.
Is it a bug? Or maybe there is some reason why EF team implemented it that way?
Any explanation will be highly appreciated! | 2014/02/23 | [
"https://Stackoverflow.com/questions/21963284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/643121/"
]
| There's no supported way of doing this. However, using Javascript, you can get it done. Here's some steps / code:
### Wait for the Webview Loading to Complete
GTMOAuth2ViewControllerTouch defines a NSNotification that you can observe through the NSNotificationCenter. It's **kGTMOAuth2WebViewStoppedLoading**:
```
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(authControllerWebViewStoppedLoading:)
name:kGTMOAuth2WebViewStoppedLoading
object:nil];
```
The NSNotification object's userInfo dictionary will have a reference to the webview in it. GTMOAuth2ViewControllerTouch also allows public access to the webview. I used the latter in my app.
### Use Javascript to Change the Email Input Entity
First, you should know that you can get the HTML of the page the webview is showing like so:
```
NSString *html = [self.authController.webView
stringByEvaluatingJavaScriptFromString:
@"document.body.innerHTML"];
```
You don't need it for this solution, but it will allow you to confirm that the HTML for the Email input entity still looks like the following:
```
<input id="Email" name="Email" type="email"
placeholder="Email" value="" spellcheck="false" class="">
```
Once you know that email input entity, you can then use javascript to change its text value:
```
- (void)authControllerWebViewStoppedLoading:(NSNotification *)notification
{
// Assume emailAddress is a property that holds the email address you
// you want to pre-populate the Email entity with....
NSString *javascript = [NSString stringWithFormat:
@"var elem = document.getElementById(\"Email\");"
@"elem.value = \"%@\";", self.emailAddress];
[self.authController.webView
stringByEvaluatingJavaScriptFromString:javascript];
}
```
### That's It
Obviously this solution runs the risk of having Google change things on their end without checking with you first. But, the worst that happens in that case is that the email stops pre-populating and your user has to type it in manually, at least until you can release an update.
Hope this helps. | I believe there is an easier way than using Javascript. Once you've created your controller, get GTMOAuth2SignIn and add additionalAuthorizationParameters with the user email address.
```
#import "GTMOAuth2SignIn.h"
GTMOAuth2ViewControllerTouch *authViewController =
[[GTMOAuth2ViewControllerTouch alloc] initWithScope:kGTLAuthScopeDriveFile
clientID:kClientId
clientSecret:kClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:finishedSelector];
GTMOAuth2SignIn *signIn = authViewController.signIn;
signIn.additionalAuthorizationParameters = @{@"login_hint" : @"[email protected]"};
```
This is from the parameters list for OAuth2 for Installed Applications:
<https://developers.google.com/accounts/docs/OAuth2InstalledApp#formingtheurl>
This worked for me at least. |
8,562,928 | It's a remote server so no GUI or fancy stuff installed, I connect to that host using SSH.
For security reasons I suppose, I cannot use the 'date -s' command to change the local server's current time.
```
$ cat /etc/issues ==> Ubuntu 10.04 LTS
$ uname -r ==> 2.6.32-042stab037.1
$ cat $SHELL ==> /bin/bash
```
'date' shows me time that is about 10 minutes early, I tried linking the right time from /usr/share/zoneinfo (New york in my case) to /etc/localtime, but nothing really changed, my clock is still 10 minutes unsynchronized.
Do I have to generate a new time zone binary using zic? Yes? how? no? What else could I try ?
Thanks a bunch in advance.
/s | 2011/12/19 | [
"https://Stackoverflow.com/questions/8562928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452069/"
]
| Use persistent data to be associated with client
------------------------------------------------
Use `$_SESSION` to associate data with the current client, don't forget to call `session_start ();` before you actually append data to the array.
*Note: This will require the use of cookies in the client*
---
Include functionality into one file
-----------------------------------
Though if the only purpose of the page where the data is posted is to validate data, do that and then you could `include ("payment.php");`, no redirects required.
Or put the functionality of the form-landing page in `payment.php` instead.
---
Use a GET-parameter sent to payment.php
---------------------------------------
You could also redirect to `payment.php?id=<val>` where `<val>` is the id of the transaction, though you should not expose the real id since this will decrease security.
Unless you check to see so that a user can only access `id`s who actually belongs to them.
A hash of the payment info can be used instead since this value will not easily, or at all, be guessed. | Just start a session before doing anything in the two pages.
```
<?php session_start()
```
and on the verification page do something like
```
$_SESSION['email'] = $email;
```
and finally on the payment page you can get the email then via
```
$email = $_SESSION['email'];
``` |
8,562,928 | It's a remote server so no GUI or fancy stuff installed, I connect to that host using SSH.
For security reasons I suppose, I cannot use the 'date -s' command to change the local server's current time.
```
$ cat /etc/issues ==> Ubuntu 10.04 LTS
$ uname -r ==> 2.6.32-042stab037.1
$ cat $SHELL ==> /bin/bash
```
'date' shows me time that is about 10 minutes early, I tried linking the right time from /usr/share/zoneinfo (New york in my case) to /etc/localtime, but nothing really changed, my clock is still 10 minutes unsynchronized.
Do I have to generate a new time zone binary using zic? Yes? how? no? What else could I try ?
Thanks a bunch in advance.
/s | 2011/12/19 | [
"https://Stackoverflow.com/questions/8562928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452069/"
]
| Use persistent data to be associated with client
------------------------------------------------
Use `$_SESSION` to associate data with the current client, don't forget to call `session_start ();` before you actually append data to the array.
*Note: This will require the use of cookies in the client*
---
Include functionality into one file
-----------------------------------
Though if the only purpose of the page where the data is posted is to validate data, do that and then you could `include ("payment.php");`, no redirects required.
Or put the functionality of the form-landing page in `payment.php` instead.
---
Use a GET-parameter sent to payment.php
---------------------------------------
You could also redirect to `payment.php?id=<val>` where `<val>` is the id of the transaction, though you should not expose the real id since this will decrease security.
Unless you check to see so that a user can only access `id`s who actually belongs to them.
A hash of the payment info can be used instead since this value will not easily, or at all, be guessed. | Once you update your payment, create/ get your GUID or your unique id from your DB, and redirect to your success page with your guid or unique id, exposing this id will not harm anyway. |
8,562,928 | It's a remote server so no GUI or fancy stuff installed, I connect to that host using SSH.
For security reasons I suppose, I cannot use the 'date -s' command to change the local server's current time.
```
$ cat /etc/issues ==> Ubuntu 10.04 LTS
$ uname -r ==> 2.6.32-042stab037.1
$ cat $SHELL ==> /bin/bash
```
'date' shows me time that is about 10 minutes early, I tried linking the right time from /usr/share/zoneinfo (New york in my case) to /etc/localtime, but nothing really changed, my clock is still 10 minutes unsynchronized.
Do I have to generate a new time zone binary using zic? Yes? how? no? What else could I try ?
Thanks a bunch in advance.
/s | 2011/12/19 | [
"https://Stackoverflow.com/questions/8562928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452069/"
]
| I think you should go back and check why `mysql_insert_id()` isn't working. That'll be the best way to get the data across. | Just start a session before doing anything in the two pages.
```
<?php session_start()
```
and on the verification page do something like
```
$_SESSION['email'] = $email;
```
and finally on the payment page you can get the email then via
```
$email = $_SESSION['email'];
``` |
8,562,928 | It's a remote server so no GUI or fancy stuff installed, I connect to that host using SSH.
For security reasons I suppose, I cannot use the 'date -s' command to change the local server's current time.
```
$ cat /etc/issues ==> Ubuntu 10.04 LTS
$ uname -r ==> 2.6.32-042stab037.1
$ cat $SHELL ==> /bin/bash
```
'date' shows me time that is about 10 minutes early, I tried linking the right time from /usr/share/zoneinfo (New york in my case) to /etc/localtime, but nothing really changed, my clock is still 10 minutes unsynchronized.
Do I have to generate a new time zone binary using zic? Yes? how? no? What else could I try ?
Thanks a bunch in advance.
/s | 2011/12/19 | [
"https://Stackoverflow.com/questions/8562928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452069/"
]
| Just start a session before doing anything in the two pages.
```
<?php session_start()
```
and on the verification page do something like
```
$_SESSION['email'] = $email;
```
and finally on the payment page you can get the email then via
```
$email = $_SESSION['email'];
``` | Once you update your payment, create/ get your GUID or your unique id from your DB, and redirect to your success page with your guid or unique id, exposing this id will not harm anyway. |
8,562,928 | It's a remote server so no GUI or fancy stuff installed, I connect to that host using SSH.
For security reasons I suppose, I cannot use the 'date -s' command to change the local server's current time.
```
$ cat /etc/issues ==> Ubuntu 10.04 LTS
$ uname -r ==> 2.6.32-042stab037.1
$ cat $SHELL ==> /bin/bash
```
'date' shows me time that is about 10 minutes early, I tried linking the right time from /usr/share/zoneinfo (New york in my case) to /etc/localtime, but nothing really changed, my clock is still 10 minutes unsynchronized.
Do I have to generate a new time zone binary using zic? Yes? how? no? What else could I try ?
Thanks a bunch in advance.
/s | 2011/12/19 | [
"https://Stackoverflow.com/questions/8562928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452069/"
]
| I think you should go back and check why `mysql_insert_id()` isn't working. That'll be the best way to get the data across. | Once you update your payment, create/ get your GUID or your unique id from your DB, and redirect to your success page with your guid or unique id, exposing this id will not harm anyway. |
389,247 | The following illustration of a generic box appears on p. 63 of the TeXbook:
[](https://i.stack.imgur.com/OYHsW.png)
What is a box's reference point in the following pathological cases?
1. The box has either (a) no width, or (b) no height and no depth, or (c) both a and b?
2. The box has a positive width and either a positive height or a positive depth (or both), which were not explicitly assigned but calculated automatically, and one of the following cases holds.
1. The box doesn't contain sub-boxes (but may contain other elements, e.g. glue)?
2. The box contains at least one sub-box, but some of the sub-boxes -- possibly all of them! -- is shifted to the left or to the right, or raised or lowered? | 2017/08/31 | [
"https://tex.stackexchange.com/questions/389247",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/21685/"
]
| Every box has height width and depth (any of which may be zero or negative) the reference point is by definition the point from which these lengths are measured. The box containing other boxes or not has no bearing on that.
Note that the height depth and width are *assignable* properties and need bear no relationship to the box contents.
If `\box0` contains some content then after
```
\ht0=5pt
\dp0=6pt
\wd0=7pt
```
the height depth and width of box 0 will be 5pt 6pt and 7pt. In horizontal mode, the box will be positioned such that its reference point is placed at the current position, and the current position will move 7pt to the right (whatever the box contents). Similarly in vertical mode the box will be placed with baselineskip glue from the previous box calculated from the previous depth and the nominal 5pt height.
---
If you do not assign the box dimensions then they will be set depending on the box contents.
if set using `\vbox` the reference point of the box is at the left edge, at the vertical position of the last box in its content (with some details to be filled in if the last item is not a box or has over-large deoth)
If set using vtop the reference point is at the left edge at the height of the reference point of the first item of the content if it is a box, or at the top of the outer box otherwise.
For \vcenter it is a at the left edge of the box positined such that placing the reference point on teh baseline centres the box on the math axis. | There are only a few ways to create boxes in TeX, and each of them has a well-defined notion of where the reference point ends up. See page 222 of *The TeXbook* (part of *Chapter 21: Making Boxes*):
>
> Now let’s summarize all of the ways there are to specify boxes explicitly to TeX. (1) A character by itself makes a character box, in horizontal mode; this character is taken from the current font. (2) The commands `\hrule` and `\vrule` make rule boxes, as just explained. (3) Otherwise you can make hboxes and vboxes, which fall under the generic term ⟨box⟩. A ⟨box⟩ has one of the following seven forms:
>
>
> `\hbox`⟨box specification⟩`{`⟨horizontal material⟩`}` (see Chapter 12)
>
> `\vbox`⟨box specification⟩`{`⟨vertical material⟩`}` (see chapter 12)
>
> `\vtop`⟨box specification⟩`{`⟨vertical material⟩`}` (see Chapter 12)
>
> `\box`⟨register number⟩ (see Chapter 15)
>
> `\copy`⟨register number⟩ (see Chapter 15)
>
> `\vsplit`⟨register number⟩`to`⟨dimen⟩ (see Chapter 15)
>
> `\lastbox` (see Chapter 21)
>
>
> […]
>
>
> In math modes an additional type of box is available: `\vcenter`⟨box specification⟩{⟨vertical material⟩} (see Chapter 17).
>
>
>
For each of these, there is a well-defined procedure for where the reference point ends up, based on the reference points of its constituents. Characters from a font already come w.r.t. a reference point. For the others, it's best to see this in pictures (taken from *A Beginner's Book of TeX*'s *Chapter 8: Boxes*, which I recommend reading):
[](https://i.stack.imgur.com/YWSmZ.png)
[](https://i.stack.imgur.com/rW89n.png)
While creating the box, you can specify the width to be positive or zero or negative (instead of letting TeX compute them from the things you put inside it). You can raise or lower boxes. You can explicitly assign the width or height or depth of a box, to change them. But in all cases the behaviour is predictable and well-defined, so the answer is just: the reference point is wherever you asked TeX to put it. :-) If you know how you made the box, you'll also know where its reference point is. |
59,859 | I'm trying to test a simple WebForms (asp.net) based UI, and follow the MVP pattern to allow my UI to be more testable.
As I follow the TDD methodology for backend algorithms, I find that there are some unit test refactorings that happen in the spirit of the DRY principle (Don't Repeat Yourself). As I try to apply this to the UI using Rhino Mocks to verify my interactions, I see many commonalities in the Controller tests when setting up the view or model expectations.
My question is: how far do you typically take this refactoring, if at all? I'm curious to see how other TDDer's test their MVC/MVP based UIs. | 2008/09/12 | [
"https://Stackoverflow.com/questions/59859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
]
| I would not refactor tests like standard code. Tests start to become more obscure as you refactor things into common base classes, helper methods, etc. Tests should be sufficiently clear on their own.
DRY is not a test concern.
That said, there are many plumbing things that are commonly done, and those should be abstracted away. | I use MVP, and on my tests I try to apply most of the refactoring I would in standard code. It normally doesn't work quite as well on the tests, due to the slight variations needed to test different scenarios, but within parts there can be commonality, and when possible I do consolidate. This does ease the needed changes later as the project evolves; just like in your standard code it is easier to change one place instead of 20. |
59,859 | I'm trying to test a simple WebForms (asp.net) based UI, and follow the MVP pattern to allow my UI to be more testable.
As I follow the TDD methodology for backend algorithms, I find that there are some unit test refactorings that happen in the spirit of the DRY principle (Don't Repeat Yourself). As I try to apply this to the UI using Rhino Mocks to verify my interactions, I see many commonalities in the Controller tests when setting up the view or model expectations.
My question is: how far do you typically take this refactoring, if at all? I'm curious to see how other TDDer's test their MVC/MVP based UIs. | 2008/09/12 | [
"https://Stackoverflow.com/questions/59859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
]
| I would not refactor tests like standard code. Tests start to become more obscure as you refactor things into common base classes, helper methods, etc. Tests should be sufficiently clear on their own.
DRY is not a test concern.
That said, there are many plumbing things that are commonly done, and those should be abstracted away. | I'd prefer to treat unit test as pure functional programs, to avoid to have to test them. If an operation is enough common in between tests, then I would evaluate it for the standard codebase, but even then I'd avoid refactoring tests, because I tend to have lots of them, specially for gui driven BL. |
59,859 | I'm trying to test a simple WebForms (asp.net) based UI, and follow the MVP pattern to allow my UI to be more testable.
As I follow the TDD methodology for backend algorithms, I find that there are some unit test refactorings that happen in the spirit of the DRY principle (Don't Repeat Yourself). As I try to apply this to the UI using Rhino Mocks to verify my interactions, I see many commonalities in the Controller tests when setting up the view or model expectations.
My question is: how far do you typically take this refactoring, if at all? I'm curious to see how other TDDer's test their MVC/MVP based UIs. | 2008/09/12 | [
"https://Stackoverflow.com/questions/59859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
]
| I would not refactor tests like standard code. Tests start to become more obscure as you refactor things into common base classes, helper methods, etc. Tests should be sufficiently clear on their own.
DRY is not a test concern.
That said, there are many plumbing things that are commonly done, and those should be abstracted away. | I use selenium for functional testing
and I'm using JUnit to test my controllers.
I'll mock out services or resources used by the controller and test to see what URI the controller is redirecting to, etc...
The only thing I'm not really testing at this point are the views. But I have employed functional testing to compensate. |
35,330,015 | I've written this code to sort an array using selection sort, but it doesn't sort the array correctly.
```
#include <cstdlib>
#include <iostream>
using namespace std;
void selectionsort(int *b, int size)
{
int i, k, menor, posmenor;
for (i = 0; i < size - 1; i++)
{
posmenor = i;
menor = b[i];
for (k = i + 1; k < size; k++)
{
if (b[k] < menor)
{
menor = b[k];
posmenor = k;
}
}
b[posmenor] = b[i];
b[i] = menor;
}
}
int main()
{
typedef int myarray[size];
myarray b;
for (int i = 1; i <= size; i++)
{
cout << "Ingrese numero " << i << ": ";
cin >> b[i];
}
selectionsort(b, size);
for (int l = 1; l <= size; l++)
{
cout << b[l] << endl;
}
system("Pause");
return 0;
}
```
I can't find the error. I'm new to C++.
Thanks for help. | 2016/02/11 | [
"https://Stackoverflow.com/questions/35330015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4186862/"
]
| The `selectionSort()` function is fine. Array init and output is not. See below.
```
int main()
{
int size = 10; // for example
typedef int myarray[size];
myarray b;
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<"Ingrese numero "<<i<<": ";
cin>>b[i];
}
selectionsort(b,size);
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<b[l]<<endl;
}
system("Pause");
return 0;
}
```
In C and C++, an array with `n` elements starts with the `0` index, and ends with the `n-1` index. For your example, the starting index is `0` and ending index is `9`. When you iterate like you do in your posted code, you check if the index variable is less than (*or not equal to*) the size of the array, i.e. `size`. Thus, on the *last step* of your iteration, you access `b[size]`, accessing the location in memory next to the last element in the array, which is not guaranteed to contain anything meaningful (being uninitialized), hence the random numbers in your output. | You provided some sample input in the comments to your question.
I compiled and executed the following, which I believe accurately reproduces your shown code, and your sample input:
```
#include <iostream>
void selectionsort(int* b, int size)
{
int i, k, menor, posmenor;
for(i=0;i<size-1;i++)
{
posmenor=i;
menor=b[i];
for(k=i+1;k<size;k++)
{
if(b[k]<menor)
{
menor=b[k];
posmenor=k;
}
}
b[posmenor]=b[i];
b[i]=menor;
}
}
int main(int argc, char **argv)
{
int a[10] = {-3, 100, 200, 2, 3, 4, -4, -5, 6, 0};
selectionsort(a, 10);
for (auto v:a)
{
std::cout << v << ' ';
}
std::cout << std::endl;
}
```
The resulting output was as follows:
```
-5 -4 -3 0 2 3 4 6 100 200
```
These results look correct. I see nothing wrong with your code, and by using the sample input you posted, this confirms that. |
20,048,851 | I have problem with my Arduino app in Qt 5.1.1
I have used QextSerialPort and then I wanted to upgrade to QtSerialPort which is a part of Qt5.1.1
The app was working with QextSerialPort.
So I have only changed some things but in core it should be the same. Therefore I am wondering why I can't connect to Arduino.
When asking for errorString() the answer is 'handle is invalid'
This is my code:
```
void MainWindow::init_schnittstelle()
{
port = new QSerialPort; //create the port
port->setPortName(schnittstelle); //create the port
port->setBaudRate(QSerialPort::Baud115200);
port->setFlowControl(QSerialPort::NoFlowControl);
port->setParity(QSerialPort::NoParity);
port->setDataBits(QSerialPort::Data8);
port->setStopBits(QSerialPort::OneStop);
port->open(QIODevice::ReadWrite | QIODevice::Unbuffered); //open the port
schnittstelleZustand = port->errorString();
if(!port->isOpen())
{
QMessageBox::warning(this, "Schnittstelle", "Schnittstelle "+schnittstelle+" reagiert nicht. "+schnittstelleZustand);
}
else{
schnittstelleZustand = ("verbunden");
}
}
```
In the variable schnittstelle is given the address. I can connect to arduino per Arduino software so I am sure that my Arduino is on COM10 but this says me it is not...
What's wrong? | 2013/11/18 | [
"https://Stackoverflow.com/questions/20048851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3004824/"
]
| I checked Qt documentation and I saw:
>
> Warning: The mode has to be QIODevice::ReadOnly, QIODevice::WriteOnly, or QIODevice::ReadWrite. Other modes are unsupported.
>
>
>
Change your code
```
port->open(QIODevice::ReadWrite | QIODevice::Unbuffered);
```
to
```
port->open(QIODevice::ReadWrite);
```
and try again.
There is documentation link
<http://qt-project.org/doc/qt-5/qserialport.html#open> | <http://qt-project.org/doc/qt-5.1/qtserialport/qserialport.html#details>
>
> Provides functions to access serial ports.
>
>
> You can get information
> about the available serial ports using the `QSerialPortInfo` helper
> class, which allows an enumeration of all the serial ports in the
> system. This is useful to obtain the correct name of the serial port
> you want to use. You can pass an object of the helper class as an
> argument to the `setPort()` or `setPortName()` methods to assign the
> desired serial device.
>
>
>
Try enumerating your ports using a `QSerialPortInfo` object, and then print out the port names.
<http://qt-project.org/doc/qt-5.1/qtserialport/qserialportinfo.html#portName>
After you have a valid port name, your invalid handle should go away.
Hope that helps. |
21,128,984 | In my UserForm, I want to set a default value for my TextBox, that will highlight when focused upon.
```
Private Sub UserForm_Initialize()
NameTextBox.Value = "Your Name Here"
NameTextBox.SetFocus
End Sub
```
When this code runs, the cursor should set at the end of the default text, i.e. after "...Here". I want "Your Name Here" to be highlighted so that when the form is generated, the user can start replacing that default/placeholder text.
Can you help me write the code to set default values that are editable? | 2014/01/15 | [
"https://Stackoverflow.com/questions/21128984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2569531/"
]
| This will select all the text in the TextBox:
```
Private Sub UserForm_Initialize()
With Me.NameTextBox
.Value = "Your Name Here"
.SetFocus
.SelStart = 0
.SelLength = Len(.Text)
End With
End Sub
``` | how about this line of code when your form loads?
```
NameTextBox.SelectAll()
``` |
21,128,984 | In my UserForm, I want to set a default value for my TextBox, that will highlight when focused upon.
```
Private Sub UserForm_Initialize()
NameTextBox.Value = "Your Name Here"
NameTextBox.SetFocus
End Sub
```
When this code runs, the cursor should set at the end of the default text, i.e. after "...Here". I want "Your Name Here" to be highlighted so that when the form is generated, the user can start replacing that default/placeholder text.
Can you help me write the code to set default values that are editable? | 2014/01/15 | [
"https://Stackoverflow.com/questions/21128984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2569531/"
]
| This will select all the text in the TextBox:
```
Private Sub UserForm_Initialize()
With Me.NameTextBox
.Value = "Your Name Here"
.SetFocus
.SelStart = 0
.SelLength = Len(.Text)
End With
End Sub
``` | Set the `EnterFieldBehavior` property to `frmEnterFieldBehaviorSelectAll` so that when the focus goes to that field, the whole field is selected. |
46,101,677 | I'm a learner of JavaScript and have a problem with Mapbox GL JS: I have a style in Mapbox Studio, where there is [one my layer — "locations"](https://i.stack.imgur.com/0MkFF.png). I've added it as a tileset. There are two GeoJSON-points in this layer, but I can't get them in GL JS.
I've found that I should use method `querySourceFeatures(sourceID, [parameters])`, but I have problems with correct filling its parameters. I wrote:
```
var allFeatures = map.querySourceFeatures('_id-of-my-tyleset_', {
'sourceLayer': 'locations'
});
```
..and it doesn't work.
More interesting, that later in the code I use this layer with method `queryRenderedFeatures`, and it's okay:
```
map.on('click', function(e) {
var features = map.queryRenderedFeatures(e.point, {
layers: ['locations']
});
if (!features.length) {
return;
}
var feature = features[0];
flyToPoint(feature);
var popup = new mapboxgl.Popup({
offset: [0, -15]
})
.setLngLat(feature.geometry.coordinates)
.setHTML('<h3>' + feature.properties.name + '</h3>' + '<p>' +
feature.properties.description + '</p>')
.addTo(map);
});
```
I have read a lot about adding layers on a map and know that the answer is easy, but I can't realise the solution, so help, please :)
[Here is](https://github.com/nikita-nikiforov/bilhorod-map/blob/master/index.html) the project on GitHub. | 2017/09/07 | [
"https://Stackoverflow.com/questions/46101677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7948652/"
]
| Your problem is that your map, like all maps created in Mapbox Studio by default, uses auto-compositing. You don't actually have a source called `morganvolter.cj77n1jkq1ale33jw0g9haxc0-2haga`, you have a source called `composite` with many sub layers.
You can find the list of layers like this:
`map.getSource('composite').vectorLayerIds`
Which reveals you have a vector layer called `akkerman`. ("`locations`" is the name of your **style** layer, not your **source** layer). Hence your query should be:
```
map.querySourceFeatures('composite', {
'sourceLayer': 'akkerman'
});
```
Which returns 4 features. | There are lots of questions about `Mapbox get features after filter` or `Mapbox get features before filter`. And I could see there are many posts are scattering around but none of them seem to have a `FULL DETAILED` solution. I spend some time and put both solution together under a function, try this in jsbin.
Here it is for someone interested:
```
function buildRenderedFeatures(map) {
// get source from a layer, `mapLayerId` == your layer id in Mapbox Studio
var compositeSource = map.getLayer(mapLayerId.toString()).source;
//console.log(map.getSource(compositeSource).vectorLayers);
var compositeVectorLayerLength = map.getSource(compositeSource).vectorLayers.length - 1;
//console.log(compositeVectorLayerLength);
// sourceId === tileset id which is known as vector layer id
var sourceId = map.getSource(compositeSource).vectorLayers[compositeVectorLayerLength].id;
//console.log(sourceId);
// get all applied filters if any, this will return an array
var appliedFilters = map.getFilter(mapLayerId.toString());
//console.log(appliedFilters);
// if you want to get all features with/without any filters
// remember if no filters applied it will show all features
// so having `filter` does not harm at all
//resultFeatures = map.querySourceFeatures(compositeSource, {sourceLayer: sourceId, filter: appliedFilters});
var resultFeatures = null;
// this fixes issues: queryRenderedFeatures getting previous features
// a timeout helps to get the updated features after filter is applied
// Mapbox documentation doesn't talk about this!
setTimeout(function() {
resultFeatures = map.queryRenderedFeatures({layers: [mapLayerId.toString()]});
//console.log(resultFeatures);
}, 500);
}
```
Then you call that function like: `buildRenderedFeatures(map)` passing the `map` object which you already have when you created the Mapbox map.
You will then have `resultFeatures` will return an object which can be iterated using `for...in`. You can test the `querySourceFeatures()` code which I commented out but left for if anyone needs it. |
53,159,639 | I'm trying to create an HTML email template that displays a bar code of a single-use coupon code dynamically in Netsuite through marketing campaign using this
```
<barcode codetype="code128" showtext="true" value="${campaignEvent.couponCode}"/>
```
and nothing is showing up, but when I try to print out the coupon code using `${campaignEvent.couponCode}` it is getting printed correctly | 2018/11/05 | [
"https://Stackoverflow.com/questions/53159639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9555068/"
]
| As already answered, BFO is only used for PDF generation and not email templates.
You can use an online barcode API such as [Barcodes4.me](http://www.barcodes4.me/apidocumentation) and embed the result in an image:
```
<img src="http://www.barcodes4.me/barcode/c128a/${campaignEvent.couponCode}.png?IsTextDrawn=1" />
```
Another similar service is [bwip-js-api](https://github.com/metafloor/bwip-js/wiki/Online-Barcode-API) | That's the correct syntax for creating a barcode on a PDF and I've used it quite a bit.
However you write you are creating an html email and I doubt the barcode tag will generate anything in html. Can you share the source of the created email around where you expect the barcode to be? You could generate a pdf with the barcode and attach it to the email.
Or you could generate the barcodes as svg values in a batch and update a custom field on the customer and then include the field contents your html that way.
<https://www.npmjs.com/package/jsbarcode> is a bar code generator that works in multiple environments so it's possible it could be made to work in a mass update script. |
44,789,558 | So I have this code:
```
def myprogram():
import string
import random
import getpass
inputpasswd = getpass.getpass("Password: ")
passwd = ("I<3StackOverflow")
if passwd == inputpasswd:
qwerty = input("Type something: ")
def add_str(lst):
_letters = ("1","2","3","4","5","6","7","8","9","0","q","w","e","r","t","z","u","i","o","p","a","s","d","f","g","h","j","k","l","y","x","c","v","b","n","m","!","#","$","%","&","/","(",")","=","?","*","+","_","-",";"," ")
return [''.join(random.sample(set(_letters), 1)) + letter + ''.join(random.sample(set(_letters), 1))for letter in lst]
print(''.join(add_str(qwerty)))
input("")
else:
print("Wrong password")
input("")
```
My question is: How can I make an opposite program, so it accepts the bunch of junk letters and converts it to text that makes sense?
Example:
If I type something like "aaaaaaa" in this program it will convert it to something like "mapma&)at7ar8a2ga-ka\*"
In this new program I want to type "mapma&)at7ar8a2ga-ka\*" and get output "aaaaaaa". | 2017/06/27 | [
"https://Stackoverflow.com/questions/44789558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8199987/"
]
| In **A1** enter:
```
=AVERAGE(OFFSET(C$1,10*(ROW(1:1)-1),0,10))
```
and copy down
[](https://i.stack.imgur.com/dIGdV.png)
See:
[A.S.H.'s Answer](https://stackoverflow.com/questions/44745800/autofilling-a-formula-is-that-possible)
**EDIT#1:**
To average **Q2** through **Q11**, use:
```
=AVERAGE(OFFSET(Q$2,10*(ROW(1:1)-1),0,10))
```
and copy down | Use INDEX() to set the ranges. In A1:
```
=AVERAGE(INDEX(C:C,(ROW(1:1)-1)*10 + 1):INDEX(C:C,(ROW(1:1)-1)*10 + 10))
```
So B1 would be:
```
=INDEX(D:D,(ROW(1:1)-1)*10 + 1)
```
Copy/Drag both formulas down.
Advantages to this over OFFSET, OFFSET is Volatile and will recalculate every time that Excel recalculates whether the data changed or not. Where INDEX will only recalc if the data to which it refers changed or not. If used to many times it will make a difference in the calc times.
Advantage to OFFSET, it is shorter and if used in moderation will not have a noticeable effect on the calc time, so it will save some wear and tear on the fingers. |
25,610,228 | In Exception Safety as created by Abrahams we have the three guarantees: basic, strong and no-throw guarantee.
Can i say that if i have a codebase using nothrow for "new" and noexcept for method signatures that i have the no-throw guarantee?
Thanks. | 2014/09/01 | [
"https://Stackoverflow.com/questions/25610228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/593177/"
]
| Looking down the list of [Array Functions](http://php.net/manual/en/ref.array.php) in the docs, I don't see anything built-in to do this. But it's easy to roll your own utility function for it:
```
/*
Returns true if the $key exists in the haystack and its value is $value.
Otherwise, returns false.
*/
function key_value_pair_exists(array $haystack, $key, $value) {
return array_key_exists($key, $haystack) &&
$haystack[$key] == $value;
}
```
Example usage:
```
$countries_to_capitals = [
'Switzerland' => 'Bern',
'Nepal' => 'Kathmandu',
'Canada' => 'Ottawa',
'Australia' => 'Canberra',
'Egypt' => 'Cairo',
'Mexico' => 'Mexico City'
];
var_dump(
key_value_pair_exists($countries_to_capitals, 'Canada', 'Ottawa')
); // true
var_dump(
key_value_pair_exists($countries_to_capitals, 'Switzerland', 'Geneva')
); // false
``` | ```
if (isset($elements[$country]) AND $elements[$country] == $capitale) {
return true;
}
return false;
``` |
25,610,228 | In Exception Safety as created by Abrahams we have the three guarantees: basic, strong and no-throw guarantee.
Can i say that if i have a codebase using nothrow for "new" and noexcept for method signatures that i have the no-throw guarantee?
Thanks. | 2014/09/01 | [
"https://Stackoverflow.com/questions/25610228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/593177/"
]
| ```
if (isset($elements[$country]) AND $elements[$country] == $capitale) {
return true;
}
return false;
``` | I put a couple of these answers together and arrived at this:
```
// enum dictionary
$QUERYABLE_FIELDS = [
'accounts' => [ 'phone', 'business_email' ],
'users' => [ 'email' ],
];
// search terms
$table = 'users';
$column = 'email';
$value = '[email protected]';
if (array_key_exists($table, $QUERYABLE_FIELDS)) {
if (in_array($column, $QUERYABLE_FIELDS[$table])) {
// if table and column are allowed, return Boolean if value already exists
// this is Laravel PHP, but just note that $exists will either be
// the first matching record, or null
$exists = DB::table($table)->where($column, $value)->first();
if ($exists) return response()->json([ 'in_use' => true ], 200);
return response()->json([ 'in_use' => false ], 200);
}
return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);
```
To break it down further, if you have an associative array that has some complex values in it, you can use `array_key_exists()` to check for them by name.
If the key exists, you can read its value as normal, as shown in my example above, as `$QUERYABLE_FIELDS[$table]` which will return `[ 'email' ]`, so you could do:
```
$QUERYABLE_FIELDS['users'][0];
```
or
```
in_array('email', $QUERYABLE_FIELDS['users']);
``` |
25,610,228 | In Exception Safety as created by Abrahams we have the three guarantees: basic, strong and no-throw guarantee.
Can i say that if i have a codebase using nothrow for "new" and noexcept for method signatures that i have the no-throw guarantee?
Thanks. | 2014/09/01 | [
"https://Stackoverflow.com/questions/25610228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/593177/"
]
| Looking down the list of [Array Functions](http://php.net/manual/en/ref.array.php) in the docs, I don't see anything built-in to do this. But it's easy to roll your own utility function for it:
```
/*
Returns true if the $key exists in the haystack and its value is $value.
Otherwise, returns false.
*/
function key_value_pair_exists(array $haystack, $key, $value) {
return array_key_exists($key, $haystack) &&
$haystack[$key] == $value;
}
```
Example usage:
```
$countries_to_capitals = [
'Switzerland' => 'Bern',
'Nepal' => 'Kathmandu',
'Canada' => 'Ottawa',
'Australia' => 'Canberra',
'Egypt' => 'Cairo',
'Mexico' => 'Mexico City'
];
var_dump(
key_value_pair_exists($countries_to_capitals, 'Canada', 'Ottawa')
); // true
var_dump(
key_value_pair_exists($countries_to_capitals, 'Switzerland', 'Geneva')
); // false
``` | I put a couple of these answers together and arrived at this:
```
// enum dictionary
$QUERYABLE_FIELDS = [
'accounts' => [ 'phone', 'business_email' ],
'users' => [ 'email' ],
];
// search terms
$table = 'users';
$column = 'email';
$value = '[email protected]';
if (array_key_exists($table, $QUERYABLE_FIELDS)) {
if (in_array($column, $QUERYABLE_FIELDS[$table])) {
// if table and column are allowed, return Boolean if value already exists
// this is Laravel PHP, but just note that $exists will either be
// the first matching record, or null
$exists = DB::table($table)->where($column, $value)->first();
if ($exists) return response()->json([ 'in_use' => true ], 200);
return response()->json([ 'in_use' => false ], 200);
}
return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);
```
To break it down further, if you have an associative array that has some complex values in it, you can use `array_key_exists()` to check for them by name.
If the key exists, you can read its value as normal, as shown in my example above, as `$QUERYABLE_FIELDS[$table]` which will return `[ 'email' ]`, so you could do:
```
$QUERYABLE_FIELDS['users'][0];
```
or
```
in_array('email', $QUERYABLE_FIELDS['users']);
``` |
15,012,344 | Basically I have written a "script" in notepad and saved it as a `.bat` file. All it does is to change directory. Written like this:
```
cd C:\Users\Hello\Documents\Stuff
```
It does change the directory, but i want to write more after that, within the `cmd`. Ex. choose a program to run. It seems simple, but i can't figure it out. I read about `pause`, but it just waits for a key and then closes down. | 2013/02/21 | [
"https://Stackoverflow.com/questions/15012344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2097106/"
]
| Put `cmd /k` on the very last line of the script. | end your bat file with `@pause` on its own line |
15,012,344 | Basically I have written a "script" in notepad and saved it as a `.bat` file. All it does is to change directory. Written like this:
```
cd C:\Users\Hello\Documents\Stuff
```
It does change the directory, but i want to write more after that, within the `cmd`. Ex. choose a program to run. It seems simple, but i can't figure it out. I read about `pause`, but it just waits for a key and then closes down. | 2013/02/21 | [
"https://Stackoverflow.com/questions/15012344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2097106/"
]
| Try the following:
```
@echo off
Cmd /k
```
`cmd /k` starts a new `cmd` instance, `/k` stops terminating the console window after the commands are finished. | end your bat file with `@pause` on its own line |
15,012,344 | Basically I have written a "script" in notepad and saved it as a `.bat` file. All it does is to change directory. Written like this:
```
cd C:\Users\Hello\Documents\Stuff
```
It does change the directory, but i want to write more after that, within the `cmd`. Ex. choose a program to run. It seems simple, but i can't figure it out. I read about `pause`, but it just waits for a key and then closes down. | 2013/02/21 | [
"https://Stackoverflow.com/questions/15012344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2097106/"
]
| Put `cmd /k` on the very last line of the script. | Try the following:
```
@echo off
Cmd /k
```
`cmd /k` starts a new `cmd` instance, `/k` stops terminating the console window after the commands are finished. |
21,446,318 | I'm getting this error on running a python script (see screen shot). The rest of the menu are fine apart from the StaticIP menu that's causing the exception.
<https://github.com/turnkeylinux/confconsole/blob/master/confconsole.py>
Appreciate any leads.
 | 2014/01/30 | [
"https://Stackoverflow.com/questions/21446318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1600047/"
]
| It turned out the stock python-dialog package won't work.
So the author advised to install the forked version of pythondialog.
Works like a charm now!
<https://github.com/turnkeylinux/pythondialog> | The "dialog not supported" string/error message one can read on the screenshot is not part of (at least current) pythondialog from <http://pythondialog.sourceforge.net/>.
Did you report a bug at <https://sourceforge.net/p/pythondialog/_list/tickets> or ask your question on the [pythondialog mailing list](https://sourceforge.net/p/pythondialog/mailman/)? Which "author" suggested to use which "forked version"? This is rather unclear... |
54,933 | How are computers able to tell the correct time and date every time?
Whenever I close the computer (shut it down) all connections and processes inside stop. How is it that when I open the computer again it tells the exact correct time? Does the computer not shut down completely when I shut it down? Are there some processes still running in it? But then how does my laptop tell the correct time when I take out the battery (and thus forcibly stop all processes) and start it again after a few days? | 2016/03/25 | [
"https://cs.stackexchange.com/questions/54933",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/48418/"
]
| Computers have a "real-time clock" -- a special hardware device (e.g., containing a quartz crystal) on the motherboard that maintains the time. It is always powered, even when you shut your computer off. Also, the motherboard has a small battery that is used to power the clock device even when you disconnect your computer from power. The battery doesn't last forever, but it will last at least a few weeks. This helps the computer keep track of the time even when your computer is shut off. The real-time clock doesn't need much power, so it's not wasting energy. If you take out the clock battery in addition to removing the main battery and disconnecting the power cable then the computer will lose track of time and will ask you to enter the time and date when you restart the computer.
To learn more, see [Real-time clock](https://en.wikipedia.org/wiki/Real-time_clock) and [CMOS battery](https://en.wikipedia.org/wiki/Nonvolatile_BIOS_memory#CMOS_battery) and [Why does my motherboard have a battery](http://www.makeuseof.com/tag/why-does-my-motherboard-have-a-battery/).
Also, on many computers, when you connect your computer to an Internet connection, the OS will go find a time server on the network and query the time server for the current time. The OS can use this to very accurately set your computer's local clock. This uses the [Network Time Protocol](https://en.wikipedia.org/wiki/Network_Time_Protocol), also called NTP. | If you remove the battery on the motherboard then the computer wouldn't have any way to tell the time.
This is also the case with mobile phones. If you let a phone discharge and then not recharge it for more than a few weeks it will also "forget the time" because the small auxiliary battery is discharged completely and nothing is powering on the real-time clock.
You could try to power on an old mobile phone if you have one and check it yourself to see that it "forgot the time".
This is how the battery looks.
<https://yandex.com/images/touch/search?text=mobo%20battery&source=tabbar>
I had to buy one a few times when mine started to last less then a day. I had to configure the clock everytime i turned on the PC. |
54,933 | How are computers able to tell the correct time and date every time?
Whenever I close the computer (shut it down) all connections and processes inside stop. How is it that when I open the computer again it tells the exact correct time? Does the computer not shut down completely when I shut it down? Are there some processes still running in it? But then how does my laptop tell the correct time when I take out the battery (and thus forcibly stop all processes) and start it again after a few days? | 2016/03/25 | [
"https://cs.stackexchange.com/questions/54933",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/48418/"
]
| Computers have a "real-time clock" -- a special hardware device (e.g., containing a quartz crystal) on the motherboard that maintains the time. It is always powered, even when you shut your computer off. Also, the motherboard has a small battery that is used to power the clock device even when you disconnect your computer from power. The battery doesn't last forever, but it will last at least a few weeks. This helps the computer keep track of the time even when your computer is shut off. The real-time clock doesn't need much power, so it's not wasting energy. If you take out the clock battery in addition to removing the main battery and disconnecting the power cable then the computer will lose track of time and will ask you to enter the time and date when you restart the computer.
To learn more, see [Real-time clock](https://en.wikipedia.org/wiki/Real-time_clock) and [CMOS battery](https://en.wikipedia.org/wiki/Nonvolatile_BIOS_memory#CMOS_battery) and [Why does my motherboard have a battery](http://www.makeuseof.com/tag/why-does-my-motherboard-have-a-battery/).
Also, on many computers, when you connect your computer to an Internet connection, the OS will go find a time server on the network and query the time server for the current time. The OS can use this to very accurately set your computer's local clock. This uses the [Network Time Protocol](https://en.wikipedia.org/wiki/Network_Time_Protocol), also called NTP. | When you start Windows, it gains direct access to the memory of the Real Time Clock (RTC) and uses its date and time values to set the computer date and time. Timer interrupts maintain the computer time when Windows is running. A Time Daemon in Windows runs approximately once each hour after the Windows starts. The Time Daemon compares the time in Windows with the time in the RTC. If the two times are more than one minute apart, Windows changes the time and date to match the RTC. You cannot change the time interval for the Time Daemon to run.
If you use a time synchronizing service, such as the TimeServ.exe tool included with the Windows NT 4.0 Resource Kit, the tool updates the time in Windows and the computer's RTC.
If the Windows Time Service runs on a Windows 2000 based-computer, the Time Daemon in Windows cannot run approximately one time each hour after the Windows starts.
For more details visit this link:<http://msdn2.microsoft.com/en-us/library/ms724936.aspxhttp://msdn2.microsoft.com/en-us/library/ms724942.aspx> |
54,933 | How are computers able to tell the correct time and date every time?
Whenever I close the computer (shut it down) all connections and processes inside stop. How is it that when I open the computer again it tells the exact correct time? Does the computer not shut down completely when I shut it down? Are there some processes still running in it? But then how does my laptop tell the correct time when I take out the battery (and thus forcibly stop all processes) and start it again after a few days? | 2016/03/25 | [
"https://cs.stackexchange.com/questions/54933",
"https://cs.stackexchange.com",
"https://cs.stackexchange.com/users/48418/"
]
| If you remove the battery on the motherboard then the computer wouldn't have any way to tell the time.
This is also the case with mobile phones. If you let a phone discharge and then not recharge it for more than a few weeks it will also "forget the time" because the small auxiliary battery is discharged completely and nothing is powering on the real-time clock.
You could try to power on an old mobile phone if you have one and check it yourself to see that it "forgot the time".
This is how the battery looks.
<https://yandex.com/images/touch/search?text=mobo%20battery&source=tabbar>
I had to buy one a few times when mine started to last less then a day. I had to configure the clock everytime i turned on the PC. | When you start Windows, it gains direct access to the memory of the Real Time Clock (RTC) and uses its date and time values to set the computer date and time. Timer interrupts maintain the computer time when Windows is running. A Time Daemon in Windows runs approximately once each hour after the Windows starts. The Time Daemon compares the time in Windows with the time in the RTC. If the two times are more than one minute apart, Windows changes the time and date to match the RTC. You cannot change the time interval for the Time Daemon to run.
If you use a time synchronizing service, such as the TimeServ.exe tool included with the Windows NT 4.0 Resource Kit, the tool updates the time in Windows and the computer's RTC.
If the Windows Time Service runs on a Windows 2000 based-computer, the Time Daemon in Windows cannot run approximately one time each hour after the Windows starts.
For more details visit this link:<http://msdn2.microsoft.com/en-us/library/ms724936.aspxhttp://msdn2.microsoft.com/en-us/library/ms724942.aspx> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.