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
7,505,663
Ok guys. This is a revision ``` class Node<E> { // (1) private E data; // Data (2) private Node<E> next; // Reference to next node (3) Node(E data, Node<E> next) { // (4) this.data = data; this.next = next; } public void setData(E e) {} // (5) public void xxxData(E e) {} // (6) public E getData(E e) {return null;} // (7) public static void main(String [] args) { Node<? extends Integer> n1 = new Node<Integer>(1,null); //8 Node<? super Integer> n2 = new Node<Integer>(1,null); //9 n1.setData(new Integer(1)); //10 compiler error n1.xxxData(new Integer(1)); //11 compiler error n2.setData(new Integer(1)); //12 ok } } ``` Here's a rewrite hopefully i can convey my confusion nicely. 1. n1 is upper bounded wildcard. So this wont allow adding of records. Clause 10 proves this. 2. clause 11 also proves that method names (in this case 'SET' to determine adding of records) not being used since xxxData method gives the same compiler error. 3. n2 is lower bounded wildcard. Since method names doesn't play a role here, how does compiler knows that setData method can be used on n2 (since n2 is a lower bounded wildcard and this wildcard allows for adding of records)? Basically what the difference on method setData on clause 10 and 12? Bear in mind nothing happens in those methods. It's empty or returning null.
2011/09/21
[ "https://Stackoverflow.com/questions/7505663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303250/" ]
If I understood your question properly, I guess it's because Integer is both super- and subtype to itself.
The question really changed now... The answer to this is [PECS](http://devender.files.wordpress.com/2008/05/effectivejava.pdf) (or [here](http://java.sun.com/docs/books/effective/generics.pdf), page 28) Also see, [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/q/2723397/897024) or [How can I add to List<? extends Number> data structures?](https://stackoverflow.com/q/2776975/897024)
7,505,663
Ok guys. This is a revision ``` class Node<E> { // (1) private E data; // Data (2) private Node<E> next; // Reference to next node (3) Node(E data, Node<E> next) { // (4) this.data = data; this.next = next; } public void setData(E e) {} // (5) public void xxxData(E e) {} // (6) public E getData(E e) {return null;} // (7) public static void main(String [] args) { Node<? extends Integer> n1 = new Node<Integer>(1,null); //8 Node<? super Integer> n2 = new Node<Integer>(1,null); //9 n1.setData(new Integer(1)); //10 compiler error n1.xxxData(new Integer(1)); //11 compiler error n2.setData(new Integer(1)); //12 ok } } ``` Here's a rewrite hopefully i can convey my confusion nicely. 1. n1 is upper bounded wildcard. So this wont allow adding of records. Clause 10 proves this. 2. clause 11 also proves that method names (in this case 'SET' to determine adding of records) not being used since xxxData method gives the same compiler error. 3. n2 is lower bounded wildcard. Since method names doesn't play a role here, how does compiler knows that setData method can be used on n2 (since n2 is a lower bounded wildcard and this wildcard allows for adding of records)? Basically what the difference on method setData on clause 10 and 12? Bear in mind nothing happens in those methods. It's empty or returning null.
2011/09/21
[ "https://Stackoverflow.com/questions/7505663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303250/" ]
Yes, you are confusing three things: 1. java method names are just names, you can call them anything you want 2. there is a convention in Java to use what are called getters and setters. If you have a field (data or next in your example), then you define two methods: . public void setData(E data) { this.data = data; } public E getData() { return this.data; } This convention is called [Java Beans](http://en.wikipedia.org/wiki/JavaBean). You'd do the same for node by the way. 3) Java selects the method to call based upon the types of the parameters that you pass to the method. This is called method overloading. It means that you can define things like: ``` public void setFile(String name) { // do something here } public void setFile(File file) { // do something here } ``` so you can call: ``` setFile(new File("barbar")); ``` or ``` setFile("c:\stuff"); ``` and the correct method will be chosen. The generic types that you have just confuse the situation even more :-)
Java doesn't care about get/set in the method name; it's all based on method parameter types. Consider ``` interface G<T> T f1(); void f2(T t); void f3(); ``` Substitute T with different types, methods signatures are changed too; for example, `G<Int>` methods ``` Int f1(); void f2(Int t); void f3(); ``` So we can do the following ``` G<Int> o = ...; Int i = o.f1(); o.f2(i); o.f3(); ``` What happens with wildcards? Actually compiler can't directly reason about wildcards; they must be replaced with fixed albeit unknown types; this process is called "wildcard capture". For example, given a `G<? super Int>` type, compiler internally treats it as `G<W>`, where `W` is an unknown supertype of `Int`. `G<W>` has methods ``` W f1(); void f2(W t); void f3(); ``` So we can do ``` G<? super Int> o = ...; Object i = o.f1(); // f1() returns W, which is subtype of Object o.f2( new Int(42) ); // f2() accepts W; Int is a subtype of W, accepted. o.f3(); ``` Similarly ``` G<? extends Int> o = ...; // G<W>, where W is a subtype of Int Int i = o.f1(); // f1() returns W, which is subtype of Int o.f2( new Int(42) ); // error: f2() accepts W; Int is NOT a subtype of W o.f3(); ```
7,505,663
Ok guys. This is a revision ``` class Node<E> { // (1) private E data; // Data (2) private Node<E> next; // Reference to next node (3) Node(E data, Node<E> next) { // (4) this.data = data; this.next = next; } public void setData(E e) {} // (5) public void xxxData(E e) {} // (6) public E getData(E e) {return null;} // (7) public static void main(String [] args) { Node<? extends Integer> n1 = new Node<Integer>(1,null); //8 Node<? super Integer> n2 = new Node<Integer>(1,null); //9 n1.setData(new Integer(1)); //10 compiler error n1.xxxData(new Integer(1)); //11 compiler error n2.setData(new Integer(1)); //12 ok } } ``` Here's a rewrite hopefully i can convey my confusion nicely. 1. n1 is upper bounded wildcard. So this wont allow adding of records. Clause 10 proves this. 2. clause 11 also proves that method names (in this case 'SET' to determine adding of records) not being used since xxxData method gives the same compiler error. 3. n2 is lower bounded wildcard. Since method names doesn't play a role here, how does compiler knows that setData method can be used on n2 (since n2 is a lower bounded wildcard and this wildcard allows for adding of records)? Basically what the difference on method setData on clause 10 and 12? Bear in mind nothing happens in those methods. It's empty or returning null.
2011/09/21
[ "https://Stackoverflow.com/questions/7505663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303250/" ]
I think i have the answer to this problem. It's true that method name doesn't play a role here but rather whether the reference assignment is valid. Compiler error for clause 10 & 11 is due to the following in terms of parameter assignment. ? extends Integer = Integer One cannot assign the Integer to ? extends Integer since the ? extends Integer could have type which is lower than Integer (figuratively speaking). Of course this works for clause 12.
Java doesn't care about get/set in the method name; it's all based on method parameter types. Consider ``` interface G<T> T f1(); void f2(T t); void f3(); ``` Substitute T with different types, methods signatures are changed too; for example, `G<Int>` methods ``` Int f1(); void f2(Int t); void f3(); ``` So we can do the following ``` G<Int> o = ...; Int i = o.f1(); o.f2(i); o.f3(); ``` What happens with wildcards? Actually compiler can't directly reason about wildcards; they must be replaced with fixed albeit unknown types; this process is called "wildcard capture". For example, given a `G<? super Int>` type, compiler internally treats it as `G<W>`, where `W` is an unknown supertype of `Int`. `G<W>` has methods ``` W f1(); void f2(W t); void f3(); ``` So we can do ``` G<? super Int> o = ...; Object i = o.f1(); // f1() returns W, which is subtype of Object o.f2( new Int(42) ); // f2() accepts W; Int is a subtype of W, accepted. o.f3(); ``` Similarly ``` G<? extends Int> o = ...; // G<W>, where W is a subtype of Int Int i = o.f1(); // f1() returns W, which is subtype of Int o.f2( new Int(42) ); // error: f2() accepts W; Int is NOT a subtype of W o.f3(); ```
7,505,663
Ok guys. This is a revision ``` class Node<E> { // (1) private E data; // Data (2) private Node<E> next; // Reference to next node (3) Node(E data, Node<E> next) { // (4) this.data = data; this.next = next; } public void setData(E e) {} // (5) public void xxxData(E e) {} // (6) public E getData(E e) {return null;} // (7) public static void main(String [] args) { Node<? extends Integer> n1 = new Node<Integer>(1,null); //8 Node<? super Integer> n2 = new Node<Integer>(1,null); //9 n1.setData(new Integer(1)); //10 compiler error n1.xxxData(new Integer(1)); //11 compiler error n2.setData(new Integer(1)); //12 ok } } ``` Here's a rewrite hopefully i can convey my confusion nicely. 1. n1 is upper bounded wildcard. So this wont allow adding of records. Clause 10 proves this. 2. clause 11 also proves that method names (in this case 'SET' to determine adding of records) not being used since xxxData method gives the same compiler error. 3. n2 is lower bounded wildcard. Since method names doesn't play a role here, how does compiler knows that setData method can be used on n2 (since n2 is a lower bounded wildcard and this wildcard allows for adding of records)? Basically what the difference on method setData on clause 10 and 12? Bear in mind nothing happens in those methods. It's empty or returning null.
2011/09/21
[ "https://Stackoverflow.com/questions/7505663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303250/" ]
Yes, you are confusing three things: 1. java method names are just names, you can call them anything you want 2. there is a convention in Java to use what are called getters and setters. If you have a field (data or next in your example), then you define two methods: . public void setData(E data) { this.data = data; } public E getData() { return this.data; } This convention is called [Java Beans](http://en.wikipedia.org/wiki/JavaBean). You'd do the same for node by the way. 3) Java selects the method to call based upon the types of the parameters that you pass to the method. This is called method overloading. It means that you can define things like: ``` public void setFile(String name) { // do something here } public void setFile(File file) { // do something here } ``` so you can call: ``` setFile(new File("barbar")); ``` or ``` setFile("c:\stuff"); ``` and the correct method will be chosen. The generic types that you have just confuse the situation even more :-)
The question really changed now... The answer to this is [PECS](http://devender.files.wordpress.com/2008/05/effectivejava.pdf) (or [here](http://java.sun.com/docs/books/effective/generics.pdf), page 28) Also see, [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/q/2723397/897024) or [How can I add to List<? extends Number> data structures?](https://stackoverflow.com/q/2776975/897024)
7,505,663
Ok guys. This is a revision ``` class Node<E> { // (1) private E data; // Data (2) private Node<E> next; // Reference to next node (3) Node(E data, Node<E> next) { // (4) this.data = data; this.next = next; } public void setData(E e) {} // (5) public void xxxData(E e) {} // (6) public E getData(E e) {return null;} // (7) public static void main(String [] args) { Node<? extends Integer> n1 = new Node<Integer>(1,null); //8 Node<? super Integer> n2 = new Node<Integer>(1,null); //9 n1.setData(new Integer(1)); //10 compiler error n1.xxxData(new Integer(1)); //11 compiler error n2.setData(new Integer(1)); //12 ok } } ``` Here's a rewrite hopefully i can convey my confusion nicely. 1. n1 is upper bounded wildcard. So this wont allow adding of records. Clause 10 proves this. 2. clause 11 also proves that method names (in this case 'SET' to determine adding of records) not being used since xxxData method gives the same compiler error. 3. n2 is lower bounded wildcard. Since method names doesn't play a role here, how does compiler knows that setData method can be used on n2 (since n2 is a lower bounded wildcard and this wildcard allows for adding of records)? Basically what the difference on method setData on clause 10 and 12? Bear in mind nothing happens in those methods. It's empty or returning null.
2011/09/21
[ "https://Stackoverflow.com/questions/7505663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303250/" ]
I think i have the answer to this problem. It's true that method name doesn't play a role here but rather whether the reference assignment is valid. Compiler error for clause 10 & 11 is due to the following in terms of parameter assignment. ? extends Integer = Integer One cannot assign the Integer to ? extends Integer since the ? extends Integer could have type which is lower than Integer (figuratively speaking). Of course this works for clause 12.
The question really changed now... The answer to this is [PECS](http://devender.files.wordpress.com/2008/05/effectivejava.pdf) (or [here](http://java.sun.com/docs/books/effective/generics.pdf), page 28) Also see, [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/q/2723397/897024) or [How can I add to List<? extends Number> data structures?](https://stackoverflow.com/q/2776975/897024)
1,137,736
This is regarding the proof of proposition 24(page 61) of Serre's Linear Representations of finite groups. Line 3 of the proof says that for $s\in G$, $\rho(s)$ permutes $V\_i$? Can someone be kind enough to tell me why this is the case? If you do not have the book, here is what I need. Suppose $\rho: G\to GL(V)$ is an irreducible representation of $G$. Let $A$ be a normal subgroup of $G$. Let $V=\bigoplus V\_i$ be the canonical decomposition of the representation $\rho$ restricted to $A$ into a direct sum of isotypic representations. Show that for $g\in G$, $\rho(g)$ permutes $V\_i$.
2015/02/07
[ "https://math.stackexchange.com/questions/1137736", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
I will denote $f^{2}=f\circ f$ and similarly for $g^2$. I would also write $fg$ for $f\circ g$ etc' . $f^{2}g^{2}f^{2}$ is invertible hence it is $1-1$ and onto. We know that if a composition $f\_{1}\circ f\_{2}$ is $1-1$ then so must be $f\_{2}$ and if the composition is onto than so is $f\_{1}$. Using those facts for our case we get that $$ f(fg^{2}f^{2}) $$ is onto hence so is $f$ . on the other hand $$ (f^{2}g^{2}f)f $$ is $1-1$ and so must be $f$ . We conclude $f$ is invertible. Now - multiplying by an invertible function doesn't change the invertability of what we multiply by so $$ f^{-1}f^{-1}(f^{2}g^{2}f^{2})f^{-1}f^{-1}=g^{2} $$ is also invertible. Now $$ g\circ g $$ is $1-1$ and onto. Setting $f\_{1}=f\_{2}=g$ we get that $g$ is also $1-1$ and onto, completing the proof.
Let $h$ be the inverse of $k := f\circ f \circ g \circ g \circ f \circ f$. Then $h \circ k = id = k \circ h$, which implies $u\circ f = id = f \circ v$, where $u = h \circ f \circ f \circ g \circ g \circ f$ and $v = f\circ g \circ g \circ f \circ f \circ h$. Since $u$ is a left inverse of $f$, $f$ is $1-1$; since $v$ is a right inverse of $f$, $f$ is onto. Therefore, $f$ is invertible. Now $g\circ g$, being the composition of invertible functions $f^{-1} \circ f^{-1}\circ k \circ f^{-1}\circ f^{-1}$, is invertible. If $w$ is the inverse of $g \circ g$, then $w \circ g$ is a left inverse of $g$ (so $g$ is $1-1$) and $g\circ w$ is a right inverse of $g$ (so $g$ is onto). Hence, $g$ is invertible.
1,137,736
This is regarding the proof of proposition 24(page 61) of Serre's Linear Representations of finite groups. Line 3 of the proof says that for $s\in G$, $\rho(s)$ permutes $V\_i$? Can someone be kind enough to tell me why this is the case? If you do not have the book, here is what I need. Suppose $\rho: G\to GL(V)$ is an irreducible representation of $G$. Let $A$ be a normal subgroup of $G$. Let $V=\bigoplus V\_i$ be the canonical decomposition of the representation $\rho$ restricted to $A$ into a direct sum of isotypic representations. Show that for $g\in G$, $\rho(g)$ permutes $V\_i$.
2015/02/07
[ "https://math.stackexchange.com/questions/1137736", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
I will denote $f^{2}=f\circ f$ and similarly for $g^2$. I would also write $fg$ for $f\circ g$ etc' . $f^{2}g^{2}f^{2}$ is invertible hence it is $1-1$ and onto. We know that if a composition $f\_{1}\circ f\_{2}$ is $1-1$ then so must be $f\_{2}$ and if the composition is onto than so is $f\_{1}$. Using those facts for our case we get that $$ f(fg^{2}f^{2}) $$ is onto hence so is $f$ . on the other hand $$ (f^{2}g^{2}f)f $$ is $1-1$ and so must be $f$ . We conclude $f$ is invertible. Now - multiplying by an invertible function doesn't change the invertability of what we multiply by so $$ f^{-1}f^{-1}(f^{2}g^{2}f^{2})f^{-1}f^{-1}=g^{2} $$ is also invertible. Now $$ g\circ g $$ is $1-1$ and onto. Setting $f\_{1}=f\_{2}=g$ we get that $g$ is also $1-1$ and onto, completing the proof.
In general and not difficult to prove: if $u\circ v$ is a bijection then $u$ is surjective and $v$ is injective. Applying that here we find that $f$ is surjective and injective, hence is a bijection. Then $g\circ g=f^{-1}\circ f^{-1}\circ f\circ f\circ g\circ g\circ f\circ f\circ f^{-1}\circ f^{-1}$ is - as composition of bijections - also a bijection, and again we can apply the rule to find this time that $g$ is bijective.
1,137,736
This is regarding the proof of proposition 24(page 61) of Serre's Linear Representations of finite groups. Line 3 of the proof says that for $s\in G$, $\rho(s)$ permutes $V\_i$? Can someone be kind enough to tell me why this is the case? If you do not have the book, here is what I need. Suppose $\rho: G\to GL(V)$ is an irreducible representation of $G$. Let $A$ be a normal subgroup of $G$. Let $V=\bigoplus V\_i$ be the canonical decomposition of the representation $\rho$ restricted to $A$ into a direct sum of isotypic representations. Show that for $g\in G$, $\rho(g)$ permutes $V\_i$.
2015/02/07
[ "https://math.stackexchange.com/questions/1137736", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
In general and not difficult to prove: if $u\circ v$ is a bijection then $u$ is surjective and $v$ is injective. Applying that here we find that $f$ is surjective and injective, hence is a bijection. Then $g\circ g=f^{-1}\circ f^{-1}\circ f\circ f\circ g\circ g\circ f\circ f\circ f^{-1}\circ f^{-1}$ is - as composition of bijections - also a bijection, and again we can apply the rule to find this time that $g$ is bijective.
Let $h$ be the inverse of $k := f\circ f \circ g \circ g \circ f \circ f$. Then $h \circ k = id = k \circ h$, which implies $u\circ f = id = f \circ v$, where $u = h \circ f \circ f \circ g \circ g \circ f$ and $v = f\circ g \circ g \circ f \circ f \circ h$. Since $u$ is a left inverse of $f$, $f$ is $1-1$; since $v$ is a right inverse of $f$, $f$ is onto. Therefore, $f$ is invertible. Now $g\circ g$, being the composition of invertible functions $f^{-1} \circ f^{-1}\circ k \circ f^{-1}\circ f^{-1}$, is invertible. If $w$ is the inverse of $g \circ g$, then $w \circ g$ is a left inverse of $g$ (so $g$ is $1-1$) and $g\circ w$ is a right inverse of $g$ (so $g$ is onto). Hence, $g$ is invertible.
6,135,761
While it seems that this has been asked many times before, but there's a nasty twist here... First, I'm working on a desktop application which calls a webpage on the same local system. This web application then calls upon a second server (in the local network) and needs to pass it's own IP address to the other server. Easy, of course: `Request.ServerVariables("LOCAL_ADDR")` and I'm done... It won't work in this case... The code for the local web application is written in classic ASP and almost every sourcefile is encrypted, thus I cannot modify it's code. All I can fix is the global.asa file. In the Application\_OnStart event of global.asa is the line `Application("InternalIp") = "172.22.14.59"` and indeed, that's the local IP address, hard-coded... And this application setting is used in the rest of the code to refer to the IP address. However, my IP address in our local network tends to change every day, so every day I need to modify global.asa to contain my new IP address. I could write a small application which will modify global.asa for me every day on startup but I'd rather see a solution where global.asa would be smart enough to detect this IP address itself! Unfortunately, the IP address must be known on the start of the application, not at the start of the session, else I could have used `Application("InternalIp") = Request.ServerVariables("LOCAL_ADDR")` in the Session\_OnStart event. Tried this, application crashed, so it won't work. But that line of code in Application\_OnStart won't work, since Request is unknown at that moment, thus that would crash too. (Tried it, didn't work...) So, my limitation is that I need to get the IP address within the Application\_OnStart event of global.asa in a reliable way. And no, using DNS names don't work either. (Tried that too, didn't work.) What options do I have?
2011/05/26
[ "https://Stackoverflow.com/questions/6135761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115305/" ]
you could use the commandline (wscript.shell) and ipconfig? or write your ip address in a textfile (with the help of another tool) and then read out that text file you could also add an asp page to your application, call that asp page from your desktop application. on the new asp page you could everything you want (e.g. set the application var with the help of request.servervariables...) then at the end do a redirect to the "original" (encrypted) asp page...
I'm not sure about Application\_Onstart(), but in your Session\_onStart() it should be possible to get the servervariables. I work on a classic ASP application that does just that. I'm currently on a linux machine, so I can't run the code, only look at it over the network, but what we do is use an include in the Global.asa, just above the script tag: ``` <!--#include virtual="~inc/global.inc"--> <script language=vbscript runat=server> ``` Then, in the SUB Session\_OnStart we use a call to a function in that global.inc include that uses Request.ServerVariables("REMOTE\_ADDR") to fetch the remote I.P. and log it in a database. If it works for the remote I.P. I think it should also work for the local I.P. Although I'm not sure if it will then log the localhost (127.0.0.1) or the external I.P.... Could you try with Request.ServerVariables("REMOTE\_ADDR"), just to see if that works If it doesn't; what is the error you get? By the way: the way we work (using an include and a function call) should not matter; you should be able to do it directly from the session\_Onstart
6,135,761
While it seems that this has been asked many times before, but there's a nasty twist here... First, I'm working on a desktop application which calls a webpage on the same local system. This web application then calls upon a second server (in the local network) and needs to pass it's own IP address to the other server. Easy, of course: `Request.ServerVariables("LOCAL_ADDR")` and I'm done... It won't work in this case... The code for the local web application is written in classic ASP and almost every sourcefile is encrypted, thus I cannot modify it's code. All I can fix is the global.asa file. In the Application\_OnStart event of global.asa is the line `Application("InternalIp") = "172.22.14.59"` and indeed, that's the local IP address, hard-coded... And this application setting is used in the rest of the code to refer to the IP address. However, my IP address in our local network tends to change every day, so every day I need to modify global.asa to contain my new IP address. I could write a small application which will modify global.asa for me every day on startup but I'd rather see a solution where global.asa would be smart enough to detect this IP address itself! Unfortunately, the IP address must be known on the start of the application, not at the start of the session, else I could have used `Application("InternalIp") = Request.ServerVariables("LOCAL_ADDR")` in the Session\_OnStart event. Tried this, application crashed, so it won't work. But that line of code in Application\_OnStart won't work, since Request is unknown at that moment, thus that would crash too. (Tried it, didn't work...) So, my limitation is that I need to get the IP address within the Application\_OnStart event of global.asa in a reliable way. And no, using DNS names don't work either. (Tried that too, didn't work.) What options do I have?
2011/05/26
[ "https://Stackoverflow.com/questions/6135761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115305/" ]
you could use the commandline (wscript.shell) and ipconfig? or write your ip address in a textfile (with the help of another tool) and then read out that text file you could also add an asp page to your application, call that asp page from your desktop application. on the new asp page you could everything you want (e.g. set the application var with the help of request.servervariables...) then at the end do a redirect to the "original" (encrypted) asp page...
Sorry, I posted this as a comment, but it is an alternative answer: You can also try using microsofts serverxmlhttp object to do a GET to the API of whatsmyip.com: <http://automation.whatismyip.com/n09230945.asp> This will return your servers external ip address. I don't know if you can instantate the serverxmlhttp object in application\_onstart() however... Look at <http://msdn.microsoft.com/en-us/library/ms766431(v=vs.85).aspx> for more info on how to use serverxmlhttp to do an HTTP GET.
57,741
I have created several projects for several different clients. Each project has OS maps, shapefile layers from Government Bodies, Shapefile layers created, AutoCAD dxf loaded in (in various manners). Is there a programme out there that I can load all my layers into (whilst maintaining their properties), keep all the original files on my computer. Send a link to a client that allows them to open the project, turn on and off various layers, interrogate the data (as in simple information tool), measure distance, and print maps, but not be able to edit the layers or save data. I have worked of a GIS browser with various different government agencies but never had to create one. Is there one that is a free, easy to use, and easy to learn by the clients? I would like to be able to load all the files from QGIS 1.8.0 to this service whilst maintaining their properties, however if this is not possible I can do it over again.
2013/04/11
[ "https://gis.stackexchange.com/questions/57741", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/7104/" ]
If you are not looking to build your own, and rather use a hosted web service, there are a few that are out there to consider: * [QGIS Cloud](http://www.qgiscloud.com/en/pages/quickstart) - A potentially easy option if you want to maintain your data in QGIS. * [MapBox](http://mapbox.com/) - Read the following question for options of converting QGIS projects to TileMill: [Are there tools to directly import QGIS projects into Tilemill?](https://gis.stackexchange.com/questions/41262/are-there-tools-to-directly-import-qgis-projects-into-tilemill) * [CartoDB](http://cartodb.com) - A great option if you want to move your data to PostGIS.
A webgis solution seems ideal for your problem. The client will be able to log to your server, view the data (based on the permissions you gave them), do basic operations, and its many-to-one solution. [Here](http://www.osgeo.org/) are some open source web-gis platforms you want to consider: * [Mapbender](http://www.mapbender.org/Demo) * [Geomajas](http://www.geomajas.org/) * [GeoMoose](http://www.geomoose.org/) * [MapServer](http://www.mapserver.org/) * [GeoServer](http://geoserver.org/display/GEOS/Welcome)
57,741
I have created several projects for several different clients. Each project has OS maps, shapefile layers from Government Bodies, Shapefile layers created, AutoCAD dxf loaded in (in various manners). Is there a programme out there that I can load all my layers into (whilst maintaining their properties), keep all the original files on my computer. Send a link to a client that allows them to open the project, turn on and off various layers, interrogate the data (as in simple information tool), measure distance, and print maps, but not be able to edit the layers or save data. I have worked of a GIS browser with various different government agencies but never had to create one. Is there one that is a free, easy to use, and easy to learn by the clients? I would like to be able to load all the files from QGIS 1.8.0 to this service whilst maintaining their properties, however if this is not possible I can do it over again.
2013/04/11
[ "https://gis.stackexchange.com/questions/57741", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/7104/" ]
A webgis solution seems ideal for your problem. The client will be able to log to your server, view the data (based on the permissions you gave them), do basic operations, and its many-to-one solution. [Here](http://www.osgeo.org/) are some open source web-gis platforms you want to consider: * [Mapbender](http://www.mapbender.org/Demo) * [Geomajas](http://www.geomajas.org/) * [GeoMoose](http://www.geomoose.org/) * [MapServer](http://www.mapserver.org/) * [GeoServer](http://geoserver.org/display/GEOS/Welcome)
You could try Geocommon, but it's very difficult to navigate through. Or give it a try ArcGIS Online (another Esri product) but lots of limitation. any way give it a try.
57,741
I have created several projects for several different clients. Each project has OS maps, shapefile layers from Government Bodies, Shapefile layers created, AutoCAD dxf loaded in (in various manners). Is there a programme out there that I can load all my layers into (whilst maintaining their properties), keep all the original files on my computer. Send a link to a client that allows them to open the project, turn on and off various layers, interrogate the data (as in simple information tool), measure distance, and print maps, but not be able to edit the layers or save data. I have worked of a GIS browser with various different government agencies but never had to create one. Is there one that is a free, easy to use, and easy to learn by the clients? I would like to be able to load all the files from QGIS 1.8.0 to this service whilst maintaining their properties, however if this is not possible I can do it over again.
2013/04/11
[ "https://gis.stackexchange.com/questions/57741", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/7104/" ]
If you are not looking to build your own, and rather use a hosted web service, there are a few that are out there to consider: * [QGIS Cloud](http://www.qgiscloud.com/en/pages/quickstart) - A potentially easy option if you want to maintain your data in QGIS. * [MapBox](http://mapbox.com/) - Read the following question for options of converting QGIS projects to TileMill: [Are there tools to directly import QGIS projects into Tilemill?](https://gis.stackexchange.com/questions/41262/are-there-tools-to-directly-import-qgis-projects-into-tilemill) * [CartoDB](http://cartodb.com) - A great option if you want to move your data to PostGIS.
You may also want to check out QGIS server. From the website: > > QGIS Server provides a web map service (WMS) using the same libraries > as the Quantum GIS (QGIS) desktop application. Maps and print > templates created in QGIS desktop can be published as web maps simply > by copying the QGIS project file into the server directory. The > resulting web maps look exactly the same as in the desktop. > > > For more information, see: * <http://hub.qgis.org/projects/quantum-gis/wiki/QGIS_Server_Tutorial> * <http://live.osgeo.org/en/quickstart/qgis_mapserver_quickstart.html> * There are various questions and answers here on StackExchange about QGIS server that might be useful.
57,741
I have created several projects for several different clients. Each project has OS maps, shapefile layers from Government Bodies, Shapefile layers created, AutoCAD dxf loaded in (in various manners). Is there a programme out there that I can load all my layers into (whilst maintaining their properties), keep all the original files on my computer. Send a link to a client that allows them to open the project, turn on and off various layers, interrogate the data (as in simple information tool), measure distance, and print maps, but not be able to edit the layers or save data. I have worked of a GIS browser with various different government agencies but never had to create one. Is there one that is a free, easy to use, and easy to learn by the clients? I would like to be able to load all the files from QGIS 1.8.0 to this service whilst maintaining their properties, however if this is not possible I can do it over again.
2013/04/11
[ "https://gis.stackexchange.com/questions/57741", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/7104/" ]
You may also want to check out QGIS server. From the website: > > QGIS Server provides a web map service (WMS) using the same libraries > as the Quantum GIS (QGIS) desktop application. Maps and print > templates created in QGIS desktop can be published as web maps simply > by copying the QGIS project file into the server directory. The > resulting web maps look exactly the same as in the desktop. > > > For more information, see: * <http://hub.qgis.org/projects/quantum-gis/wiki/QGIS_Server_Tutorial> * <http://live.osgeo.org/en/quickstart/qgis_mapserver_quickstart.html> * There are various questions and answers here on StackExchange about QGIS server that might be useful.
You could try Geocommon, but it's very difficult to navigate through. Or give it a try ArcGIS Online (another Esri product) but lots of limitation. any way give it a try.
57,741
I have created several projects for several different clients. Each project has OS maps, shapefile layers from Government Bodies, Shapefile layers created, AutoCAD dxf loaded in (in various manners). Is there a programme out there that I can load all my layers into (whilst maintaining their properties), keep all the original files on my computer. Send a link to a client that allows them to open the project, turn on and off various layers, interrogate the data (as in simple information tool), measure distance, and print maps, but not be able to edit the layers or save data. I have worked of a GIS browser with various different government agencies but never had to create one. Is there one that is a free, easy to use, and easy to learn by the clients? I would like to be able to load all the files from QGIS 1.8.0 to this service whilst maintaining their properties, however if this is not possible I can do it over again.
2013/04/11
[ "https://gis.stackexchange.com/questions/57741", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/7104/" ]
If you are not looking to build your own, and rather use a hosted web service, there are a few that are out there to consider: * [QGIS Cloud](http://www.qgiscloud.com/en/pages/quickstart) - A potentially easy option if you want to maintain your data in QGIS. * [MapBox](http://mapbox.com/) - Read the following question for options of converting QGIS projects to TileMill: [Are there tools to directly import QGIS projects into Tilemill?](https://gis.stackexchange.com/questions/41262/are-there-tools-to-directly-import-qgis-projects-into-tilemill) * [CartoDB](http://cartodb.com) - A great option if you want to move your data to PostGIS.
If you want to avoid writing any code then [MangoMap](http://www.mangomap.com) is your best bet. It's also free which is a bonus! Just upload your shapes, update the styles, press publish and you're done! **Disclosure**: I am the Founder of MangoMap
57,741
I have created several projects for several different clients. Each project has OS maps, shapefile layers from Government Bodies, Shapefile layers created, AutoCAD dxf loaded in (in various manners). Is there a programme out there that I can load all my layers into (whilst maintaining their properties), keep all the original files on my computer. Send a link to a client that allows them to open the project, turn on and off various layers, interrogate the data (as in simple information tool), measure distance, and print maps, but not be able to edit the layers or save data. I have worked of a GIS browser with various different government agencies but never had to create one. Is there one that is a free, easy to use, and easy to learn by the clients? I would like to be able to load all the files from QGIS 1.8.0 to this service whilst maintaining their properties, however if this is not possible I can do it over again.
2013/04/11
[ "https://gis.stackexchange.com/questions/57741", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/7104/" ]
If you are not looking to build your own, and rather use a hosted web service, there are a few that are out there to consider: * [QGIS Cloud](http://www.qgiscloud.com/en/pages/quickstart) - A potentially easy option if you want to maintain your data in QGIS. * [MapBox](http://mapbox.com/) - Read the following question for options of converting QGIS projects to TileMill: [Are there tools to directly import QGIS projects into Tilemill?](https://gis.stackexchange.com/questions/41262/are-there-tools-to-directly-import-qgis-projects-into-tilemill) * [CartoDB](http://cartodb.com) - A great option if you want to move your data to PostGIS.
You could try Geocommon, but it's very difficult to navigate through. Or give it a try ArcGIS Online (another Esri product) but lots of limitation. any way give it a try.
57,741
I have created several projects for several different clients. Each project has OS maps, shapefile layers from Government Bodies, Shapefile layers created, AutoCAD dxf loaded in (in various manners). Is there a programme out there that I can load all my layers into (whilst maintaining their properties), keep all the original files on my computer. Send a link to a client that allows them to open the project, turn on and off various layers, interrogate the data (as in simple information tool), measure distance, and print maps, but not be able to edit the layers or save data. I have worked of a GIS browser with various different government agencies but never had to create one. Is there one that is a free, easy to use, and easy to learn by the clients? I would like to be able to load all the files from QGIS 1.8.0 to this service whilst maintaining their properties, however if this is not possible I can do it over again.
2013/04/11
[ "https://gis.stackexchange.com/questions/57741", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/7104/" ]
If you want to avoid writing any code then [MangoMap](http://www.mangomap.com) is your best bet. It's also free which is a bonus! Just upload your shapes, update the styles, press publish and you're done! **Disclosure**: I am the Founder of MangoMap
You could try Geocommon, but it's very difficult to navigate through. Or give it a try ArcGIS Online (another Esri product) but lots of limitation. any way give it a try.
57,042,499
I'm gonna ask a weird question: Is there a way to run a code snippet on a breakpoint set on the DOM? Use example: - Visit a website with a table. - Set a *Break On Subtree Modification* - Run MySnippet when the breakpoint hits.
2019/07/15
[ "https://Stackoverflow.com/questions/57042499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324133/" ]
What you can do though is set a conditional breakpoint with an `eval('...')` statement. for example the following with log to the console: > > test 11:59:51:326 > > > Good for checking timing issues... ``` eval('let current=new Date();console.log("test",current.getHours()+":" +current.getMinutes()+":"+current.getSeconds()+":" +current.getMilliseconds());') ``` you can also print a local object, e.g if **localVar** is defined: ``` eval('let current=new Date();console.log("test”,localVar,current.getHours()+":" +current.getMinutes()+":"+current.getSeconds()+":"+current.getMilliseconds());') ```
DevTools doesn't have this feature. After your DOM breakpoint triggers you can run a [Snippet](https://developers.google.com/web/tools/chrome-devtools/javascript/snippets) though. You can [run Snippets from the Command Menu](https://developers.google.com/web/tools/chrome-devtools/javascript/snippets#runcommandmenu).
604,881
I often see people interpreting Hooke's Law $σ=Eε$ as, > > "The deformation $ε$ that occurs when you subject a material to a stress $σ$." > > > This makes it sound like stress is an *external stimulus* that causes the material to deform. But from what I know, stress is an **internal phenomenon**, **not an external one**. So technically, isn't it more correct to interpret Hooke's law as > > "The stress σ that develops in a material given a deformation of $ε$"? > > > I would greatly appreciate it if someone could clear this up for me.
2021/01/03
[ "https://physics.stackexchange.com/questions/604881", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/272724/" ]
Unfortunately, both descriptions are misleading because both describe the relationship as a one-way cause-and-effect relationship. The correct way to describe it is > > the stress is proportional to the strain > > > It doesn’t matter if the stress is given and the strain is obtained by Hooke’s law or if the strain is given and the stress is obtained by Hooke’s law. Either way they are proportional to each other. Unfortunately, whether it is Newton’s laws, Ohm’s law, Hooke’s law, or Maxwell’s equations, the tendency to verbally express such equations in cause-and-effect language is fairly strong and common in many introductory physics courses. It is almost universally inappropriate. A real cause-and-effect relationship is given by an equation of the form $$f(t)=g(t-\Delta t)$$ In this equation $g$ is the cause and $f$ is the effect and $0<\Delta t$ so that the cause always precedes the effect. In an expression like Hooke’s law both stress and strain are happening at the same time and causes happen before effects. It is a simple proportionality, not a cause-and-effect relationship.
Hooke's Law—in the standard form as you've written it—says that the normal stress $\sigma$ and normal strain $\varepsilon$ are linearly coupled by a constant of proportionality $E$ (termed Young's modulus). This is a good approximation for a long rod of a stable, constant-temperature solid for small axial deformations over moderate time scales. (All these qualifiers are needed to eliminate the effects of stresses in other directions, temperature dependence, creep, etc.) Note that no specific cause or effect regarding the stress or strain is implied.
27,117,652
The code is simple,I just want to test the priority between & and ++. ``` int main() { int a=10; int *p; int *q; p=&++a;//error: lvalue required as unary ‘&’ operand q=&a++;//error: lvalue required as unary ‘&’ operand return 0; } ``` when **gcc** compile it, two errors came out. In my opinion,`a++` is a right value,but the `++a` is a lvalue,so it should not be an error when use & to get it address,
2014/11/25
[ "https://Stackoverflow.com/questions/27117652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4160994/" ]
It seems that you have misunderstood the difference between `lvalue` and `rvalue`. In your case both the expressions `a++` and `++a` are `rvalues` and cannot be assigned. [Here](https://stackoverflow.com/a/3601661/391161) is a good description of the distinction, but the quick way to tell whether it is an `lvalue` is to see whether you get an error if you put it on the left side of an `=`. Observe that both of the following two statements produce the same error you describe. ``` ++a = 5; a++ = 6; ``` Update: As @mafso mentioned below, `++a` is indeed an `lvalue` in the language `c++`, and you will not see the error for that expression when compiling with `g++`.
the object of operator & is `lvalue` , an the same is operator ++.but after ++a is done , it returns `rvalue` , that's the reason wrong.
7,709,121
I have a Dll which is added into another solution now my code for reading the configuration file is in DLL But my configuration file is in current solution what should be the proper solution ?
2011/10/10
[ "https://Stackoverflow.com/questions/7709121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/947191/" ]
I'd suggest using XHTML 1.0 Strict (if you don't want to use HTML5) instead of Transitional. That forces browser to standards mode instead of quirks mode (which could be the case with IE9): <http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict> <http://www.quirksmode.org/css/quirksmode.html>
Finally i find out the problem .The problem was with `jquery.ui.all.css` . There is a sub css file named `jquery.ui.dialog.css` in the above css and i changed the below line of code ``` .ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; } ``` to ``` .ui-dialog { position: absolute; padding: .2em; width: 300px; } ``` Now its works fine
60,579,432
I'm trying to stream MP4 videos from my server to YouTube and so I installed FFMPEG version. When I then look at the configuration of FFMPEG, I am then presented with the following: ``` ffmpeg version 3.3.6 Copyright (c) 2000-2017 the FFmpeg developers built with gcc 4.9.2 (Debian 4.9.2-10) configuration: --enable-cross-compile --arch=i686 --target-os=linux --disable-yasm --disable-static --enable-shared --enable-gpl --enable-libmp3lame --enable-libx264 --enable-libsoxr --enable-version3 --enable-nonfree --enable-openssl --disable-decoder=ac3 --disable-decoder=ac3_fixed --disable-decoder=eac3 --disable-decoder=dca --disable-decoder=truehd --disable-encoder=ac3 --disable-encoder=ac3_fixed --disable-encoder=eac3 --disable-encoder=dca --disable-decoder=hevc --disable-decoder=hevc_cuvid --disable-encoder=hevc_nvenc --disable-encoder=nvenc_hevc --extra-ldflags='-L/root/daily_build/64_05/4.4.1/LinkFS/usr/lib -L/root/daily_build/64_05/4.4.1/Model/TS-X72/build/RootFS/usr/local/medialibrary/lib -Wl,--rpath -Wl,/usr/local/medialibrary/lib' --extra-cflags='-I/root/daily_build/64_05/4.4.1/LinkFS/usr/include -I/root/daily_build/64_05/4.4.1/Model/TS-X72/build/RootFS/usr/local/medialibrary/include -D_GNU_SOURCE -DQNAP' --prefix=/root/daily_build/64_05/4.4.1/Model/TS-X72/build/RootFS/usr/local/medialibrary libavutil 55. 58.100 / 55. 58.100 libavcodec 57. 89.100 / 57. 89.100 libavformat 57. 71.100 / 57. 71.100 libavdevice 57. 6.100 / 57. 6.100 libavfilter 6. 82.100 / 6. 82.100 libswscale 4. 6.100 / 4. 6.100 libswresample 2. 7.100 / 2. 7.100 libpostproc 54. 5.100 / 54. 5.100 ``` However, when I then try `ffmpeg ---enable-libx264` I then get an error saying: ``` Unrecognized option '--enable-libx264'. Error splitting the argument list: Option not found ``` Do I need to change the configuaration of FFMPEG somehow or run another configuration option first or is there just something wrong with my call to enable libx264?
2020/03/07
[ "https://Stackoverflow.com/questions/60579432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4162831/" ]
This error means that Alamofire unexpectedly had no `Data` to process when trying to parse a response. You can run `debugPrint(response)` to see a lot more detail about the response, but this usually occurs when the server returns an empty response without a proper 204 or 205 code (usually a 200) to indicate the response should be empty. If that's the case, and you're running Alamofire 5.2+, you can pass additional empty response codes to your response handler: ```swift AF.request(...) .validate() .responseData(emptyResponseCodes: [200, 204, 205]) { response in // Process response. } ``` In Alamofire 5.0 to < 5.2, you can customize your response serializer by creating an instance directly: ```swift let serializer = DataResponseSerializer(emptyResponseCodes: Set([200, 204, 205])) // Use it to process your responses. AF.request(...) .validate() .response(responseSerializer: serializer) { response in // Process response. } ```
Firstly check if the data sent from server is valid json may be by running in postman and validating received json. Or else try sending the encoding type in request. e.g if its JSON or urlEncoded. for json: ``` `encoding: JSONEncoding.default` ``` for url encoded params: ``` encoding: URLEncoding.default ```
53,862,746
I have a navbar on the top and set the html and body to height 100% and i seperated the page into two columns using bootstrap grid and I want to set the height of the two columns that it should not exceed the page so that No scroll bar appears How to set the column height so that scroll bar do not appears
2018/12/20
[ "https://Stackoverflow.com/questions/53862746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8638750/" ]
You can achieve it using `height: 100%` on the **parent** and **grandparent** and so on. You can see a demo on codepen: <https://codepen.io/k-five/pen/gZgwqO> or here: ```css html,body{ height: 100%; margin: 0; padding: 0; border: none; } body > div.parent { height: 100%; } div.parent > span { display: inline-block; width: 50%; } div.parent > span:first-child { height: 100%; background-color: #F00; } div.parent > span:last-child { height: 100%; background-color: #FF0; } ``` ```html <!DOCTYPE> <html> <body> <div class="parent"> <span>1</span><span>2</span> </div> </body> </html> ``` And if you want to use **bootstrap** take look at <https://getbootstrap.com/docs/4.0/utilities/sizing/> which is `h-100`
Have you tried vh? ``` .column2{ height: 100vh } ``` It stands for viewport height, and will be the exact size of the screen you're viewing this on.
53,862,746
I have a navbar on the top and set the html and body to height 100% and i seperated the page into two columns using bootstrap grid and I want to set the height of the two columns that it should not exceed the page so that No scroll bar appears How to set the column height so that scroll bar do not appears
2018/12/20
[ "https://Stackoverflow.com/questions/53862746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8638750/" ]
You can achieve it using `height: 100%` on the **parent** and **grandparent** and so on. You can see a demo on codepen: <https://codepen.io/k-five/pen/gZgwqO> or here: ```css html,body{ height: 100%; margin: 0; padding: 0; border: none; } body > div.parent { height: 100%; } div.parent > span { display: inline-block; width: 50%; } div.parent > span:first-child { height: 100%; background-color: #F00; } div.parent > span:last-child { height: 100%; background-color: #FF0; } ``` ```html <!DOCTYPE> <html> <body> <div class="parent"> <span>1</span><span>2</span> </div> </body> </html> ``` And if you want to use **bootstrap** take look at <https://getbootstrap.com/docs/4.0/utilities/sizing/> which is `h-100`
Have you tried using `.row-eq-height` from Bootstrap? Have a look [here](http://getbootstrap.com.vn/examples/equal-height-columns/). Be warn though that they're using `flex` style so check your supported browsers first before using these kind of css. ``` /* * Row with equal height columns * -------------------------------------------------- */ .row-eq-height { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } ``` One more thing, for classes like these `col-md-6 col-sm-6 col-xs-6 col-lg-6` you don't have to specify all the breakpoints. Just use `col-xs-6` and it will be applied to all breakpoints hence "mobile first", to save you some code and filesize. Let me know if that helps. ;)
49,481,996
I have some functions that do a lot of calculations with data and arrays but all in memory, it does not do any IO. I've been reading trying to get into nodejs, I was wondering if there is any benefit on making then async? For example, function `a`: ``` function a(b, c, d) { // a lot of operations with arrays return value; } ``` Does it make any sense to return a promise in this case if it does not involve any IO blocking operation? For example: ``` function a(b, c, d) { return new Promise(resolve, reject) { // a lot of operations with arrays resolve(value); } } ``` Is there any improvement in using promises in this case or am I only overcomplicating this and should just return the value and not a promise?
2018/03/25
[ "https://Stackoverflow.com/questions/49481996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2002514/" ]
No, async functions are only syntax sugar on top of promises. If your function doesn't actually have any asynchronous operations (like a network request), it will keep executing synchronously and will resolve synchronously, so it'll be no different from an ordinary function. Javascript is single-threaded.
You can do the `lot of operations with arrays` in "batches" to avoid "blocking" other execution - the following is "pseudo" code in that you haven't shown what `// a lot of operations with arrays` actually is ... so ``` function a(b, c, d) { return new Promise((resolve, reject) => { function processBatch() { // do some operations with arrays if (error) { reject(error); } else if (needToProcessMore) { setImmediate(processBatch); } else { resolve(someResult); } } setImmediate(processBatch); }); } ``` Alternatively, (though I've never used them myself) there are "thread" and "thread worker" type libraries available for node
72,335,368
I am trying to send an API request to a server that needs http authentication. The (Wordpress server) is set to authenticate the API using basic authentication. First I am setting the session using the code ``` with requests.sessions.Session() as session: session.auth = ('my_user', 'my_password') session.get(url) ``` I get 200 as expected. Then I send the API request ``` credentials = "user:password" token = base64.b64encode(credentials.encode()) header = {"Authorization": "Basic " + token.decode('utf-8')} response = requests.get(url=url, headers=header) ``` But I get error 401 in the response. How can I do it differently to make it work?
2022/05/22
[ "https://Stackoverflow.com/questions/72335368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572919/" ]
i have some sample of mine, i hope it'll help you: ``` header = {....} data = {...} response= requests.post(url=url, data=data,headers=header,auth=(user,password)) ```
Taking from the two answers (thanks!), here is the answer that is a merge of the two. The API authentication is sent in the header (and an API authentication plugin is needed in WP). ``` credentials = "user:password" token = base64.b64encode(credentials.encode()) header = {"Authorization": "Basic " + token.decode('utf-8')} ``` The session authentication is sent in the auth parameter of the request ``` response = requests.get(url=url, headers=header, auth=('my_user', 'my_password')) ```
72,335,368
I am trying to send an API request to a server that needs http authentication. The (Wordpress server) is set to authenticate the API using basic authentication. First I am setting the session using the code ``` with requests.sessions.Session() as session: session.auth = ('my_user', 'my_password') session.get(url) ``` I get 200 as expected. Then I send the API request ``` credentials = "user:password" token = base64.b64encode(credentials.encode()) header = {"Authorization": "Basic " + token.decode('utf-8')} response = requests.get(url=url, headers=header) ``` But I get error 401 in the response. How can I do it differently to make it work?
2022/05/22
[ "https://Stackoverflow.com/questions/72335368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572919/" ]
as far as I know, wordpress does not even accept Authentication user/password by default. you can only login through cookies ([source](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#cookie-authentication)) but there is a way to authenticate rest api using user/password and that is plugins. I suggest [Wordpress REST API Authentication](https://wordpress.org/plugins/wp-rest-api-authentication/) then usage would be so easy like : ``` import requests headers = { 'Authorization': 'Basic base64encoded <username:password>', 'Content-Type': 'application/x-www-form-urlencoded', } data = 'title=sample post&status=publish' response = requests.post('http://example.com/wp-json/wp/v2/posts', headers=headers, data=data) ```
Taking from the two answers (thanks!), here is the answer that is a merge of the two. The API authentication is sent in the header (and an API authentication plugin is needed in WP). ``` credentials = "user:password" token = base64.b64encode(credentials.encode()) header = {"Authorization": "Basic " + token.decode('utf-8')} ``` The session authentication is sent in the auth parameter of the request ``` response = requests.get(url=url, headers=header, auth=('my_user', 'my_password')) ```
37,068,196
I have a SQL Server table like this ``` +----+-----------+------------+ | id | acoount | date | +----+-----------+------------+ | | John | 2/6/2016 | | | John | 2/6/2016 | | | John | 4/6/2016 | | | John | 4/6/2016 | | | Andi | 5/6/2016 | | | Steve | 4/6/2016 | +----+-----------+------------+ ``` i want insert the id coloumn like this. ``` +-----------+-----------+------------+ | id | acoount | date | +-----------+-----------+------------+ | 020616001 | John | 2/6/2016 | | 020616002 | John | 2/6/2016 | | 040616001 | John | 4/6/2016 | | 040616002 | John | 4/6/2016 | | 050616001 | Andi | 5/6/2016 | | 040616003 | Steve | 4/6/2016 | +-----------+-----------+------------+ ``` I want to generate id number of the date provided like this. 02+06+16(from date)+001 = 020616001. if have same date, id + 1. I have tried but still failed . I want make it in oracle sql develop. Someone help me. Thanks.
2016/05/06
[ "https://Stackoverflow.com/questions/37068196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4776200/" ]
Try the below SQL as per the given data, Its in SQL Server 2012.... ``` select REPLACE(CONVERT(VARCHAR(10),convert(date,t.[date]), 101), '/', '') +'00'+convert(varchar(2),row_number()over(partition by account,[date] order by t.[date])) as ID, t.account, t.date from (values ('John','2/6/2016'), ('John','2/6/2016'), ('John','4/6/2016'), ('John','4/6/2016'), ('Andi','5/6/2016'), ('Steve','4/6/2016'))T(account,[date]) ```
**MySql** i can give you the logic of `020616001` this part right now ....... for same id +1 i have to work on it....that i ll let u know after my work ``` insert into table_name(id) select concat ( if(length (day(current_date))>1,day(current_date),Concat(0,day(current_date))), if(length (month(current_date))>1,month(current_date),Concat(0,month(current_date))), (right(year(current_date),2)),'001' )as id ```
37,068,196
I have a SQL Server table like this ``` +----+-----------+------------+ | id | acoount | date | +----+-----------+------------+ | | John | 2/6/2016 | | | John | 2/6/2016 | | | John | 4/6/2016 | | | John | 4/6/2016 | | | Andi | 5/6/2016 | | | Steve | 4/6/2016 | +----+-----------+------------+ ``` i want insert the id coloumn like this. ``` +-----------+-----------+------------+ | id | acoount | date | +-----------+-----------+------------+ | 020616001 | John | 2/6/2016 | | 020616002 | John | 2/6/2016 | | 040616001 | John | 4/6/2016 | | 040616002 | John | 4/6/2016 | | 050616001 | Andi | 5/6/2016 | | 040616003 | Steve | 4/6/2016 | +-----------+-----------+------------+ ``` I want to generate id number of the date provided like this. 02+06+16(from date)+001 = 020616001. if have same date, id + 1. I have tried but still failed . I want make it in oracle sql develop. Someone help me. Thanks.
2016/05/06
[ "https://Stackoverflow.com/questions/37068196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4776200/" ]
Try the below SQL as per the given data, Its in SQL Server 2012.... ``` select REPLACE(CONVERT(VARCHAR(10),convert(date,t.[date]), 101), '/', '') +'00'+convert(varchar(2),row_number()over(partition by account,[date] order by t.[date])) as ID, t.account, t.date from (values ('John','2/6/2016'), ('John','2/6/2016'), ('John','4/6/2016'), ('John','4/6/2016'), ('Andi','5/6/2016'), ('Steve','4/6/2016'))T(account,[date]) ```
Update your table using statement . ``` update table set id= replace(CONVERT(VARCHAR(10),CONVERT(datetime ,date,103),3) ,'/', '') + Right('00'+convert(varchar(2),row_number()over(partition by account,[date] order by t.[date])) ,3) ```
37,068,196
I have a SQL Server table like this ``` +----+-----------+------------+ | id | acoount | date | +----+-----------+------------+ | | John | 2/6/2016 | | | John | 2/6/2016 | | | John | 4/6/2016 | | | John | 4/6/2016 | | | Andi | 5/6/2016 | | | Steve | 4/6/2016 | +----+-----------+------------+ ``` i want insert the id coloumn like this. ``` +-----------+-----------+------------+ | id | acoount | date | +-----------+-----------+------------+ | 020616001 | John | 2/6/2016 | | 020616002 | John | 2/6/2016 | | 040616001 | John | 4/6/2016 | | 040616002 | John | 4/6/2016 | | 050616001 | Andi | 5/6/2016 | | 040616003 | Steve | 4/6/2016 | +-----------+-----------+------------+ ``` I want to generate id number of the date provided like this. 02+06+16(from date)+001 = 020616001. if have same date, id + 1. I have tried but still failed . I want make it in oracle sql develop. Someone help me. Thanks.
2016/05/06
[ "https://Stackoverflow.com/questions/37068196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4776200/" ]
Try the below SQL as per the given data, Its in SQL Server 2012.... ``` select REPLACE(CONVERT(VARCHAR(10),convert(date,t.[date]), 101), '/', '') +'00'+convert(varchar(2),row_number()over(partition by account,[date] order by t.[date])) as ID, t.account, t.date from (values ('John','2/6/2016'), ('John','2/6/2016'), ('John','4/6/2016'), ('John','4/6/2016'), ('Andi','5/6/2016'), ('Steve','4/6/2016'))T(account,[date]) ```
you cannot convert your dates column to datetime type in normal way because it is dd/mm/yyyy. Try this, ``` declare @t table(acoount varchar(50),dates varchar(20)) insert into @t values ('John','2/6/2016') ,('John','2/6/2016') ,('John','4/6/2016') ,('John','4/6/2016') ,('Andi','5/6/2016') ,('Steve','4/6/2016') ;With CTE as (select * , SUBSTRING(dates,0,charindex('/',dates)) dd ,SUBSTRING(stuff(dates,1,charindex('/',dates),''),0, charindex('/',stuff(dates,1,charindex('/',dates),''))) MM ,right(dates,2) yy from @t ) ,CTE1 as ( select * ,ROW_NUMBER()over(partition by yy,mm,dd order by yy,mm,dd)rn from cte c ) select *, REPLICATE('0',2-len(dd))+cast(dd as varchar(2)) +REPLICATE('0',2-len(MM))+cast(MM as varchar(2)) +yy+REPLICATE('0',3-len(rn))+cast(rn as varchar(2)) from cte1 ```
36,434
My husband has been offered a job at a large company on the other side of the country. He told them he would commit to a long-term contract of up to two years, but that we did not want to move permanently. This was okay with the employer. The search firm who recruited him said they would "hire" him for the length of the contract, because he has not set up an LLC and the employer will only do 1099s with LLCs and corporations. He will be an employee of the search firm. The search firm offers benefits but they are not great. Cost of health insurance would be $1,800 per month for our family. There is a 401k plan but no matching. No paid time off. I have two questions: 1. Is it still best to go W-2 rather than 1099 tax-wise? (All work will be on-site at the employer, position won't require travel,few write-offs that I can see); 2. We are currently on Medi-Cal so pay nothing for health insurance. We have been living off taxed and penalized withdrawals from our retirement accounts for three years. The search firm requires a 60-day waiting period before we get coverage. Can we sign up for coverage through Obamacare until the health insurance plan kicks in or do we have to buy our own coverage? Once we leave the state, we won't be covered, and won't qualify for Medicare anyway once he has a salary again.
2014/08/27
[ "https://money.stackexchange.com/questions/36434", "https://money.stackexchange.com", "https://money.stackexchange.com/users/19931/" ]
I don't think anyone can give you a definitive answer without knowing all about your situation, but some things to consider: 1. If you are on a 1099, you have to pay self-employment tax, while on a W-2 you do not. That is, social security tax is 12.4% of your income. If you're a 1099, you pay the full 12.4%. If you're W-2, you pay 6.2% and the employer pays 6.2%. So if they offer you the same nominal rate of pay, you're 6.2% better off with the W-2. 2. What sort of insurance could you get privately and what would it cost you? I have no idea what the going rates for insurance are in California. If you're all in generally good health, you might want to consider a high-deductible policy. Then if no one gets seriously sick you've saved a bunch of money on premiums. If someone does get sick you might still pay less paying the deductible than you would have paid on higher premiums. I won't go into further details as that's getting off into another question. 3. Even if the benefits are poor, if there are any benefits at all it can be better than nothing. The only advantage I see to going with a 1099 is that if you are legally an independent contractor, then all your business expenses are deductible, while if you are an employee, there are sharp limits on deducting employee business expenses. Maybe others can think of other advantages. If there is some reason to go the 1099 route, I understand that setting up an LLC is not that hard. I've never done it, but I briefly looked into it once and it appeared to basically be a matter of filling out a form and paying a modest fee.
The tax savings of being 1099 can be significant. It depends on your salary, and what you can deduct. You may want to consult with an accountant. The social security tax, for the self employed, is 12.4% of profit not on revenue. If you can write off more than half of the income as expenses then you could be paying less than a w-2 employee. Also you might make a higher salary as a 1099, it is rare the offer the same compensation for a W-2 as a 1099 as the former has higher expenses for the employer. It is hard to know without actual numbers, actual expected expense deductions and so forth. Which is why I would suggest consulting with an accountant. You may want to talk to one in the state where he will be working rather than where you live now.
8,083,481
I would like to create an NSDate from a string: ``` NSString *mostRecentMentionMessageTimestamp = [mostRecentMessage valueForKey:@"updated_at"]; NSLog(@"%@",mostRecentMentionMessageTimestamp); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; NSDate *mostRecentMentionDate = [dateFormatter dateFromString:mostRecentMentionMessageTimestamp]; NSLog(@"%@",mostRecentMentionDate); ``` When I print my string it is: 2011-11-10T07:22:59Z After I make a date from string and print it, it is `(null)` What am I doing wrong?
2011/11/10
[ "https://Stackoverflow.com/questions/8083481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19875/" ]
You need to set the time zone and drop the `Z` at the end of the date format. Since your date has a `Z`, it is in UTC. So you can use: ``` [dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"UTC"]]; [dateFormatter setDateFormat: @"yyyy-MM-dd'T'HH:mm:ss"]; ```
the string value which you are trying to convert to NSDate is incorrect. "2011-11-10T07:22:59Z" it should have a timezone difference value in place of "Z" to make it compatible to date formatter's format. e.g. 2011-11-10T07:22:59+0430
8,083,481
I would like to create an NSDate from a string: ``` NSString *mostRecentMentionMessageTimestamp = [mostRecentMessage valueForKey:@"updated_at"]; NSLog(@"%@",mostRecentMentionMessageTimestamp); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; NSDate *mostRecentMentionDate = [dateFormatter dateFromString:mostRecentMentionMessageTimestamp]; NSLog(@"%@",mostRecentMentionDate); ``` When I print my string it is: 2011-11-10T07:22:59Z After I make a date from string and print it, it is `(null)` What am I doing wrong?
2011/11/10
[ "https://Stackoverflow.com/questions/8083481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19875/" ]
The format is almost correct, use: ``` [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; ``` to solve the time zone issue use the solution by @Jef add: ``` [dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"UTC"]]; ``` Full example code: ``` NSString *mostRecentMentionMessageTimestamp = @"2011-11-10T07:22:59Z"; NSLog(@"input: %@",mostRecentMentionMessageTimestamp); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"UTC"]]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; NSDate *mostRecentMentionDate = [dateFormatter dateFromString:mostRecentMentionMessageTimestamp]; NSLog(@"output: %@",mostRecentMentionDate); ``` NSLog output: ``` input: 2011-11-10T07:22:59Z output: 2011-11-10 07:22:59 +0000 ```
the string value which you are trying to convert to NSDate is incorrect. "2011-11-10T07:22:59Z" it should have a timezone difference value in place of "Z" to make it compatible to date formatter's format. e.g. 2011-11-10T07:22:59+0430
105,303
I've been out of college for a couple years and i'm quickly paying off my student loans. I have some loans and other bills I pay every month. I'll provide as many details as I can in order to get as much accuracy as possible! Student loans - $18k remaining - $1000/month Car - $22 remaining - $500/month (no interest) Jet Ski - $12k remaining - $250/month (until student loans are paid off, And various other bills such as cell phone, ISP, etc, but above are the loans I have. I have never missed any payments. I've paid off one other loan already (engagement ring - $2k). Below you can find some details about my credit score. These details are provided for free through one of my credit card providers (hopefully they are accurate and represent my true credit score?). [![Credit score details](https://i.stack.imgur.com/mvXF1.png)](https://i.stack.imgur.com/mvXF1.png) Finally for the question. If I continue at this pace, which I definitely plan to, how high will my credit score go and how quickly? My father has told me his score floats around 850 and it doesn't change too much anymore, but he is 56 years old and i'm only 24. I'm curious as to how long it takes to build up such a great credit score? Maybe the answer is to keep old accounts so your credit length goes up and to not miss a payment, but that doesn't tell me how fast my score will continue to go up. My score seems to go up little by little according to the chart above.
2019/02/13
[ "https://money.stackexchange.com/questions/105303", "https://money.stackexchange.com", "https://money.stackexchange.com/users/78903/" ]
> > **Can I pay tax on only the £25,000?** > > > No. you can claim some relief on CGT but you don't get to specify what gains occurred in what years. You get relief on a proportion of *overall* capital gain based on the ratio of time that was your main home to total years owned. You can't get relief on more than one property. See <https://www.gov.uk/tax-relief-selling-home/y/yes/no/no/yes>
I will add to the answer by @RedGrittyBrick that if you lived in a house, you get 18 months of exemption from capital gains tax "for free". So if you live in a house for 6 months, you are exempt from capital gains tax for a proportion of 2 years of the time you owned the house, for example. I will also add that if you complete before the end of this tax year (5th of April 2019), I think you qualify for Lettings Relief as you have lived in the house yourself as well has having let it out.
3,494,573
**User 2** offers to buy an item from **User 1**. **User 1** can *accept* or *reject*. If **User 1** *accepts*, then they will both be able to offer feedback about the transaction. I have 2 blocks of IF statements. **They both work and do the same thing but which is better coding practice?** > > **IF BLOCK 1** checks if which user is there first and then checks if the transaction was accepted or if its still pending > > > ``` if ($_SESSION['user_id'] == $seller) { if ($row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } else if ($_SESSION['user_id'] == $buyer) { if ($row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } ``` Or > > **IF BLOCK 2** has only 4 if statements and checks both user and status of transaction at same time > > > ``` if ($_SESSION['user_id'] == $seller && $row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($_SESSION['user_id'] == $seller && $row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } ```
2010/08/16
[ "https://Stackoverflow.com/questions/3494573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363004/" ]
This is subject to opinion, but I'm sure that most people will agree that the first one is cleaner because you're removing duplication (the check to see if they are buyer or seller). This will be even more apparent if you had more `status` types.
I would say block 1 is better coding practice in general, since you do not duplicate information. Having said that, Block 2 more accurately describes the set of Strategy patterned objects which might arise in a different language environment and which could reduce the complexity of your code further.
3,494,573
**User 2** offers to buy an item from **User 1**. **User 1** can *accept* or *reject*. If **User 1** *accepts*, then they will both be able to offer feedback about the transaction. I have 2 blocks of IF statements. **They both work and do the same thing but which is better coding practice?** > > **IF BLOCK 1** checks if which user is there first and then checks if the transaction was accepted or if its still pending > > > ``` if ($_SESSION['user_id'] == $seller) { if ($row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } else if ($_SESSION['user_id'] == $buyer) { if ($row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } ``` Or > > **IF BLOCK 2** has only 4 if statements and checks both user and status of transaction at same time > > > ``` if ($_SESSION['user_id'] == $seller && $row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($_SESSION['user_id'] == $seller && $row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } ```
2010/08/16
[ "https://Stackoverflow.com/questions/3494573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363004/" ]
The first one shows you the path: if the statuses were to increase in number, you could abstract the functionality into a function with little work. It looks and is cleaner. I'd also prefer to separate the actual HTML from PHP. Instead of ``` echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; ``` I'd prefer ``` <p> <?= get_username_by_id($row['buyer']) ?> has made a bid of <?= $row['price'] ?> for your <?= $row['title'] ?> <a href="transactions.php?id=<?= $transactionid ?>&action=accept">Accept</a> / <a href="transactions.php?id=<?=$transactionid?>&action=reject">Reject</a> </p> ``` But to each his own.
This is subject to opinion, but I'm sure that most people will agree that the first one is cleaner because you're removing duplication (the check to see if they are buyer or seller). This will be even more apparent if you had more `status` types.
3,494,573
**User 2** offers to buy an item from **User 1**. **User 1** can *accept* or *reject*. If **User 1** *accepts*, then they will both be able to offer feedback about the transaction. I have 2 blocks of IF statements. **They both work and do the same thing but which is better coding practice?** > > **IF BLOCK 1** checks if which user is there first and then checks if the transaction was accepted or if its still pending > > > ``` if ($_SESSION['user_id'] == $seller) { if ($row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } else if ($_SESSION['user_id'] == $buyer) { if ($row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } ``` Or > > **IF BLOCK 2** has only 4 if statements and checks both user and status of transaction at same time > > > ``` if ($_SESSION['user_id'] == $seller && $row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($_SESSION['user_id'] == $seller && $row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } ```
2010/08/16
[ "https://Stackoverflow.com/questions/3494573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363004/" ]
This is subject to opinion, but I'm sure that most people will agree that the first one is cleaner because you're removing duplication (the check to see if they are buyer or seller). This will be even more apparent if you had more `status` types.
As a personal choice I prefer the structure of option 1 because of the lower number of conditions. But I would change each `else if` to `elseif` to prevent errors because of omitted braces. To let the code show some common data is used in the output, and the differences in the closing `</p>` tag of each choice, I would change it into something like this: ``` $buyerName = get_username_by_id($row['buyer']); $price = $row['price']; $title = $row['title']; if ($_SESSION['user_id'] == $seller) { if ($row['status'] == 'P') { echo "<p>$buyerName has made a bid of $price for your $title" . " <a href='transactions.php?id=$transactionid&amp;action=accept'>Accept</a> /" . " <a href='transactions.php?id=$transactionid&amp;action=reject'>Reject</a><br />"; } elseif ($row['status'] == 'A') { echo "<p>$buyerName paid $price for your $title</p>" . "<a href='feedback.php?id=$transactionid&amp;action=givefeedback'>Give Feedback</a></p>"; } } elseif ($_SESSION['user_id'] == $buyer) { if ($row['status'] == 'P') { echo "<p> You have made a bid of $price for $title</p>"; } elseif ($row['status'] == 'A') { echo "<p> You have paid $price for $title</p>" . " <a href='feedback.php?id=$transactionid&amp;action=givefeedback'>Give Feedback</a></p>"; } } ```
3,494,573
**User 2** offers to buy an item from **User 1**. **User 1** can *accept* or *reject*. If **User 1** *accepts*, then they will both be able to offer feedback about the transaction. I have 2 blocks of IF statements. **They both work and do the same thing but which is better coding practice?** > > **IF BLOCK 1** checks if which user is there first and then checks if the transaction was accepted or if its still pending > > > ``` if ($_SESSION['user_id'] == $seller) { if ($row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } else if ($_SESSION['user_id'] == $buyer) { if ($row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } ``` Or > > **IF BLOCK 2** has only 4 if statements and checks both user and status of transaction at same time > > > ``` if ($_SESSION['user_id'] == $seller && $row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($_SESSION['user_id'] == $seller && $row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } ```
2010/08/16
[ "https://Stackoverflow.com/questions/3494573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363004/" ]
The first one shows you the path: if the statuses were to increase in number, you could abstract the functionality into a function with little work. It looks and is cleaner. I'd also prefer to separate the actual HTML from PHP. Instead of ``` echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; ``` I'd prefer ``` <p> <?= get_username_by_id($row['buyer']) ?> has made a bid of <?= $row['price'] ?> for your <?= $row['title'] ?> <a href="transactions.php?id=<?= $transactionid ?>&action=accept">Accept</a> / <a href="transactions.php?id=<?=$transactionid?>&action=reject">Reject</a> </p> ``` But to each his own.
I would say block 1 is better coding practice in general, since you do not duplicate information. Having said that, Block 2 more accurately describes the set of Strategy patterned objects which might arise in a different language environment and which could reduce the complexity of your code further.
3,494,573
**User 2** offers to buy an item from **User 1**. **User 1** can *accept* or *reject*. If **User 1** *accepts*, then they will both be able to offer feedback about the transaction. I have 2 blocks of IF statements. **They both work and do the same thing but which is better coding practice?** > > **IF BLOCK 1** checks if which user is there first and then checks if the transaction was accepted or if its still pending > > > ``` if ($_SESSION['user_id'] == $seller) { if ($row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } else if ($_SESSION['user_id'] == $buyer) { if ($row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } } ``` Or > > **IF BLOCK 2** has only 4 if statements and checks both user and status of transaction at same time > > > ``` if ($_SESSION['user_id'] == $seller && $row['status'] == 'P') { echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'P') { echo '<p> You have made a bid of ' . $row['price'] . ' for ' . $row['title'] . '</p>'; } else if ($_SESSION['user_id'] == $seller && $row['status'] == 'A') { echo '<p>' . get_username_by_id($row['buyer']) . ' paid ' . $row['price'] . ' for your ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } else if ($_SESSION['user_id'] == $buyer && $row['status'] == 'A') { echo '<p> You have paid ' . $row['price'] . ' for ' . $row['title'] . '</p>'; echo '<a href="feedback.php?id=' . $transactionid . '&action=givefeedback">Give Feedback</a></p>'; } ```
2010/08/16
[ "https://Stackoverflow.com/questions/3494573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363004/" ]
The first one shows you the path: if the statuses were to increase in number, you could abstract the functionality into a function with little work. It looks and is cleaner. I'd also prefer to separate the actual HTML from PHP. Instead of ``` echo '<p>' . get_username_by_id($row['buyer']) . ' has made a bid of ' . $row['price'] . ' for your ' . $row['title'] . ' <a href="transactions.php?id=' . $transactionid . '&action=accept">Accept</a> / <a href="transactions.php?id=' . $transactionid . '&action=reject">Reject</a><br />'; ``` I'd prefer ``` <p> <?= get_username_by_id($row['buyer']) ?> has made a bid of <?= $row['price'] ?> for your <?= $row['title'] ?> <a href="transactions.php?id=<?= $transactionid ?>&action=accept">Accept</a> / <a href="transactions.php?id=<?=$transactionid?>&action=reject">Reject</a> </p> ``` But to each his own.
As a personal choice I prefer the structure of option 1 because of the lower number of conditions. But I would change each `else if` to `elseif` to prevent errors because of omitted braces. To let the code show some common data is used in the output, and the differences in the closing `</p>` tag of each choice, I would change it into something like this: ``` $buyerName = get_username_by_id($row['buyer']); $price = $row['price']; $title = $row['title']; if ($_SESSION['user_id'] == $seller) { if ($row['status'] == 'P') { echo "<p>$buyerName has made a bid of $price for your $title" . " <a href='transactions.php?id=$transactionid&amp;action=accept'>Accept</a> /" . " <a href='transactions.php?id=$transactionid&amp;action=reject'>Reject</a><br />"; } elseif ($row['status'] == 'A') { echo "<p>$buyerName paid $price for your $title</p>" . "<a href='feedback.php?id=$transactionid&amp;action=givefeedback'>Give Feedback</a></p>"; } } elseif ($_SESSION['user_id'] == $buyer) { if ($row['status'] == 'P') { echo "<p> You have made a bid of $price for $title</p>"; } elseif ($row['status'] == 'A') { echo "<p> You have paid $price for $title</p>" . " <a href='feedback.php?id=$transactionid&amp;action=givefeedback'>Give Feedback</a></p>"; } } ```
39,016,994
I have 2 two level JavaScript structures, which I need to merge. What would be the easiest way? ``` var object1={ "section1": { "prop1": 0, "prop2": 0 }, "section2": { "something": 0, "other": 0 } } var object2={ "section1": { "prop1": 1 } } ``` object2 contains changes made in the UI by user and I need to get the merged object, showing all the data, with only those properties present in object2 overwritten by object2's values.
2016/08/18
[ "https://Stackoverflow.com/questions/39016994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1328249/" ]
You can do this with `Object.keys()` and `reduce()` and update each object if key is found i object2 with `Object.assign()`. ```js var object1={ "section1": { "prop1": 0, "prop2": 0 }, "section2": { "something": 0, "other": 0 } } var object2={ "section1": { "prop1": 5 } } var result = Object.keys(object1).reduce(function(r, k) { if(object2[k]) { r[k] = Object.assign({}, object1[k], object2[k]); } else { r[k] = object1[k]; } return r; }, {}); console.log(result); ```
`var mergedObj = Object.assign({}, object1, object2)` if I understood your question correctly.
31,367,767
``` public class MyFibonacci { public static void main(String a[]){ int febCount = 15; int[] feb = new int[febCount]; feb[0] = 0; feb[1] = 1; for(int i=2; i < febCount; i++){ feb[i] = feb[i-1] + feb[i-2]; } for(int i=0; i< febCount; i++){ System.out.print(feb[i] + " "); } } } ``` What do I need to add in this so I can reverse the printed fiboonaci series?
2015/07/12
[ "https://Stackoverflow.com/questions/31367767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2520118/" ]
You don't need hierarchy of Views, you should use [Route Config](http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs) that will allow you to get View that you need base on URL. From 4 Version of MVC also have [areas](http://www.codeproject.com/Articles/714356/Areas-in-ASP-NET-MVC) not only controlles and View by default. So check this [tutorial](http://www.codeproject.com/Articles/641783/Customizing-Routes-in-ASP-NET-MVC) to know how to customise your Routing.
You don't need to create views in this hierarchy but you need to create URLs in this fashion and that is called friendly URLs. Look at following stack overflow question [How can I create a friendly URL in ASP.NET MVC?](https://stackoverflow.com/questions/217960/how-can-i-create-a-friendly-url-in-asp-net-mvc) and [Friendly URL](http://www.asp.net/aspnet/overview/friendly-urls) --- You will be defining another route which will end up on your single action method. So You will add a route in routeConfig.cs as follows ``` routes.MapRoute( name: "custom", url: "{category}/{type}/{manufacturer}/{version}/{Title}", defaults: new { controller = "Home", action = "customRoute"} ); ``` and your custom action will have all values passed in as param be as follows ``` public string customRoute(string category, string type, string manufacturer, string version, string Title) { return category + type + manufacturer + version + Title; } ``` You can achieve the same using action based routing as well ``` // eg: electronics/mobiles/samsung/samsungS3/adTitle [Route("{category}/{type}/{manufacturer}/{Title}")] public ActionResult Index(string cateogry, string type,string manfacture, string Title) { ... } ```
73,778,482
I need your help trying to automate this web page by getting the data of all the players on the different pages. ``` import request import pandas as pd from bs4 import BeautifulSoup url = 'https://www.mlb.com/es/stats/spring-training' pagina = requests.get(url2) soup = BeautifulSoup(pagina.text, 'lxml') table = soup.find('table', {'class':"bui-table is-desktop-sKqjv9Sb"}) encabezados = [] for i in table.find_all('th')[:18]: datos = i.find_all('button') for td in datos: titulo = td.text.strip() encabezados.append(titulo) datos_mlb = pd.DataFrame(columns = encabezados) nombres = [] for i in table.find_all('th')[18:]: datos = i.find_all('a') for td in datos: jugadores = td.text.strip() nombres.append(jugadores) datos_mlb['JUGADOR'] = nombres for fila in table.find_all('tr')[1:]: data = fila.find_all('td') data_fila = [td.text.strip() for td in data] largo = len(datos_mlb)-1 datos_mlb.iloc[:,1:] = data_fila ``` I have tried to fit the vast majority of information, however I cannot complete the data correctly and iterate all the pages.
2022/09/19
[ "https://Stackoverflow.com/questions/73778482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14284945/" ]
1. It sounds like you're getting a compile error on line 8: ``` wiringPiSetup() /* <-- You need to end the line with ";" */ ``` 2. Your loop should look like this: ``` for(x=0; x<4; x++) {...} /* "x+1" doesn't change the value of "x", so the loop will never terminate */ ```
The problem is in your for loop. ``` for(x=0; x<4; x+1) ``` The third parameter in brackets does not do anything. You probably wanted to increment `x` and you will do that with `x++` or `x+=1`. `x+1` will return the value, but that will not be stored anywhere.
37,390,846
I'm using a EEG detection kit called Gtec.NAUTILUS which gives me binary data for 32 channels at 500hz. The data is then converted to CSV format. Now I want to process these data in Microsoft Azure using python 3.5.1 however CSV file is not recognized in MNE library (which is used for EEG data analysis). There are also other formats that are supported in MNE. ( .cnt , .edf , .bdf , .egi , .set ) Additional info @ : <http://martinos.org/mne/stable/manual/io.html#ch-convert> My primary question is; - How can i convert csv file to one of the supported formats? Additionaly; - How can i convert binary file to one of the supported formats in mne? (if previous question is not possible) Also; - Does someone have an experience in processing EEG data? Am i doing an essential mistake while data processing? Note : I am performing this process for EEG data analysis in MATLAB, however it seems microsoft azure does not support it. Therefore I'm trying to learn python for compatibility. Thanks in advance. --- For those who are interested: Free programs from third party developers: <http://www.biosemi.com/download.htm>
2016/05/23
[ "https://Stackoverflow.com/questions/37390846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6371028/" ]
MNE doesn't support reading from Gtec devices out of the box. However, reading the CSV file with Numpy and creating an MNE Raw object is not that difficult: ``` import numpy as np import mne # Read the CSV file as a NumPy array data = np.loadtxt('path/to/csv/file', delimiter=',') # Some information about the channels ch_names = ['CH 1', 'CH 2', 'CH 3'] # TODO: finish this list # Sampling rate of the Nautilus machine sfreq = 500 # Hz # Create the info structure needed by MNE info = mne.create_info(ch_names, sfreq) # Finally, create the Raw object raw = mne.io.RawArray(data, info) # Plot it! raw.plot() ```
I searched the GitHub project [`EEGrunt`](https://github.com/curiositry/EEGrunt) which can read EEG data from CSV files. According to their offical site, the `EEGrunt` & `MNE` all depend on the package `Numpy`, so I think you can try to read raw data from CSV file using `EEGrunt and read the raw data from memory using`MNE`. Hope it helps.
13,123,069
I am new to this forum and also fairly new to jQuery so it is (as I think) a basic question but I could not find the answer and everything I tried did not work. I have a button on a page that should do certain things and change the class. And with the new class revert those things. This is the code: ``` $("#info_button.buttonOff").click(function() { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); }); $("#info_button.buttonOn").click(function() { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); ``` The first event alone work. But as soon as I add the second event nothing works anymore. I think I have to do something with .unbind() but could not figure out how. Please help.
2012/10/29
[ "https://Stackoverflow.com/questions/13123069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782887/" ]
The problem is that the jQuery collection is computed only once. Use ``` $(document).on('click', "#info_button.buttonOff", function() { ``` and ``` $(document).on('click', "#info_button.buttonOn", function() { ``` With this, the selector will be tested everytime a click occurs. As your element has an ID, a lighter solution could be ``` $("#info_button").click(function() { if ($(this).hasClass('buttonOn')) { // do something } else { ... ``` But I'd generally prefer the first one.
The easiest solution would be to test the class inside the click handler for the button: ``` $("#info_button").click(function() { if ($(this).hasClass('buttonOff')) { // ... } else if ($(this).hasClass('buttonOn')) { // ... } }); ```
13,123,069
I am new to this forum and also fairly new to jQuery so it is (as I think) a basic question but I could not find the answer and everything I tried did not work. I have a button on a page that should do certain things and change the class. And with the new class revert those things. This is the code: ``` $("#info_button.buttonOff").click(function() { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); }); $("#info_button.buttonOn").click(function() { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); ``` The first event alone work. But as soon as I add the second event nothing works anymore. I think I have to do something with .unbind() but could not figure out how. Please help.
2012/10/29
[ "https://Stackoverflow.com/questions/13123069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782887/" ]
The problem is that the jQuery collection is computed only once. Use ``` $(document).on('click', "#info_button.buttonOff", function() { ``` and ``` $(document).on('click', "#info_button.buttonOn", function() { ``` With this, the selector will be tested everytime a click occurs. As your element has an ID, a lighter solution could be ``` $("#info_button").click(function() { if ($(this).hasClass('buttonOn')) { // do something } else { ... ``` But I'd generally prefer the first one.
Use : ``` $(document).on('click', "#info_button", function() { $(".content").slideUp(300, function() { if ($("#info").is(':visible')) $("#info").slideUp(300); else $("#info").slideDown(300); $("#info").toggleClass("contentOn"); this.toggleClass("buttonOn").toggleClass("buttonOff"); if ($("#overlay").is(':visible')) $("#overlay").fadeOut(300); else $("#overlay").fadeIn(300); }); }); ```
13,123,069
I am new to this forum and also fairly new to jQuery so it is (as I think) a basic question but I could not find the answer and everything I tried did not work. I have a button on a page that should do certain things and change the class. And with the new class revert those things. This is the code: ``` $("#info_button.buttonOff").click(function() { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); }); $("#info_button.buttonOn").click(function() { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); ``` The first event alone work. But as soon as I add the second event nothing works anymore. I think I have to do something with .unbind() but could not figure out how. Please help.
2012/10/29
[ "https://Stackoverflow.com/questions/13123069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782887/" ]
The problem is that the jQuery collection is computed only once. Use ``` $(document).on('click', "#info_button.buttonOff", function() { ``` and ``` $(document).on('click', "#info_button.buttonOn", function() { ``` With this, the selector will be tested everytime a click occurs. As your element has an ID, a lighter solution could be ``` $("#info_button").click(function() { if ($(this).hasClass('buttonOn')) { // do something } else { ... ``` But I'd generally prefer the first one.
What probably is happening is that both of your binding events are referring to the same element, so these functions would probably be interfering with each other. You may try doing something like this: ``` $("#info_button").click(function() { if($(this).hasClass('buttonOff') { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); } else if($(this).hasClass('buttonOn') { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); } }); ```
13,123,069
I am new to this forum and also fairly new to jQuery so it is (as I think) a basic question but I could not find the answer and everything I tried did not work. I have a button on a page that should do certain things and change the class. And with the new class revert those things. This is the code: ``` $("#info_button.buttonOff").click(function() { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); }); $("#info_button.buttonOn").click(function() { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); ``` The first event alone work. But as soon as I add the second event nothing works anymore. I think I have to do something with .unbind() but could not figure out how. Please help.
2012/10/29
[ "https://Stackoverflow.com/questions/13123069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782887/" ]
The easiest solution would be to test the class inside the click handler for the button: ``` $("#info_button").click(function() { if ($(this).hasClass('buttonOff')) { // ... } else if ($(this).hasClass('buttonOn')) { // ... } }); ```
What probably is happening is that both of your binding events are referring to the same element, so these functions would probably be interfering with each other. You may try doing something like this: ``` $("#info_button").click(function() { if($(this).hasClass('buttonOff') { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); } else if($(this).hasClass('buttonOn') { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); } }); ```
13,123,069
I am new to this forum and also fairly new to jQuery so it is (as I think) a basic question but I could not find the answer and everything I tried did not work. I have a button on a page that should do certain things and change the class. And with the new class revert those things. This is the code: ``` $("#info_button.buttonOff").click(function() { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); }); $("#info_button.buttonOn").click(function() { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); ``` The first event alone work. But as soon as I add the second event nothing works anymore. I think I have to do something with .unbind() but could not figure out how. Please help.
2012/10/29
[ "https://Stackoverflow.com/questions/13123069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782887/" ]
Use : ``` $(document).on('click', "#info_button", function() { $(".content").slideUp(300, function() { if ($("#info").is(':visible')) $("#info").slideUp(300); else $("#info").slideDown(300); $("#info").toggleClass("contentOn"); this.toggleClass("buttonOn").toggleClass("buttonOff"); if ($("#overlay").is(':visible')) $("#overlay").fadeOut(300); else $("#overlay").fadeIn(300); }); }); ```
What probably is happening is that both of your binding events are referring to the same element, so these functions would probably be interfering with each other. You may try doing something like this: ``` $("#info_button").click(function() { if($(this).hasClass('buttonOff') { $(".content").slideUp(300, function() { $("#info").slideDown(300); $("#info").addClass("contentOn"); $("#info_button").removeClass("buttonOff").addClass("buttonOn"); $("#overlay").fadeIn(300); }); } else if($(this).hasClass('buttonOn') { $(".content").slideUp(300); $("#info").removeClass("contentOn"); $("#info_button").removeClass("buttonOn").addClass("buttonOff"); $("#overlay").fadeOut(300); }); } }); ```
5,120,395
I have been looking into using PDFKit to generate pdf reports for a Rail 3 app I'm working on. Basically if I use PDFKit as middleware any page in the app is nicely rendered to pdf including the javascript generated graphs. However, I want to use a different layout for pdf reports that removes any of the sidebar or navigation details so instead of using the middleware option I have been playing around with adding the following to the relevant controller action ``` format.pdf { html = render_to_string(:action => "show.html.erb", :layout => "report.html.erb") kit = PDFKit.new(html) kit.stylesheets << "#{Rails.root}/public/stylesheets/application.css" send_data kit.to_pdf, :filename => "file.pdf", :type => :pdf} ``` (I also tried the neater option of extracting this functionality to a renderer option as Katz describes [here](http://www.engineyard.com/blog/2010/render-options-in-rails-3/#idc-container) but the logic and the problem are the same) This definitely solves my layout problem but it appears that none of the app's javascripts are being run and the graphs are no longer appearing. I had a look at the PDFKit source but I couldn't spot any major differences in the way the pdfs are produced. I'm still finding my feet with a lot of things with rails so I'm sure it is probably something pretty obvious that is staring me in the face. Any pointers that anyone might have would be greatly appreciated
2011/02/25
[ "https://Stackoverflow.com/questions/5120395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509776/" ]
This basically is the solution I went with which is roughly based on Katz's really great [blog post](http://www.engineyard.com/blog/2010/render-options-in-rails-3/) ``` ActionController.add_renderer :pdf do |template, options| html = render_to_string template, options html = translate_paths(html, env) kit = PDFKit.new(html) css_files = Array.wrap(options.delete(:css)).each do |css_sheet| kit.stylesheets << "#{Rails.root}/public/stylesheets/#{css_sheet}.css" end send_data kit.to_pdf, :filename => options[:filename], :type => Mime::PDF end ``` The translate\_paths method is basically the same as the one used in PDKKit rack middleware code which can be seen [here](https://github.com/jdpace/PDFKit/blob/master/lib/pdfkit/middleware.rb) and below ``` def translate_paths(body, env) # Host with protocol root = "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/" body.gsub(/(href|src)=(['"])\/([^\"']*|[^"']*)['"]/, '\1=\2' + root + '\3\2') end ```
1. add :print\_media\_type => true as an option with the middleware for example: config.middleware.use "PDFKit::Middleware", :print\_media\_type => true 2. add :media => "all" while including your stylesheets 3. in you stylesheet file add the following > > > ``` > @media print { > #id_of_divs_to_hide{ > display: none; > } > } > > ``` > >
3,764,650
Is someone out there who is using ZooKeeper for their sites? If you do, what do you use it for? i just want to see real word use case?
2010/09/21
[ "https://Stackoverflow.com/questions/3764650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454451/" ]
I've just started doing the research for using Zookeeper for a number of cases in my companies infrastructure. The one that seems to fit ZK the best is where we have an array of 30+ dynamic content servers that rely heavily on file based caching ( Memcached is too slow ). Each of these servers will have an agent watching a specific ZK path and when a new node shows up, all servers join into a barrier lock, then once all of them are present, they all update their configuration at the exact same time. This way we can keep all 30 servers configuration / run-states consistent. Second use case, we receive 45-70 million page views a day in a typical bell curve like pattern. The caching strategy implemented falls from client, to CDN, to memcache, and then to file cache before determining when to make a DB call. Even with a series of locks in place, it's pretty typical to get race conditions ( I've nicknamed them stampedes ) that can strain our backend. The hope is that ZK can provide a tool for developing a consistent and unified locking service across multiple servers and maybe data-centers.
The ZooKeeper "PoweredBy" page has some detail that you might find interesting: <https://cwiki.apache.org/confluence/display/ZOOKEEPER/PoweredBy> HBase uses ZK and is open source (Apache) which would allow you to look at actual code. <http://hbase.apache.org/>
3,764,650
Is someone out there who is using ZooKeeper for their sites? If you do, what do you use it for? i just want to see real word use case?
2010/09/21
[ "https://Stackoverflow.com/questions/3764650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454451/" ]
I've just started doing the research for using Zookeeper for a number of cases in my companies infrastructure. The one that seems to fit ZK the best is where we have an array of 30+ dynamic content servers that rely heavily on file based caching ( Memcached is too slow ). Each of these servers will have an agent watching a specific ZK path and when a new node shows up, all servers join into a barrier lock, then once all of them are present, they all update their configuration at the exact same time. This way we can keep all 30 servers configuration / run-states consistent. Second use case, we receive 45-70 million page views a day in a typical bell curve like pattern. The caching strategy implemented falls from client, to CDN, to memcache, and then to file cache before determining when to make a DB call. Even with a series of locks in place, it's pretty typical to get race conditions ( I've nicknamed them stampedes ) that can strain our backend. The hope is that ZK can provide a tool for developing a consistent and unified locking service across multiple servers and maybe data-centers.
You may be interested in the recently published scientific paper on ZooKeeper: <http://research.yahoo.com/node/3280> The paper also describes three use cases and comparable projects. We do use ZK as a dependency of HBase and have implemented a scheduled work queue for a feed reader (millions of feeds) with it.
16,169,815
I want to find all indexes for each occurrence of single alphabetical characters in a string. I don't want to catch single char html codes. Here is my code: ``` import re s = "fish oil B stack peanut c <b>" words = re.finditer('\S+', s) has_alpha = re.compile(??????).search for word in words: if has_alpha(word.group()): print (word.start()) ``` Desired output: ``` 9 24 ```
2013/04/23
[ "https://Stackoverflow.com/questions/16169815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2104778/" ]
This does it: ``` r'(?i)\b[a-z]\b' ``` Breaking it down: * Case insensitive match * A word boundary * A letter * A word boundary Your code can be simplified to this: ``` for match in re.finditer(r'(?i)\b[a-z]\b', s): print match.start() ```
In the most general case I'd say: ``` re.compile(r'(?i)(?<![a-z])[a-z](?![a-z])').search ``` Using [lookarounds](http://www.regular-expressions.info/lookaround.html) to say "a letter not preceded by another letter nor followed by another letter".
16,169,815
I want to find all indexes for each occurrence of single alphabetical characters in a string. I don't want to catch single char html codes. Here is my code: ``` import re s = "fish oil B stack peanut c <b>" words = re.finditer('\S+', s) has_alpha = re.compile(??????).search for word in words: if has_alpha(word.group()): print (word.start()) ``` Desired output: ``` 9 24 ```
2013/04/23
[ "https://Stackoverflow.com/questions/16169815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2104778/" ]
Using your format ([as you wanted](https://stackoverflow.com/questions/16169815/python-regex-find-all-single-alphabetical-characters/16170564#comment23110496_16169898)) but adding only a simple check. ``` import re s = "fish oil B stack peanut c <b>" words = re.finditer('\S+', s) has_alpha = re.compile(r'[a-zA-Z]').search for word in words: if len(word.group()) == 1 and has_alpha(word.group()): print (word.start()) >>> 9 24 ```
In the most general case I'd say: ``` re.compile(r'(?i)(?<![a-z])[a-z](?![a-z])').search ``` Using [lookarounds](http://www.regular-expressions.info/lookaround.html) to say "a letter not preceded by another letter nor followed by another letter".
21,644,312
I tried to get the output for this code but I am getting error, when compiling the program and the error is > > illegal start of expression > > > ``` class Main { public static void main(String[] args) { static int t = 5; for(int i = 0;i<2; i++){ t += i; } System.out.println (t); } } } ``` and one more question can we write static variable inside static method and can we change static value? and please give any exact reason...
2014/02/08
[ "https://Stackoverflow.com/questions/21644312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3164190/" ]
You can't have a `static` local variable. That's one issue. Also, you've an extra closing parenthesis.
In method you can not use `static` variables. Use the same variable without `static`.
21,644,312
I tried to get the output for this code but I am getting error, when compiling the program and the error is > > illegal start of expression > > > ``` class Main { public static void main(String[] args) { static int t = 5; for(int i = 0;i<2; i++){ t += i; } System.out.println (t); } } } ``` and one more question can we write static variable inside static method and can we change static value? and please give any exact reason...
2014/02/08
[ "https://Stackoverflow.com/questions/21644312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3164190/" ]
You can't have a `static` local variable. That's one issue. Also, you've an extra closing parenthesis.
`static` variable cannot be declared as a local variable. ``` static int t = 5; public static void main(String[] args) { // static int t = 5; for (int i = 0; i < 2; i++) { t += i; } System.out.println(t); } ```
6,067,945
I am working on project where I need to delete all empty folder (directories) from specific location. I am sure there is no direct way to find empty director in folder. I just write below method to delete empty folder in hierarchy. Can anyone have better solution? ``` <cffunction name="deleteEmptyFolder" access="public" output="true" returntype="boolean"> <cfargument name="path" required="true" type="string" /> <cfset var qList=""> <cfset var qDir = ""> <cfset var qFiles = ""> <cfset var isEmpty = 1> <!--- List Directory ---> <cfdirectory action="list" directory="#arguments.path#" recurse="no" name="qList"> <!--- get sub directory list ---> <cfquery name="qDir" dbtype="query"> select * from qList where type='Dir' </cfquery> <!--- Call recursive function to check directory empty or not ---> <cfloop query="qDir"> <!--- If sub directory not empty mark current directory as not empty. ---> <cfif not deleteEmptyFolder(qDir.directory & "\" & qDir.name)> <cfset isEmpty=0> </cfif> </cfloop> <!--- Check for file exists in current directory ---> <cfquery name="qFiles" dbtype="query"> select * from qList where type='File' </cfquery> <!--- If file exists mark as not empty ---> <cfif qFiles.recordCount gt 0> <cfset isEmpty = 0> </cfif> <!--- If current directory empty then delete it ---> <cfif isEmpty> <cfdirectory action="delete" recurse="false" directory="#arguments.path#"> </cfif> <!--- Return empty status for current directory ---> <cfreturn isEmpty> </cffunction> ```
2011/05/20
[ "https://Stackoverflow.com/questions/6067945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/639209/" ]
``` <cffunction name="deleteEmptyFolders" output="false"> <cfargument name="path" required="true" /> <cfset var subfolders = "" /> <cfdirectory name="subfolders" action="list" directory="#path#" type="dir" /> <cfloop query="subfolders"> <cfset deleteEmptyFolders("#path#/#subfolders.name#") /> </cfloop> <cftry> <cfdirectory action="delete" directory="#path#" /> <cfcatch></cfcatch> </cftry> </cffunction> ``` Edit: The error catch is there just to make the code simpler and avoid another file list calls. You can also use this instead... ``` <cfdirectory name="files" action="list" directory="#path#" /> <cfif not files.recordcount> <cfdirectory action="delete" directory="#path#" /> </cfif> ```
take help of following it will serve the purpose though i am not a cf programmer ``` <!---Deleting a directory Check that the directory exists and that files are not in the directory to avoid getting ColdFusion error messages. ---> <cfset currentDirectory = GetDirectoryFromPath(GetTemplatePath()) & "otherNewDir"> <!--- Check whether the directory exists. ---> <cfif DirectoryExists(currentDirectory)> <!--- If yes, check whether there are files in the directory before deleting. ---> <cfdirectory action="list" directory="#currentDirectory#" name="myDirectory"> <cfif myDirectory.recordcount gt 0> <!--- If yes, delete the files from the directory. ---> <cfoutput> <p>Files exist in this directory. Either delete the files or code something to do so.</P> </cfoutput> <cfelse> <!--- Directory is empty - just delete the directory. ---> <cfdirectory action = "delete" directory = "#currentDirectory#"> <cfoutput> <p>The directory existed and has been deleted.</P> </cfoutput> </cfif> <cfelse> <!--- If no, post message or do some other function. ---> <cfoutput><p>The directory did NOT exist.</p></cfoutput> </cfif> ``` [ANSWER SOURCE](http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_d-e_03.html)
17,580
Our client build tons of articles in our craft system instead of *his*. Both systems have the identical structure, in fact, his system is a exact copy of ours, which runs on a different server. How can we move all *his* content on *our* craft system into *his* system? (As you may have noticed I am not a developer. I hope you get what my problem is here ... )
2016/11/04
[ "https://craftcms.stackexchange.com/questions/17580", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/5082/" ]
This can be a challenging situation. Craft content can be highly relational which makes it tricky to just export and re-import. Scenario 1: *If your database and your clients database were both equivalent before your client added the additional content, you may be able to just migrate over your clients database and replace your own database and get both back in sync.* To **migrate the database** would involve exporting the database from the clients environment (either via `Settings->Tools->Backup Database` or via a database admin tool) and reimporting it into your environment with a database admin tool. Scenario 2: *If both you and your client made changes to your respective databases (for example, you both added articles in each environment) and you need to preserve the new articles added in your environment while also migrating over the articles added in the clients environment you have two options.* First, you could just **manually re-enter the articles** in the right environment. As it sounds like your client added a lot of articles, that might be time consuming, but sometimes these types of mistakes take time to correct manually. It's often the best option. In the case you added a few articles and your client added many articles, it may make more sense to add your articles to your clients database and then migrate the full database back to your servers as described in Scenario 1. Your second option would be to **migrate the content programmatically**. This becomes a bit more technical so you'd probably need to get a front-end or back-end developer involved. And it will only make sense to go this route if the quantity of data you need to migrate is too much to just do manually. A plugin like [Sprout Import](http://sprout.barrelstrengthdesign.com/craft-plugins/import) can help with this scenario. (Full disclosure, my team developed Sprout Import.) The steps would involve outputting the content from your clients database into a template into an importable JSON format. And then importing the content defined in the JSON file into your database. The docs and examples within the plugin would go into more detail about the exact format you would need. For this answer, the more general point is that if your data was complex enough, a database migration plugin like Sprout Import could help provide a path toward a solution.
You should be able to back up the database in the Settings panel in *your* version of Craft, and then drop the database on *his* server in PHPmyAdmin and load in the backup. This will replace everything on his server with what's on yours.
17,580
Our client build tons of articles in our craft system instead of *his*. Both systems have the identical structure, in fact, his system is a exact copy of ours, which runs on a different server. How can we move all *his* content on *our* craft system into *his* system? (As you may have noticed I am not a developer. I hope you get what my problem is here ... )
2016/11/04
[ "https://craftcms.stackexchange.com/questions/17580", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/5082/" ]
This can be a challenging situation. Craft content can be highly relational which makes it tricky to just export and re-import. Scenario 1: *If your database and your clients database were both equivalent before your client added the additional content, you may be able to just migrate over your clients database and replace your own database and get both back in sync.* To **migrate the database** would involve exporting the database from the clients environment (either via `Settings->Tools->Backup Database` or via a database admin tool) and reimporting it into your environment with a database admin tool. Scenario 2: *If both you and your client made changes to your respective databases (for example, you both added articles in each environment) and you need to preserve the new articles added in your environment while also migrating over the articles added in the clients environment you have two options.* First, you could just **manually re-enter the articles** in the right environment. As it sounds like your client added a lot of articles, that might be time consuming, but sometimes these types of mistakes take time to correct manually. It's often the best option. In the case you added a few articles and your client added many articles, it may make more sense to add your articles to your clients database and then migrate the full database back to your servers as described in Scenario 1. Your second option would be to **migrate the content programmatically**. This becomes a bit more technical so you'd probably need to get a front-end or back-end developer involved. And it will only make sense to go this route if the quantity of data you need to migrate is too much to just do manually. A plugin like [Sprout Import](http://sprout.barrelstrengthdesign.com/craft-plugins/import) can help with this scenario. (Full disclosure, my team developed Sprout Import.) The steps would involve outputting the content from your clients database into a template into an importable JSON format. And then importing the content defined in the JSON file into your database. The docs and examples within the plugin would go into more detail about the exact format you would need. For this answer, the more general point is that if your data was complex enough, a database migration plugin like Sprout Import could help provide a path toward a solution.
If your systems are *exactly* the same, you should be able to: a) back up the Craft database for each system: client and 'ours'. This is your protection against errors or unknown issues, so don't skip it please. b) if your backup isn't a kind to create a full structure and content sql file for each database, make this kind of backup also, for safety and for the actual transfer of content that you want. A tool like Navicat should make this very easy, but your database administrator will know how. c) you're fully backed up, right? d) on the 'client' system, delete all tables in the Craft database, or drop the database itself, in which case you'll have to re-create it,set utf8mb4 character and sort, and add back allowed users. Again, a tool like Navicat can make this easy, and your database administrator should know how. e) with the now-empty 'client' database, execute (play back) the structure and content sql file from the 'ours' system, that you createdd in step a) or b) f) now the 'client' system is running with the same data as the 'ours' system, so you will have successfully transferred the work they did there. Caveat. If the client actually did some work on their system, like setting up users or adding/changing content, this would be lost. Recovering it from the backup won't be possible, as complex record identities and relations won't be the same. The way to prepare for this is to re-key any extra work like this into the 'ours' Craft system, before you do the backups and start the above procedure. If you don't prepare this way, then you can re-key on the client system after you've moved the 'ours' data to it as above. I think I've covered everything, but have your database administrator look at these notes and have a think about it. Good fortune, and since you're near the beginning, probably the worst that could happen is to need more re-keying. This procedure is the one many developers use all the time -- it's standard. If you have doubts, please don't use this process; instead, re-key the missing work, as that will be safest. If the procedure fails, you will have your structure-and-content sql file, and can replay it into the client database after emptying it again, to restore the current situation. Or use your other database backup restore method from step a), if there was one. Best fortune, then.
11,854,627
In my HTML I have this table setup which is composed of separated images for each table cell. I have a < hr /> break at the bottom of the div, separating the table from the rest of the content. When I test on Chrome it shows correctly, however in Firefox the line break isn't aligned properly, it's pushed up a few pixels. The second issue is with the images. Between the second and third table cells, there is a gap of white space, about 2px wide, separating the images. I'm not exactly sure if this is browser compatibility issue, but how do I fix it? <http://jsfiddle.net/Fe7DC/> - JSfiddle with the code ``` <div class="fade" id="Latest-Stories"> <h3 class="section-header"> Son Xəbərlər </h3> <table id="stories-preview" width="330" height="598" border="0" cellpadding="0" cellspacing="0"> <tr> <td id="tablecell1"><a id="link_1"> <img id="img1" src="NewsBarAZ/Article-Nav-Bar2_01.gif" alt="" /></a></td> </tr> <tr> <td id="tablecell2"><a id="link_2" ><img id="img2" src="NewsBarAZ/Article-Nav-Bar1_02.gif" alt="" /> </a></td> </tr> <tr> <td id="tablecell3"><a id="link_3" ><img id="img3" src="NewsBarAZ/Article-Nav-Bar1_03.gif" alt="" /></a></td> </tr> <tr> <td id="tablecell4"><a id="link_4" ><img id="img4" src="NewsBarAZ/Article-Nav-Bar1_04.gif" alt="" /></a></td> </tr> <tr> <td id="tablecell5"><a id="link_5" ><img id="img5" src="NewsBarAZ/Article-Nav-Bar1_05.gif" alt="" /></a></td> </tr> </table> </div> <hr /> #Latest-Stories { width:1000px; height:598px; padding-bottom:36px; background-color:#FFF; padding-left:20px; } #stories-preview { float:right; border-left:2px groove; border-right:2px groove; border-top:2px groove; border-bottom:1px solid #9A9A9A; } ```
2012/08/07
[ "https://Stackoverflow.com/questions/11854627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/995519/" ]
I must say that i am not a big fan of using tables for non tabular data, a list would probably be more appropriate here. That is besides the question however. The implementation of hr is very browser dependent and therfore i hardly ever use it (wait till you start testing in IE...). My advise would be to replace it with a div with a class of .hr and style it to your wishes in css. An example: ``` <div class='.hr'></div> .hr { padding-top: 5px; border-bottom: 1px solid #000; margin-bottom: 5px; } ``` If you are not happy with the default border, you could even use a small image and repeat it along the x axis. Don't forget to give your div some height in this case though. As for the gap between the images, I do not have an imediate explanation for this. Perhaps it has to do with the actual images, that might have some transparent pixels on the top or bottom. Hard to tell without the actual images though.
Normally I add css styling to my hr elements: ``` line-height: 0.01; height: 1pt; border: 1pt solid black; border-width: 0 0 1pt 0; background: transparent; ``` And to avoid problems with erroneous spacing between cells and rows, I usually omit ALL whitespace from between the tags in my source code. Yes, makes for a difficult read, but some browsers just refuse to behave.
25,575
I've recently updated a site from EE 2.7.3 to 2.9.0. A client has pointed out to me that she can't log into the CP but instead get's the message: **This form has expired. Please refresh and try again.** I didn't get this message using Opera but managed to repeat the error using Firefox (on OSX). After much fruitless searching around and playing with session settings with the CP, I tried disabling Cookie Consent and suddenly was able to log in using Firefox. The problem is that I really need to have Cookie Consent enabled because of the nature of the client's business. So I'm wondering if anyone has had this same problem and has found a work-around? I'm also using the latest version of Cookie Consent 1.1
2014/09/08
[ "https://expressionengine.stackexchange.com/questions/25575", "https://expressionengine.stackexchange.com", "https://expressionengine.stackexchange.com/users/1162/" ]
I'm having this problem too. What I do is, um, refreshing the form. You may find this [bug report](https://support.ellislab.com/bugs/detail/20367/cant-login-to-cp-after-server-move-this-form-has-expired.-please-refresh-an) useful
Also helpful is this bug report and workaround by on Github by diogomiguel: <https://github.com/EllisLab/Cookie-Consent/issues/2> (I found the line numbers a little off, with line 111 actually needing to be line 107 and line 98 actually 96) > > Cookie consent tries to clear csrf token preventing forms from being > submitted on newer versions of Expression Engine (tested with 2.8). > Possible workaround solution, is to add an if statement to prevent > csrf token from being cleared. If extension->end\_script is called on > the same function, the problem will occur during the first submission > too. > > > Temporary suggested solution: > > > add to ext.cookie\_consent.php (Line 111): > > > if ($name == $data['prefix'] . 'csrf\_token') { > continue; } comment out on same file (Line 98) > > > //$this->EE->extensions->end\_script = TRUE; > > >
422,897
Подскажите, пожалуйста, на месте () нужна запятая или лучше точка с запятой? "Во сне мне видится бесконечный цветущий сад() и я всё бегу по нему, всё бегу, и бегу, и бегу". Спасибо!
2016/03/18
[ "https://rus.stackexchange.com/questions/422897", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/176715/" ]
Нужна запятая. В сложносочиненном предложении перед союзами **и,да** (в значении «и»), **или** точка с запятой ставится в том случае, когда они соединяют два предложения, которые без них были бы разделены точкой. В вашем случае первая часть сложного предложения не может быть закончена точкой, к тому же оно не достаточно распространено. Подробно о знаках препинания в сложном предложении можете прочитать здесь: [Розенталь Д.Э., Джанджакова Е.В., Кабанова Н.П. СПРАВОЧНИК ПО ПРАВОПИСАНИЮ, ПРОИЗНОШЕНИЮ, ЛИТЕРАТУРНОМУ РЕДАКТИРОВАНИЮ М.: ЧеРо, 1999](http://www.evartist.narod.ru/text1/48.htm)
Всё не так просто с этим предложением. Нужно посмотеть, нет ли здесь общего второстепенного члена для двух частей сложносочинённого предложения. Именно он влияет на знак (или его отсутствие) перед И. Я думаю, что общий второстепенный член всё-таки есть - обстоятельство *во сне*. ***Во сне*** *мне видится бесконечный цветущий сад и я всё бегу по нему, всё бегу, и бегу, и бегу.* Обстоятельство ***"во сне"*** относится к двум предикативным единицам. Поэтому запятую или другой знак перед И ставить не нужно.
422,897
Подскажите, пожалуйста, на месте () нужна запятая или лучше точка с запятой? "Во сне мне видится бесконечный цветущий сад() и я всё бегу по нему, всё бегу, и бегу, и бегу". Спасибо!
2016/03/18
[ "https://rus.stackexchange.com/questions/422897", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/176715/" ]
> > Запятая или точка с запятой? > > > Я бы поставил **тире:** ***Во сне мне видится бесконечный цветущий сад — и я всё бегу по нему, всё бегу, и бегу, и бегу...*** > > [**§ 114.**](http://orthographia.ru/punctuatio.php?sid=133#pp133) Между частями сложносочиненного предложения ставится > тире, если вторая часть предложения заключает в себе значение > результата, следствия, резкого противопоставления (чаще перед союзом > ***и,*** реже перед союзами ***но, а***): Надо успеть записать. *Малейшая задержка — и мысль, блеснув, исчезнет* (Пауст.); *Сначала я старался не зачерпнуть воды или грязи в туфли, но оступился раз, > оступился другой — и стало всё равно* (Сол.)... *Положишь палочку на > воду — и она поплывет по течению* (Пришв.)... > > >
Всё не так просто с этим предложением. Нужно посмотеть, нет ли здесь общего второстепенного члена для двух частей сложносочинённого предложения. Именно он влияет на знак (или его отсутствие) перед И. Я думаю, что общий второстепенный член всё-таки есть - обстоятельство *во сне*. ***Во сне*** *мне видится бесконечный цветущий сад и я всё бегу по нему, всё бегу, и бегу, и бегу.* Обстоятельство ***"во сне"*** относится к двум предикативным единицам. Поэтому запятую или другой знак перед И ставить не нужно.
422,897
Подскажите, пожалуйста, на месте () нужна запятая или лучше точка с запятой? "Во сне мне видится бесконечный цветущий сад() и я всё бегу по нему, всё бегу, и бегу, и бегу". Спасибо!
2016/03/18
[ "https://rus.stackexchange.com/questions/422897", "https://rus.stackexchange.com", "https://rus.stackexchange.com/users/176715/" ]
"Во сне мне видится бесконечный цветущий сад — и я всё бегу по нему, всё бегу, и бегу, и бегу". Мне больше нравится вариант с тире, так как две части предложения явно разделяются паузой, а такой вариант запятая не обеспечивает. Если поставить точку с запятой, то это полная остановка голоса (как в конце предложения), а пауза короткая. Получается, что связь предложений ослаблена, а деления на две части всё равно нет. А такое деление необходимо, так как во второй части своя интонация, связанная с перечислением. И на письме тире отделяет первую часть от второй части, в которой уже есть запятые.
Всё не так просто с этим предложением. Нужно посмотеть, нет ли здесь общего второстепенного члена для двух частей сложносочинённого предложения. Именно он влияет на знак (или его отсутствие) перед И. Я думаю, что общий второстепенный член всё-таки есть - обстоятельство *во сне*. ***Во сне*** *мне видится бесконечный цветущий сад и я всё бегу по нему, всё бегу, и бегу, и бегу.* Обстоятельство ***"во сне"*** относится к двум предикативным единицам. Поэтому запятую или другой знак перед И ставить не нужно.
63,458,112
I use jQuery for playing sound. If I click my `.sound_control` button a few times, the sound always restarts from the beginning. I would need a pause function instead of that. This is my code: ```js $(document).ready(function() { var background_sound = document.createElement("audio"); background_sound.src = "https://www.pacdv.com/sounds/ambience_sounds/airport-gate-1.mp3"; background_sound.volume = 0.1; background_sound.autoPlay = true; background_sound.loop = true; background_sound.controls = true; background_sound.play(); var click_sound = document.createElement("audio"); click_sound.src = "http://soundbible.com/mp3/Stapler-SoundBible.com-374581609.mp3"; click_sound.volume = 0.1; click_sound.autoPlay = false; click_sound.preLoad = true; click_sound.controls = true; $(".click_sound").click(function() { click_sound.currentTime = 0; click_sound.play(); }); $(".sound_control").click(function() { $(".on_off").toggle(); if (background_sound.currentTime) { background_sound.currentTime = 0; background_sound.pause(); } else { background_sound.play(); } }); }); ``` ```css .on_off:nth-child(2) { display: none; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="sound_control">Sound <span class="on_off">on</span><span class="on_off">off</span></button> <button class="click_sound">Button One</button> <button class="click_sound">Button Two</button> <button class="click_sound">Button Three</button> <button class="click_sound">Button Four</button> ``` How is it possible to do that? Would be very happy if someone could help me!
2020/08/17
[ "https://Stackoverflow.com/questions/63458112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12501851/" ]
Your if statement has for some reason the side effect of stopping playback, I'm not a 100% sure why, but here's what you should use instead: ```js $(".sound_control").click(function() { $(".on_off").toggle(); if (!background_sound.paused) { background_sound.pause(); } else { background_sound.play(); } }); ``` ### Edit: mute click sound when sound is off. Since we're using the background sound as an indicator on whether the sound is **on** or **off**. We can just add an extra check to the *click\_sound* handler. ```js $(".click_sound").click(function() { if(!background_sound.paused){ click_sound.currentTime = 0; click_sound.play(); } }); ``` Here's a live snippet: ```js $(document).ready(function() { var background_sound = document.createElement("audio"); background_sound.src = "https://www.pacdv.com/sounds/ambience_sounds/airport-gate-1.mp3"; background_sound.volume = 0.1; background_sound.autoPlay = true; background_sound.loop = false; background_sound.controls = true; background_sound.play(); var click_sound = document.createElement("audio"); click_sound.src = "http://soundbible.com/mp3/Stapler-SoundBible.com-374581609.mp3"; click_sound.volume = 0.1; click_sound.autoPlay = true; click_sound.preLoad = true; click_sound.controls = true; $(".click_sound").click(function() { if(!background_sound.paused){ click_sound.currentTime = 0; click_sound.play(); } }); $(".sound_control").click(function() { $(".on_off").toggle(); if (!background_sound.paused) { background_sound.pause(); } else { background_sound.play(); } }); }); ``` ```css .on_off:nth-child(2) { display: none; } ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="sound_control">Sound <span class="on_off">on</span><span class="on_off">off</span></button> <button class="click_sound">Button One</button> <button class="click_sound">Button Two</button> <button class="click_sound">Button Three</button> <button class="click_sound">Button Four</button> ```
You are setting the current time to 0. **sound.currentTime = 0;** And in this snippet you did not define sound.
24,345,717
I'm trying to make a website and as I'm making it I test it out on two monitors: my 1366 x 768 laptop and a 1080p monitor hooked up to it. I am trying to align a div tag to always stay in the same place and I am using this: ``` nav{ position:absolute; left: 40%; top: 60% } ``` However this does not seem to get the job done. It works fine on one monitor but not the other. I would have assumed that if I use percentages instead of pixels then it would work. Any advice on whats going wrong here would be very appreciated.
2014/06/21
[ "https://Stackoverflow.com/questions/24345717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915700/" ]
Approach 1 (Vectorized apprach with [**`bsxfun`**](http://www.mathworks.in/help/matlab/ref/bsxfun.html) ) - ``` squeeze(sqrt(sum(bsxfun(@minus,cord,permute(cord,[1 3 2])).^2))) ``` Not sure if this will be faster though. Approach 2 - Inspired by this [`very smart approach`](https://stackoverflow.com/a/23911671/3293881) and all credits to the poster. The code posted here is just slightly customized for your case and hopefully slightly better in terms of runtime. Here it is - ``` A = cord'; %//' numA = size(cord,2); helpA = ones(numA,9); helpB = ones(numA,9); for idx = 1:3 sqA_idx = A(:,idx).^2; helpA(:,3*idx-1:3*idx) = [-2*A(:,idx), sqA_idx ]; helpB(:,3*idx-2:3*idx-1) = [sqA_idx , A(:,idx)]; end dist1 = sqrt(helpA * helpB'); %// desired output ```
From your code, you have recognized that the `dist` matrix is symmetric ``` dist(i,j) = norm(cord(:,i)-cord(:,j)); dist(j,i) = dist(i,j); ``` You could change the inner loop to account for this and reduce by roughly one half the number of calculations needed ``` for j = i:size(cord,2) ``` Further, we can avoid the `dist(j,i) = dist(i,j);` at each iteration and just do that at the end by extracting the upper triangle part of `dist` and adding its transpose to the `dist` matrix to account for the symmetry ``` dist = zeros(size(cord,2),size(cord,2)); for i = 1:size(cord,2) for j = i:size(cord,2) dist(i,j) = norm(cord(:,i)-cord(:,j)); end end dist = dist + triu(dist)'; ``` The above addition is fine since the main diagonal is all zeros. It still performs poorly though and so we should take advantage of vectorization. We can do that as follows against the inner loop ``` dist = zeros(size(cord,2),size(cord,2)); for i = 1:size(cord,2) dist(i,i+1:end) = sum((repmat(cord(:,i),1,size(cord,2)-i)-cord(:,i+1:end)).^2); end dist = dist + triu(dist)'; dist = sqrt(dist); ``` For every element in `cord` we need to calculate its distance with all other elements that *follow* it. We reproduce the element with `repmat` so that we can subtract it from every element that follows without the need for the loop. The differences are squared and summed and assigned to the `dist` matrix. We take care of the symmetry and then take the square root of the matrix to complete the `norm` operation. With `tic` and `toc`, the original distance calculation with a random cord (`cord = rand(3,num);`) took ~93 seconds. This version took ~2.8.
24,345,717
I'm trying to make a website and as I'm making it I test it out on two monitors: my 1366 x 768 laptop and a 1080p monitor hooked up to it. I am trying to align a div tag to always stay in the same place and I am using this: ``` nav{ position:absolute; left: 40%; top: 60% } ``` However this does not seem to get the job done. It works fine on one monitor but not the other. I would have assumed that if I use percentages instead of pixels then it would work. Any advice on whats going wrong here would be very appreciated.
2014/06/21
[ "https://Stackoverflow.com/questions/24345717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915700/" ]
[`pdist`](http://www.mathworks.es/es/help/stats/pdist.html) does exactly that. [`squareform`](http://www.mathworks.es/es/help/stats/squareform.html) is needed to get the result in the form of a square, symmetric matrix: ``` dist = squareform(pdist(cord.')); ```
Approach 1 (Vectorized apprach with [**`bsxfun`**](http://www.mathworks.in/help/matlab/ref/bsxfun.html) ) - ``` squeeze(sqrt(sum(bsxfun(@minus,cord,permute(cord,[1 3 2])).^2))) ``` Not sure if this will be faster though. Approach 2 - Inspired by this [`very smart approach`](https://stackoverflow.com/a/23911671/3293881) and all credits to the poster. The code posted here is just slightly customized for your case and hopefully slightly better in terms of runtime. Here it is - ``` A = cord'; %//' numA = size(cord,2); helpA = ones(numA,9); helpB = ones(numA,9); for idx = 1:3 sqA_idx = A(:,idx).^2; helpA(:,3*idx-1:3*idx) = [-2*A(:,idx), sqA_idx ]; helpB(:,3*idx-2:3*idx-1) = [sqA_idx , A(:,idx)]; end dist1 = sqrt(helpA * helpB'); %// desired output ```
24,345,717
I'm trying to make a website and as I'm making it I test it out on two monitors: my 1366 x 768 laptop and a 1080p monitor hooked up to it. I am trying to align a div tag to always stay in the same place and I am using this: ``` nav{ position:absolute; left: 40%; top: 60% } ``` However this does not seem to get the job done. It works fine on one monitor but not the other. I would have assumed that if I use percentages instead of pixels then it would work. Any advice on whats going wrong here would be very appreciated.
2014/06/21
[ "https://Stackoverflow.com/questions/24345717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915700/" ]
[`pdist`](http://www.mathworks.es/es/help/stats/pdist.html) does exactly that. [`squareform`](http://www.mathworks.es/es/help/stats/squareform.html) is needed to get the result in the form of a square, symmetric matrix: ``` dist = squareform(pdist(cord.')); ```
From your code, you have recognized that the `dist` matrix is symmetric ``` dist(i,j) = norm(cord(:,i)-cord(:,j)); dist(j,i) = dist(i,j); ``` You could change the inner loop to account for this and reduce by roughly one half the number of calculations needed ``` for j = i:size(cord,2) ``` Further, we can avoid the `dist(j,i) = dist(i,j);` at each iteration and just do that at the end by extracting the upper triangle part of `dist` and adding its transpose to the `dist` matrix to account for the symmetry ``` dist = zeros(size(cord,2),size(cord,2)); for i = 1:size(cord,2) for j = i:size(cord,2) dist(i,j) = norm(cord(:,i)-cord(:,j)); end end dist = dist + triu(dist)'; ``` The above addition is fine since the main diagonal is all zeros. It still performs poorly though and so we should take advantage of vectorization. We can do that as follows against the inner loop ``` dist = zeros(size(cord,2),size(cord,2)); for i = 1:size(cord,2) dist(i,i+1:end) = sum((repmat(cord(:,i),1,size(cord,2)-i)-cord(:,i+1:end)).^2); end dist = dist + triu(dist)'; dist = sqrt(dist); ``` For every element in `cord` we need to calculate its distance with all other elements that *follow* it. We reproduce the element with `repmat` so that we can subtract it from every element that follows without the need for the loop. The differences are squared and summed and assigned to the `dist` matrix. We take care of the symmetry and then take the square root of the matrix to complete the `norm` operation. With `tic` and `toc`, the original distance calculation with a random cord (`cord = rand(3,num);`) took ~93 seconds. This version took ~2.8.
4,994
There's this funny gap I tried to write a paper once upon a time when I studied linguistics, and I'd like to know if anyone has insight into it. The construction in question is the possessive determiner with 's in English. It's a noun phrase made up of a noun phrase followed by 's, and its extremely liberal in the noun phrases it allows: * Jack's house * Tom and Mary's music collection * several stories' endings * the bus's headlights * the guy I talked to yesterday's cat * a lighthouse in the bay's coordinates * don't you know who's snide comment But there are certain noun phrases that are not allowed -- those that end in personal pronouns: * all of us's friend [a friend of all of us] * you and me's picture [a picture of you and me] * the gift I gave to them's receipt Anyhow, I'd appreciate any thoughts on this and/or pointers to papers that discuss it.
2010/11/13
[ "https://english.stackexchange.com/questions/4994", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
What a great observation. I’m not aware of any linguistic literature on this (but I’ll post an edit if I come across some). A few comments on the data: First, I’d be careful of using coordinated pronouns (*you and me*) to illustrate the core problem, as people have wild ideas about what is normatively sanctioned and this often affects their judgments. I think a reasonably safe frame would be *Anyone who likes X’s answer would be “yes”*; e.g.: > > Anyone who likes butter’s answer would be “yes”. > Anyone who likes running’s answer would be “yes”. > Anyone who likes cats’ answer would be “yes”. > ??Anyone who likes me’s answer would be “yes”. > ??Anyone who likes you’s answer would be “yes”. > ??Anyone who likes him’s answer would be “yes”. > > > > Second, the effect applies to demonstrative too, I think: > > ??Anyone who likes that’s answer would be “yes”. > ??Anyone who likes these’(s) answer would be “yes”. > > > > Third, I find these all slightly to quite uncomfortable, rather than crashingly bad. This last fact might be significant, as it suggests a parsing, rather than a generation, difficulty. Pursuing that hunch, I’d look for an explanation in *’s*’s being a determiner. Part of the motivation for treating *’s* as a determiner is the complementary distribution between *DP’s* (e.g., *John’s*, *the policeman’s*) and *the*, personal pronouns, and demonstratives (e.g., \**the policeman’s that hat*). Significantly, these last two sets (personal pronouns and demonstratives) are what *’s* attaches to in the preceding ‘??’ examples. As nohat observes in the comment on your question, *’s* attaches to the whole phrase. But that’s at the semantic level. In linear terms, it encliticizes to the last word the phrase. It appears that this encliticization process doesn’t like moving a determiner onto another determiner (which is reminiscent of Norvin Richard’s findings on linearization more generally). This may be getting a bit technical, so I’d better stop; but I hope that gives you some ideas. P.S.: I find a difference between weak and strong pronouns. *Anyone who like hím’s answer* is worse than *Anyone who líkes ’im’s answer*. P.P.S.: Of course, copular *’s* is fine in all of these. *Anyone who like me’s going to answer “yes”*, *Anyone who likes you’s going to answer “yes”*, etc.
The simple rule is just that pronouns follow different rules from nouns. You can take any noun phrase and apply an `'s` in order to make it possessive. You can not do the same with a pronoun. Every pronoun has its own possessive form: `I` -> `my` `you` -> `your` `he` -> `his` `she` -> `her` `we` -> `our` `you all` (second person plural) -> (someone help me on this one) `they` -> `their` Note also that `they` is sometimes used as a singular gender-ambiguous pronoun. In this case it is still converted as the plural to `their`. Looking at all three of your examples: ``` *all of us's friend (a friend of all of us) ``` Since `us` is a pronoun (in this case, it's the objective form of `we`) we need to use a pronoun possessive instead. ``` all of our friend ``` Next: ``` *you and me's picture (a picture of you and me) ``` Again, we see two pronouns (`me` is the objective form of `I`). So the correct form is: ``` your and my picture ``` Finally: ``` *the gift I gave to them's receipt ``` This one is a little different, since the problem doesn't lie with the usage of pronouns. The object in particular is "the gift", which we referenced directly without the use of the word "it". The problem with this sentence is the existence of the word "gave". Once you add a verb this is no longer a noun phrase, but is now an independent clause. As a clause you must either give it its own sentence, introduce a conjunction, or make it part of a prepositional phrase. ``` I gave them the gift. Its receipt... (new sentence) I gave them the gift, and its receipt... (conjunction) the receipt of the gift I gave to them (prepositional phrase) ``` Note that in the first two cases we had to introduce the pronoun "it". We could also substitute "it" with the word "the gift" ("the gift's receipt..."). The reason that we had to do this becomes obvious if you consider the rest of the sentence. The receipt is part of a separate clause, so in order to reference something in a previous clause we must either use a pronoun or repeat the object we are bringing back. On final note, if you wanted the receipt to be part of the predicate then you would follow the same rules: ``` They lost the gift's receipt. It was the gift I gave to them. (new sentence) (Someone help me on making this into a conjunctive phrase, please) They lost the receipt of the gift I gave to them ```
4,994
There's this funny gap I tried to write a paper once upon a time when I studied linguistics, and I'd like to know if anyone has insight into it. The construction in question is the possessive determiner with 's in English. It's a noun phrase made up of a noun phrase followed by 's, and its extremely liberal in the noun phrases it allows: * Jack's house * Tom and Mary's music collection * several stories' endings * the bus's headlights * the guy I talked to yesterday's cat * a lighthouse in the bay's coordinates * don't you know who's snide comment But there are certain noun phrases that are not allowed -- those that end in personal pronouns: * all of us's friend [a friend of all of us] * you and me's picture [a picture of you and me] * the gift I gave to them's receipt Anyhow, I'd appreciate any thoughts on this and/or pointers to papers that discuss it.
2010/11/13
[ "https://english.stackexchange.com/questions/4994", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
The simple rule is just that pronouns follow different rules from nouns. You can take any noun phrase and apply an `'s` in order to make it possessive. You can not do the same with a pronoun. Every pronoun has its own possessive form: `I` -> `my` `you` -> `your` `he` -> `his` `she` -> `her` `we` -> `our` `you all` (second person plural) -> (someone help me on this one) `they` -> `their` Note also that `they` is sometimes used as a singular gender-ambiguous pronoun. In this case it is still converted as the plural to `their`. Looking at all three of your examples: ``` *all of us's friend (a friend of all of us) ``` Since `us` is a pronoun (in this case, it's the objective form of `we`) we need to use a pronoun possessive instead. ``` all of our friend ``` Next: ``` *you and me's picture (a picture of you and me) ``` Again, we see two pronouns (`me` is the objective form of `I`). So the correct form is: ``` your and my picture ``` Finally: ``` *the gift I gave to them's receipt ``` This one is a little different, since the problem doesn't lie with the usage of pronouns. The object in particular is "the gift", which we referenced directly without the use of the word "it". The problem with this sentence is the existence of the word "gave". Once you add a verb this is no longer a noun phrase, but is now an independent clause. As a clause you must either give it its own sentence, introduce a conjunction, or make it part of a prepositional phrase. ``` I gave them the gift. Its receipt... (new sentence) I gave them the gift, and its receipt... (conjunction) the receipt of the gift I gave to them (prepositional phrase) ``` Note that in the first two cases we had to introduce the pronoun "it". We could also substitute "it" with the word "the gift" ("the gift's receipt..."). The reason that we had to do this becomes obvious if you consider the rest of the sentence. The receipt is part of a separate clause, so in order to reference something in a previous clause we must either use a pronoun or repeat the object we are bringing back. On final note, if you wanted the receipt to be part of the predicate then you would follow the same rules: ``` They lost the gift's receipt. It was the gift I gave to them. (new sentence) (Someone help me on making this into a conjunctive phrase, please) They lost the receipt of the gift I gave to them ```
\*the gift I gave to them's receipt... How about "The receipt of the gift I gave to them"? As for "All of our friend" or "A friend of all of us"... I believe this should just be "Our friend"... If you wanted to be more specific, you might say "A friend **to** all of us" or "A friend to us all."
4,994
There's this funny gap I tried to write a paper once upon a time when I studied linguistics, and I'd like to know if anyone has insight into it. The construction in question is the possessive determiner with 's in English. It's a noun phrase made up of a noun phrase followed by 's, and its extremely liberal in the noun phrases it allows: * Jack's house * Tom and Mary's music collection * several stories' endings * the bus's headlights * the guy I talked to yesterday's cat * a lighthouse in the bay's coordinates * don't you know who's snide comment But there are certain noun phrases that are not allowed -- those that end in personal pronouns: * all of us's friend [a friend of all of us] * you and me's picture [a picture of you and me] * the gift I gave to them's receipt Anyhow, I'd appreciate any thoughts on this and/or pointers to papers that discuss it.
2010/11/13
[ "https://english.stackexchange.com/questions/4994", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
I think you've already said most of what's to be said about this, aside from the obvious fact that these pronouns have their own possessive forms. I think this is related to a phenomenon called *[blocking](https://en.wikipedia.org/wiki/Blocking_(linguistics))*, whereby we avoid creating regular forms when there is an irregular form available. In your examples, of course, the irregular form isn't actually available — we can't say \*"you and my picture" — but such situations are not unheard of. For example, consider the verb *stride*. It has an irregular past tense, *strode* . . . and basically no past participle. I assume that if it weren't for the irregular past tense, then the past participle would just be \**strided*; but *strode* seems to have somehow blocked that option, leaving an odd gap. (Quite a few dictionaries claim that the past participle is *stridden* — compare *drive/drove/driven*, *write/wrote/written*, *ride/rode/ridden*, *rise/rose/risen* — but in fact [*stridden* is vanishingly rare, as are all likely alternatives](https://books.google.com/ngrams/graph?content=stride%2Cstrode%2Cstridden%2Cstriden%2Cstrided%2Chave+strode%2Chas+strode%2Chad+strode&year_start=1800&year_end=2000&corpus=15&smoothing=3).) (This has been remarked upon many times independently; see ["When you stride away, what is it that you've done?" on Language Log](http://languagelog.ldc.upenn.edu/nll/?p=737).) It can be hard to predict what will and won't be blocked, and it may vary from speaker to speaker. You give ?"the gift I gave to them's receipt" as one of your ungrammatical examples, but I don't find that to be much less acceptable than ?"the gift's receipt". I find something like "One of them liked us, but the rest hated us, and the one who liked us's wife was one of the worst" (made-up example) to be pretty acceptable, at least in speech. For a better-studied case where different speakers differ in terms of blocking, consider the baseball jargon phrase *fly out*. In baseball, a "fly-out" is when the batter successfully hits the ball, and hits it high, but someone from the other team manages to catch the ball on its way down, knocking the batter out of the inning. [[link](https://en.wikipedia.org/wiki/Batted_ball)] This phrase is often verbed — so, "to fly out" means to hit a fly ball but then become out because someone caught it — raising the question of what past tense and past participle to use. Some linguists have argued that native speakers will naturally use the regular form, *flied out*, because this clearly isn't the ordinary verb *fly*. (This case is made in a 1992 paper, "Why no mere mortal has ever flown out to center field".) However, the data are actually ambiguous; many native speakers do prefer *flew out* and *flown out*. (This point is made in a 1993 response, "Why no mere mortal has ever flown out to center field but people often say they do".) In fact, it seems that nowadays the "flew out" version has almost completely won out: ["flew out to left field" gets thousands of Google hits](https://www.google.com/search?q="flew+out+to+left+field"), whereas ["flied out to left field" gets only nine](https://www.google.com/search?q="flied+out+to+left+field").
The simple rule is just that pronouns follow different rules from nouns. You can take any noun phrase and apply an `'s` in order to make it possessive. You can not do the same with a pronoun. Every pronoun has its own possessive form: `I` -> `my` `you` -> `your` `he` -> `his` `she` -> `her` `we` -> `our` `you all` (second person plural) -> (someone help me on this one) `they` -> `their` Note also that `they` is sometimes used as a singular gender-ambiguous pronoun. In this case it is still converted as the plural to `their`. Looking at all three of your examples: ``` *all of us's friend (a friend of all of us) ``` Since `us` is a pronoun (in this case, it's the objective form of `we`) we need to use a pronoun possessive instead. ``` all of our friend ``` Next: ``` *you and me's picture (a picture of you and me) ``` Again, we see two pronouns (`me` is the objective form of `I`). So the correct form is: ``` your and my picture ``` Finally: ``` *the gift I gave to them's receipt ``` This one is a little different, since the problem doesn't lie with the usage of pronouns. The object in particular is "the gift", which we referenced directly without the use of the word "it". The problem with this sentence is the existence of the word "gave". Once you add a verb this is no longer a noun phrase, but is now an independent clause. As a clause you must either give it its own sentence, introduce a conjunction, or make it part of a prepositional phrase. ``` I gave them the gift. Its receipt... (new sentence) I gave them the gift, and its receipt... (conjunction) the receipt of the gift I gave to them (prepositional phrase) ``` Note that in the first two cases we had to introduce the pronoun "it". We could also substitute "it" with the word "the gift" ("the gift's receipt..."). The reason that we had to do this becomes obvious if you consider the rest of the sentence. The receipt is part of a separate clause, so in order to reference something in a previous clause we must either use a pronoun or repeat the object we are bringing back. On final note, if you wanted the receipt to be part of the predicate then you would follow the same rules: ``` They lost the gift's receipt. It was the gift I gave to them. (new sentence) (Someone help me on making this into a conjunctive phrase, please) They lost the receipt of the gift I gave to them ```
4,994
There's this funny gap I tried to write a paper once upon a time when I studied linguistics, and I'd like to know if anyone has insight into it. The construction in question is the possessive determiner with 's in English. It's a noun phrase made up of a noun phrase followed by 's, and its extremely liberal in the noun phrases it allows: * Jack's house * Tom and Mary's music collection * several stories' endings * the bus's headlights * the guy I talked to yesterday's cat * a lighthouse in the bay's coordinates * don't you know who's snide comment But there are certain noun phrases that are not allowed -- those that end in personal pronouns: * all of us's friend [a friend of all of us] * you and me's picture [a picture of you and me] * the gift I gave to them's receipt Anyhow, I'd appreciate any thoughts on this and/or pointers to papers that discuss it.
2010/11/13
[ "https://english.stackexchange.com/questions/4994", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
What a great observation. I’m not aware of any linguistic literature on this (but I’ll post an edit if I come across some). A few comments on the data: First, I’d be careful of using coordinated pronouns (*you and me*) to illustrate the core problem, as people have wild ideas about what is normatively sanctioned and this often affects their judgments. I think a reasonably safe frame would be *Anyone who likes X’s answer would be “yes”*; e.g.: > > Anyone who likes butter’s answer would be “yes”. > Anyone who likes running’s answer would be “yes”. > Anyone who likes cats’ answer would be “yes”. > ??Anyone who likes me’s answer would be “yes”. > ??Anyone who likes you’s answer would be “yes”. > ??Anyone who likes him’s answer would be “yes”. > > > > Second, the effect applies to demonstrative too, I think: > > ??Anyone who likes that’s answer would be “yes”. > ??Anyone who likes these’(s) answer would be “yes”. > > > > Third, I find these all slightly to quite uncomfortable, rather than crashingly bad. This last fact might be significant, as it suggests a parsing, rather than a generation, difficulty. Pursuing that hunch, I’d look for an explanation in *’s*’s being a determiner. Part of the motivation for treating *’s* as a determiner is the complementary distribution between *DP’s* (e.g., *John’s*, *the policeman’s*) and *the*, personal pronouns, and demonstratives (e.g., \**the policeman’s that hat*). Significantly, these last two sets (personal pronouns and demonstratives) are what *’s* attaches to in the preceding ‘??’ examples. As nohat observes in the comment on your question, *’s* attaches to the whole phrase. But that’s at the semantic level. In linear terms, it encliticizes to the last word the phrase. It appears that this encliticization process doesn’t like moving a determiner onto another determiner (which is reminiscent of Norvin Richard’s findings on linearization more generally). This may be getting a bit technical, so I’d better stop; but I hope that gives you some ideas. P.S.: I find a difference between weak and strong pronouns. *Anyone who like hím’s answer* is worse than *Anyone who líkes ’im’s answer*. P.P.S.: Of course, copular *’s* is fine in all of these. *Anyone who like me’s going to answer “yes”*, *Anyone who likes you’s going to answer “yes”*, etc.
"All of our friend" could conceivably be technically correct but is so ambiguous (all of our friend except his feet ?) as to require rejection. "A friend of all of us" is clearly to be preferred, on the basis that one should never sacrifice clarity for form. It is worth noting, incidentally, that us's was until recently and may still be in use in Yorkshire dialect as in "Let's go for a ride in us's car."
4,994
There's this funny gap I tried to write a paper once upon a time when I studied linguistics, and I'd like to know if anyone has insight into it. The construction in question is the possessive determiner with 's in English. It's a noun phrase made up of a noun phrase followed by 's, and its extremely liberal in the noun phrases it allows: * Jack's house * Tom and Mary's music collection * several stories' endings * the bus's headlights * the guy I talked to yesterday's cat * a lighthouse in the bay's coordinates * don't you know who's snide comment But there are certain noun phrases that are not allowed -- those that end in personal pronouns: * all of us's friend [a friend of all of us] * you and me's picture [a picture of you and me] * the gift I gave to them's receipt Anyhow, I'd appreciate any thoughts on this and/or pointers to papers that discuss it.
2010/11/13
[ "https://english.stackexchange.com/questions/4994", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
What a great observation. I’m not aware of any linguistic literature on this (but I’ll post an edit if I come across some). A few comments on the data: First, I’d be careful of using coordinated pronouns (*you and me*) to illustrate the core problem, as people have wild ideas about what is normatively sanctioned and this often affects their judgments. I think a reasonably safe frame would be *Anyone who likes X’s answer would be “yes”*; e.g.: > > Anyone who likes butter’s answer would be “yes”. > Anyone who likes running’s answer would be “yes”. > Anyone who likes cats’ answer would be “yes”. > ??Anyone who likes me’s answer would be “yes”. > ??Anyone who likes you’s answer would be “yes”. > ??Anyone who likes him’s answer would be “yes”. > > > > Second, the effect applies to demonstrative too, I think: > > ??Anyone who likes that’s answer would be “yes”. > ??Anyone who likes these’(s) answer would be “yes”. > > > > Third, I find these all slightly to quite uncomfortable, rather than crashingly bad. This last fact might be significant, as it suggests a parsing, rather than a generation, difficulty. Pursuing that hunch, I’d look for an explanation in *’s*’s being a determiner. Part of the motivation for treating *’s* as a determiner is the complementary distribution between *DP’s* (e.g., *John’s*, *the policeman’s*) and *the*, personal pronouns, and demonstratives (e.g., \**the policeman’s that hat*). Significantly, these last two sets (personal pronouns and demonstratives) are what *’s* attaches to in the preceding ‘??’ examples. As nohat observes in the comment on your question, *’s* attaches to the whole phrase. But that’s at the semantic level. In linear terms, it encliticizes to the last word the phrase. It appears that this encliticization process doesn’t like moving a determiner onto another determiner (which is reminiscent of Norvin Richard’s findings on linearization more generally). This may be getting a bit technical, so I’d better stop; but I hope that gives you some ideas. P.S.: I find a difference between weak and strong pronouns. *Anyone who like hím’s answer* is worse than *Anyone who líkes ’im’s answer*. P.P.S.: Of course, copular *’s* is fine in all of these. *Anyone who like me’s going to answer “yes”*, *Anyone who likes you’s going to answer “yes”*, etc.
\*the gift I gave to them's receipt... How about "The receipt of the gift I gave to them"? As for "All of our friend" or "A friend of all of us"... I believe this should just be "Our friend"... If you wanted to be more specific, you might say "A friend **to** all of us" or "A friend to us all."
4,994
There's this funny gap I tried to write a paper once upon a time when I studied linguistics, and I'd like to know if anyone has insight into it. The construction in question is the possessive determiner with 's in English. It's a noun phrase made up of a noun phrase followed by 's, and its extremely liberal in the noun phrases it allows: * Jack's house * Tom and Mary's music collection * several stories' endings * the bus's headlights * the guy I talked to yesterday's cat * a lighthouse in the bay's coordinates * don't you know who's snide comment But there are certain noun phrases that are not allowed -- those that end in personal pronouns: * all of us's friend [a friend of all of us] * you and me's picture [a picture of you and me] * the gift I gave to them's receipt Anyhow, I'd appreciate any thoughts on this and/or pointers to papers that discuss it.
2010/11/13
[ "https://english.stackexchange.com/questions/4994", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
"All of our friend" could conceivably be technically correct but is so ambiguous (all of our friend except his feet ?) as to require rejection. "A friend of all of us" is clearly to be preferred, on the basis that one should never sacrifice clarity for form. It is worth noting, incidentally, that us's was until recently and may still be in use in Yorkshire dialect as in "Let's go for a ride in us's car."
\*the gift I gave to them's receipt... How about "The receipt of the gift I gave to them"? As for "All of our friend" or "A friend of all of us"... I believe this should just be "Our friend"... If you wanted to be more specific, you might say "A friend **to** all of us" or "A friend to us all."
4,994
There's this funny gap I tried to write a paper once upon a time when I studied linguistics, and I'd like to know if anyone has insight into it. The construction in question is the possessive determiner with 's in English. It's a noun phrase made up of a noun phrase followed by 's, and its extremely liberal in the noun phrases it allows: * Jack's house * Tom and Mary's music collection * several stories' endings * the bus's headlights * the guy I talked to yesterday's cat * a lighthouse in the bay's coordinates * don't you know who's snide comment But there are certain noun phrases that are not allowed -- those that end in personal pronouns: * all of us's friend [a friend of all of us] * you and me's picture [a picture of you and me] * the gift I gave to them's receipt Anyhow, I'd appreciate any thoughts on this and/or pointers to papers that discuss it.
2010/11/13
[ "https://english.stackexchange.com/questions/4994", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
I think you've already said most of what's to be said about this, aside from the obvious fact that these pronouns have their own possessive forms. I think this is related to a phenomenon called *[blocking](https://en.wikipedia.org/wiki/Blocking_(linguistics))*, whereby we avoid creating regular forms when there is an irregular form available. In your examples, of course, the irregular form isn't actually available — we can't say \*"you and my picture" — but such situations are not unheard of. For example, consider the verb *stride*. It has an irregular past tense, *strode* . . . and basically no past participle. I assume that if it weren't for the irregular past tense, then the past participle would just be \**strided*; but *strode* seems to have somehow blocked that option, leaving an odd gap. (Quite a few dictionaries claim that the past participle is *stridden* — compare *drive/drove/driven*, *write/wrote/written*, *ride/rode/ridden*, *rise/rose/risen* — but in fact [*stridden* is vanishingly rare, as are all likely alternatives](https://books.google.com/ngrams/graph?content=stride%2Cstrode%2Cstridden%2Cstriden%2Cstrided%2Chave+strode%2Chas+strode%2Chad+strode&year_start=1800&year_end=2000&corpus=15&smoothing=3).) (This has been remarked upon many times independently; see ["When you stride away, what is it that you've done?" on Language Log](http://languagelog.ldc.upenn.edu/nll/?p=737).) It can be hard to predict what will and won't be blocked, and it may vary from speaker to speaker. You give ?"the gift I gave to them's receipt" as one of your ungrammatical examples, but I don't find that to be much less acceptable than ?"the gift's receipt". I find something like "One of them liked us, but the rest hated us, and the one who liked us's wife was one of the worst" (made-up example) to be pretty acceptable, at least in speech. For a better-studied case where different speakers differ in terms of blocking, consider the baseball jargon phrase *fly out*. In baseball, a "fly-out" is when the batter successfully hits the ball, and hits it high, but someone from the other team manages to catch the ball on its way down, knocking the batter out of the inning. [[link](https://en.wikipedia.org/wiki/Batted_ball)] This phrase is often verbed — so, "to fly out" means to hit a fly ball but then become out because someone caught it — raising the question of what past tense and past participle to use. Some linguists have argued that native speakers will naturally use the regular form, *flied out*, because this clearly isn't the ordinary verb *fly*. (This case is made in a 1992 paper, "Why no mere mortal has ever flown out to center field".) However, the data are actually ambiguous; many native speakers do prefer *flew out* and *flown out*. (This point is made in a 1993 response, "Why no mere mortal has ever flown out to center field but people often say they do".) In fact, it seems that nowadays the "flew out" version has almost completely won out: ["flew out to left field" gets thousands of Google hits](https://www.google.com/search?q="flew+out+to+left+field"), whereas ["flied out to left field" gets only nine](https://www.google.com/search?q="flied+out+to+left+field").
"All of our friend" could conceivably be technically correct but is so ambiguous (all of our friend except his feet ?) as to require rejection. "A friend of all of us" is clearly to be preferred, on the basis that one should never sacrifice clarity for form. It is worth noting, incidentally, that us's was until recently and may still be in use in Yorkshire dialect as in "Let's go for a ride in us's car."
4,994
There's this funny gap I tried to write a paper once upon a time when I studied linguistics, and I'd like to know if anyone has insight into it. The construction in question is the possessive determiner with 's in English. It's a noun phrase made up of a noun phrase followed by 's, and its extremely liberal in the noun phrases it allows: * Jack's house * Tom and Mary's music collection * several stories' endings * the bus's headlights * the guy I talked to yesterday's cat * a lighthouse in the bay's coordinates * don't you know who's snide comment But there are certain noun phrases that are not allowed -- those that end in personal pronouns: * all of us's friend [a friend of all of us] * you and me's picture [a picture of you and me] * the gift I gave to them's receipt Anyhow, I'd appreciate any thoughts on this and/or pointers to papers that discuss it.
2010/11/13
[ "https://english.stackexchange.com/questions/4994", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
I think you've already said most of what's to be said about this, aside from the obvious fact that these pronouns have their own possessive forms. I think this is related to a phenomenon called *[blocking](https://en.wikipedia.org/wiki/Blocking_(linguistics))*, whereby we avoid creating regular forms when there is an irregular form available. In your examples, of course, the irregular form isn't actually available — we can't say \*"you and my picture" — but such situations are not unheard of. For example, consider the verb *stride*. It has an irregular past tense, *strode* . . . and basically no past participle. I assume that if it weren't for the irregular past tense, then the past participle would just be \**strided*; but *strode* seems to have somehow blocked that option, leaving an odd gap. (Quite a few dictionaries claim that the past participle is *stridden* — compare *drive/drove/driven*, *write/wrote/written*, *ride/rode/ridden*, *rise/rose/risen* — but in fact [*stridden* is vanishingly rare, as are all likely alternatives](https://books.google.com/ngrams/graph?content=stride%2Cstrode%2Cstridden%2Cstriden%2Cstrided%2Chave+strode%2Chas+strode%2Chad+strode&year_start=1800&year_end=2000&corpus=15&smoothing=3).) (This has been remarked upon many times independently; see ["When you stride away, what is it that you've done?" on Language Log](http://languagelog.ldc.upenn.edu/nll/?p=737).) It can be hard to predict what will and won't be blocked, and it may vary from speaker to speaker. You give ?"the gift I gave to them's receipt" as one of your ungrammatical examples, but I don't find that to be much less acceptable than ?"the gift's receipt". I find something like "One of them liked us, but the rest hated us, and the one who liked us's wife was one of the worst" (made-up example) to be pretty acceptable, at least in speech. For a better-studied case where different speakers differ in terms of blocking, consider the baseball jargon phrase *fly out*. In baseball, a "fly-out" is when the batter successfully hits the ball, and hits it high, but someone from the other team manages to catch the ball on its way down, knocking the batter out of the inning. [[link](https://en.wikipedia.org/wiki/Batted_ball)] This phrase is often verbed — so, "to fly out" means to hit a fly ball but then become out because someone caught it — raising the question of what past tense and past participle to use. Some linguists have argued that native speakers will naturally use the regular form, *flied out*, because this clearly isn't the ordinary verb *fly*. (This case is made in a 1992 paper, "Why no mere mortal has ever flown out to center field".) However, the data are actually ambiguous; many native speakers do prefer *flew out* and *flown out*. (This point is made in a 1993 response, "Why no mere mortal has ever flown out to center field but people often say they do".) In fact, it seems that nowadays the "flew out" version has almost completely won out: ["flew out to left field" gets thousands of Google hits](https://www.google.com/search?q="flew+out+to+left+field"), whereas ["flied out to left field" gets only nine](https://www.google.com/search?q="flied+out+to+left+field").
\*the gift I gave to them's receipt... How about "The receipt of the gift I gave to them"? As for "All of our friend" or "A friend of all of us"... I believe this should just be "Our friend"... If you wanted to be more specific, you might say "A friend **to** all of us" or "A friend to us all."
28,687,680
i have fragment that has scrollview as a parent of layout and in scrollview i have a LinearLayout . when i'm trying to programmatically add view to that LinearLayout but i get the error " The specified child already has a parent. You must call removeView() on the child's parent first." this is my layout ``` <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layoutDirection="ltr" tools:context="ir.pnuopen5.application.fragment.LeaugeFragment"> <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"> <TextView android:id="@+id/tv_LeagueFragment_title_lastNews" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/last_news" android:textSize="17sp" android:layout_gravity="right" android:layout_alignParentTop="true" android:layout_alignRight="@+id/view1" android:layout_alignEnd="@+id/view1" /> <View android:id="@+id/view1" android:layout_width="match_parent" android:layout_height="3dp" android:layout_marginTop="10dp" android:background="@color/line" android:layout_below="@+id/tv_LeagueFragment_title_lastNews" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/lv_LeagueFragment_lastNews" android:layout_below="@+id/view1" android:orientation="horizontal"/> ... ``` and this is my java code ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_leauge, container, false); ... LinearLayout newsListView = (LinearLayout)view.findViewById(R.id.lv_LeagueFragment_lastNews); View newsListRow; TextView title,time; for (int i = 0;i<newsList.size();i++){ newsListRow = inflater.inflate(R.layout.list_news_row0, container, false); title = (TextView)newsListRow.findViewById(R.id.rowNewsTitle); time = (TextView)newsListRow.findViewById(R.id.rowNewsTime); title.setText(newsList.get(i).getTitle()); time.setText(newsList.get(i).getTime()); newsListView.addView(newsListView); } ... return view; } ```
2015/02/24
[ "https://Stackoverflow.com/questions/28687680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2549089/" ]
In the code snippet `newsListView.addView(newsListView)`, you are adding a view to itself. I think what you meant to do was: ``` newsListView.addView(newsListRow); ``` ...to put it back in context... ``` for (int i = 0;i<newsList.size();i++){ newsListRow = inflater.inflate(R.layout.list_news_row0, container, false); title = (TextView)newsListRow.findViewById(R.id.rowNewsTitle); time = (TextView)newsListRow.findViewById(R.id.rowNewsTime); title.setText(newsList.get(i).getTitle()); time.setText(newsList.get(i).getTime()); newsListView.addView(newsListRow); } ```
It's obvious that you get that error. Look you are inflating an View, for first time when your loop runs it adds that view in your linear layout. When next time your loop runs it takes the same object of that view which you have previously added. As this is a static view it wont create a new object when you initialize it. You should use dynamic View. Following is your answer ``` for(int i = 0;i<newsList.size();i++) { LinearLayout newsListRow = new LinearLayout(this); TextView title = new TextView(this); TextView time = new TextView(this); title.setText(newsList.get(i).getTitle()); time.setText(newsList.get(i).getTime()); newsListRow.addView(title); newsListRow.addView(time); newsListView.addView(newsListView); } ``` You can add LayoutParameter to make it look like your static row view. That's it... Enjoy... :-)
28,687,680
i have fragment that has scrollview as a parent of layout and in scrollview i have a LinearLayout . when i'm trying to programmatically add view to that LinearLayout but i get the error " The specified child already has a parent. You must call removeView() on the child's parent first." this is my layout ``` <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layoutDirection="ltr" tools:context="ir.pnuopen5.application.fragment.LeaugeFragment"> <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"> <TextView android:id="@+id/tv_LeagueFragment_title_lastNews" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/last_news" android:textSize="17sp" android:layout_gravity="right" android:layout_alignParentTop="true" android:layout_alignRight="@+id/view1" android:layout_alignEnd="@+id/view1" /> <View android:id="@+id/view1" android:layout_width="match_parent" android:layout_height="3dp" android:layout_marginTop="10dp" android:background="@color/line" android:layout_below="@+id/tv_LeagueFragment_title_lastNews" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/lv_LeagueFragment_lastNews" android:layout_below="@+id/view1" android:orientation="horizontal"/> ... ``` and this is my java code ``` @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_leauge, container, false); ... LinearLayout newsListView = (LinearLayout)view.findViewById(R.id.lv_LeagueFragment_lastNews); View newsListRow; TextView title,time; for (int i = 0;i<newsList.size();i++){ newsListRow = inflater.inflate(R.layout.list_news_row0, container, false); title = (TextView)newsListRow.findViewById(R.id.rowNewsTitle); time = (TextView)newsListRow.findViewById(R.id.rowNewsTime); title.setText(newsList.get(i).getTitle()); time.setText(newsList.get(i).getTime()); newsListView.addView(newsListView); } ... return view; } ```
2015/02/24
[ "https://Stackoverflow.com/questions/28687680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2549089/" ]
In the code snippet `newsListView.addView(newsListView)`, you are adding a view to itself. I think what you meant to do was: ``` newsListView.addView(newsListRow); ``` ...to put it back in context... ``` for (int i = 0;i<newsList.size();i++){ newsListRow = inflater.inflate(R.layout.list_news_row0, container, false); title = (TextView)newsListRow.findViewById(R.id.rowNewsTitle); time = (TextView)newsListRow.findViewById(R.id.rowNewsTime); title.setText(newsList.get(i).getTitle()); time.setText(newsList.get(i).getTime()); newsListView.addView(newsListRow); } ```
Before adding the view , remove it by calling ``` newsListView.removeView(view); ```
841,864
I have a library that interacts with our phone system, ie, Hey phone, call this number for me. This library is used in one of our in house products. I would like to put this instead in a service, so that any of our in house products can send the service a message to place a phone call. So basically I want to communicate from a program built in .Net 3.5 with a service running on the same machine also built in the 3.5 framework. I have done some work with WCF and was considering using this but thought I would ask what others have done or would do.
2009/05/08
[ "https://Stackoverflow.com/questions/841864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
I think WCF is perfectly suited to this.. It allows you to separate your plumbing from your application code, and the configuration allows you to easily change transports(http, tcp, named pipes), add security, throttling, etc., without writing more code.
There are many ways. WCF is a good one. Depending on the circumstance, you might want to consider named pipes, [IpcChannel](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.channels.ipc.ipcchannel.aspx), sockets and other methods.
841,864
I have a library that interacts with our phone system, ie, Hey phone, call this number for me. This library is used in one of our in house products. I would like to put this instead in a service, so that any of our in house products can send the service a message to place a phone call. So basically I want to communicate from a program built in .Net 3.5 with a service running on the same machine also built in the 3.5 framework. I have done some work with WCF and was considering using this but thought I would ask what others have done or would do.
2009/05/08
[ "https://Stackoverflow.com/questions/841864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
There are many ways. WCF is a good one. Depending on the circumstance, you might want to consider named pipes, [IpcChannel](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.channels.ipc.ipcchannel.aspx), sockets and other methods.
Doh, dont know why i Didnt find this link before, more or less what I want to do. My previous work was using a TCP connection, this one uses named pipes: [Expose a WCF Service through a Named Pipes binding](https://stackoverflow.com/questions/184878/expose-a-wcf-service-through-a-named-pipes-binding)
841,864
I have a library that interacts with our phone system, ie, Hey phone, call this number for me. This library is used in one of our in house products. I would like to put this instead in a service, so that any of our in house products can send the service a message to place a phone call. So basically I want to communicate from a program built in .Net 3.5 with a service running on the same machine also built in the 3.5 framework. I have done some work with WCF and was considering using this but thought I would ask what others have done or would do.
2009/05/08
[ "https://Stackoverflow.com/questions/841864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
There are many ways. WCF is a good one. Depending on the circumstance, you might want to consider named pipes, [IpcChannel](http://msdn.microsoft.com/en-us/library/system.runtime.remoting.channels.ipc.ipcchannel.aspx), sockets and other methods.
I find WCF overcomplicated. I would use MSMQ either directly or via [Spring.Framework Messaging](http://www.springframework.net/doc-latest/reference/html/msmq.html)
841,864
I have a library that interacts with our phone system, ie, Hey phone, call this number for me. This library is used in one of our in house products. I would like to put this instead in a service, so that any of our in house products can send the service a message to place a phone call. So basically I want to communicate from a program built in .Net 3.5 with a service running on the same machine also built in the 3.5 framework. I have done some work with WCF and was considering using this but thought I would ask what others have done or would do.
2009/05/08
[ "https://Stackoverflow.com/questions/841864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
I think WCF is perfectly suited to this.. It allows you to separate your plumbing from your application code, and the configuration allows you to easily change transports(http, tcp, named pipes), add security, throttling, etc., without writing more code.
Doh, dont know why i Didnt find this link before, more or less what I want to do. My previous work was using a TCP connection, this one uses named pipes: [Expose a WCF Service through a Named Pipes binding](https://stackoverflow.com/questions/184878/expose-a-wcf-service-through-a-named-pipes-binding)
841,864
I have a library that interacts with our phone system, ie, Hey phone, call this number for me. This library is used in one of our in house products. I would like to put this instead in a service, so that any of our in house products can send the service a message to place a phone call. So basically I want to communicate from a program built in .Net 3.5 with a service running on the same machine also built in the 3.5 framework. I have done some work with WCF and was considering using this but thought I would ask what others have done or would do.
2009/05/08
[ "https://Stackoverflow.com/questions/841864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
I think WCF is perfectly suited to this.. It allows you to separate your plumbing from your application code, and the configuration allows you to easily change transports(http, tcp, named pipes), add security, throttling, etc., without writing more code.
I find WCF overcomplicated. I would use MSMQ either directly or via [Spring.Framework Messaging](http://www.springframework.net/doc-latest/reference/html/msmq.html)
16,028,095
I'm new in C#, these days I'm studying this tutorial from msdn.microsoft.com (<http://msdn.microsoft.com/en-us/library/vstudio/dd492172.aspx>), a part of this tutorial there is a statement to make a new object as think but I'm not sure for a numeric up down control, and the statement is: ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and it's on this page (<http://msdn.microsoft.com/en-us/library/vstudio/dd492138.aspx>) the question is, what is the difference between these two statements?, and what both mean. ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and ``` NumericUpDown answerBox = new NumericUpDown(); ``` Thank you in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16028095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284749/" ]
They are *very* different. 1. `NumericUpDown answerBox = sender as NumericUpdown;` In this case you are casting the object being passed into your function to a object of type `NumericUpDown`, so you can safely use the properties and methods defined in that class. 2. `NumericUpDown answerBox = new NumericUpDown();` In this case you are creating a *completely new object* of type `NumericUpDown` that has no relation to the object being passed in. Any methods you call or properties you access on this new instance will have no effect on the `sender`\*. (\*Disclaimer: unless the class is doing some strange things with static members)
If you put the code back into context you can see that: ``` private void answer_Enter(object sender, EventArgs e) { // Select the whole answer in the NumericUpDown control. NumericUpDown answerBox = sender as NumericUpDown; } ``` `object sender` has already been defined as an `object` called `sender` that has been passed into the function. What the line `sender as NumericUpDown;` is doing, is parsing the `object` into a `NumericUpDown` for use within the function. So there is no similarity between [`new`](http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx) and [`as`](http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx).
16,028,095
I'm new in C#, these days I'm studying this tutorial from msdn.microsoft.com (<http://msdn.microsoft.com/en-us/library/vstudio/dd492172.aspx>), a part of this tutorial there is a statement to make a new object as think but I'm not sure for a numeric up down control, and the statement is: ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and it's on this page (<http://msdn.microsoft.com/en-us/library/vstudio/dd492138.aspx>) the question is, what is the difference between these two statements?, and what both mean. ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and ``` NumericUpDown answerBox = new NumericUpDown(); ``` Thank you in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16028095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284749/" ]
If you put the code back into context you can see that: ``` private void answer_Enter(object sender, EventArgs e) { // Select the whole answer in the NumericUpDown control. NumericUpDown answerBox = sender as NumericUpDown; } ``` `object sender` has already been defined as an `object` called `sender` that has been passed into the function. What the line `sender as NumericUpDown;` is doing, is parsing the `object` into a `NumericUpDown` for use within the function. So there is no similarity between [`new`](http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx) and [`as`](http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx).
This one creates a new instance of `NumericUpDown`: ``` new NumericUpDown(); ``` `As` is used to perform conversions between compatible types. ``` sender as NumericUpDown; ``` See MSDN: [as](http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx) [new](http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx)
16,028,095
I'm new in C#, these days I'm studying this tutorial from msdn.microsoft.com (<http://msdn.microsoft.com/en-us/library/vstudio/dd492172.aspx>), a part of this tutorial there is a statement to make a new object as think but I'm not sure for a numeric up down control, and the statement is: ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and it's on this page (<http://msdn.microsoft.com/en-us/library/vstudio/dd492138.aspx>) the question is, what is the difference between these two statements?, and what both mean. ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and ``` NumericUpDown answerBox = new NumericUpDown(); ``` Thank you in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16028095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284749/" ]
If you put the code back into context you can see that: ``` private void answer_Enter(object sender, EventArgs e) { // Select the whole answer in the NumericUpDown control. NumericUpDown answerBox = sender as NumericUpDown; } ``` `object sender` has already been defined as an `object` called `sender` that has been passed into the function. What the line `sender as NumericUpDown;` is doing, is parsing the `object` into a `NumericUpDown` for use within the function. So there is no similarity between [`new`](http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx) and [`as`](http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx).
When a NumericUpDown is entered (the event the tutorial has you subscribe to), Windows Forms passes the specific NumericUpDown box that was entered as the `sender`. `sender` is an Object, which means anything could be passed in, as many objects have events like this. You need to tell the compiler that this `sender` is a NumericUpDown, which is what the first does. The second creates an entirely new NumericUpDown which isn't on any forms, so is basically useless.
16,028,095
I'm new in C#, these days I'm studying this tutorial from msdn.microsoft.com (<http://msdn.microsoft.com/en-us/library/vstudio/dd492172.aspx>), a part of this tutorial there is a statement to make a new object as think but I'm not sure for a numeric up down control, and the statement is: ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and it's on this page (<http://msdn.microsoft.com/en-us/library/vstudio/dd492138.aspx>) the question is, what is the difference between these two statements?, and what both mean. ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and ``` NumericUpDown answerBox = new NumericUpDown(); ``` Thank you in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16028095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284749/" ]
If you put the code back into context you can see that: ``` private void answer_Enter(object sender, EventArgs e) { // Select the whole answer in the NumericUpDown control. NumericUpDown answerBox = sender as NumericUpDown; } ``` `object sender` has already been defined as an `object` called `sender` that has been passed into the function. What the line `sender as NumericUpDown;` is doing, is parsing the `object` into a `NumericUpDown` for use within the function. So there is no similarity between [`new`](http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx) and [`as`](http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx).
The first one, is actually taking the object "sender" and casting it as the "NumericUpDown" type. It's closer to the following casting code: "(NumericUpDown)sender", with the key difference being that the "as" operator returns null if the type of "sender" is not able to be cast to the NumericUpDown type, whereas (NumericUpDown)sender will throw an InvalidCastException. The second statement, "NumericUpDown answerBox = new NumericUpDown()", is creating a new instance of the NumericUpDown type using its parameterless constructor.
16,028,095
I'm new in C#, these days I'm studying this tutorial from msdn.microsoft.com (<http://msdn.microsoft.com/en-us/library/vstudio/dd492172.aspx>), a part of this tutorial there is a statement to make a new object as think but I'm not sure for a numeric up down control, and the statement is: ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and it's on this page (<http://msdn.microsoft.com/en-us/library/vstudio/dd492138.aspx>) the question is, what is the difference between these two statements?, and what both mean. ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and ``` NumericUpDown answerBox = new NumericUpDown(); ``` Thank you in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16028095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284749/" ]
They are *very* different. 1. `NumericUpDown answerBox = sender as NumericUpdown;` In this case you are casting the object being passed into your function to a object of type `NumericUpDown`, so you can safely use the properties and methods defined in that class. 2. `NumericUpDown answerBox = new NumericUpDown();` In this case you are creating a *completely new object* of type `NumericUpDown` that has no relation to the object being passed in. Any methods you call or properties you access on this new instance will have no effect on the `sender`\*. (\*Disclaimer: unless the class is doing some strange things with static members)
This one creates a new instance of `NumericUpDown`: ``` new NumericUpDown(); ``` `As` is used to perform conversions between compatible types. ``` sender as NumericUpDown; ``` See MSDN: [as](http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx) [new](http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx)
16,028,095
I'm new in C#, these days I'm studying this tutorial from msdn.microsoft.com (<http://msdn.microsoft.com/en-us/library/vstudio/dd492172.aspx>), a part of this tutorial there is a statement to make a new object as think but I'm not sure for a numeric up down control, and the statement is: ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and it's on this page (<http://msdn.microsoft.com/en-us/library/vstudio/dd492138.aspx>) the question is, what is the difference between these two statements?, and what both mean. ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and ``` NumericUpDown answerBox = new NumericUpDown(); ``` Thank you in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16028095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284749/" ]
They are *very* different. 1. `NumericUpDown answerBox = sender as NumericUpdown;` In this case you are casting the object being passed into your function to a object of type `NumericUpDown`, so you can safely use the properties and methods defined in that class. 2. `NumericUpDown answerBox = new NumericUpDown();` In this case you are creating a *completely new object* of type `NumericUpDown` that has no relation to the object being passed in. Any methods you call or properties you access on this new instance will have no effect on the `sender`\*. (\*Disclaimer: unless the class is doing some strange things with static members)
When a NumericUpDown is entered (the event the tutorial has you subscribe to), Windows Forms passes the specific NumericUpDown box that was entered as the `sender`. `sender` is an Object, which means anything could be passed in, as many objects have events like this. You need to tell the compiler that this `sender` is a NumericUpDown, which is what the first does. The second creates an entirely new NumericUpDown which isn't on any forms, so is basically useless.
16,028,095
I'm new in C#, these days I'm studying this tutorial from msdn.microsoft.com (<http://msdn.microsoft.com/en-us/library/vstudio/dd492172.aspx>), a part of this tutorial there is a statement to make a new object as think but I'm not sure for a numeric up down control, and the statement is: ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and it's on this page (<http://msdn.microsoft.com/en-us/library/vstudio/dd492138.aspx>) the question is, what is the difference between these two statements?, and what both mean. ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and ``` NumericUpDown answerBox = new NumericUpDown(); ``` Thank you in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16028095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284749/" ]
They are *very* different. 1. `NumericUpDown answerBox = sender as NumericUpdown;` In this case you are casting the object being passed into your function to a object of type `NumericUpDown`, so you can safely use the properties and methods defined in that class. 2. `NumericUpDown answerBox = new NumericUpDown();` In this case you are creating a *completely new object* of type `NumericUpDown` that has no relation to the object being passed in. Any methods you call or properties you access on this new instance will have no effect on the `sender`\*. (\*Disclaimer: unless the class is doing some strange things with static members)
The first one, is actually taking the object "sender" and casting it as the "NumericUpDown" type. It's closer to the following casting code: "(NumericUpDown)sender", with the key difference being that the "as" operator returns null if the type of "sender" is not able to be cast to the NumericUpDown type, whereas (NumericUpDown)sender will throw an InvalidCastException. The second statement, "NumericUpDown answerBox = new NumericUpDown()", is creating a new instance of the NumericUpDown type using its parameterless constructor.
16,028,095
I'm new in C#, these days I'm studying this tutorial from msdn.microsoft.com (<http://msdn.microsoft.com/en-us/library/vstudio/dd492172.aspx>), a part of this tutorial there is a statement to make a new object as think but I'm not sure for a numeric up down control, and the statement is: ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and it's on this page (<http://msdn.microsoft.com/en-us/library/vstudio/dd492138.aspx>) the question is, what is the difference between these two statements?, and what both mean. ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and ``` NumericUpDown answerBox = new NumericUpDown(); ``` Thank you in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16028095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284749/" ]
This one creates a new instance of `NumericUpDown`: ``` new NumericUpDown(); ``` `As` is used to perform conversions between compatible types. ``` sender as NumericUpDown; ``` See MSDN: [as](http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx) [new](http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx)
When a NumericUpDown is entered (the event the tutorial has you subscribe to), Windows Forms passes the specific NumericUpDown box that was entered as the `sender`. `sender` is an Object, which means anything could be passed in, as many objects have events like this. You need to tell the compiler that this `sender` is a NumericUpDown, which is what the first does. The second creates an entirely new NumericUpDown which isn't on any forms, so is basically useless.
16,028,095
I'm new in C#, these days I'm studying this tutorial from msdn.microsoft.com (<http://msdn.microsoft.com/en-us/library/vstudio/dd492172.aspx>), a part of this tutorial there is a statement to make a new object as think but I'm not sure for a numeric up down control, and the statement is: ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and it's on this page (<http://msdn.microsoft.com/en-us/library/vstudio/dd492138.aspx>) the question is, what is the difference between these two statements?, and what both mean. ``` NumericUpDown answerBox = sender as NumericUpDown; ``` and ``` NumericUpDown answerBox = new NumericUpDown(); ``` Thank you in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16028095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2284749/" ]
This one creates a new instance of `NumericUpDown`: ``` new NumericUpDown(); ``` `As` is used to perform conversions between compatible types. ``` sender as NumericUpDown; ``` See MSDN: [as](http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.71%29.aspx) [new](http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx)
The first one, is actually taking the object "sender" and casting it as the "NumericUpDown" type. It's closer to the following casting code: "(NumericUpDown)sender", with the key difference being that the "as" operator returns null if the type of "sender" is not able to be cast to the NumericUpDown type, whereas (NumericUpDown)sender will throw an InvalidCastException. The second statement, "NumericUpDown answerBox = new NumericUpDown()", is creating a new instance of the NumericUpDown type using its parameterless constructor.
49,682
I applied for a UK business visitor visa for two weeks and my application was refused having attached the following: * My Bank statement * Identity * Passport * Income tax returns. Other than this, my company CEO provided the following documents, attached with application: CEO's letter inviting me for a business visit in UK (they forgot to mention I'm an employee of this company, although they wrote they would providing accommodation and flight charges). Other than this I attached copy of his passport and bank statement. According to refusal notice they said "CEO had nowhere mentioned that you are their employee while you've said that in your application". > > "I am not sure you meet the requirement of Appendix V, Immigration > rules for visitors" > > > you have sought the entry clearance to visit the UK for two weeks. > Your stated purpose is meeting and collaboration with with CEO, the > CEO of the company called COMPANY. CEO has provided a letter of > support for your application, which states that you have a work > related meeting with him. I note whereas you state you are employed by > “COMPANY”, CEO makes no mention of this in his letter, stating only he > is a CEO of a company called COMPANY. You have not provided any > evidence that you are employed by this company in India or else where. > > > "Therefore I am not satisfied as to your motives to seeking entry in > UK at this time. I am not therefore satisfied that you intend to leave > united kingdom at the end of your visit. I'm also not satisfied that > you are genuinely seeking entry for a purpose permitted by visitor > routes and you will not undertake any of the prohibited activities > under V4.5 - V4.10. V4.2 (a) (c) and (d)" > > > Future Applications - > > > Any Future UK visa applications you make will be considered on their > individual merits, but they may be refused unless: > > > * Your personal circumstances change significantly between now and your next application. > * Your provide compelling new evidence with your application. > > > I'm not sure what to do now, I would need to apply again and pay visa fee again? They have also written there is no right of appeal, nor of administrative review.
2015/06/20
[ "https://travel.stackexchange.com/questions/49682", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/30903/" ]
*They have also wrote there is not rights for appeal or administrative reviews.* This is not a problem. They write this paragraph in *all* refusal notices where the application is for a term of 6 months or less. It is 'boilerplate'. So the paths of appeal or administrative review are not options for you. Even if an appeal *were* allowed, it costs GBP 140 to reach the hearing stage; this compares unfavourably to the cost of a fresh application, which is GBP 83. *I'm not sure what to do now, I would need to apply again and pay visa fee again?* Following a refusal of an application where the term is 6 months or less, everything starts at square 1. It means you will have to complete the form again, collect and submit your evidence again, do your biometrics again, and pay the fee(s) again. Also, since the ECO was citing from [Appendix V](https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/423477/20150424_mmigration_rules_app_v_final_v2.pdf), it means your application was *not* considered as a business visit, but rather as a [standard visitor](https://www.gov.uk/standard-visitor-visa/overview). You should adapt your application strategy accordingly. History tells us that it is unwise to submit a fresh application without a detailed analysis of the refusal because it contains the 'legal' text. That's why people asked to see it in the comments above. You provided only a partial text (which is boilerplate and tells us nothing), and hence the best answer for the part of your question "*I'm not sure what to do now...*" is to fix the deficiencies and make a fresh application, consulting a [legal professional](http://solicitors.lawsociety.org.uk/) if necessary.
Regardless of whether you can appeal or not, the simplest thing is to reapply now. You have 'only' lost the fees of your original application and a little time, whereas any administrative review or appeal would take longer. Have your CEO write you a new letter, and reapply. Having said this, there may be another deficiency in your application which Visas & Immigration haven't noticed, but could refuse you for in the new application. If you need the visa urgently and cannot go through another round of reapplication then you might want to contact an experienced UK based immigration solicitor to make the application for you.
14,433,349
I am using `struts2-json-plugin-2.2.3.jar`. and trying to serialize `filterList` property of class like this: `struts.xml` code ``` <action name="jsonUserFilterListAction" class="com.my.fitnessb.actions.UserArticlesAction" method="filterList"> <result name="success" type="json"> <param name="includeProperties">filterList</param> </result> </action> ``` Action class ``` public class UserArticlesAction extends ActionSupport implements SessionAware, ServletRequestAware { private List<FilterType> filterList; HttpServletRequest request; public String filterList() { filterList = new ArrayList<FilterType>(); filterList.add(new FilterType(10, "Latest Articles")); filterList.add(new FilterType(1, "Trending Articles")); filterList.add(new FilterType(2, "Top Rated Articles")); filterList.add(new FilterType(3, "Most Viewd Atricles")); filterList.add(new FilterType(4, "All Atricles")); return SUCCESS; } //setter & getter of filterList } ``` but I'm not able to get this property of FilterType class.
2013/01/21
[ "https://Stackoverflow.com/questions/14433349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1719504/" ]
Assuming the fields in your `FilterType` are named `id` and `desc` Try ``` <param name="includeProperties"> filterList\[\d+\]\.id, filterList\[\d+\]\.desc </param> ```
Struts2-json plugin will seralize your all action attributes in the action class. Its a problem that I had faced using struts2-json-plugin. Even though the [plugin-doc](http://struts.apache.org/2.2.3/docs/json-plugin.html) show a working examples for `includeProperties` parameter, it never worked for me and never did after so many trials and googling. So i had to use `excludeProperties` to remove non-required contents from being serialized, instead of specifying what I want to serialize.
14,433,349
I am using `struts2-json-plugin-2.2.3.jar`. and trying to serialize `filterList` property of class like this: `struts.xml` code ``` <action name="jsonUserFilterListAction" class="com.my.fitnessb.actions.UserArticlesAction" method="filterList"> <result name="success" type="json"> <param name="includeProperties">filterList</param> </result> </action> ``` Action class ``` public class UserArticlesAction extends ActionSupport implements SessionAware, ServletRequestAware { private List<FilterType> filterList; HttpServletRequest request; public String filterList() { filterList = new ArrayList<FilterType>(); filterList.add(new FilterType(10, "Latest Articles")); filterList.add(new FilterType(1, "Trending Articles")); filterList.add(new FilterType(2, "Top Rated Articles")); filterList.add(new FilterType(3, "Most Viewd Atricles")); filterList.add(new FilterType(4, "All Atricles")); return SUCCESS; } //setter & getter of filterList } ``` but I'm not able to get this property of FilterType class.
2013/01/21
[ "https://Stackoverflow.com/questions/14433349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1719504/" ]
Struts2-json plugin will seralize your all action attributes in the action class. Its a problem that I had faced using struts2-json-plugin. Even though the [plugin-doc](http://struts.apache.org/2.2.3/docs/json-plugin.html) show a working examples for `includeProperties` parameter, it never worked for me and never did after so many trials and googling. So i had to use `excludeProperties` to remove non-required contents from being serialized, instead of specifying what I want to serialize.
In case prefer the annotation flavor ``` @ParentPackage("json-default") @Namespace("/") @ResultPath(value = "/") @Results({ @Result(name="firstDir",type="json" ,params = {"includeProperties","fileList\\[\\d+\\]"} ) }) fileList = new ArrayList<String>(); for (File img : folder.listFiles()) { fileList.add(img.getName()); } return "firstDir" ```
14,433,349
I am using `struts2-json-plugin-2.2.3.jar`. and trying to serialize `filterList` property of class like this: `struts.xml` code ``` <action name="jsonUserFilterListAction" class="com.my.fitnessb.actions.UserArticlesAction" method="filterList"> <result name="success" type="json"> <param name="includeProperties">filterList</param> </result> </action> ``` Action class ``` public class UserArticlesAction extends ActionSupport implements SessionAware, ServletRequestAware { private List<FilterType> filterList; HttpServletRequest request; public String filterList() { filterList = new ArrayList<FilterType>(); filterList.add(new FilterType(10, "Latest Articles")); filterList.add(new FilterType(1, "Trending Articles")); filterList.add(new FilterType(2, "Top Rated Articles")); filterList.add(new FilterType(3, "Most Viewd Atricles")); filterList.add(new FilterType(4, "All Atricles")); return SUCCESS; } //setter & getter of filterList } ``` but I'm not able to get this property of FilterType class.
2013/01/21
[ "https://Stackoverflow.com/questions/14433349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1719504/" ]
Struts2-json plugin will seralize your all action attributes in the action class. Its a problem that I had faced using struts2-json-plugin. Even though the [plugin-doc](http://struts.apache.org/2.2.3/docs/json-plugin.html) show a working examples for `includeProperties` parameter, it never worked for me and never did after so many trials and googling. So i had to use `excludeProperties` to remove non-required contents from being serialized, instead of specifying what I want to serialize.
You may try this: ``` <param name="includeProperties"> filterList.* </param> ```
14,433,349
I am using `struts2-json-plugin-2.2.3.jar`. and trying to serialize `filterList` property of class like this: `struts.xml` code ``` <action name="jsonUserFilterListAction" class="com.my.fitnessb.actions.UserArticlesAction" method="filterList"> <result name="success" type="json"> <param name="includeProperties">filterList</param> </result> </action> ``` Action class ``` public class UserArticlesAction extends ActionSupport implements SessionAware, ServletRequestAware { private List<FilterType> filterList; HttpServletRequest request; public String filterList() { filterList = new ArrayList<FilterType>(); filterList.add(new FilterType(10, "Latest Articles")); filterList.add(new FilterType(1, "Trending Articles")); filterList.add(new FilterType(2, "Top Rated Articles")); filterList.add(new FilterType(3, "Most Viewd Atricles")); filterList.add(new FilterType(4, "All Atricles")); return SUCCESS; } //setter & getter of filterList } ``` but I'm not able to get this property of FilterType class.
2013/01/21
[ "https://Stackoverflow.com/questions/14433349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1719504/" ]
Assuming the fields in your `FilterType` are named `id` and `desc` Try ``` <param name="includeProperties"> filterList\[\d+\]\.id, filterList\[\d+\]\.desc </param> ```
In case prefer the annotation flavor ``` @ParentPackage("json-default") @Namespace("/") @ResultPath(value = "/") @Results({ @Result(name="firstDir",type="json" ,params = {"includeProperties","fileList\\[\\d+\\]"} ) }) fileList = new ArrayList<String>(); for (File img : folder.listFiles()) { fileList.add(img.getName()); } return "firstDir" ```
14,433,349
I am using `struts2-json-plugin-2.2.3.jar`. and trying to serialize `filterList` property of class like this: `struts.xml` code ``` <action name="jsonUserFilterListAction" class="com.my.fitnessb.actions.UserArticlesAction" method="filterList"> <result name="success" type="json"> <param name="includeProperties">filterList</param> </result> </action> ``` Action class ``` public class UserArticlesAction extends ActionSupport implements SessionAware, ServletRequestAware { private List<FilterType> filterList; HttpServletRequest request; public String filterList() { filterList = new ArrayList<FilterType>(); filterList.add(new FilterType(10, "Latest Articles")); filterList.add(new FilterType(1, "Trending Articles")); filterList.add(new FilterType(2, "Top Rated Articles")); filterList.add(new FilterType(3, "Most Viewd Atricles")); filterList.add(new FilterType(4, "All Atricles")); return SUCCESS; } //setter & getter of filterList } ``` but I'm not able to get this property of FilterType class.
2013/01/21
[ "https://Stackoverflow.com/questions/14433349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1719504/" ]
Assuming the fields in your `FilterType` are named `id` and `desc` Try ``` <param name="includeProperties"> filterList\[\d+\]\.id, filterList\[\d+\]\.desc </param> ```
You may try this: ``` <param name="includeProperties"> filterList.* </param> ```
33,188,116
The Idea is I want to generate a heatmap using some data. The values of the data may be from 0 to 100. I want to assign color in the following way: ``` 0: Red , 50: Yellow, 100: Green ``` That means the color will be gradually go from red..yellow..to green like gradient of 3 colors. Previously I was using ``` R = (255 * (20 - i)) / 20; G = (255 * i) / 20; B = 0; ``` For gradient of Red and Green color. Can anyone suggest me how to include yellow in between.
2015/10/17
[ "https://Stackoverflow.com/questions/33188116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3416272/" ]
Just get rid of this code line ``` previousTagHistoryMap = new std::map< uint32_t, std::list<Addr_t> >; ``` The instance of `previousTagHistoryMap` is already present from your member declaration: ``` template<class State, class Addr_t = uint32_t, bool Energy=false> class CacheAssoc : public CacheGeneric<State, Addr_t, Energy> { //using XYZ classes protected: std::map<uint32_t, std::list<Addr_t>> previousTagHistoryMap; // ^^^^^^^^^^^^ An instance is automatically created on construction. }; ``` --- In general usage of `new` is avoided like hell in c++ code. There are either [smart pointer](http://en.cppreference.com/w/cpp/memory) classes, or [containers](http://en.cppreference.com/w/cpp/container) that are used to do the dynamic memory allocation management for you (if actually needed). Most of the time you just go with the [RAII](http://en.cppreference.com/w/cpp/language/raii) principle, that handles all of this from your call stack scope. --- As you mentioned you're coming here from a java/c# background, where `new` is the standard way to obtain and initialize any instances of a class, c++ is different regarding this. The former mentioned languages provide automatic garbage collection for instances going out of scope, where c++ doesn't provide such mechanism. So for every `new`, you need to apply a balanced `delete` statement, which is error prone to handle correctly. Well, as mentioned there are the container classes (as those you're using) or smart pointers, that do all of the hard to get stuff for you.
`previousTagHistoryMap` is not a pointer. You should not assign a pointer to it.
33,188,116
The Idea is I want to generate a heatmap using some data. The values of the data may be from 0 to 100. I want to assign color in the following way: ``` 0: Red , 50: Yellow, 100: Green ``` That means the color will be gradually go from red..yellow..to green like gradient of 3 colors. Previously I was using ``` R = (255 * (20 - i)) / 20; G = (255 * i) / 20; B = 0; ``` For gradient of Red and Green color. Can anyone suggest me how to include yellow in between.
2015/10/17
[ "https://Stackoverflow.com/questions/33188116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3416272/" ]
Just get rid of this code line ``` previousTagHistoryMap = new std::map< uint32_t, std::list<Addr_t> >; ``` The instance of `previousTagHistoryMap` is already present from your member declaration: ``` template<class State, class Addr_t = uint32_t, bool Energy=false> class CacheAssoc : public CacheGeneric<State, Addr_t, Energy> { //using XYZ classes protected: std::map<uint32_t, std::list<Addr_t>> previousTagHistoryMap; // ^^^^^^^^^^^^ An instance is automatically created on construction. }; ``` --- In general usage of `new` is avoided like hell in c++ code. There are either [smart pointer](http://en.cppreference.com/w/cpp/memory) classes, or [containers](http://en.cppreference.com/w/cpp/container) that are used to do the dynamic memory allocation management for you (if actually needed). Most of the time you just go with the [RAII](http://en.cppreference.com/w/cpp/language/raii) principle, that handles all of this from your call stack scope. --- As you mentioned you're coming here from a java/c# background, where `new` is the standard way to obtain and initialize any instances of a class, c++ is different regarding this. The former mentioned languages provide automatic garbage collection for instances going out of scope, where c++ doesn't provide such mechanism. So for every `new`, you need to apply a balanced `delete` statement, which is error prone to handle correctly. Well, as mentioned there are the container classes (as those you're using) or smart pointers, that do all of the hard to get stuff for you.
You can not assign to map object its pointer, use pointer in class declaration for this purpose ``` template<class State, class Addr_t = uint32_t, bool Energy=false> class CacheAssoc : public CacheGeneric<State, Addr_t, Energy> { //using XYZ classes protected: std::map<uint32_t, std::list<Addr_t>>* previousTagHistoryMap; //more stuff below ``` than it will work correctly ``` template<class State, class Addr_t, bool Energy> CacheAssoc<State, Addr_t, Energy>::CacheAssoc(int32_t size, int32_t assoc, int32_t blksize, int32_t addrUnit, const char *pStr) : CacheGeneric<State, Addr_t, Energy>(size, assoc, blksize, addrUnit) { //code previousTagHistoryMap = new std::map< uint32_t, std::list<Addr_t> >; //complains about this line } ``` do not forget about copy constructor, assignment operator and destructor, for proper memory management **or simply do not use** ``` previousTagHistoryMap = new std::map< uint32_t, std::list<Addr_t> >; //complains about this line ``` instead `previousTagHistoryMap` already was created by default and you do not suppose to do that ``` previousTagHistoryMap = new std::map< uint32_t, std::list<Addr_t> >; ``` because `previousTagHistoryMap` already exists
44,347,923
I'm using spring-boot `@Scheduled` annotation with fixedDelay in milliseconds as documented in javadoc: > > Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next. > > > Code: ``` @Scheduled(fixedDelay=1000) public void task() { LOG.info("START: " + System.currentTimeInMillis()); ....do some work here... LOG.info("END: " + System.currentTimeInMillis()); } ``` And sometimes I get such output that time between previous task end and next task starts is less than `1000ms` for about `2-30 milliseconds`. Is it normal due to some granularity or why is it happening? Is there any guaranties about this delta value?
2017/06/03
[ "https://Stackoverflow.com/questions/44347923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308639/" ]
There are different ways in which you can use **@Scheduled** annotation. According to the [documentation](https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-annotation-support-scheduled): The **fixedRate** invokes the method every t ms but the time delay is measured from the start of the invocation. If t ms are passed and the method is still in execution then the next invocation will wait for it to finish and will invoke right after the first one. Try putting `Thread.sleep(3000)` in your method. I think that your method is taking about 950ms to complete. If you want to wait after finishing the execution you can use **fixedDelay**.
Obviously it cannot be guaranteed since you're most likely not on a real time system. Depending on what the CPU(s) do at the moment it can vary like that. It's quite hard to do something like that actually on most PC's due to the OS scheduling calls and so on (unless you have direct access to the CPU/GPU but even then)