qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
49,328,818 | In Swift, we can create a custom UICollectionViewCell as follows:
`class MyCell : UICollectionViewCell {}`
Next, if we have the method:
`override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {}`
which expects us to return a `UICollectionViewCell`, we can return an instance of `MyCell` without any issue.
In F#, we must first do the following cast:
`thisCell :> UICollectionViewCell` or else F# will complain that we are returning an object of the wrong type. I understand that this is an issue in F# related to type inference, as described here: [Why isn't up-casting automatic in f#](https://stackoverflow.com/questions/16807839/why-isnt-up-casting-automatic-in-f)
Why is this not an issue for Swift, which also uses type inference? | 2018/03/16 | [
"https://Stackoverflow.com/questions/49328818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909000/"
] | That question you reference appears to be having trouble in F# inferring the correct type of some property merely through through the declaration of conformance to some interface. `IThings` is an interface to which `FSharpThings` conforms.
It strikes me that the equivalent in Swift would be:
```
class A { }
class B: A { }
protocol MyProtocol {
var value: A { get set }
}
class Test: MyProtocol {
var value = B()
}
```
This results in a warning that `Test` does not conform to the protocol.
You can see the problem here: What type should the compiler infer for `value`? If it did the standard inference, it would infer that `value` in `Test` is a `B` and that `Test` should feel free to call `B` methods. But what if something else tried to change `value` to some `A` instance, like the protocol says it can: Then `Test` methods calling `B` methods on `value` would fail.
The other potential alternative would be for the compiler to infer that `value` is of type `A`. This would be complicated for the compiler and, worse, confusing for the programmer writing code for `Test`. Any programmer glancing at the code would be confused why they can't call `B` methods because they'd logically assume it was type `B` on the basis of the declaration. It would be a mess.
So, the compiler is going to require you to explicitly declare it as type `A`. One solution is to manually upcast to eliminate any ambiguity:
```
class Test: MyProtocol {
var value = B() as A
}
```
Or, more natural in Swift, one could explicitly declare the type to conform to the protocol:
```
class Test: MyProtocol {
var value: A = B()
}
```
The `cellForItemAt` situation is different. You are not trying to have the compiler infer the type of some property. It knows precisely what `cellForItemAt` returns, and all the compiler cares about is whether whatever is returned by this method is a `UICollectionViewCell`. It, quite correctly, doesn't care if it's a `UICollectionViewCell` or a subclass of that.
Bottom line, the `cellForItemAt` scenario is very different than the one presented in that other question. | It's Swift's object-oriented design. I don't know how things work in F#, but that's not the question here.
The inheritance model of Swift is quite plain and similar to real-life: Any subclass `B`of a class `A` is also an instance of the class `A`.
Same as in real-life: You're basically a `Mammal`. Consider this the base class for this (quite odd) example. But you're also an instance of type `Human`. And being a `Human` doesn't mean you're not a `Mammal` anymore:
```
Mammal
|--- Human
|--- Man
|--- Woman
```
Now take that concept to programming with Swift:
```
UICollectionViewCell
|--- MyCell
|--- AnotherCell
```
It's now perfectly fine that `MyCell(...) is UICollectionViewCell` equals `true` and a `MyCell` instance is accepted as a return value considering the above model. Just don't confuse between an object being an instance of a class and this class being its "most precise / downstream" type. |
49,328,818 | In Swift, we can create a custom UICollectionViewCell as follows:
`class MyCell : UICollectionViewCell {}`
Next, if we have the method:
`override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {}`
which expects us to return a `UICollectionViewCell`, we can return an instance of `MyCell` without any issue.
In F#, we must first do the following cast:
`thisCell :> UICollectionViewCell` or else F# will complain that we are returning an object of the wrong type. I understand that this is an issue in F# related to type inference, as described here: [Why isn't up-casting automatic in f#](https://stackoverflow.com/questions/16807839/why-isnt-up-casting-automatic-in-f)
Why is this not an issue for Swift, which also uses type inference? | 2018/03/16 | [
"https://Stackoverflow.com/questions/49328818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4909000/"
] | That question you reference appears to be having trouble in F# inferring the correct type of some property merely through through the declaration of conformance to some interface. `IThings` is an interface to which `FSharpThings` conforms.
It strikes me that the equivalent in Swift would be:
```
class A { }
class B: A { }
protocol MyProtocol {
var value: A { get set }
}
class Test: MyProtocol {
var value = B()
}
```
This results in a warning that `Test` does not conform to the protocol.
You can see the problem here: What type should the compiler infer for `value`? If it did the standard inference, it would infer that `value` in `Test` is a `B` and that `Test` should feel free to call `B` methods. But what if something else tried to change `value` to some `A` instance, like the protocol says it can: Then `Test` methods calling `B` methods on `value` would fail.
The other potential alternative would be for the compiler to infer that `value` is of type `A`. This would be complicated for the compiler and, worse, confusing for the programmer writing code for `Test`. Any programmer glancing at the code would be confused why they can't call `B` methods because they'd logically assume it was type `B` on the basis of the declaration. It would be a mess.
So, the compiler is going to require you to explicitly declare it as type `A`. One solution is to manually upcast to eliminate any ambiguity:
```
class Test: MyProtocol {
var value = B() as A
}
```
Or, more natural in Swift, one could explicitly declare the type to conform to the protocol:
```
class Test: MyProtocol {
var value: A = B()
}
```
The `cellForItemAt` situation is different. You are not trying to have the compiler infer the type of some property. It knows precisely what `cellForItemAt` returns, and all the compiler cares about is whether whatever is returned by this method is a `UICollectionViewCell`. It, quite correctly, doesn't care if it's a `UICollectionViewCell` or a subclass of that.
Bottom line, the `cellForItemAt` scenario is very different than the one presented in that other question. | The reason is simple: Swift supports Object Oriented Programming, and thus it honours one of the OOP principles - polymorphism. And this is exactly what a `UICollectionView` does: in treats all `UICollectionViewCell` instances and it subclasses instances the same way, referring to the base class when doing operations.
Since a subclass inherits all members of the parent class, it's logical to be able to use it wherever the superclass is needed.
Note that this feature is unrelated to type inference, the ability of using a subclass instance where a superclass is related to type compatibility, not type inference. |
19,951,954 | I have a Generic which hast a string Method. If the Type of the generic is a container (Array, IEnumerable, etc.) their values should be separated by a comma.
```
public class Test<T>
{
public T GenericProperty { get; set; }
public override string ToString()
{
string ret;
if (GenericProperty is Array || GenericProperty is IEnumerable)
{
ret = String.Join(",", GenericProperty);
}
else
{
ret = GenericProperty.ToString();
}
return ret;
}
}
```
I want to test it by adding a linq expression (`Select(x => x.ToString()`) to it, but linq isn't available.
When I debug the code above, the if clause is executed properly. But I only get "System.Int32[]" as result.
How can I achieve this? | 2013/11/13 | [
"https://Stackoverflow.com/questions/19951954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998657/"
] | Since `T` hasn't any constraints, this line:
```
String.Join(",", GenericProperty);
```
calls this overload:
```
public static string Join(string separator, params object[] values);
```
which causes call to `GenericProperty.ToString()`. You need to call another `Join` overload, which can be achieved this way:
```
if (GenericProperty is IEnumerable)
{
ret = string.Join(",", ((IEnumerable)GenericProperty).Cast<object>());
}
```
By the way, `is Array` condition isn't necessary, because `Array` implements `IEnumerable`. | The problem is that `string.Join` treats `GenericProperty` as `new[] {GenericProperty}` not as collection (see [params](http://msdn.microsoft.com/en-us/library/vstudio/w5zay9db.aspx) keyword).
Try this code:
```
string.Join(",", ((IEnumerable)GenericProperty).Cast<object>());
``` |
19,951,954 | I have a Generic which hast a string Method. If the Type of the generic is a container (Array, IEnumerable, etc.) their values should be separated by a comma.
```
public class Test<T>
{
public T GenericProperty { get; set; }
public override string ToString()
{
string ret;
if (GenericProperty is Array || GenericProperty is IEnumerable)
{
ret = String.Join(",", GenericProperty);
}
else
{
ret = GenericProperty.ToString();
}
return ret;
}
}
```
I want to test it by adding a linq expression (`Select(x => x.ToString()`) to it, but linq isn't available.
When I debug the code above, the if clause is executed properly. But I only get "System.Int32[]" as result.
How can I achieve this? | 2013/11/13 | [
"https://Stackoverflow.com/questions/19951954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998657/"
] | Since `T` hasn't any constraints, this line:
```
String.Join(",", GenericProperty);
```
calls this overload:
```
public static string Join(string separator, params object[] values);
```
which causes call to `GenericProperty.ToString()`. You need to call another `Join` overload, which can be achieved this way:
```
if (GenericProperty is IEnumerable)
{
ret = string.Join(",", ((IEnumerable)GenericProperty).Cast<object>());
}
```
By the way, `is Array` condition isn't necessary, because `Array` implements `IEnumerable`. | You're actually using the `String.Join` overload that takes a string and `params object[]` as arguments.
You need to cast GenericProperty to `IEnumerable<T>`.
```
public class Test<T>
{
public T GenericProperty { get; set; }
public override string ToString()
{
string ret;
if ( GenericProperty is IEnumerable)
{
IEnumerable en = GenericProperty as IEnumerable;
ret = String.Join(",", en.Cast<object>());
}
else
{
ret = GenericProperty.ToString();
}
return ret;
}
}
``` |
409,460 | I was wondering if it is possible to multiply a 3D matrix (say a cube $n\times n\times n$) to a matrix of dimension $n\times 1$? If yes, then how. Maybe you can suggest some resources which I can read to do this. Thanks! | 2013/06/02 | [
"https://math.stackexchange.com/questions/409460",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/77225/"
] | If you view the $n\times n\times n$ object as $n$ different $n\times n$ matrices, then you can apply each one to the $n\times 1$ vector, yielding $n$ different $n\times1$ vectors, which could be viewed as a $n\times n$ matrix.
This won't have interesting multiplication properties though beyond those that come from the regular matrix-vector multiplication. | [Tensors](http://en.wikipedia.org/wiki/Tensor) are very relevant to your question, as they can be represented as multi-dimensional arrays.
A tensor product of a order 3 tensor (the $n \times n\times n$ cube) and a 1st order tensor (the $n\times 1$ vector) will give you a tensor of order 4 (i.e. a 4-dimensional array). |
409,460 | I was wondering if it is possible to multiply a 3D matrix (say a cube $n\times n\times n$) to a matrix of dimension $n\times 1$? If yes, then how. Maybe you can suggest some resources which I can read to do this. Thanks! | 2013/06/02 | [
"https://math.stackexchange.com/questions/409460",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/77225/"
] | If you view the $n\times n\times n$ object as $n$ different $n\times n$ matrices, then you can apply each one to the $n\times 1$ vector, yielding $n$ different $n\times1$ vectors, which could be viewed as a $n\times n$ matrix.
This won't have interesting multiplication properties though beyond those that come from the regular matrix-vector multiplication. | Multiplication of regular matrices arises from their interpretation as linear transformations. For a square matrix you get a map $T:V\to V$ (after having chosen a basis for $V$.) Since the domain and range of $T$ are the same, you can compose linear transformations, and this gives you matrix multiplication.
A cubical matrix can correspond to a linear map $V\to V\otimes V$ or $V\otimes V\to V$ (or a number of other possibilities such as $V\otimes V\otimes V\to \mathbb R$). (As Milind points out, this type of thing is called a tensor, and the different possibilities correspond to different placement of the indices up or down on the tensor, $t^i\_{jk}, t^{ij}\_k, t\_{ijk}$, etc.
An $n\times 1$ matrix can represent a map from $V$ to $\mathbb R$. So if you think of the 3D array as a map from $V\otimes V\to V$, then you can compose it with the map $V\to\mathbb R$. The resulting map is a map $V\otimes V\to \mathbb R$, which can be thought of as an $n\times n$ matrix. |
409,460 | I was wondering if it is possible to multiply a 3D matrix (say a cube $n\times n\times n$) to a matrix of dimension $n\times 1$? If yes, then how. Maybe you can suggest some resources which I can read to do this. Thanks! | 2013/06/02 | [
"https://math.stackexchange.com/questions/409460",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/77225/"
] | Multiplication of regular matrices arises from their interpretation as linear transformations. For a square matrix you get a map $T:V\to V$ (after having chosen a basis for $V$.) Since the domain and range of $T$ are the same, you can compose linear transformations, and this gives you matrix multiplication.
A cubical matrix can correspond to a linear map $V\to V\otimes V$ or $V\otimes V\to V$ (or a number of other possibilities such as $V\otimes V\otimes V\to \mathbb R$). (As Milind points out, this type of thing is called a tensor, and the different possibilities correspond to different placement of the indices up or down on the tensor, $t^i\_{jk}, t^{ij}\_k, t\_{ijk}$, etc.
An $n\times 1$ matrix can represent a map from $V$ to $\mathbb R$. So if you think of the 3D array as a map from $V\otimes V\to V$, then you can compose it with the map $V\to\mathbb R$. The resulting map is a map $V\otimes V\to \mathbb R$, which can be thought of as an $n\times n$ matrix. | [Tensors](http://en.wikipedia.org/wiki/Tensor) are very relevant to your question, as they can be represented as multi-dimensional arrays.
A tensor product of a order 3 tensor (the $n \times n\times n$ cube) and a 1st order tensor (the $n\times 1$ vector) will give you a tensor of order 4 (i.e. a 4-dimensional array). |
47,007,379 | Say I have a Product table with a json array attribute called "name". For example, `Product.first.name == ["large", "black", "hoodie"]`. I want to search through my database for Products with names that contain words in my search query. So if I type in "large hoodie", Product.first should be returned in the results.
So first I have to turn the search key into an array of strings:
```
def search
search_array = params[:search].split(" ")
results = #???
```
but how can I search for Products with names that include values also contained in `search_array`? I've found documentation on how to search for values *within* arrays, but not on how to search for arrays themselves. | 2017/10/30 | [
"https://Stackoverflow.com/questions/47007379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3739453/"
] | You can simply use, `@>` (contains) operator.
```
select * from products;
id | name | tags | created_at | updated_at
----+---------+--------------------------------+----------------------------+----------------------------
3 | T-Shirt | {clothing,summer} | 2017-10-30 05:28:19.394888 | 2017-10-30 05:28:19.394888
4 | Sweater | {clothing,winter,large,hoodie} | 2017-10-30 05:28:38.189589 | 2017-10-30 05:28:38.189589
(2 rows)
select * from products where tags @> '{large, hoodie}';
id | name | tags | created_at | updated_at
----+---------+--------------------------------+----------------------------+----------------------------
4 | Sweater | {clothing,winter,large,hoodie} | 2017-10-30 05:28:38.189589 | 2017-10-30 05:28:38.189589
(1 row)
```
Or, as an AR query,
```
2.3.1 :002 > Product.where("tags @> '{large, hoodie}'")
Product Load (0.4ms) SELECT "products".* FROM "products" WHERE (tags @> '{large, hoodie}')
=> #<ActiveRecord::Relation [#<Product id: 4, name: "Sweater", tags: ["clothing", "winter", "large", "hoodie"], created_at: "2017-10-30 05:28:38", updated_at: "2017-10-30 05:28:38">]>
``` | Okay, as you are using `postgresql`, you can use gem [pg\_search](https://github.com/Casecommons/pg_search).
Add search scope in model:
```
include PgSearch
pg_search_scope :search_on_text_columns,
against: %i(name),
using: { tsearch: { prefix: true } }
```
For more details check out the [documentation](https://github.com/Casecommons/pg_search#usage). Cheers! |
24,372 | I want to break the input of a path in order to draw pushdown automaton, so I tried to use the break line symbol `\\` and even `$$ $$`, but it still doesn't break the lines.

For example, the input should be
`0, 1, 2`
`3, 4, 5`
Any idea? Thank you.
Code sample:
```
\documentclass[10pt,letterpaper]{article}
\usepackage[latin1]{inputenc}
\usepackage[left=1in,right=1in,top=1in,bottom=1in]{geometry}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\setlength{\parindent}{0pt}
\setlength{\parskip}{1ex}
\textbf{PDA:}\\
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\node[state,accepting] (q_1) [right=of q_0] {$q_1$};
\node[state] (q_2) [right=of q_1] {$q_2$};
\node[state] (q_3) [below=of q_1] {$q_3$};
\path[->]
(q_0) edge node {0,1} (q_1)
edge [loop above] node {0,1,2,3,4,5} (q_0)
(q_1) edge node {0,1} (q_2)
(q_2) edge [loop right] node {1} (q_2)
; %end path
\end{tikzpicture}
\\
\end{document}
``` | 2011/07/28 | [
"https://tex.stackexchange.com/questions/24372",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/4322/"
] | One simple method is to specify text characteristics within the node : text width, etc. This will let you do exactly what you want, without any extra package. For example,
```
\documentclass[]{minimal}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\path[->] (q_0) edge[loop above] node[text width=1cm,align=center] {0,1,2\\3,4,5} (q_0);
\end{tikzpicture}
\end{document}
```
The result is
 | You could use the [`makecell` package](http://www.ctan.org/pkg/makecell). As stated in the [package documentation](http://mirror.its.dal.ca/ctan/macros/latex/contrib/makecell/makecell.pdf), it provides
```
\makecell[<vertical or/and horizontal alignment>]{<cell text>}
```
that aids in the creation of (small-scale) multi-lined tabular cell. In that regard, consider the following alteration to your code:
```
...
\usepackage{makecell}%
...
\path[->]
(q_0) edge node {0,1} (q_1)
edge [loop above] node {\makecell[l]{0,1,2,\\3,4,5}} (q_0)
(q_1) edge node {0,1} (q_2)
(q_2) edge [loop right] node {1} (q_2)
; %end path
```
 |
24,372 | I want to break the input of a path in order to draw pushdown automaton, so I tried to use the break line symbol `\\` and even `$$ $$`, but it still doesn't break the lines.

For example, the input should be
`0, 1, 2`
`3, 4, 5`
Any idea? Thank you.
Code sample:
```
\documentclass[10pt,letterpaper]{article}
\usepackage[latin1]{inputenc}
\usepackage[left=1in,right=1in,top=1in,bottom=1in]{geometry}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\setlength{\parindent}{0pt}
\setlength{\parskip}{1ex}
\textbf{PDA:}\\
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\node[state,accepting] (q_1) [right=of q_0] {$q_1$};
\node[state] (q_2) [right=of q_1] {$q_2$};
\node[state] (q_3) [below=of q_1] {$q_3$};
\path[->]
(q_0) edge node {0,1} (q_1)
edge [loop above] node {0,1,2,3,4,5} (q_0)
(q_1) edge node {0,1} (q_2)
(q_2) edge [loop right] node {1} (q_2)
; %end path
\end{tikzpicture}
\\
\end{document}
``` | 2011/07/28 | [
"https://tex.stackexchange.com/questions/24372",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/4322/"
] | Based on Frédérics answer and Chans comment you can just do:
```
\documentclass[]{minimal}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\path[->] (q_0) edge[loop above] node[align=center] {0,1,2\\3,4,5} (q_0);
\end{tikzpicture}
\end{document}
```
You don't need the `text width` option, just the `align` | You could use the [`makecell` package](http://www.ctan.org/pkg/makecell). As stated in the [package documentation](http://mirror.its.dal.ca/ctan/macros/latex/contrib/makecell/makecell.pdf), it provides
```
\makecell[<vertical or/and horizontal alignment>]{<cell text>}
```
that aids in the creation of (small-scale) multi-lined tabular cell. In that regard, consider the following alteration to your code:
```
...
\usepackage{makecell}%
...
\path[->]
(q_0) edge node {0,1} (q_1)
edge [loop above] node {\makecell[l]{0,1,2,\\3,4,5}} (q_0)
(q_1) edge node {0,1} (q_2)
(q_2) edge [loop right] node {1} (q_2)
; %end path
```
 |
24,372 | I want to break the input of a path in order to draw pushdown automaton, so I tried to use the break line symbol `\\` and even `$$ $$`, but it still doesn't break the lines.

For example, the input should be
`0, 1, 2`
`3, 4, 5`
Any idea? Thank you.
Code sample:
```
\documentclass[10pt,letterpaper]{article}
\usepackage[latin1]{inputenc}
\usepackage[left=1in,right=1in,top=1in,bottom=1in]{geometry}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\setlength{\parindent}{0pt}
\setlength{\parskip}{1ex}
\textbf{PDA:}\\
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\node[state,accepting] (q_1) [right=of q_0] {$q_1$};
\node[state] (q_2) [right=of q_1] {$q_2$};
\node[state] (q_3) [below=of q_1] {$q_3$};
\path[->]
(q_0) edge node {0,1} (q_1)
edge [loop above] node {0,1,2,3,4,5} (q_0)
(q_1) edge node {0,1} (q_2)
(q_2) edge [loop right] node {1} (q_2)
; %end path
\end{tikzpicture}
\\
\end{document}
``` | 2011/07/28 | [
"https://tex.stackexchange.com/questions/24372",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/4322/"
] | You could use the [`makecell` package](http://www.ctan.org/pkg/makecell). As stated in the [package documentation](http://mirror.its.dal.ca/ctan/macros/latex/contrib/makecell/makecell.pdf), it provides
```
\makecell[<vertical or/and horizontal alignment>]{<cell text>}
```
that aids in the creation of (small-scale) multi-lined tabular cell. In that regard, consider the following alteration to your code:
```
...
\usepackage{makecell}%
...
\path[->]
(q_0) edge node {0,1} (q_1)
edge [loop above] node {\makecell[l]{0,1,2,\\3,4,5}} (q_0)
(q_1) edge node {0,1} (q_2)
(q_2) edge [loop right] node {1} (q_2)
; %end path
```
 | You could use `\shortstack[alignment]{text1 \\ text1 \\ text1 etc. }`
Where alignment can take:
`r` - right aligned
`l` - left aligned
`c` - centered (default)
```
\usepackage{tikz}
\usetikzlibrary{shapes.geometric, arrows}
\tikzstyle{box} = [rectangle, rounded corners, minimum width=2cm, minimum height=1cm,text centered, draw=black, ]
\begin{tikzpicture}[node distance=2cm]
\node (box1) [box] {\shortstack{text1 \\ text2} };
\node (box2) [box, right of=box1, xshift=1cm] {Process 2b};
\end{tikzpicture}
```
[](https://i.stack.imgur.com/62Zzj.png) |
24,372 | I want to break the input of a path in order to draw pushdown automaton, so I tried to use the break line symbol `\\` and even `$$ $$`, but it still doesn't break the lines.

For example, the input should be
`0, 1, 2`
`3, 4, 5`
Any idea? Thank you.
Code sample:
```
\documentclass[10pt,letterpaper]{article}
\usepackage[latin1]{inputenc}
\usepackage[left=1in,right=1in,top=1in,bottom=1in]{geometry}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\setlength{\parindent}{0pt}
\setlength{\parskip}{1ex}
\textbf{PDA:}\\
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\node[state,accepting] (q_1) [right=of q_0] {$q_1$};
\node[state] (q_2) [right=of q_1] {$q_2$};
\node[state] (q_3) [below=of q_1] {$q_3$};
\path[->]
(q_0) edge node {0,1} (q_1)
edge [loop above] node {0,1,2,3,4,5} (q_0)
(q_1) edge node {0,1} (q_2)
(q_2) edge [loop right] node {1} (q_2)
; %end path
\end{tikzpicture}
\\
\end{document}
``` | 2011/07/28 | [
"https://tex.stackexchange.com/questions/24372",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/4322/"
] | One simple method is to specify text characteristics within the node : text width, etc. This will let you do exactly what you want, without any extra package. For example,
```
\documentclass[]{minimal}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\path[->] (q_0) edge[loop above] node[text width=1cm,align=center] {0,1,2\\3,4,5} (q_0);
\end{tikzpicture}
\end{document}
```
The result is
 | Based on Frédérics answer and Chans comment you can just do:
```
\documentclass[]{minimal}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\path[->] (q_0) edge[loop above] node[align=center] {0,1,2\\3,4,5} (q_0);
\end{tikzpicture}
\end{document}
```
You don't need the `text width` option, just the `align` |
24,372 | I want to break the input of a path in order to draw pushdown automaton, so I tried to use the break line symbol `\\` and even `$$ $$`, but it still doesn't break the lines.

For example, the input should be
`0, 1, 2`
`3, 4, 5`
Any idea? Thank you.
Code sample:
```
\documentclass[10pt,letterpaper]{article}
\usepackage[latin1]{inputenc}
\usepackage[left=1in,right=1in,top=1in,bottom=1in]{geometry}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\setlength{\parindent}{0pt}
\setlength{\parskip}{1ex}
\textbf{PDA:}\\
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\node[state,accepting] (q_1) [right=of q_0] {$q_1$};
\node[state] (q_2) [right=of q_1] {$q_2$};
\node[state] (q_3) [below=of q_1] {$q_3$};
\path[->]
(q_0) edge node {0,1} (q_1)
edge [loop above] node {0,1,2,3,4,5} (q_0)
(q_1) edge node {0,1} (q_2)
(q_2) edge [loop right] node {1} (q_2)
; %end path
\end{tikzpicture}
\\
\end{document}
``` | 2011/07/28 | [
"https://tex.stackexchange.com/questions/24372",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/4322/"
] | One simple method is to specify text characteristics within the node : text width, etc. This will let you do exactly what you want, without any extra package. For example,
```
\documentclass[]{minimal}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\path[->] (q_0) edge[loop above] node[text width=1cm,align=center] {0,1,2\\3,4,5} (q_0);
\end{tikzpicture}
\end{document}
```
The result is
 | You could use `\shortstack[alignment]{text1 \\ text1 \\ text1 etc. }`
Where alignment can take:
`r` - right aligned
`l` - left aligned
`c` - centered (default)
```
\usepackage{tikz}
\usetikzlibrary{shapes.geometric, arrows}
\tikzstyle{box} = [rectangle, rounded corners, minimum width=2cm, minimum height=1cm,text centered, draw=black, ]
\begin{tikzpicture}[node distance=2cm]
\node (box1) [box] {\shortstack{text1 \\ text2} };
\node (box2) [box, right of=box1, xshift=1cm] {Process 2b};
\end{tikzpicture}
```
[](https://i.stack.imgur.com/62Zzj.png) |
24,372 | I want to break the input of a path in order to draw pushdown automaton, so I tried to use the break line symbol `\\` and even `$$ $$`, but it still doesn't break the lines.

For example, the input should be
`0, 1, 2`
`3, 4, 5`
Any idea? Thank you.
Code sample:
```
\documentclass[10pt,letterpaper]{article}
\usepackage[latin1]{inputenc}
\usepackage[left=1in,right=1in,top=1in,bottom=1in]{geometry}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\setlength{\parindent}{0pt}
\setlength{\parskip}{1ex}
\textbf{PDA:}\\
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\node[state,accepting] (q_1) [right=of q_0] {$q_1$};
\node[state] (q_2) [right=of q_1] {$q_2$};
\node[state] (q_3) [below=of q_1] {$q_3$};
\path[->]
(q_0) edge node {0,1} (q_1)
edge [loop above] node {0,1,2,3,4,5} (q_0)
(q_1) edge node {0,1} (q_2)
(q_2) edge [loop right] node {1} (q_2)
; %end path
\end{tikzpicture}
\\
\end{document}
``` | 2011/07/28 | [
"https://tex.stackexchange.com/questions/24372",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/4322/"
] | Based on Frédérics answer and Chans comment you can just do:
```
\documentclass[]{minimal}
\usepackage{amsmath,amsfonts,amssymb}
\usepackage{tikz}
\usetikzlibrary{automata,positioning}
\begin{document}
\begin{tikzpicture}[shorten >=1pt,node distance=5cm,on grid,auto]
\node[state,initial] (q_0) {$q_0$};
\path[->] (q_0) edge[loop above] node[align=center] {0,1,2\\3,4,5} (q_0);
\end{tikzpicture}
\end{document}
```
You don't need the `text width` option, just the `align` | You could use `\shortstack[alignment]{text1 \\ text1 \\ text1 etc. }`
Where alignment can take:
`r` - right aligned
`l` - left aligned
`c` - centered (default)
```
\usepackage{tikz}
\usetikzlibrary{shapes.geometric, arrows}
\tikzstyle{box} = [rectangle, rounded corners, minimum width=2cm, minimum height=1cm,text centered, draw=black, ]
\begin{tikzpicture}[node distance=2cm]
\node (box1) [box] {\shortstack{text1 \\ text2} };
\node (box2) [box, right of=box1, xshift=1cm] {Process 2b};
\end{tikzpicture}
```
[](https://i.stack.imgur.com/62Zzj.png) |
12,750,582 | Okay, I am tearing my hair out trying to do this. I've read through dozens of webpages and they've all given me contradictory information, and none of what they've told me to do has worked.
I have a folder full of scripts I downloaded that will only work if they're part of the pythonpath. I want to either move the folder itself into the default path or temporarily (not permanently) add /desktop/search to the path.
What is the default path, and how would I do the latter? | 2012/10/05 | [
"https://Stackoverflow.com/questions/12750582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1713850/"
] | ```
class Click_btn:
@classmethod
def click_btn(cls, event):
cls.tc.WriteText("clicked\n") #this will probably break now
```
this will allow you to call it on the class rather than an instance of the class
the class is `Click_btn`
an instance would be `btn = Click_btn()` (btn is the instance of Click\_btn) | First of all you should drive your class from `object`:
```
class Click_btn:
def click_btn(self, event):
self.tc.WriteText("clicked\n")
```
But that's not the problem. To get a bound method, you have to write your `Bind` like this:
```
# create an instance
button = Click_btn()
# and now assign the click_btn method of that instance
btn.Bind(wx.EVT_BUTTON, button.click_btn)
``` |
68,816,320 | I am in process of writing a spring boot based microservice, which will be deployed on GKE. To configure service account credentials i do see there are multiple options available . What is the most preferred and possibly safer option available. I have tried below approaches, kindly suggest other ways
1. CredentialsProvider interface with spring.cloud.gcp.credentials.location
2. spring.cloud.gcp.credentials.encoded-key
3. GCP secrete manager | 2021/08/17 | [
"https://Stackoverflow.com/questions/68816320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2511915/"
] | In Cloud environment generally the safest and best option with least administrative overhead is to use the corresponding service from the Cloud provider - in your case it would be [Secret Manager](https://cloud.google.com/secret-manager). Of course if you are planning to not tie your applications with a specific cloud provider or cater to on-prem environment as well then you can use third party Secret management providers like [HashiCorp Vault](https://www.vaultproject.io/).
However even with Secret Manager if you interact with the API directly you will have to provide keys to call the API somewhere which creates another problem. The general recommended solution is to to use application authenticating as Service accounts and interacting with Secret manager directly as outlined [here](https://cloud.google.com/docs/authentication/production). Or there are alternative ways of mounting Secrets from Secret Manager on the GKE Volume using CSI Driver as explained [here](https://github.com/GoogleCloudPlatform/secrets-store-csi-driver-provider-gcp).
Running a secure cluster and container applications is a critical requirement and [here](https://cloud.google.com/kubernetes-engine/docs/how-to/hardening-your-cluster) are further recommendations for GKE security hardening which covers Secret management as well. More specifically you can check the recommendation in section "CIS GKE Benchmark Recommendation: 6.3.1" | The preferred way is hard to answer. Depends on your wishes...
Personally, I prefer to keep a high level of security, it's related to service account authentication and a breach can be a disaster.
Therefore, too keep the secrets secret, I prefer not having secrets. Neither in K8S secret nor in secret manager! Problem solved!!
You can achieve that with [ADC (application default credential)](https://cloud.google.com/docs/authentication/production). But like that, out of the box, the ADC use the Node identity. The problem here is if you run several pods on the same node, all will have the same identity and thus the same permissions.
A cool feature is to use [Workload Identity](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity). It allows you to bind a service account with your K8S deployment. The ADC principle is the same, except that it's bind at the pods level and not at the node level (a proxy is created that intercept the ADC requests) |
68,816,320 | I am in process of writing a spring boot based microservice, which will be deployed on GKE. To configure service account credentials i do see there are multiple options available . What is the most preferred and possibly safer option available. I have tried below approaches, kindly suggest other ways
1. CredentialsProvider interface with spring.cloud.gcp.credentials.location
2. spring.cloud.gcp.credentials.encoded-key
3. GCP secrete manager | 2021/08/17 | [
"https://Stackoverflow.com/questions/68816320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2511915/"
] | In Cloud environment generally the safest and best option with least administrative overhead is to use the corresponding service from the Cloud provider - in your case it would be [Secret Manager](https://cloud.google.com/secret-manager). Of course if you are planning to not tie your applications with a specific cloud provider or cater to on-prem environment as well then you can use third party Secret management providers like [HashiCorp Vault](https://www.vaultproject.io/).
However even with Secret Manager if you interact with the API directly you will have to provide keys to call the API somewhere which creates another problem. The general recommended solution is to to use application authenticating as Service accounts and interacting with Secret manager directly as outlined [here](https://cloud.google.com/docs/authentication/production). Or there are alternative ways of mounting Secrets from Secret Manager on the GKE Volume using CSI Driver as explained [here](https://github.com/GoogleCloudPlatform/secrets-store-csi-driver-provider-gcp).
Running a secure cluster and container applications is a critical requirement and [here](https://cloud.google.com/kubernetes-engine/docs/how-to/hardening-your-cluster) are further recommendations for GKE security hardening which covers Secret management as well. More specifically you can check the recommendation in section "CIS GKE Benchmark Recommendation: 6.3.1" | If your application is running on GCP the preferred way would be to use default credentials provided by the Google GCP clients. When using the default credentials provider the clients will use the service account that is associated with you application. |
68,816,320 | I am in process of writing a spring boot based microservice, which will be deployed on GKE. To configure service account credentials i do see there are multiple options available . What is the most preferred and possibly safer option available. I have tried below approaches, kindly suggest other ways
1. CredentialsProvider interface with spring.cloud.gcp.credentials.location
2. spring.cloud.gcp.credentials.encoded-key
3. GCP secrete manager | 2021/08/17 | [
"https://Stackoverflow.com/questions/68816320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2511915/"
] | Although @Shailendra gives you a good solution, as you are using GKE, you can store sensitive information as [Kubernetes secrets](https://kubernetes.io/docs/concepts/configuration/secret/).
Both the [Kubernetes](https://kubernetes.io/docs/concepts/configuration/secret/#creating-a-secret) and [GKE](https://cloud.google.com/kubernetes-engine/docs/concepts/secret#creating_a_secret) documentation provide several examples of creating secrets.
You can later use the configured secrets in [multiple ways](https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets), in the simple use case, as [environment variables](https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-environment-variables) that can be consumed in the application. Please, see as well [this article](https://www.baeldung.com/spring-cloud-kubernetes#secrets_springcloudk8).
Th Spring Cloud Kubernetes project provides support for consuming this secrets as [property sources](https://cloud.spring.io/spring-cloud-static/spring-cloud-kubernetes/2.1.0.RC1/single/spring-cloud-kubernetes.html#_secrets_propertysource).
This approach allows you to test your application deployment locally, with `minikube` or `kind`, and later deploy the same artifacts to the cloud provider. In addition, it is cloud provider *agnostic* as you are using out-of-the-box Kubernetes artifacts.
---
I am afraid that we were so focused in provide you further alternatives that at the end we do not actually answer your question.
Previously, I will give you the advice of use Kubernetes Secrets, and it is still perfectly fine, but please, allow me to come back to it later.
According to the [different properties](https://docs.spring.io/spring-cloud-gcp/docs/1.0.0.BUILD-SNAPSHOT/reference/htmlsingle/#_credentials) you are trying setting, you are trying configuring the credentials on behalf your application with interact with other services deployed in GCP.
For that purpose the first thing you need is a [service account](https://cloud.google.com/iam/docs/service-accounts).
In a nutshell, a service account is a software artifact that agglutinates several permissions.
This service account can be later assigned to a certain GCP resource, to a certain GCP service, and it will allow that resource to *inherit* or *act on behalf of* the configured permissions when interacting with other GCP resources and services.
Every service account will have an associated set of keys which identify the service account - the information you are trying to keep safe.
There are different types of service accounts, mainly, *default service accounts*, created by GCP when you enable or use some Google Cloud services - one for Compute Engine and one for App Engine - and *user defined* ones.
You can modify the permissions associated with these service accounts: the important thing to keep in mind is always follow the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege), only grant the service account the necessary permissions for performing its task, nothing else.
By default, your GKE cluster will use the [default Compute Engine service account](https://cloud.google.com/compute/docs/access/service-accounts#compute_engine_default_service_account) and the [scopes for it defined](https://cloud.google.com/compute/docs/access/service-accounts#associating_a_service_account_to_an_instance). These permissions will be inherited by your pods when contacting other services.
As a consequence, one possible option is just configuring an appropriate service account for GKE and use these permissions in your code.
You can use the default Compute Engine service account, but, as indicated in the [GCP docs](https://cloud.google.com/kubernetes-engine/docs/how-to/hardening-your-cluster#use_least_privilege_sa) when describing how to harden the cluster security:
>
> Each GKE node has an Identity and Access Management (IAM) Service Account associated with it. By default, nodes are given the Compute Engine default service account, which you can find by navigating to the IAM section of the Cloud Console. This account has broad access by default, making it useful to wide variety of applications, but it has more permissions than are required to run your Kubernetes Engine cluster. **You should create and use a minimally privileged service account to run your GKE cluster instead of using the Compute Engine default service account.**
>
>
>
So probably you will need to create a service account with the minimum permissions to run your cluster (and) application. The aforementioned [link](https://cloud.google.com/kubernetes-engine/docs/how-to/hardening-your-cluster#use_least_privilege_sa) provides all the necessary information.
As an alternative, you can configure a different service account for your application and this is where, as a possible alternative, you can use Kubernetes Secrets.
Please:
* Do not directly provide your own implementation of `CredentialsProvider`, I think it will not provide you any additional benefit compared with the rest of solutions.
* If you want to use the `spring.cloud.gcp.credentials.location` configuration property, create a Kubernetes secret and [expose it as a file](https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod), and set the value of this property to that file location.
* In a very similar way, using Kubernetes Secrets, and as exemplified for instance in [this article](https://blog.realkinetic.com/using-google-cloud-service-accounts-on-gke-e0ca4b81b9a2), you can expose the service account credentials under the environment variable `GOOGLE_APPLICATION_CREDENTIALS`, both [Spring GCP](https://docs.spring.io/spring-cloud-gcp/docs/1.0.0.BUILD-SNAPSHOT/reference/htmlsingle/#_credentials) and the different [GCP client libraries](https://cloud.google.com/docs/authentication/production#obtaining_credentials_on_compute_engine_kubernetes_engine_app_engine_flexible_environment_and_cloud_functions) will look for this variable in order to obtain the required credentials.
* I would not use the configuration property `spring.cloud.gcp.credentials.encoded-key`, in my opinion this approach makes the key more suitable for threats - probably you have to deal with VCS problems, etc.
* Secret Manager... as I told, it is a suitable solution as indicated by @Shailendra in his answer.
* The options provided by Guillaume are very good as well. | The preferred way is hard to answer. Depends on your wishes...
Personally, I prefer to keep a high level of security, it's related to service account authentication and a breach can be a disaster.
Therefore, too keep the secrets secret, I prefer not having secrets. Neither in K8S secret nor in secret manager! Problem solved!!
You can achieve that with [ADC (application default credential)](https://cloud.google.com/docs/authentication/production). But like that, out of the box, the ADC use the Node identity. The problem here is if you run several pods on the same node, all will have the same identity and thus the same permissions.
A cool feature is to use [Workload Identity](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity). It allows you to bind a service account with your K8S deployment. The ADC principle is the same, except that it's bind at the pods level and not at the node level (a proxy is created that intercept the ADC requests) |
68,816,320 | I am in process of writing a spring boot based microservice, which will be deployed on GKE. To configure service account credentials i do see there are multiple options available . What is the most preferred and possibly safer option available. I have tried below approaches, kindly suggest other ways
1. CredentialsProvider interface with spring.cloud.gcp.credentials.location
2. spring.cloud.gcp.credentials.encoded-key
3. GCP secrete manager | 2021/08/17 | [
"https://Stackoverflow.com/questions/68816320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2511915/"
] | Although @Shailendra gives you a good solution, as you are using GKE, you can store sensitive information as [Kubernetes secrets](https://kubernetes.io/docs/concepts/configuration/secret/).
Both the [Kubernetes](https://kubernetes.io/docs/concepts/configuration/secret/#creating-a-secret) and [GKE](https://cloud.google.com/kubernetes-engine/docs/concepts/secret#creating_a_secret) documentation provide several examples of creating secrets.
You can later use the configured secrets in [multiple ways](https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets), in the simple use case, as [environment variables](https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-environment-variables) that can be consumed in the application. Please, see as well [this article](https://www.baeldung.com/spring-cloud-kubernetes#secrets_springcloudk8).
Th Spring Cloud Kubernetes project provides support for consuming this secrets as [property sources](https://cloud.spring.io/spring-cloud-static/spring-cloud-kubernetes/2.1.0.RC1/single/spring-cloud-kubernetes.html#_secrets_propertysource).
This approach allows you to test your application deployment locally, with `minikube` or `kind`, and later deploy the same artifacts to the cloud provider. In addition, it is cloud provider *agnostic* as you are using out-of-the-box Kubernetes artifacts.
---
I am afraid that we were so focused in provide you further alternatives that at the end we do not actually answer your question.
Previously, I will give you the advice of use Kubernetes Secrets, and it is still perfectly fine, but please, allow me to come back to it later.
According to the [different properties](https://docs.spring.io/spring-cloud-gcp/docs/1.0.0.BUILD-SNAPSHOT/reference/htmlsingle/#_credentials) you are trying setting, you are trying configuring the credentials on behalf your application with interact with other services deployed in GCP.
For that purpose the first thing you need is a [service account](https://cloud.google.com/iam/docs/service-accounts).
In a nutshell, a service account is a software artifact that agglutinates several permissions.
This service account can be later assigned to a certain GCP resource, to a certain GCP service, and it will allow that resource to *inherit* or *act on behalf of* the configured permissions when interacting with other GCP resources and services.
Every service account will have an associated set of keys which identify the service account - the information you are trying to keep safe.
There are different types of service accounts, mainly, *default service accounts*, created by GCP when you enable or use some Google Cloud services - one for Compute Engine and one for App Engine - and *user defined* ones.
You can modify the permissions associated with these service accounts: the important thing to keep in mind is always follow the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege), only grant the service account the necessary permissions for performing its task, nothing else.
By default, your GKE cluster will use the [default Compute Engine service account](https://cloud.google.com/compute/docs/access/service-accounts#compute_engine_default_service_account) and the [scopes for it defined](https://cloud.google.com/compute/docs/access/service-accounts#associating_a_service_account_to_an_instance). These permissions will be inherited by your pods when contacting other services.
As a consequence, one possible option is just configuring an appropriate service account for GKE and use these permissions in your code.
You can use the default Compute Engine service account, but, as indicated in the [GCP docs](https://cloud.google.com/kubernetes-engine/docs/how-to/hardening-your-cluster#use_least_privilege_sa) when describing how to harden the cluster security:
>
> Each GKE node has an Identity and Access Management (IAM) Service Account associated with it. By default, nodes are given the Compute Engine default service account, which you can find by navigating to the IAM section of the Cloud Console. This account has broad access by default, making it useful to wide variety of applications, but it has more permissions than are required to run your Kubernetes Engine cluster. **You should create and use a minimally privileged service account to run your GKE cluster instead of using the Compute Engine default service account.**
>
>
>
So probably you will need to create a service account with the minimum permissions to run your cluster (and) application. The aforementioned [link](https://cloud.google.com/kubernetes-engine/docs/how-to/hardening-your-cluster#use_least_privilege_sa) provides all the necessary information.
As an alternative, you can configure a different service account for your application and this is where, as a possible alternative, you can use Kubernetes Secrets.
Please:
* Do not directly provide your own implementation of `CredentialsProvider`, I think it will not provide you any additional benefit compared with the rest of solutions.
* If you want to use the `spring.cloud.gcp.credentials.location` configuration property, create a Kubernetes secret and [expose it as a file](https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod), and set the value of this property to that file location.
* In a very similar way, using Kubernetes Secrets, and as exemplified for instance in [this article](https://blog.realkinetic.com/using-google-cloud-service-accounts-on-gke-e0ca4b81b9a2), you can expose the service account credentials under the environment variable `GOOGLE_APPLICATION_CREDENTIALS`, both [Spring GCP](https://docs.spring.io/spring-cloud-gcp/docs/1.0.0.BUILD-SNAPSHOT/reference/htmlsingle/#_credentials) and the different [GCP client libraries](https://cloud.google.com/docs/authentication/production#obtaining_credentials_on_compute_engine_kubernetes_engine_app_engine_flexible_environment_and_cloud_functions) will look for this variable in order to obtain the required credentials.
* I would not use the configuration property `spring.cloud.gcp.credentials.encoded-key`, in my opinion this approach makes the key more suitable for threats - probably you have to deal with VCS problems, etc.
* Secret Manager... as I told, it is a suitable solution as indicated by @Shailendra in his answer.
* The options provided by Guillaume are very good as well. | If your application is running on GCP the preferred way would be to use default credentials provided by the Google GCP clients. When using the default credentials provider the clients will use the service account that is associated with you application. |
68,816,320 | I am in process of writing a spring boot based microservice, which will be deployed on GKE. To configure service account credentials i do see there are multiple options available . What is the most preferred and possibly safer option available. I have tried below approaches, kindly suggest other ways
1. CredentialsProvider interface with spring.cloud.gcp.credentials.location
2. spring.cloud.gcp.credentials.encoded-key
3. GCP secrete manager | 2021/08/17 | [
"https://Stackoverflow.com/questions/68816320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2511915/"
] | The preferred way is hard to answer. Depends on your wishes...
Personally, I prefer to keep a high level of security, it's related to service account authentication and a breach can be a disaster.
Therefore, too keep the secrets secret, I prefer not having secrets. Neither in K8S secret nor in secret manager! Problem solved!!
You can achieve that with [ADC (application default credential)](https://cloud.google.com/docs/authentication/production). But like that, out of the box, the ADC use the Node identity. The problem here is if you run several pods on the same node, all will have the same identity and thus the same permissions.
A cool feature is to use [Workload Identity](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity). It allows you to bind a service account with your K8S deployment. The ADC principle is the same, except that it's bind at the pods level and not at the node level (a proxy is created that intercept the ADC requests) | If your application is running on GCP the preferred way would be to use default credentials provided by the Google GCP clients. When using the default credentials provider the clients will use the service account that is associated with you application. |
60,359 | sorry the original question was answered by an expert but somehow I cannot edit the original question and add comments. so posting it again with some follow up questions:
i have a number of bonds that I need to get coupon payment dates, an example is listed below:
issue date is 2020-03-026, maturity date is 2020-09-30, and the bond pays coupon on quarterly basis. The first coupon date is 2020-06-30 so this has a long stub in the front.
the following code gives me
[Date(26,3,2020), Date(30,6,2020), Date(30,9,2020), **Date(30,12,2020)**, **Date(30,3,2021)**, Date(30,6,2021), Date(30,9,2021), Date(30,12,2021), **Date(30,3,2022)**, Date(30,6,2022), Date(30,9,2022)]
however I expect to have that 3 highlighted to be 31st instead of 30th. 31Dec2021 is US holiday so it should stay as 30th Dec when using modified following. any suggestions on how to solve this?
endOfMonth cannot be used here since the issue date 26th March is not end of month.
```
schedule = ql.Schedule(
ql.Date('26-03-2020', '%d-%m-%Y'),
ql.Date('30-09-2022', '%d-%m-%Y'),
ql.Period("3m"),
ql.UnitedStates(),
ql.ModifiedFollowing,
ql.ModifiedFollowing,
ql.DateGeneration.Forward,
False,
ql.Date('30-06-2020', '%d-%m-%Y'))
``` | 2021/01/06 | [
"https://quant.stackexchange.com/questions/60359",
"https://quant.stackexchange.com",
"https://quant.stackexchange.com/users/51726/"
] | With end-of-month set to `False`, the schedule doesn't even try to hit the 31st; it starts from a stub on the 30th, so it uses the 30th of the month for all other dates.
Unfortunately, as you say, you can't set end-of-month to `True` in this case; so you'll probably have to use the `Schedule` constructor that takes an explicit list of dates (you can generate them by starting a mock schedule on March 31st and removing the June stub). In Python, the constructor can also take a number of other parameters: this will enable bonds and other instruments to use the schedule correctly. You can see the full signature [here](https://github.com/lballabio/QuantLib-SWIG/blob/master/SWIG/scheduler.i#L65). | These dates are not included as US holidays in QuantLib's United States calendar. They are considered as business days.
```python
import QuantLib as ql
print(ql.UnitedStates().isBusinessDay(ql.Date(31, 12, 2020)))
print(ql.UnitedStates().isBusinessDay(ql.Date(30, 3, 2021)))
print(ql.UnitedStates().isBusinessDay(ql.Date(30, 3, 2022)))
```
The above lines check if the 31st December 2020, the 30th March 2021, and the 30th March 2022 are business days, and the returns are:
>
> True
>
>
>
>
> True
>
>
>
>
> True
>
>
> |
23,750,858 | I have setup a digital ocean box with dokku on my home computer. I've added ssh keys for both my home and work computer. I've then turned password access off. Accessing the server from both computers works via ssh without the need for a password. Git push with dokku@ however will only work from my home computer. What am I missing? - should I just create a new droplet and try again?. | 2014/05/20 | [
"https://Stackoverflow.com/questions/23750858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3003156/"
] | You need to check on your work computer:
* if the `~/.ssh/id_rsa`(`.pub`) is the [right key added to dokku](https://www.digitalocean.com/community/questions/dokku-add-new-ssh-key)
* if the url uses the right user: `root@url` isn't the same than `dokku@url` | I have a similar error. I needed to run this command:
```
$ cat ~/.ssh/id_rsa.pub | ssh progriumapp.com "sudo sshcommand acl-add dokku progrium"
```
This adds an ssh key for the user. Make sure that your first `$ source ~/.bashrc` on the server to make sure the command runs as expected. |
23,750,858 | I have setup a digital ocean box with dokku on my home computer. I've added ssh keys for both my home and work computer. I've then turned password access off. Accessing the server from both computers works via ssh without the need for a password. Git push with dokku@ however will only work from my home computer. What am I missing? - should I just create a new droplet and try again?. | 2014/05/20 | [
"https://Stackoverflow.com/questions/23750858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3003156/"
] | You need to check on your work computer:
* if the `~/.ssh/id_rsa`(`.pub`) is the [right key added to dokku](https://www.digitalocean.com/community/questions/dokku-add-new-ssh-key)
* if the url uses the right user: `root@url` isn't the same than `dokku@url` | Now you can add sshs simple: dokku ssh-keys:add dokku ~/.ssh/id\_rsa.pub |
23,750,858 | I have setup a digital ocean box with dokku on my home computer. I've added ssh keys for both my home and work computer. I've then turned password access off. Accessing the server from both computers works via ssh without the need for a password. Git push with dokku@ however will only work from my home computer. What am I missing? - should I just create a new droplet and try again?. | 2014/05/20 | [
"https://Stackoverflow.com/questions/23750858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3003156/"
] | I have a similar error. I needed to run this command:
```
$ cat ~/.ssh/id_rsa.pub | ssh progriumapp.com "sudo sshcommand acl-add dokku progrium"
```
This adds an ssh key for the user. Make sure that your first `$ source ~/.bashrc` on the server to make sure the command runs as expected. | Now you can add sshs simple: dokku ssh-keys:add dokku ~/.ssh/id\_rsa.pub |
252,606 | I have code in Python 3 where I fetch data from the GitHub API, and I want some advice on the architecture of this code.
```
import urllib.request, urllib.parse, urllib.error
import json
import sys
from collections import Counter
from datetime import datetime, timedelta, date
from tabulate import tabulate
from LanguagesRepoCounter import LanguagesCounter
from RepoListLanguages import RepoListLanguages
#getting the date of one mounth ago from today
One_Mouth_ago_date = datetime.date(datetime.now()) - timedelta(days=30)
url = 'https://api.github.com/search/repositories?q=created:%3E'+One_Mouth_ago_date.isoformat()+'&sort=stars&order=desc&page=1&per_page=100'
data_connection_request = urllib.request.urlopen(url)
unicoded_data = data_connection_request.read().decode()
try:
json_data = json.loads(unicoded_data)
except:
json_data = None
# testing retrieaved data
if not json_data or json_data["total_count"]<1:
print(json_data)
sys.exit('######## Failure To Retrieve ########')
#Counting the number of repo using every language
Lang_Dic_Count = LanguagesCounter(json_data)
# Getting the list of repo using every language
DicDataList = RepoListLanguages(json_data, Lang_Dic_Count)
# Displaye the repo's urls for every language
for key in DicDataList:
print(key, ' language used in')
for i in range(len(DicDataList[key])):
print(" ", DicDataList[key][i])
# Displaye the number of repos using every language in a table
table = []
for key in Lang_Dic_Count:
under_table=[]
under_table.append(key)
under_table.append(Lang_Dic_Count[key])
table.append(under_table)
print(tabulate(table, headers=('Language', 'number of Repo using it'), tablefmt="grid"))
```
and the first function is :
```
def LanguagesCounter(Data):
''' Count how many times every programming language is used in the 100 most starred repos created in the last 30 days given in a parameter as json object, return a dict with languages as a keys and number of repo using this language as a value
'''
Languages_liste = []
for i in range(len(Data["items"])):
Languages_liste.append(Data["items"][i]["language"])
Lang_Dic_Count ={i:Languages_liste.count(i) for i in Languages_liste}
return Lang_Dic_Count
```
the third function is:
```
def RepoListLanguages(Data, list):
'''
return the list of repositories from Data parameter for every programming language in the list parameter as a dictionary with the programming language as key and a list of repositories as value
'''
languagesRepo = {}
for key in list:
languagesRepo[key]= []
for repo in range(len(Data["items"])):
if (key == Data["items"][repo]["language"]):
languagesRepo[key].append(Data["items"][repo]["html_url"])
return languagesRepo
```
The code fetches the most starred repos from GitHub API that were created in the last 30 days, counts how many repos use every programming language, and lists the repo links for every language. | 2020/11/24 | [
"https://codereview.stackexchange.com/questions/252606",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/233675/"
] | Since your concern is chiefly falling on the controller and I don't have particular expertise with twig scripting, I'll speak on the controller. **Please do not take my snippet at the end to be ready for copy-pasta** -- it is not tested and it is likely that I have made mistakes and/or misunderstood the data that is being passed into these controllers. Hopefully the itemized advice will help you to realize some techniques to clean up your methods.
1. [PSR-12 says: Method names MUST NOT be prefixed with a single underscore to indicate protected or private visibility. That is, an underscore prefix explicitly has no meaning.](https://www.php-fig.org/psr/psr-12/#:%7E:text=Method%20names,%20no%20meaning.)
2. I prefer to declare data types on all incoming parameters and return values. Not only does this help with debugging, it also coerces values like numeric strings to ints and floats.
3. Rather than repeat the `$config` each time you want to declare a new element, just declare the full array in one go.
4. Better yet, don't declare the `$config` variable at all (or any single-use variables for that matter). Any time you declare a variable then only actually use it one time, then this is a good argument for writing the value directly into where you originally had the variable. There are some exceptions to this, for instance, you want to be declarative about the value or, perhaps, directly injecting the value makes the code less readable / too wide.
5. We shouldn't be seeing any instances of `$_GET` in your CI code. CI passes all this slash-delimited data in the url and all of the data is instantly available in your controller method's argument list. From memory, I don't think I ever use `$this->input->get()` in any of my CI work.
6. I prefer to use camelCase variable naming because PHPStorm does a good job of finding my misspellings and it is more concise than snake\_case. Well, actually, `$queryStringSegment` is too verbose and only vaguely describes the value, `$segment` is just as vague, but more concise. Perhaps there is a better variable name to use.
7. You may have confused me with `/pages/page/{{page.id}}`, but I am assuming that `index()` method is what is receiving these page load requests and the only value that you actually need is the last one `{{page.id}}`. Add `$pageNumber` as the lone parameter of `index()` and pass the value along with other expected values to `_initPagination()`. Ensure that `$pageNumber` cannot be less than 1 -- I'll recommend `max()`.
---
```
class Posts extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
private function _initPagination(string $baseUrl, int $totalRows, string $segment = 'page', ?int $pageNumber = 1): array
{
$this->load->library('pagination');
$limit = 12;
$this->pagination->initialize([
'base_url' => $baseUrl,
'query_string_segment' => $segment,
'enable_query_strings' => true,
'reuse_query_string' => true,
'total_rows' = $totalRows,
'per_page' => $limit,
]);
return [$limit, $pageNumber - 1];
}
public function index(int $pageNumber = 1): void
{
$baseUrl = base_url('/');
//call initialization method
$rangeParameters = $this->_initPagination(
$baseUrl,
$this->Posts_model->get_num_rows(),
'page',
max(1, $pageNumber),
);
$data = $this->Static_model->get_static_data()
+ [
'base_url' => $baseUrl,
'pages' => $this->Pages_model->get_pages(),
'categories' => $this->Categories_model->get_categories(),
'posts' = $this->Posts_model->get_posts(...$rangeParameters)
];
$this->twig->addGlobal('maincss', base_url('themes/caminar/assets/css/main.css'));
$this->twig->addGlobal('pagination', $this->pagination->create_links());
$this->twig->display('themes/caminar/layout', $data);
}
...
}
``` | Well just some refactoring.
i.e. `$this->twig->display('themes/caminar/layout', $data);` only needs to appear once.
When you have code that repeats inside an `if`/`else`, it can come outside of that block.
```
if (!empty($data['post'])) {
// Overwrite the default tagline with the post title
$data['tagline'] = $data['post']->title;
// Get post comments
$post_id = $data['post']->id;
$data['comments'] = $this->Comments_model->get_comments($post_id);
$this->twig->addGlobal('singlePost','themes/caminar/templates/singlepost.twig');
$this->twig->display('themes/caminar/layout', $data);
} else {
$data['tagline'] = "Page not found";
$this->twig->addGlobal('notFound','themes/caminar/templates/404.twig');
$this->twig->display('themes/caminar/layout', $data);
}
```
Becomes
```
if (!empty($data['post'])) {
// Overwrite the default tagline with the post title
$data['tagline'] = $data['post']->title;
// Get post comments
$post_id = $data['post']->id;
$data['comments'] = $this->Comments_model->get_comments($post_id);
$this->twig->addGlobal('singlePost','themes/caminar/templates/singlepost.twig');
} else {
$data['tagline'] = "Page not found";
$this->twig->addGlobal('notFound','themes/caminar/templates/404.twig');
}
$this->twig->display('themes/caminar/layout', $data);
``` |
240,359 | Can anyone please explain below line in magento2 checkout page
```
<item name="customEntry" xsi:type="string">shippingAddress.region</item>
``` | 2018/08/31 | [
"https://magento.stackexchange.com/questions/240359",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/67054/"
] | This line is part of the checkout layout handle (checkout\_index\_index.xml):
```
<!-- code above -->
<item name="region_id" xsi:type="array">
<item name="component" xsi:type="string">Magento_Ui/js/form/element/region</item>
<item name="config" xsi:type="array">
<item name="template" xsi:type="string">ui/form/field</item>
<item name="elementTmpl" xsi:type="string">ui/form/element/select</item>
<item name="customEntry" xsi:type="string">shippingAddress.region</item>
</item>
<!-- code bellow -->
```
The top level item is named "region\_id" and therefore, with the child item "component", its component is set to "Magento\_Ui/js/form/element/region".
The actual file that matches this string is found at /vendor/magento/module-ui/view/base/web/js/form/element/region.js
The item "config" actually configures the component.
If you were to add any item of type string, just like the "customEntry" is added, this is immediately available to the component as JavaScript variable,
and therefore can be referenced in the HTML template.
For example, if you were to declare the "customEntry" as
```
<item name="customEntry" xsi:type="string">My fixed message here!</item>
```
you should be able to type this KO binding in the HTML template:
```
<div><span data-bind="text: customEntry"></span></div>
```
And the span will be filled with the value "My fixed message here!"
In Magento\_Ui/js/form/element/region component this is used in a different fashion (lines 88-90)
```
if (this.customEntry) {// eslint-disable-line max-depth
this.toggleInput(false);
}
```
In effect, this toggles the input if the "customEntry" is not undefined I guess.
Now, the last question is what is shippingAddress.region.
Well, that would be an already present JavaScript object named "shippingAddress" which has a property "region".
How do you find it?
Login in as a customer that has a shipping address already saved and open the checkout page in magento.
Open "Inspect" and then "Console" in Mozilla Firefox.
Execute
```
var reg = requirejs('uiRegistry');
```
Now, the "reg" variable contains all the data from magento uiRegistry.
Next, lets list all entries in the registry with
```
reg.get(function(item){
console.log(item.name);
console.log(item.component);
console.log(item.template);
});
```
Then, filter these results by typing "shipping" in the "Filter output".
Now, take a moment a thank Alam Storm for this way of looping through the uiRegistry.
Eventually, you will notice that Magento\_Checkout/js/view/shipping-address/address-renderer/default is loaded.
The actual file that matches this string is found at /vendor/magento/module-checkout/view/frontend/web/js/view/shipping-address/address-renderer/default.js
You will notice that this file asks a "quote" object to be inserted via Magento\_Checkout/js/model/quote.
Later on line 30, quote.shippingAddress() is called an assigned to a variable named shippingAddress.
You should debug, using Mozilla "Debugger", the corresponding js file found in /pub/static and see if you have actual "region" set to this shippingAddress set and what the value is.
By the way, the value here, should match the value entered in the "State/Province" field of the "Addresses" in the Customer edit page in the admin of the site. | Motivation for `customEntry`
----------------------------
[Marjan's answer](https://magento.stackexchange.com/a/240370/55289) is excellent, but I was also curious about the functional purpose of the `customEntry` property within UI component configuration.
As it turns out, UI dropdown components (from `Magento_Ui/js/form/element/select.js`) use the `customEntry` property to **define a backup text input field for when the dropdown has no options available**.
In the case of the Magento 2 checkout page (`checkout_index_index.xml`), the configuration in question (found [here](https://github.com/magento/magento2/blob/19e8507a6758cca06bbd554965002c0907b79f8f/app/code/Magento/Checkout/view/frontend/layout/checkout_index_index.xml#L197) in the source code) creates a hidden input field for the `region` dropdown of the shipping address. Since the available regions are filtered by the selected country (see the `filterBy` configuration property [here](https://github.com/magento/magento2/blob/19e8507a6758cca06bbd554965002c0907b79f8f/app/code/Magento/Checkout/view/frontend/layout/checkout_index_index.xml#L203) for more details on that functionality), the possibility exists that a customer might choose a country for which no regions are configured. In that case, the dropdown would disappear and be replaced with a text input field where the customer could type in their region/state/province name manually.
Implementation
--------------
Although the `region.js` component does reference `customEntry` once, most of the implementation is actually found in the parent component definition, `select.js`. When select components are initialized, the `initInput` method is registered to run only if `customEntry` is defined:
```
if (this.customEntry) {
registry.get(this.name, this.initInput.bind(this));
}
```
[source](https://github.com/magento/magento2/blob/19e8507a6758cca06bbd554965002c0907b79f8f/app/code/Magento/Ui/view/base/web/js/form/element/select.js#L125)
The `initInput` method simply defines and renders another UI component as a sibling of the current select component.
```
layout([utils.template(inputNode, this)]);
```
[source](https://github.com/magento/magento2/blob/19e8507a6758cca06bbd554965002c0907b79f8f/app/code/Magento/Ui/view/base/web/js/form/element/select.js#L175)
The `inputNode` is a simple Javascript object [defined at the top](https://github.com/magento/magento2/blob/19e8507a6758cca06bbd554965002c0907b79f8f/app/code/Magento/Ui/view/base/web/js/form/element/select.js#L18) of `select.js`, containing the configuration for the new input component.
Most importantly, once all of the components are initialized, there is a section of the `setOptions` method that sets the visibility of both components (the dropdown and the text input) based on the given options.
```
if (this.customEntry) {
isVisible = !!result.options.length;
this.setVisible(isVisible);
this.toggleInput(!isVisible);
}
```
[source](https://github.com/magento/magento2/blob/19e8507a6758cca06bbd554965002c0907b79f8f/app/code/Magento/Ui/view/base/web/js/form/element/select.js#L253)
Here is what that cryptic boolean manipulation is doing, explained in English:
* If at least one dropdown option exists, show the dropdown and hide the text input.
* If no dropdown options exist, hide the dropdown and show the text input.
There are more details that would take too long to explain in this answer, but hopefully this explanation is enough to get others started using the `customEntry` configuration item. |
54,414,978 | I have imported a stock's data from yahoo into a dataframe using pandas\_datareader.
There are 2 columns : date and the adjusted close of the stock.
```
Date Adj Close
2017-08-31 168.851196
2017-09-01 169.867691
2017-09-05 165.333496
2017-09-06 165.233810
2017-09-07 166.001160
2017-09-08 163.121201
2017-09-11 168.412735
2017-09-12 169.020630
2017-09-13 169.777969
2017-09-14 168.811356
2017-09-15 179.484131
2017-09-18 186.898300
2017-09-19 186.698990
2017-09-20 185.194214
2017-09-21 180.131882
2017-09-22 178.377991
2017-09-25 170.405807
2017-09-26 171.362473
2017-09-27 175.119354
2017-09-28 175.069534
2017-09-29 178.148788
2017-10-02 178.377991
2017-10-03 178.746704
2017-10-04 180.241486
2017-10-05 180.141861
2017-10-06 180.670013
2017-10-09 184.745804
2017-10-10 188.273499
2017-10-11 190.276505
2017-10-12 190.366211
```
I want to be able to insert another column called 'Log return' which takes the Adj Close of the current day (the dates aren't all 1 day apart because of trading days) and divide it by the previous days Adj Close and then *take the natural logarithm of that quotient*
I.e. Ln(A(today)/A(yesterday)), where A is just the adj close.
By the way, my dataframe variable is called df.
```
import pandas as pd
import pandas_datareader as web
#import datetime internal datetime module
#datetime is a Python module
import datetime
#datetime.datetime is a data type within the datetime module
start = datetime.datetime(2015, 9, 1)
end = datetime.datetime(2018, 12, 31)
#DataReader method name is case sensitive
df = web.DataReader("nvda", 'yahoo', start, end)
#invoke to_csv for df dataframe object from
#DataReader method in the pandas_datareader library
#..\first_yahoo_prices_to_csv_demo.csv must not
#be open in another app, such as Excel
df = df.iloc[0:, 5:] #Trims the set to Adj Close
```
That is what I have so far in my code.
**EDIT** I do not want A(today)/A(yesterday)-1, I actually need Ln(A(today)/A(yesterday)). (natural logarithm) | 2019/01/29 | [
"https://Stackoverflow.com/questions/54414978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10982754/"
] | Try this:
```
df['Adj Yesterday'] = df['Adj Close'].shift()
df['Log Return'] = df['Adj Close'] / df['Adj Yesterday'] - 1.
```
If this is not quite what you wanted, but close, [here is the docs for shift](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html).
You can also use [resample](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.resample.html), or [set\_index](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html) with [date\_range](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html) if missing temporal data. | You can try this:
```
# First ensure dates are in order
df = df.sort_values('Date')
# Divide all rows by their previous and find log
diff = np.log(df[1:]['Adj Close'] / df[0:-1]['Adj Close'])
# Add new column, first row will be NaN as it has no previous day
df['Log Return'] = pd.concat(pd.Series([pd.nan]), diff)
``` |
54,414,978 | I have imported a stock's data from yahoo into a dataframe using pandas\_datareader.
There are 2 columns : date and the adjusted close of the stock.
```
Date Adj Close
2017-08-31 168.851196
2017-09-01 169.867691
2017-09-05 165.333496
2017-09-06 165.233810
2017-09-07 166.001160
2017-09-08 163.121201
2017-09-11 168.412735
2017-09-12 169.020630
2017-09-13 169.777969
2017-09-14 168.811356
2017-09-15 179.484131
2017-09-18 186.898300
2017-09-19 186.698990
2017-09-20 185.194214
2017-09-21 180.131882
2017-09-22 178.377991
2017-09-25 170.405807
2017-09-26 171.362473
2017-09-27 175.119354
2017-09-28 175.069534
2017-09-29 178.148788
2017-10-02 178.377991
2017-10-03 178.746704
2017-10-04 180.241486
2017-10-05 180.141861
2017-10-06 180.670013
2017-10-09 184.745804
2017-10-10 188.273499
2017-10-11 190.276505
2017-10-12 190.366211
```
I want to be able to insert another column called 'Log return' which takes the Adj Close of the current day (the dates aren't all 1 day apart because of trading days) and divide it by the previous days Adj Close and then *take the natural logarithm of that quotient*
I.e. Ln(A(today)/A(yesterday)), where A is just the adj close.
By the way, my dataframe variable is called df.
```
import pandas as pd
import pandas_datareader as web
#import datetime internal datetime module
#datetime is a Python module
import datetime
#datetime.datetime is a data type within the datetime module
start = datetime.datetime(2015, 9, 1)
end = datetime.datetime(2018, 12, 31)
#DataReader method name is case sensitive
df = web.DataReader("nvda", 'yahoo', start, end)
#invoke to_csv for df dataframe object from
#DataReader method in the pandas_datareader library
#..\first_yahoo_prices_to_csv_demo.csv must not
#be open in another app, such as Excel
df = df.iloc[0:, 5:] #Trims the set to Adj Close
```
That is what I have so far in my code.
**EDIT** I do not want A(today)/A(yesterday)-1, I actually need Ln(A(today)/A(yesterday)). (natural logarithm) | 2019/01/29 | [
"https://Stackoverflow.com/questions/54414978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10982754/"
] | You need [`Series.pct_change`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.pct_change.html):
```
df['Log Return'] = df['Adj Close'].pct_change()
```
If need `ln`:
```
df['Log Return'] = np.log(df['Adj Close'].pct_change())
``` | You can try this:
```
# First ensure dates are in order
df = df.sort_values('Date')
# Divide all rows by their previous and find log
diff = np.log(df[1:]['Adj Close'] / df[0:-1]['Adj Close'])
# Add new column, first row will be NaN as it has no previous day
df['Log Return'] = pd.concat(pd.Series([pd.nan]), diff)
``` |
54,414,978 | I have imported a stock's data from yahoo into a dataframe using pandas\_datareader.
There are 2 columns : date and the adjusted close of the stock.
```
Date Adj Close
2017-08-31 168.851196
2017-09-01 169.867691
2017-09-05 165.333496
2017-09-06 165.233810
2017-09-07 166.001160
2017-09-08 163.121201
2017-09-11 168.412735
2017-09-12 169.020630
2017-09-13 169.777969
2017-09-14 168.811356
2017-09-15 179.484131
2017-09-18 186.898300
2017-09-19 186.698990
2017-09-20 185.194214
2017-09-21 180.131882
2017-09-22 178.377991
2017-09-25 170.405807
2017-09-26 171.362473
2017-09-27 175.119354
2017-09-28 175.069534
2017-09-29 178.148788
2017-10-02 178.377991
2017-10-03 178.746704
2017-10-04 180.241486
2017-10-05 180.141861
2017-10-06 180.670013
2017-10-09 184.745804
2017-10-10 188.273499
2017-10-11 190.276505
2017-10-12 190.366211
```
I want to be able to insert another column called 'Log return' which takes the Adj Close of the current day (the dates aren't all 1 day apart because of trading days) and divide it by the previous days Adj Close and then *take the natural logarithm of that quotient*
I.e. Ln(A(today)/A(yesterday)), where A is just the adj close.
By the way, my dataframe variable is called df.
```
import pandas as pd
import pandas_datareader as web
#import datetime internal datetime module
#datetime is a Python module
import datetime
#datetime.datetime is a data type within the datetime module
start = datetime.datetime(2015, 9, 1)
end = datetime.datetime(2018, 12, 31)
#DataReader method name is case sensitive
df = web.DataReader("nvda", 'yahoo', start, end)
#invoke to_csv for df dataframe object from
#DataReader method in the pandas_datareader library
#..\first_yahoo_prices_to_csv_demo.csv must not
#be open in another app, such as Excel
df = df.iloc[0:, 5:] #Trims the set to Adj Close
```
That is what I have so far in my code.
**EDIT** I do not want A(today)/A(yesterday)-1, I actually need Ln(A(today)/A(yesterday)). (natural logarithm) | 2019/01/29 | [
"https://Stackoverflow.com/questions/54414978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10982754/"
] | Try this:
```
df['Adj Yesterday'] = df['Adj Close'].shift()
df['Log Return'] = df['Adj Close'] / df['Adj Yesterday'] - 1.
```
If this is not quite what you wanted, but close, [here is the docs for shift](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.shift.html).
You can also use [resample](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.resample.html), or [set\_index](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html) with [date\_range](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html) if missing temporal data. | You need [`Series.pct_change`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.pct_change.html):
```
df['Log Return'] = df['Adj Close'].pct_change()
```
If need `ln`:
```
df['Log Return'] = np.log(df['Adj Close'].pct_change())
``` |
78,857 | I have tablet - Dell latitude 10, running Windows 8, with integrated Broadcom GNSS Receiver BCM47511 (GPS,Glonass...). Because it is integrated GPS and Windows 8, there is the "new" way of providing GPS data called Windows Location Provider. This "new" way means it doesn't work properly or at all in almost any navigation/localisation software at this moment - because this software expect GPS data coming from COM port. Including QGIS - at this moment it is on the road map - <http://hub.qgis.org/issues/7878>
Anyway after extensive search I found software which can bypass MS localisation platform. It is called Centrafuse Localizer. This software can simulate COM port and send through it GPS data so some software is able to read it.
Unfortunately not QGIS. QGIS can see the port (just to test it I changed COM 1 to 5 and 7) and it changes Serial device list in QGIS but after hitting Connect it always fails.
If you are thinking about tablet with integrated GPS think twice! From my point of view it is just too early - probably also no proper drivers yet as what I have read from Broadcom Readme file. Even when GPS "works" the refresh rate and precision is terrible comparing to my phone. And all software must be changed to work with this new interface...
**Is there other way I could try to make work tablet integrated GNSS (GPS) on Windows 8 with QGIS?** | 2013/11/28 | [
"https://gis.stackexchange.com/questions/78857",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/7771/"
] | At the end I decided to try newer driver from other company.
Broadcom GNSS Geolocation Driver for Windows 8.1 (32-bit), 8 (32-bit) - ThinkPad Tablet 2
19.14.8401.4 24 Nov 2012
With this driver and Centrafuse Localizer the GPS finally works in QGIS (and also in some way in Google Earth). Hooray!
**You need at this moment these things:**
1. Centrafuse Localizer (which is unfortunately not freeware) to bypass Windows Location Provider which is useless
2. Install driver from Lenovo (which makes Broadcom GNSS work properly)
3. QGIS (tested with version 2.0.1) - GPS is under View / Panels / GPS information
* I decided to set connection to Serial device to see if COM port is available
Shame on you Microsoft to totally cut out backward compatibility!
Shame on you DELL to not provide proper functional driver!
Make sure you see sensor working in the localizer:

My saved test track in QGIS:

Good Luck! | after a lot of investigation, I've found a solution for this problem using only free tools.
* GNSSDataInterface: a great tool that read from windows location API and send data to a COM port. You can configure wich port and if you want to start all autmatically.
* Com0com: creates virtual ports and pair them. So you can transfer data form one port to another. in my case (COM4 <-> COM5)
So with GNSSDataInterface you can send data to COM4 and thanks to com0com pair with COM5. QGIS will must use COM5 (free port) to get data.
Another interesting tool are SensorDisgnosticTool (for checking if you GPS is adquiring data through sensor) and GPSView, for check the data from a COM port.
Regards. |
78,857 | I have tablet - Dell latitude 10, running Windows 8, with integrated Broadcom GNSS Receiver BCM47511 (GPS,Glonass...). Because it is integrated GPS and Windows 8, there is the "new" way of providing GPS data called Windows Location Provider. This "new" way means it doesn't work properly or at all in almost any navigation/localisation software at this moment - because this software expect GPS data coming from COM port. Including QGIS - at this moment it is on the road map - <http://hub.qgis.org/issues/7878>
Anyway after extensive search I found software which can bypass MS localisation platform. It is called Centrafuse Localizer. This software can simulate COM port and send through it GPS data so some software is able to read it.
Unfortunately not QGIS. QGIS can see the port (just to test it I changed COM 1 to 5 and 7) and it changes Serial device list in QGIS but after hitting Connect it always fails.
If you are thinking about tablet with integrated GPS think twice! From my point of view it is just too early - probably also no proper drivers yet as what I have read from Broadcom Readme file. Even when GPS "works" the refresh rate and precision is terrible comparing to my phone. And all software must be changed to work with this new interface...
**Is there other way I could try to make work tablet integrated GNSS (GPS) on Windows 8 with QGIS?** | 2013/11/28 | [
"https://gis.stackexchange.com/questions/78857",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/7771/"
] | At the end I decided to try newer driver from other company.
Broadcom GNSS Geolocation Driver for Windows 8.1 (32-bit), 8 (32-bit) - ThinkPad Tablet 2
19.14.8401.4 24 Nov 2012
With this driver and Centrafuse Localizer the GPS finally works in QGIS (and also in some way in Google Earth). Hooray!
**You need at this moment these things:**
1. Centrafuse Localizer (which is unfortunately not freeware) to bypass Windows Location Provider which is useless
2. Install driver from Lenovo (which makes Broadcom GNSS work properly)
3. QGIS (tested with version 2.0.1) - GPS is under View / Panels / GPS information
* I decided to set connection to Serial device to see if COM port is available
Shame on you Microsoft to totally cut out backward compatibility!
Shame on you DELL to not provide proper functional driver!
Make sure you see sensor working in the localizer:

My saved test track in QGIS:

Good Luck! | I had to solve this issue for a client running QGIS on Windows tablets 8-10.
The best solution I found so far is [GpsGate Splitter Express](http://gpsgate.com/purchase/gpsgate_client_licenses). If you install it with the plugin, it makes it possible to read the GPS data from the location provider and send it to a virtual COM port. The program runs at startup, so UEFI secure boot has to be disabled for this to work.
And the best part: GpsGate Splitter Express is free for both private and commercial use, as they state on their website. |
78,857 | I have tablet - Dell latitude 10, running Windows 8, with integrated Broadcom GNSS Receiver BCM47511 (GPS,Glonass...). Because it is integrated GPS and Windows 8, there is the "new" way of providing GPS data called Windows Location Provider. This "new" way means it doesn't work properly or at all in almost any navigation/localisation software at this moment - because this software expect GPS data coming from COM port. Including QGIS - at this moment it is on the road map - <http://hub.qgis.org/issues/7878>
Anyway after extensive search I found software which can bypass MS localisation platform. It is called Centrafuse Localizer. This software can simulate COM port and send through it GPS data so some software is able to read it.
Unfortunately not QGIS. QGIS can see the port (just to test it I changed COM 1 to 5 and 7) and it changes Serial device list in QGIS but after hitting Connect it always fails.
If you are thinking about tablet with integrated GPS think twice! From my point of view it is just too early - probably also no proper drivers yet as what I have read from Broadcom Readme file. Even when GPS "works" the refresh rate and precision is terrible comparing to my phone. And all software must be changed to work with this new interface...
**Is there other way I could try to make work tablet integrated GNSS (GPS) on Windows 8 with QGIS?** | 2013/11/28 | [
"https://gis.stackexchange.com/questions/78857",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/7771/"
] | At the end I decided to try newer driver from other company.
Broadcom GNSS Geolocation Driver for Windows 8.1 (32-bit), 8 (32-bit) - ThinkPad Tablet 2
19.14.8401.4 24 Nov 2012
With this driver and Centrafuse Localizer the GPS finally works in QGIS (and also in some way in Google Earth). Hooray!
**You need at this moment these things:**
1. Centrafuse Localizer (which is unfortunately not freeware) to bypass Windows Location Provider which is useless
2. Install driver from Lenovo (which makes Broadcom GNSS work properly)
3. QGIS (tested with version 2.0.1) - GPS is under View / Panels / GPS information
* I decided to set connection to Serial device to see if COM port is available
Shame on you Microsoft to totally cut out backward compatibility!
Shame on you DELL to not provide proper functional driver!
Make sure you see sensor working in the localizer:

My saved test track in QGIS:

Good Luck! | There's also GPSReverse: <https://www.gpssensordrivers.com/>
It's free for evaluation purposes... but never seems to expire.
Download GPSComplete evaluation (it comes with everything) with the correct bitness. Open the tool. Install the com port driver, select iLocation as the sensor, leave the rest as default. Then install the transfer tool service, set ILocation query as source and COM port driver as the destination. The UI can be closed after that, everything works as a background service.
Sometimes it's possible to enable COM ports on the device directly with some settings or a different driver but it varies a lot between manufacturers / models and it's often not documented. Here's a tutorial for EM7455: <https://zukota.com/sierra-wireless-em7455-how-to-enable-com-ports/> |
78,857 | I have tablet - Dell latitude 10, running Windows 8, with integrated Broadcom GNSS Receiver BCM47511 (GPS,Glonass...). Because it is integrated GPS and Windows 8, there is the "new" way of providing GPS data called Windows Location Provider. This "new" way means it doesn't work properly or at all in almost any navigation/localisation software at this moment - because this software expect GPS data coming from COM port. Including QGIS - at this moment it is on the road map - <http://hub.qgis.org/issues/7878>
Anyway after extensive search I found software which can bypass MS localisation platform. It is called Centrafuse Localizer. This software can simulate COM port and send through it GPS data so some software is able to read it.
Unfortunately not QGIS. QGIS can see the port (just to test it I changed COM 1 to 5 and 7) and it changes Serial device list in QGIS but after hitting Connect it always fails.
If you are thinking about tablet with integrated GPS think twice! From my point of view it is just too early - probably also no proper drivers yet as what I have read from Broadcom Readme file. Even when GPS "works" the refresh rate and precision is terrible comparing to my phone. And all software must be changed to work with this new interface...
**Is there other way I could try to make work tablet integrated GNSS (GPS) on Windows 8 with QGIS?** | 2013/11/28 | [
"https://gis.stackexchange.com/questions/78857",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/7771/"
] | I had to solve this issue for a client running QGIS on Windows tablets 8-10.
The best solution I found so far is [GpsGate Splitter Express](http://gpsgate.com/purchase/gpsgate_client_licenses). If you install it with the plugin, it makes it possible to read the GPS data from the location provider and send it to a virtual COM port. The program runs at startup, so UEFI secure boot has to be disabled for this to work.
And the best part: GpsGate Splitter Express is free for both private and commercial use, as they state on their website. | after a lot of investigation, I've found a solution for this problem using only free tools.
* GNSSDataInterface: a great tool that read from windows location API and send data to a COM port. You can configure wich port and if you want to start all autmatically.
* Com0com: creates virtual ports and pair them. So you can transfer data form one port to another. in my case (COM4 <-> COM5)
So with GNSSDataInterface you can send data to COM4 and thanks to com0com pair with COM5. QGIS will must use COM5 (free port) to get data.
Another interesting tool are SensorDisgnosticTool (for checking if you GPS is adquiring data through sensor) and GPSView, for check the data from a COM port.
Regards. |
78,857 | I have tablet - Dell latitude 10, running Windows 8, with integrated Broadcom GNSS Receiver BCM47511 (GPS,Glonass...). Because it is integrated GPS and Windows 8, there is the "new" way of providing GPS data called Windows Location Provider. This "new" way means it doesn't work properly or at all in almost any navigation/localisation software at this moment - because this software expect GPS data coming from COM port. Including QGIS - at this moment it is on the road map - <http://hub.qgis.org/issues/7878>
Anyway after extensive search I found software which can bypass MS localisation platform. It is called Centrafuse Localizer. This software can simulate COM port and send through it GPS data so some software is able to read it.
Unfortunately not QGIS. QGIS can see the port (just to test it I changed COM 1 to 5 and 7) and it changes Serial device list in QGIS but after hitting Connect it always fails.
If you are thinking about tablet with integrated GPS think twice! From my point of view it is just too early - probably also no proper drivers yet as what I have read from Broadcom Readme file. Even when GPS "works" the refresh rate and precision is terrible comparing to my phone. And all software must be changed to work with this new interface...
**Is there other way I could try to make work tablet integrated GNSS (GPS) on Windows 8 with QGIS?** | 2013/11/28 | [
"https://gis.stackexchange.com/questions/78857",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/7771/"
] | I had to solve this issue for a client running QGIS on Windows tablets 8-10.
The best solution I found so far is [GpsGate Splitter Express](http://gpsgate.com/purchase/gpsgate_client_licenses). If you install it with the plugin, it makes it possible to read the GPS data from the location provider and send it to a virtual COM port. The program runs at startup, so UEFI secure boot has to be disabled for this to work.
And the best part: GpsGate Splitter Express is free for both private and commercial use, as they state on their website. | There's also GPSReverse: <https://www.gpssensordrivers.com/>
It's free for evaluation purposes... but never seems to expire.
Download GPSComplete evaluation (it comes with everything) with the correct bitness. Open the tool. Install the com port driver, select iLocation as the sensor, leave the rest as default. Then install the transfer tool service, set ILocation query as source and COM port driver as the destination. The UI can be closed after that, everything works as a background service.
Sometimes it's possible to enable COM ports on the device directly with some settings or a different driver but it varies a lot between manufacturers / models and it's often not documented. Here's a tutorial for EM7455: <https://zukota.com/sierra-wireless-em7455-how-to-enable-com-ports/> |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | Since you already know the formula, it should be easy enough to create a function to do the calculation for you.
Here, I've created a basic function to get you started. The function takes four arguments:
* `frequencies`: A vector of frequencies ("number" in your first example)
* `intervals`: A 2-row `matrix` with the same number of columns as the length of frequencies, with the first row being the lower class boundary, and the second row being the upper class boundary. Alternatively, "`intervals`" may be a column in your `data.frame`, and you may specify `sep` (and possibly, `trim`) to have the function automatically create the required matrix for you.
* `sep`: The separator character in your "`intervals`" column in your `data.frame`.
* `trim`: A regular expression of characters that need to be removed before trying to coerce to a numeric matrix. One pattern is built into the function: `trim = "cut"`. This sets the regular expression pattern to remove (, ), [, and ] from the input.
Here's the function (with comments showing how I used your instructions to put it together):
```
GroupedMedian <- function(frequencies, intervals, sep = NULL, trim = NULL) {
# If "sep" is specified, the function will try to create the
# required "intervals" matrix. "trim" removes any unwanted
# characters before attempting to convert the ranges to numeric.
if (!is.null(sep)) {
if (is.null(trim)) pattern <- ""
else if (trim == "cut") pattern <- "\\[|\\]|\\(|\\)"
else pattern <- trim
intervals <- sapply(strsplit(gsub(pattern, "", intervals), sep), as.numeric)
}
Midpoints <- rowMeans(intervals)
cf <- cumsum(frequencies)
Midrow <- findInterval(max(cf)/2, cf) + 1
L <- intervals[1, Midrow] # lower class boundary of median class
h <- diff(intervals[, Midrow]) # size of median class
f <- frequencies[Midrow] # frequency of median class
cf2 <- cf[Midrow - 1] # cumulative frequency class before median class
n_2 <- max(cf)/2 # total observations divided by 2
unname(L + (n_2 - cf2)/f * h)
}
```
---
Here's a sample `data.frame` to work with:
```
mydf <- structure(list(salary = c("1500-1600", "1600-1700", "1700-1800",
"1800-1900", "1900-2000", "2000-2100", "2100-2200", "2200-2300",
"2300-2400", "2400-2500"), number = c(110L, 180L, 320L, 460L,
850L, 250L, 130L, 70L, 20L, 10L)), .Names = c("salary", "number"),
class = "data.frame", row.names = c(NA, -10L))
mydf
# salary number
# 1 1500-1600 110
# 2 1600-1700 180
# 3 1700-1800 320
# 4 1800-1900 460
# 5 1900-2000 850
# 6 2000-2100 250
# 7 2100-2200 130
# 8 2200-2300 70
# 9 2300-2400 20
# 10 2400-2500 10
```
---
Now, we can simply do:
```
GroupedMedian(mydf$number, mydf$salary, sep = "-")
# [1] 1915.294
```
---
Here's an example of the function in action on some made up data:
```
set.seed(1)
x <- sample(100, 100, replace = TRUE)
y <- data.frame(table(cut(x, 10)))
y
# Var1 Freq
# 1 (1.9,11.7] 8
# 2 (11.7,21.5] 8
# 3 (21.5,31.4] 8
# 4 (31.4,41.2] 15
# 5 (41.2,51] 13
# 6 (51,60.8] 5
# 7 (60.8,70.6] 11
# 8 (70.6,80.5] 15
# 9 (80.5,90.3] 11
# 10 (90.3,100] 6
### Here's GroupedMedian's output on the grouped data.frame...
GroupedMedian(y$Freq, y$Var1, sep = ",", trim = "cut")
# [1] 49.49231
### ... and the output of median on the original vector
median(x)
# [1] 49.5
```
---
By the way, with the sample data that you provided, where I think there was a mistake in one of your ranges (all were separated by dashes except one, which was separated by a comma), since `strsplit` uses a regular expression by default to split on, you can use the function like this:
```
x<-c(110,180,320,460,850,250,130,70,20,10)
colnames<-c("numbers")
rownames<-c("[1500-1600]","(1600-1700]","(1700-1800]","(1800-1900]",
"(1900-2000]"," (2000,2100]","(2100-2200]","(2200-2300]",
"(2300-2400]","(2400-2500]")
y<-matrix(x,nrow=length(x),dimnames=list(rownames,colnames))
GroupedMedian(y[, "numbers"], rownames(y), sep="-|,", trim="cut")
# [1] 1915.294
``` | Have you tried `median` or `apply(yourobject,2,median)` if it is a `matrix` or `data.frame` ? |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | ```
(Sal <- sapply( strsplit(as.character(dat[[1]]), "-"),
function(x) mean( as.numeric(x) ) ) )
[1] 1550 1650 1750 1850 1950 2050 2150 2250 2350 2450
require(Hmisc)
wtd.mean(Sal, weights = dat[[2]])
[1] 1898.75
wtd.quantile(Sal, weights=dat[[2]], probs=0.5)
```
Generalization to a weighed median might require looking for a package that has such. | Have you tried `median` or `apply(yourobject,2,median)` if it is a `matrix` or `data.frame` ? |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | Since you already know the formula, it should be easy enough to create a function to do the calculation for you.
Here, I've created a basic function to get you started. The function takes four arguments:
* `frequencies`: A vector of frequencies ("number" in your first example)
* `intervals`: A 2-row `matrix` with the same number of columns as the length of frequencies, with the first row being the lower class boundary, and the second row being the upper class boundary. Alternatively, "`intervals`" may be a column in your `data.frame`, and you may specify `sep` (and possibly, `trim`) to have the function automatically create the required matrix for you.
* `sep`: The separator character in your "`intervals`" column in your `data.frame`.
* `trim`: A regular expression of characters that need to be removed before trying to coerce to a numeric matrix. One pattern is built into the function: `trim = "cut"`. This sets the regular expression pattern to remove (, ), [, and ] from the input.
Here's the function (with comments showing how I used your instructions to put it together):
```
GroupedMedian <- function(frequencies, intervals, sep = NULL, trim = NULL) {
# If "sep" is specified, the function will try to create the
# required "intervals" matrix. "trim" removes any unwanted
# characters before attempting to convert the ranges to numeric.
if (!is.null(sep)) {
if (is.null(trim)) pattern <- ""
else if (trim == "cut") pattern <- "\\[|\\]|\\(|\\)"
else pattern <- trim
intervals <- sapply(strsplit(gsub(pattern, "", intervals), sep), as.numeric)
}
Midpoints <- rowMeans(intervals)
cf <- cumsum(frequencies)
Midrow <- findInterval(max(cf)/2, cf) + 1
L <- intervals[1, Midrow] # lower class boundary of median class
h <- diff(intervals[, Midrow]) # size of median class
f <- frequencies[Midrow] # frequency of median class
cf2 <- cf[Midrow - 1] # cumulative frequency class before median class
n_2 <- max(cf)/2 # total observations divided by 2
unname(L + (n_2 - cf2)/f * h)
}
```
---
Here's a sample `data.frame` to work with:
```
mydf <- structure(list(salary = c("1500-1600", "1600-1700", "1700-1800",
"1800-1900", "1900-2000", "2000-2100", "2100-2200", "2200-2300",
"2300-2400", "2400-2500"), number = c(110L, 180L, 320L, 460L,
850L, 250L, 130L, 70L, 20L, 10L)), .Names = c("salary", "number"),
class = "data.frame", row.names = c(NA, -10L))
mydf
# salary number
# 1 1500-1600 110
# 2 1600-1700 180
# 3 1700-1800 320
# 4 1800-1900 460
# 5 1900-2000 850
# 6 2000-2100 250
# 7 2100-2200 130
# 8 2200-2300 70
# 9 2300-2400 20
# 10 2400-2500 10
```
---
Now, we can simply do:
```
GroupedMedian(mydf$number, mydf$salary, sep = "-")
# [1] 1915.294
```
---
Here's an example of the function in action on some made up data:
```
set.seed(1)
x <- sample(100, 100, replace = TRUE)
y <- data.frame(table(cut(x, 10)))
y
# Var1 Freq
# 1 (1.9,11.7] 8
# 2 (11.7,21.5] 8
# 3 (21.5,31.4] 8
# 4 (31.4,41.2] 15
# 5 (41.2,51] 13
# 6 (51,60.8] 5
# 7 (60.8,70.6] 11
# 8 (70.6,80.5] 15
# 9 (80.5,90.3] 11
# 10 (90.3,100] 6
### Here's GroupedMedian's output on the grouped data.frame...
GroupedMedian(y$Freq, y$Var1, sep = ",", trim = "cut")
# [1] 49.49231
### ... and the output of median on the original vector
median(x)
# [1] 49.5
```
---
By the way, with the sample data that you provided, where I think there was a mistake in one of your ranges (all were separated by dashes except one, which was separated by a comma), since `strsplit` uses a regular expression by default to split on, you can use the function like this:
```
x<-c(110,180,320,460,850,250,130,70,20,10)
colnames<-c("numbers")
rownames<-c("[1500-1600]","(1600-1700]","(1700-1800]","(1800-1900]",
"(1900-2000]"," (2000,2100]","(2100-2200]","(2200-2300]",
"(2300-2400]","(2400-2500]")
y<-matrix(x,nrow=length(x),dimnames=list(rownames,colnames))
GroupedMedian(y[, "numbers"], rownames(y), sep="-|,", trim="cut")
# [1] 1915.294
``` | I think this concept should work you.
```
$salaries = array(
array("1500","1600"),
array("1600","1700"),
array("1700","1800"),
array("1800","1900"),
array("1900","2000"),
array("2000","2100"),
array("2100","2200"),
array("2200","2300"),
array("2300","2400"),
array("2400","2500"),
);
$numbers = array("110","180","320","460","850","250","130","70","20","10");
$cumsum = array();
$n = 0;
$count = 0;
foreach($numbers as $key=>$number){
$cumsum[$key] = $number;
$n += $number;
if($count > 0){
$cumsum[$key] += $cumsum[$key-1];
}
++$count;
}
$classIndex = 0;
foreach($cumsum as $key=>$cum){
if($cum < ($n/2)){
$classIndex = $key+1;
}
}
$classRange = $salaries[$classIndex];
$L = $classRange[0];
$h = (float) $classRange[1] - $classRange[0];
$f = $numbers[$classIndex];
$c = $numbers[$classIndex-1];
$Median = $L + ($h/$f)*(($n/2)-$c);
echo $Median;
``` |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | ```
(Sal <- sapply( strsplit(as.character(dat[[1]]), "-"),
function(x) mean( as.numeric(x) ) ) )
[1] 1550 1650 1750 1850 1950 2050 2150 2250 2350 2450
require(Hmisc)
wtd.mean(Sal, weights = dat[[2]])
[1] 1898.75
wtd.quantile(Sal, weights=dat[[2]], probs=0.5)
```
Generalization to a weighed median might require looking for a package that has such. | I think this concept should work you.
```
$salaries = array(
array("1500","1600"),
array("1600","1700"),
array("1700","1800"),
array("1800","1900"),
array("1900","2000"),
array("2000","2100"),
array("2100","2200"),
array("2200","2300"),
array("2300","2400"),
array("2400","2500"),
);
$numbers = array("110","180","320","460","850","250","130","70","20","10");
$cumsum = array();
$n = 0;
$count = 0;
foreach($numbers as $key=>$number){
$cumsum[$key] = $number;
$n += $number;
if($count > 0){
$cumsum[$key] += $cumsum[$key-1];
}
++$count;
}
$classIndex = 0;
foreach($cumsum as $key=>$cum){
if($cum < ($n/2)){
$classIndex = $key+1;
}
}
$classRange = $salaries[$classIndex];
$L = $classRange[0];
$h = (float) $classRange[1] - $classRange[0];
$f = $numbers[$classIndex];
$c = $numbers[$classIndex-1];
$Median = $L + ($h/$f)*(($n/2)-$c);
echo $Median;
``` |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | What about this way? Create vectors for each salary bracket, assuming an even spread over each band. Then make one big vector from those vectors, and take the median. Similar to you, but a slightly different result. I'm not a mathematician, so the method could be incorrect.
```
dat <- matrix(c(seq(1500, 2400, 100), seq(1600, 2500, 100), c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)), ncol=3)
median(unlist(apply(dat, 1, function(x) { ((1:x[3])/x[3])*(x[2]-x[1])+x[1] })))
```
Returns 1915.353 | I think this concept should work you.
```
$salaries = array(
array("1500","1600"),
array("1600","1700"),
array("1700","1800"),
array("1800","1900"),
array("1900","2000"),
array("2000","2100"),
array("2100","2200"),
array("2200","2300"),
array("2300","2400"),
array("2400","2500"),
);
$numbers = array("110","180","320","460","850","250","130","70","20","10");
$cumsum = array();
$n = 0;
$count = 0;
foreach($numbers as $key=>$number){
$cumsum[$key] = $number;
$n += $number;
if($count > 0){
$cumsum[$key] += $cumsum[$key-1];
}
++$count;
}
$classIndex = 0;
foreach($cumsum as $key=>$cum){
if($cum < ($n/2)){
$classIndex = $key+1;
}
}
$classRange = $salaries[$classIndex];
$L = $classRange[0];
$h = (float) $classRange[1] - $classRange[0];
$f = $numbers[$classIndex];
$c = $numbers[$classIndex-1];
$Median = $L + ($h/$f)*(($n/2)-$c);
echo $Median;
``` |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | I've written it like this to clearly explain how it's being worked out. A more compact version is appended.
```
library(data.table)
#constructing the dataset with the salary range split into low and high
salarydata <- data.table(
salaries_low = 100*c(15:24),
salaries_high = 100*c(16:25),
numbers = c(110,180,320,460,850,250,130,70,20,10)
)
#calculating cumulative number of observations
salarydata <- salarydata[,cumnumbers := cumsum(numbers)]
salarydata
# salaries_low salaries_high numbers cumnumbers
# 1: 1500 1600 110 110
# 2: 1600 1700 180 290
# 3: 1700 1800 320 610
# 4: 1800 1900 460 1070
# 5: 1900 2000 850 1920
# 6: 2000 2100 250 2170
# 7: 2100 2200 130 2300
# 8: 2200 2300 70 2370
# 9: 2300 2400 20 2390
# 10: 2400 2500 10 2400
#identifying median group
mediangroup <- salarydata[
(cumnumbers - numbers) <= (max(cumnumbers)/2) &
cumnumbers >= (max(cumnumbers)/2)]
mediangroup
# salaries_low salaries_high numbers cumnumbers
# 1: 1900 2000 850 1920
#creating the variables needed to calculate median
mediangroup[,l := salaries_low]
mediangroup[,h := salaries_high - salaries_low]
mediangroup[,f := numbers]
mediangroup[,c := cumnumbers- numbers]
n = salarydata[,sum(numbers)]
#calculating median
median <- mediangroup[,l + ((h/f)*((n/2)-c))]
median
# [1] 1915.294
```
The compact version -
EDIT: Changed to a function at @AnandaMahto's suggestion. Also, using more general variable names.
```
library(data.table)
#Creating function
CalculateMedian <- function(
LowerBound,
UpperBound,
Obs
)
{
#calculating cumulative number of observations and n
dataset <- data.table(UpperBound, LowerBound, Obs)
dataset <- dataset[,cumObs := cumsum(Obs)]
n = dataset[,max(cumObs)]
#identifying mediangroup and dynamically calculating l,h,f,c. We already have n.
median <- dataset[
(cumObs - Obs) <= (max(cumObs)/2) &
cumObs >= (max(cumObs)/2),
LowerBound + ((UpperBound - LowerBound)/Obs) * ((n/2) - (cumObs- Obs))
]
return(median)
}
# Using function
CalculateMedian(
LowerBound = 100*c(15:24),
UpperBound = 100*c(16:25),
Obs = c(110,180,320,460,850,250,130,70,20,10)
)
# [1] 1915.294
``` | Have you tried `median` or `apply(yourobject,2,median)` if it is a `matrix` or `data.frame` ? |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | Since you already know the formula, it should be easy enough to create a function to do the calculation for you.
Here, I've created a basic function to get you started. The function takes four arguments:
* `frequencies`: A vector of frequencies ("number" in your first example)
* `intervals`: A 2-row `matrix` with the same number of columns as the length of frequencies, with the first row being the lower class boundary, and the second row being the upper class boundary. Alternatively, "`intervals`" may be a column in your `data.frame`, and you may specify `sep` (and possibly, `trim`) to have the function automatically create the required matrix for you.
* `sep`: The separator character in your "`intervals`" column in your `data.frame`.
* `trim`: A regular expression of characters that need to be removed before trying to coerce to a numeric matrix. One pattern is built into the function: `trim = "cut"`. This sets the regular expression pattern to remove (, ), [, and ] from the input.
Here's the function (with comments showing how I used your instructions to put it together):
```
GroupedMedian <- function(frequencies, intervals, sep = NULL, trim = NULL) {
# If "sep" is specified, the function will try to create the
# required "intervals" matrix. "trim" removes any unwanted
# characters before attempting to convert the ranges to numeric.
if (!is.null(sep)) {
if (is.null(trim)) pattern <- ""
else if (trim == "cut") pattern <- "\\[|\\]|\\(|\\)"
else pattern <- trim
intervals <- sapply(strsplit(gsub(pattern, "", intervals), sep), as.numeric)
}
Midpoints <- rowMeans(intervals)
cf <- cumsum(frequencies)
Midrow <- findInterval(max(cf)/2, cf) + 1
L <- intervals[1, Midrow] # lower class boundary of median class
h <- diff(intervals[, Midrow]) # size of median class
f <- frequencies[Midrow] # frequency of median class
cf2 <- cf[Midrow - 1] # cumulative frequency class before median class
n_2 <- max(cf)/2 # total observations divided by 2
unname(L + (n_2 - cf2)/f * h)
}
```
---
Here's a sample `data.frame` to work with:
```
mydf <- structure(list(salary = c("1500-1600", "1600-1700", "1700-1800",
"1800-1900", "1900-2000", "2000-2100", "2100-2200", "2200-2300",
"2300-2400", "2400-2500"), number = c(110L, 180L, 320L, 460L,
850L, 250L, 130L, 70L, 20L, 10L)), .Names = c("salary", "number"),
class = "data.frame", row.names = c(NA, -10L))
mydf
# salary number
# 1 1500-1600 110
# 2 1600-1700 180
# 3 1700-1800 320
# 4 1800-1900 460
# 5 1900-2000 850
# 6 2000-2100 250
# 7 2100-2200 130
# 8 2200-2300 70
# 9 2300-2400 20
# 10 2400-2500 10
```
---
Now, we can simply do:
```
GroupedMedian(mydf$number, mydf$salary, sep = "-")
# [1] 1915.294
```
---
Here's an example of the function in action on some made up data:
```
set.seed(1)
x <- sample(100, 100, replace = TRUE)
y <- data.frame(table(cut(x, 10)))
y
# Var1 Freq
# 1 (1.9,11.7] 8
# 2 (11.7,21.5] 8
# 3 (21.5,31.4] 8
# 4 (31.4,41.2] 15
# 5 (41.2,51] 13
# 6 (51,60.8] 5
# 7 (60.8,70.6] 11
# 8 (70.6,80.5] 15
# 9 (80.5,90.3] 11
# 10 (90.3,100] 6
### Here's GroupedMedian's output on the grouped data.frame...
GroupedMedian(y$Freq, y$Var1, sep = ",", trim = "cut")
# [1] 49.49231
### ... and the output of median on the original vector
median(x)
# [1] 49.5
```
---
By the way, with the sample data that you provided, where I think there was a mistake in one of your ranges (all were separated by dashes except one, which was separated by a comma), since `strsplit` uses a regular expression by default to split on, you can use the function like this:
```
x<-c(110,180,320,460,850,250,130,70,20,10)
colnames<-c("numbers")
rownames<-c("[1500-1600]","(1600-1700]","(1700-1800]","(1800-1900]",
"(1900-2000]"," (2000,2100]","(2100-2200]","(2200-2300]",
"(2300-2400]","(2400-2500]")
y<-matrix(x,nrow=length(x),dimnames=list(rownames,colnames))
GroupedMedian(y[, "numbers"], rownames(y), sep="-|,", trim="cut")
# [1] 1915.294
``` | ```
(Sal <- sapply( strsplit(as.character(dat[[1]]), "-"),
function(x) mean( as.numeric(x) ) ) )
[1] 1550 1650 1750 1850 1950 2050 2150 2250 2350 2450
require(Hmisc)
wtd.mean(Sal, weights = dat[[2]])
[1] 1898.75
wtd.quantile(Sal, weights=dat[[2]], probs=0.5)
```
Generalization to a weighed median might require looking for a package that has such. |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | Since you already know the formula, it should be easy enough to create a function to do the calculation for you.
Here, I've created a basic function to get you started. The function takes four arguments:
* `frequencies`: A vector of frequencies ("number" in your first example)
* `intervals`: A 2-row `matrix` with the same number of columns as the length of frequencies, with the first row being the lower class boundary, and the second row being the upper class boundary. Alternatively, "`intervals`" may be a column in your `data.frame`, and you may specify `sep` (and possibly, `trim`) to have the function automatically create the required matrix for you.
* `sep`: The separator character in your "`intervals`" column in your `data.frame`.
* `trim`: A regular expression of characters that need to be removed before trying to coerce to a numeric matrix. One pattern is built into the function: `trim = "cut"`. This sets the regular expression pattern to remove (, ), [, and ] from the input.
Here's the function (with comments showing how I used your instructions to put it together):
```
GroupedMedian <- function(frequencies, intervals, sep = NULL, trim = NULL) {
# If "sep" is specified, the function will try to create the
# required "intervals" matrix. "trim" removes any unwanted
# characters before attempting to convert the ranges to numeric.
if (!is.null(sep)) {
if (is.null(trim)) pattern <- ""
else if (trim == "cut") pattern <- "\\[|\\]|\\(|\\)"
else pattern <- trim
intervals <- sapply(strsplit(gsub(pattern, "", intervals), sep), as.numeric)
}
Midpoints <- rowMeans(intervals)
cf <- cumsum(frequencies)
Midrow <- findInterval(max(cf)/2, cf) + 1
L <- intervals[1, Midrow] # lower class boundary of median class
h <- diff(intervals[, Midrow]) # size of median class
f <- frequencies[Midrow] # frequency of median class
cf2 <- cf[Midrow - 1] # cumulative frequency class before median class
n_2 <- max(cf)/2 # total observations divided by 2
unname(L + (n_2 - cf2)/f * h)
}
```
---
Here's a sample `data.frame` to work with:
```
mydf <- structure(list(salary = c("1500-1600", "1600-1700", "1700-1800",
"1800-1900", "1900-2000", "2000-2100", "2100-2200", "2200-2300",
"2300-2400", "2400-2500"), number = c(110L, 180L, 320L, 460L,
850L, 250L, 130L, 70L, 20L, 10L)), .Names = c("salary", "number"),
class = "data.frame", row.names = c(NA, -10L))
mydf
# salary number
# 1 1500-1600 110
# 2 1600-1700 180
# 3 1700-1800 320
# 4 1800-1900 460
# 5 1900-2000 850
# 6 2000-2100 250
# 7 2100-2200 130
# 8 2200-2300 70
# 9 2300-2400 20
# 10 2400-2500 10
```
---
Now, we can simply do:
```
GroupedMedian(mydf$number, mydf$salary, sep = "-")
# [1] 1915.294
```
---
Here's an example of the function in action on some made up data:
```
set.seed(1)
x <- sample(100, 100, replace = TRUE)
y <- data.frame(table(cut(x, 10)))
y
# Var1 Freq
# 1 (1.9,11.7] 8
# 2 (11.7,21.5] 8
# 3 (21.5,31.4] 8
# 4 (31.4,41.2] 15
# 5 (41.2,51] 13
# 6 (51,60.8] 5
# 7 (60.8,70.6] 11
# 8 (70.6,80.5] 15
# 9 (80.5,90.3] 11
# 10 (90.3,100] 6
### Here's GroupedMedian's output on the grouped data.frame...
GroupedMedian(y$Freq, y$Var1, sep = ",", trim = "cut")
# [1] 49.49231
### ... and the output of median on the original vector
median(x)
# [1] 49.5
```
---
By the way, with the sample data that you provided, where I think there was a mistake in one of your ranges (all were separated by dashes except one, which was separated by a comma), since `strsplit` uses a regular expression by default to split on, you can use the function like this:
```
x<-c(110,180,320,460,850,250,130,70,20,10)
colnames<-c("numbers")
rownames<-c("[1500-1600]","(1600-1700]","(1700-1800]","(1800-1900]",
"(1900-2000]"," (2000,2100]","(2100-2200]","(2200-2300]",
"(2300-2400]","(2400-2500]")
y<-matrix(x,nrow=length(x),dimnames=list(rownames,colnames))
GroupedMedian(y[, "numbers"], rownames(y), sep="-|,", trim="cut")
# [1] 1915.294
``` | What about this way? Create vectors for each salary bracket, assuming an even spread over each band. Then make one big vector from those vectors, and take the median. Similar to you, but a slightly different result. I'm not a mathematician, so the method could be incorrect.
```
dat <- matrix(c(seq(1500, 2400, 100), seq(1600, 2500, 100), c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)), ncol=3)
median(unlist(apply(dat, 1, function(x) { ((1:x[3])/x[3])*(x[2]-x[1])+x[1] })))
```
Returns 1915.353 |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | ```
(Sal <- sapply( strsplit(as.character(dat[[1]]), "-"),
function(x) mean( as.numeric(x) ) ) )
[1] 1550 1650 1750 1850 1950 2050 2150 2250 2350 2450
require(Hmisc)
wtd.mean(Sal, weights = dat[[2]])
[1] 1898.75
wtd.quantile(Sal, weights=dat[[2]], probs=0.5)
```
Generalization to a weighed median might require looking for a package that has such. | What about this way? Create vectors for each salary bracket, assuming an even spread over each band. Then make one big vector from those vectors, and take the median. Similar to you, but a slightly different result. I'm not a mathematician, so the method could be incorrect.
```
dat <- matrix(c(seq(1500, 2400, 100), seq(1600, 2500, 100), c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)), ncol=3)
median(unlist(apply(dat, 1, function(x) { ((1:x[3])/x[3])*(x[2]-x[1])+x[1] })))
```
Returns 1915.353 |
18,887,382 | My dataset is as following:
```
salary number
1500-1600 110
1600-1700 180
1700-1800 320
1800-1900 460
1900-2000 850
2000-2100 250
2100-2200 130
2200-2300 70
2300-2400 20
2400-2500 10
```
How can I calculate the median of this dataset? Here's what I have tried:
```
x <- c(110, 180, 320, 460, 850, 250, 130, 70, 20, 10)
colnames <- "numbers"
rownames <- c("[1500-1600]", "(1600-1700]", "(1700-1800]", "(1800-1900]",
"(1900-2000]", "(2000,2100]", "(2100-2200]", "(2200-2300]",
"(2300-2400]", "(2400-2500]")
y <- matrix(x, nrow=length(x), dimnames=list(rownames, colnames))
data.frame(y, "cumsum"=cumsum(y))
numbers cumsum
[1500-1600] 110 110
(1600-1700] 180 290
(1700-1800] 320 610
(1800-1900] 460 1070
(1900-2000] 850 1920
(2000,2100] 250 2170
(2100-2200] 130 2300
(2200-2300] 70 2370
(2300-2400] 20 2390
(2400-2500] 10 2400
```
Here, you can see the half-way frequency is `2400/2`=`1200`. It is between `1070` and `1920`. Thus the **median class** is the `(1900-2000]` group. You can use the formula below to get this result:
>
> Median = L + h/f (n/2 - c)
>
>
>
where:
>
> **L** is the lower class boundary of median class
>
> **h** is the size of the median class i.e. difference between upper and lower class boundaries of median class
>
> **f** is the frequency of median class
>
> **c** is previous cumulative frequency of the median class
>
> **n/2** is total no. of observations divided by 2 (i.e. sum **f** / 2)
>
>
>
Alternatively, **median class** is defined by the following method:
>
> Locate n/2 in the column of cumulative frequency.
>
>
> Get the class in which this lies.
>
>
>
And in code:
```
> 1900 + (1200 - 1070) / (1920 - 1070) * (2000 - 1900)
[1] 1915.294
```
Now what I want to do is to make the above expression more elegant - i.e. `1900+(1200-1070)/(1920-1070)*(2000-1900)`. How can I achieve this? | 2013/09/19 | [
"https://Stackoverflow.com/questions/18887382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982032/"
] | I've written it like this to clearly explain how it's being worked out. A more compact version is appended.
```
library(data.table)
#constructing the dataset with the salary range split into low and high
salarydata <- data.table(
salaries_low = 100*c(15:24),
salaries_high = 100*c(16:25),
numbers = c(110,180,320,460,850,250,130,70,20,10)
)
#calculating cumulative number of observations
salarydata <- salarydata[,cumnumbers := cumsum(numbers)]
salarydata
# salaries_low salaries_high numbers cumnumbers
# 1: 1500 1600 110 110
# 2: 1600 1700 180 290
# 3: 1700 1800 320 610
# 4: 1800 1900 460 1070
# 5: 1900 2000 850 1920
# 6: 2000 2100 250 2170
# 7: 2100 2200 130 2300
# 8: 2200 2300 70 2370
# 9: 2300 2400 20 2390
# 10: 2400 2500 10 2400
#identifying median group
mediangroup <- salarydata[
(cumnumbers - numbers) <= (max(cumnumbers)/2) &
cumnumbers >= (max(cumnumbers)/2)]
mediangroup
# salaries_low salaries_high numbers cumnumbers
# 1: 1900 2000 850 1920
#creating the variables needed to calculate median
mediangroup[,l := salaries_low]
mediangroup[,h := salaries_high - salaries_low]
mediangroup[,f := numbers]
mediangroup[,c := cumnumbers- numbers]
n = salarydata[,sum(numbers)]
#calculating median
median <- mediangroup[,l + ((h/f)*((n/2)-c))]
median
# [1] 1915.294
```
The compact version -
EDIT: Changed to a function at @AnandaMahto's suggestion. Also, using more general variable names.
```
library(data.table)
#Creating function
CalculateMedian <- function(
LowerBound,
UpperBound,
Obs
)
{
#calculating cumulative number of observations and n
dataset <- data.table(UpperBound, LowerBound, Obs)
dataset <- dataset[,cumObs := cumsum(Obs)]
n = dataset[,max(cumObs)]
#identifying mediangroup and dynamically calculating l,h,f,c. We already have n.
median <- dataset[
(cumObs - Obs) <= (max(cumObs)/2) &
cumObs >= (max(cumObs)/2),
LowerBound + ((UpperBound - LowerBound)/Obs) * ((n/2) - (cumObs- Obs))
]
return(median)
}
# Using function
CalculateMedian(
LowerBound = 100*c(15:24),
UpperBound = 100*c(16:25),
Obs = c(110,180,320,460,850,250,130,70,20,10)
)
# [1] 1915.294
``` | I think this concept should work you.
```
$salaries = array(
array("1500","1600"),
array("1600","1700"),
array("1700","1800"),
array("1800","1900"),
array("1900","2000"),
array("2000","2100"),
array("2100","2200"),
array("2200","2300"),
array("2300","2400"),
array("2400","2500"),
);
$numbers = array("110","180","320","460","850","250","130","70","20","10");
$cumsum = array();
$n = 0;
$count = 0;
foreach($numbers as $key=>$number){
$cumsum[$key] = $number;
$n += $number;
if($count > 0){
$cumsum[$key] += $cumsum[$key-1];
}
++$count;
}
$classIndex = 0;
foreach($cumsum as $key=>$cum){
if($cum < ($n/2)){
$classIndex = $key+1;
}
}
$classRange = $salaries[$classIndex];
$L = $classRange[0];
$h = (float) $classRange[1] - $classRange[0];
$f = $numbers[$classIndex];
$c = $numbers[$classIndex-1];
$Median = $L + ($h/$f)*(($n/2)-$c);
echo $Median;
``` |
14,782,496 | I understand that Google caps requests to 2,500 per day... but there's no way on EARTH that I've made that many requests today, and I just keep getting 'OVER\_QUERY\_LIMIT'
```
$street_no = get_post_meta($prop->ID, 'street_no', true);
$street = get_post_meta($prop->ID, 'street', true);
$street_suffix = get_post_meta($prop->ID, 'street_suffix', true);
$addr = urlencode( $street_no." ".$street." ".$street_suffix." BC Canada" );
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$addr.'&sensor=true';
$json_result = json_decode(file_get_contents($url));
if ( $json_result->status === "OVER_QUERY_LIMIT" ) :
sleep(2);
$json_result = json_decode(file_get_contents($url));
endif;
```
As you can see, if I get the status of `OVER_QUERY_LIMIT` I tell the script to sleep for 2 seconds and then continue on... which seemed to work at some point this morning, but now I just can't even get a single address geocoded.
I'm at a loss as to what to do at this point... it makes my application utterly useless. | 2013/02/08 | [
"https://Stackoverflow.com/questions/14782496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337806/"
] | Maybe you are sending too many queries per second?
Check out this thread:
[OVER\_QUERY\_LIMIT while using google maps](https://stackoverflow.com/questions/3529746/over-query-limit-while-using-google-maps) | I have the same problem making calls to the geocoding REST interface from a server on Heroku (hosted on Amazon EC2)
This could be fixed if I could use my Maps API key in the request and they tracked the number of calls per api key.
I agree that this is a serious problem...
[Bing](http://msdn.microsoft.com/en-us/library/ff701715.aspx), MapQuest and others have free geocoding APIs - you (and I) should look at those. |
14,782,496 | I understand that Google caps requests to 2,500 per day... but there's no way on EARTH that I've made that many requests today, and I just keep getting 'OVER\_QUERY\_LIMIT'
```
$street_no = get_post_meta($prop->ID, 'street_no', true);
$street = get_post_meta($prop->ID, 'street', true);
$street_suffix = get_post_meta($prop->ID, 'street_suffix', true);
$addr = urlencode( $street_no." ".$street." ".$street_suffix." BC Canada" );
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$addr.'&sensor=true';
$json_result = json_decode(file_get_contents($url));
if ( $json_result->status === "OVER_QUERY_LIMIT" ) :
sleep(2);
$json_result = json_decode(file_get_contents($url));
endif;
```
As you can see, if I get the status of `OVER_QUERY_LIMIT` I tell the script to sleep for 2 seconds and then continue on... which seemed to work at some point this morning, but now I just can't even get a single address geocoded.
I'm at a loss as to what to do at this point... it makes my application utterly useless. | 2013/02/08 | [
"https://Stackoverflow.com/questions/14782496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337806/"
] | Maybe you are sending too many queries per second?
Check out this thread:
[OVER\_QUERY\_LIMIT while using google maps](https://stackoverflow.com/questions/3529746/over-query-limit-while-using-google-maps) | I faced a similar issue to this with my heroku hosted java application. The way I got around it was to set up a micro EC2 instance and install Dante on it to run as a proxy server. Then I just route my gecoding requests through the proxy and can make the full 2,000 requests per day. Obviously it's worth caching results to minimise the api calls too. The EC2 instance is free for the first year and after that still not that expensive and you can always use it for more than just Dante.
I've written details of how I set this up here: [Using Google geocoding from Heroku](http://onlinetakeawayfood.wordpress.com/2013/05/11/using-google-geocoding-api-from-heroku-application/) |
14,782,496 | I understand that Google caps requests to 2,500 per day... but there's no way on EARTH that I've made that many requests today, and I just keep getting 'OVER\_QUERY\_LIMIT'
```
$street_no = get_post_meta($prop->ID, 'street_no', true);
$street = get_post_meta($prop->ID, 'street', true);
$street_suffix = get_post_meta($prop->ID, 'street_suffix', true);
$addr = urlencode( $street_no." ".$street." ".$street_suffix." BC Canada" );
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$addr.'&sensor=true';
$json_result = json_decode(file_get_contents($url));
if ( $json_result->status === "OVER_QUERY_LIMIT" ) :
sleep(2);
$json_result = json_decode(file_get_contents($url));
endif;
```
As you can see, if I get the status of `OVER_QUERY_LIMIT` I tell the script to sleep for 2 seconds and then continue on... which seemed to work at some point this morning, but now I just can't even get a single address geocoded.
I'm at a loss as to what to do at this point... it makes my application utterly useless. | 2013/02/08 | [
"https://Stackoverflow.com/questions/14782496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337806/"
] | Maybe you are sending too many queries per second?
Check out this thread:
[OVER\_QUERY\_LIMIT while using google maps](https://stackoverflow.com/questions/3529746/over-query-limit-while-using-google-maps) | You can use a hosted proxy service like QuotaGuard which will stop your requests coming from a shared IP so you don't get blocked by Google when using Rackspace/Heroku etc. |
14,782,496 | I understand that Google caps requests to 2,500 per day... but there's no way on EARTH that I've made that many requests today, and I just keep getting 'OVER\_QUERY\_LIMIT'
```
$street_no = get_post_meta($prop->ID, 'street_no', true);
$street = get_post_meta($prop->ID, 'street', true);
$street_suffix = get_post_meta($prop->ID, 'street_suffix', true);
$addr = urlencode( $street_no." ".$street." ".$street_suffix." BC Canada" );
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$addr.'&sensor=true';
$json_result = json_decode(file_get_contents($url));
if ( $json_result->status === "OVER_QUERY_LIMIT" ) :
sleep(2);
$json_result = json_decode(file_get_contents($url));
endif;
```
As you can see, if I get the status of `OVER_QUERY_LIMIT` I tell the script to sleep for 2 seconds and then continue on... which seemed to work at some point this morning, but now I just can't even get a single address geocoded.
I'm at a loss as to what to do at this point... it makes my application utterly useless. | 2013/02/08 | [
"https://Stackoverflow.com/questions/14782496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337806/"
] | The quota is shared among all the users of the shared IP, so other sites on the same shared IP must be using the Google Geocoder.
See [this thread in the Google Maps API v2 group](https://groups.google.com/group/google-maps-api/browse_frm/thread/4b8dd63d97b8b799/877bb7024b045f61?lnk=gst&q=OVER_QUERY_LIMIT+rackspace#877bb7024b045f61) for more information.
BTW - rackspace was a guess...
A workaround would be to use client based geocoding, but verify your use complies with the terms of use.
The [webservice now supports a key](https://developers.google.com/maps/documentation/geocoding/#GeocodingRequests), another option is to use a key in your request so you get your own quota. | I have the same problem making calls to the geocoding REST interface from a server on Heroku (hosted on Amazon EC2)
This could be fixed if I could use my Maps API key in the request and they tracked the number of calls per api key.
I agree that this is a serious problem...
[Bing](http://msdn.microsoft.com/en-us/library/ff701715.aspx), MapQuest and others have free geocoding APIs - you (and I) should look at those. |
14,782,496 | I understand that Google caps requests to 2,500 per day... but there's no way on EARTH that I've made that many requests today, and I just keep getting 'OVER\_QUERY\_LIMIT'
```
$street_no = get_post_meta($prop->ID, 'street_no', true);
$street = get_post_meta($prop->ID, 'street', true);
$street_suffix = get_post_meta($prop->ID, 'street_suffix', true);
$addr = urlencode( $street_no." ".$street." ".$street_suffix." BC Canada" );
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$addr.'&sensor=true';
$json_result = json_decode(file_get_contents($url));
if ( $json_result->status === "OVER_QUERY_LIMIT" ) :
sleep(2);
$json_result = json_decode(file_get_contents($url));
endif;
```
As you can see, if I get the status of `OVER_QUERY_LIMIT` I tell the script to sleep for 2 seconds and then continue on... which seemed to work at some point this morning, but now I just can't even get a single address geocoded.
I'm at a loss as to what to do at this point... it makes my application utterly useless. | 2013/02/08 | [
"https://Stackoverflow.com/questions/14782496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337806/"
] | The quota is shared among all the users of the shared IP, so other sites on the same shared IP must be using the Google Geocoder.
See [this thread in the Google Maps API v2 group](https://groups.google.com/group/google-maps-api/browse_frm/thread/4b8dd63d97b8b799/877bb7024b045f61?lnk=gst&q=OVER_QUERY_LIMIT+rackspace#877bb7024b045f61) for more information.
BTW - rackspace was a guess...
A workaround would be to use client based geocoding, but verify your use complies with the terms of use.
The [webservice now supports a key](https://developers.google.com/maps/documentation/geocoding/#GeocodingRequests), another option is to use a key in your request so you get your own quota. | I faced a similar issue to this with my heroku hosted java application. The way I got around it was to set up a micro EC2 instance and install Dante on it to run as a proxy server. Then I just route my gecoding requests through the proxy and can make the full 2,000 requests per day. Obviously it's worth caching results to minimise the api calls too. The EC2 instance is free for the first year and after that still not that expensive and you can always use it for more than just Dante.
I've written details of how I set this up here: [Using Google geocoding from Heroku](http://onlinetakeawayfood.wordpress.com/2013/05/11/using-google-geocoding-api-from-heroku-application/) |
14,782,496 | I understand that Google caps requests to 2,500 per day... but there's no way on EARTH that I've made that many requests today, and I just keep getting 'OVER\_QUERY\_LIMIT'
```
$street_no = get_post_meta($prop->ID, 'street_no', true);
$street = get_post_meta($prop->ID, 'street', true);
$street_suffix = get_post_meta($prop->ID, 'street_suffix', true);
$addr = urlencode( $street_no." ".$street." ".$street_suffix." BC Canada" );
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$addr.'&sensor=true';
$json_result = json_decode(file_get_contents($url));
if ( $json_result->status === "OVER_QUERY_LIMIT" ) :
sleep(2);
$json_result = json_decode(file_get_contents($url));
endif;
```
As you can see, if I get the status of `OVER_QUERY_LIMIT` I tell the script to sleep for 2 seconds and then continue on... which seemed to work at some point this morning, but now I just can't even get a single address geocoded.
I'm at a loss as to what to do at this point... it makes my application utterly useless. | 2013/02/08 | [
"https://Stackoverflow.com/questions/14782496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337806/"
] | The quota is shared among all the users of the shared IP, so other sites on the same shared IP must be using the Google Geocoder.
See [this thread in the Google Maps API v2 group](https://groups.google.com/group/google-maps-api/browse_frm/thread/4b8dd63d97b8b799/877bb7024b045f61?lnk=gst&q=OVER_QUERY_LIMIT+rackspace#877bb7024b045f61) for more information.
BTW - rackspace was a guess...
A workaround would be to use client based geocoding, but verify your use complies with the terms of use.
The [webservice now supports a key](https://developers.google.com/maps/documentation/geocoding/#GeocodingRequests), another option is to use a key in your request so you get your own quota. | You can use a hosted proxy service like QuotaGuard which will stop your requests coming from a shared IP so you don't get blocked by Google when using Rackspace/Heroku etc. |
14,782,496 | I understand that Google caps requests to 2,500 per day... but there's no way on EARTH that I've made that many requests today, and I just keep getting 'OVER\_QUERY\_LIMIT'
```
$street_no = get_post_meta($prop->ID, 'street_no', true);
$street = get_post_meta($prop->ID, 'street', true);
$street_suffix = get_post_meta($prop->ID, 'street_suffix', true);
$addr = urlencode( $street_no." ".$street." ".$street_suffix." BC Canada" );
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$addr.'&sensor=true';
$json_result = json_decode(file_get_contents($url));
if ( $json_result->status === "OVER_QUERY_LIMIT" ) :
sleep(2);
$json_result = json_decode(file_get_contents($url));
endif;
```
As you can see, if I get the status of `OVER_QUERY_LIMIT` I tell the script to sleep for 2 seconds and then continue on... which seemed to work at some point this morning, but now I just can't even get a single address geocoded.
I'm at a loss as to what to do at this point... it makes my application utterly useless. | 2013/02/08 | [
"https://Stackoverflow.com/questions/14782496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337806/"
] | I faced a similar issue to this with my heroku hosted java application. The way I got around it was to set up a micro EC2 instance and install Dante on it to run as a proxy server. Then I just route my gecoding requests through the proxy and can make the full 2,000 requests per day. Obviously it's worth caching results to minimise the api calls too. The EC2 instance is free for the first year and after that still not that expensive and you can always use it for more than just Dante.
I've written details of how I set this up here: [Using Google geocoding from Heroku](http://onlinetakeawayfood.wordpress.com/2013/05/11/using-google-geocoding-api-from-heroku-application/) | I have the same problem making calls to the geocoding REST interface from a server on Heroku (hosted on Amazon EC2)
This could be fixed if I could use my Maps API key in the request and they tracked the number of calls per api key.
I agree that this is a serious problem...
[Bing](http://msdn.microsoft.com/en-us/library/ff701715.aspx), MapQuest and others have free geocoding APIs - you (and I) should look at those. |
14,782,496 | I understand that Google caps requests to 2,500 per day... but there's no way on EARTH that I've made that many requests today, and I just keep getting 'OVER\_QUERY\_LIMIT'
```
$street_no = get_post_meta($prop->ID, 'street_no', true);
$street = get_post_meta($prop->ID, 'street', true);
$street_suffix = get_post_meta($prop->ID, 'street_suffix', true);
$addr = urlencode( $street_no." ".$street." ".$street_suffix." BC Canada" );
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$addr.'&sensor=true';
$json_result = json_decode(file_get_contents($url));
if ( $json_result->status === "OVER_QUERY_LIMIT" ) :
sleep(2);
$json_result = json_decode(file_get_contents($url));
endif;
```
As you can see, if I get the status of `OVER_QUERY_LIMIT` I tell the script to sleep for 2 seconds and then continue on... which seemed to work at some point this morning, but now I just can't even get a single address geocoded.
I'm at a loss as to what to do at this point... it makes my application utterly useless. | 2013/02/08 | [
"https://Stackoverflow.com/questions/14782496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337806/"
] | I faced a similar issue to this with my heroku hosted java application. The way I got around it was to set up a micro EC2 instance and install Dante on it to run as a proxy server. Then I just route my gecoding requests through the proxy and can make the full 2,000 requests per day. Obviously it's worth caching results to minimise the api calls too. The EC2 instance is free for the first year and after that still not that expensive and you can always use it for more than just Dante.
I've written details of how I set this up here: [Using Google geocoding from Heroku](http://onlinetakeawayfood.wordpress.com/2013/05/11/using-google-geocoding-api-from-heroku-application/) | You can use a hosted proxy service like QuotaGuard which will stop your requests coming from a shared IP so you don't get blocked by Google when using Rackspace/Heroku etc. |
65,366 | I'm a beginning guitar player, with a secondhand Yamaha FG-180J I got as a gift. The strings were already wound when I got it. Upon playing it, I had a lot of trouble playing barre chords. The strings feel tight and it's relatively high-action. It's a really old guitar by the way, with some of the old pegs having been replaced.
How can I change/adjust the guitar to make it easier to play barre chords? I can play barre chords using other guitars with relative ease but I'm stumped using mine. It's frustrating. I'm trying finger strengthening exercises but to still no avail. The middle and sometimes last strings are the the most difficult, I find. I can't put enough pressure on the fret and I end up muting the strings. | 2018/01/07 | [
"https://music.stackexchange.com/questions/65366",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/46871/"
] | Put a new set of light gauge strings on it and adjust the truss rod accordingly to give just a bit of neck relief. It needs adjusted from time to time especially if you change string gauges. It may have had heavier strings put on at some point—which are great for tone but harder to play if you aren't used to them—or the neck just got out of whack over time.
The amount of neck relief is a matter of preference, but basically you want something like this:
* Never bowed back (away from the body)
* Usually not perfectly flat. If it's flat or backbowed you'll get buzzing.
* Not *too much* relief (upbow) because the action will get too high
* You want it somewhere in the middle where less relief will mean lower action and better playability but more relief will mean better tone and less chance of buzzing.
Take it into a guitar shop and have them do it if you've never done that before. | You need to reduce the action to get the strings closer to the fretboard.
This can be done by following:-
1. Adjusting action at bridge
2. Adjusting action at nut.
3. Adjusting action with truss rod.
[Here](http://www.guitarrepairbench.com/acoustic-guitar-repairs/acoustic_guitar_action_adjustment.html) is a detailed explanation of how to do it. If you have never tried it before try not to put to much pressure using truss rod, it might break your guitar :). But the sad part is you will never learn without breaking one or two guitars. So if you love your guitar too much try going to a music shop and getting it fixed else you can try it on your own. |
65,366 | I'm a beginning guitar player, with a secondhand Yamaha FG-180J I got as a gift. The strings were already wound when I got it. Upon playing it, I had a lot of trouble playing barre chords. The strings feel tight and it's relatively high-action. It's a really old guitar by the way, with some of the old pegs having been replaced.
How can I change/adjust the guitar to make it easier to play barre chords? I can play barre chords using other guitars with relative ease but I'm stumped using mine. It's frustrating. I'm trying finger strengthening exercises but to still no avail. The middle and sometimes last strings are the the most difficult, I find. I can't put enough pressure on the fret and I end up muting the strings. | 2018/01/07 | [
"https://music.stackexchange.com/questions/65366",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/46871/"
] | Those strings look like .011s or .012s. Not only that but 10 years too late being changed ! Put some .009s on first, and feel the difference. If that doesn't solve all the problem, check the action, and the relief in the neck - they're related, and in old guitars often need adjustment.
Don't bother with finger strengthening - playing is the best way to get them right for guitar playing. | You need to reduce the action to get the strings closer to the fretboard.
This can be done by following:-
1. Adjusting action at bridge
2. Adjusting action at nut.
3. Adjusting action with truss rod.
[Here](http://www.guitarrepairbench.com/acoustic-guitar-repairs/acoustic_guitar_action_adjustment.html) is a detailed explanation of how to do it. If you have never tried it before try not to put to much pressure using truss rod, it might break your guitar :). But the sad part is you will never learn without breaking one or two guitars. So if you love your guitar too much try going to a music shop and getting it fixed else you can try it on your own. |
37,604,129 | I have a nested data like this which is passed to blade-
[](https://i.stack.imgur.com/EXx0l.png)
I want to display it's data in blade view.
So what I have done is-
```
<ul class="dropdown-menu h-ctr h-ctr2 col-md-12 col-sm-12">
@foreach ($categories as $category)
<li class="no-border">
<label class="pull-left">
<input type="checkbox" value="{{ $category->id }}" checked>
<strong> {{ $category->name }} (21)</strong>
</label>
<ul>
@foreach($category->sub_category as $sub_cat)
<li>
<label class="pull-left">
<input type="checkbox" checked value="1"> {{ $sub_cat->name }} (7)
</label>
</li>
@endforeach
</ul>
</li>
@endforeach
</ul>
```
And I am getting error for nested loop's part-
```
foreach($category->sub_category as $sub_cat)
<li>
<label class="pull-left">
<input type="checkbox" checked value="1"> {{ $sub_cat->name }} (7)
</label>
</li>
@endforeach
```
The error is like this-
[](https://i.stack.imgur.com/D5oUH.png)
Can anyone please help?
Thanks in advance for helping. | 2016/06/03 | [
"https://Stackoverflow.com/questions/37604129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2193439/"
] | Try this mate
```
@foreach($category['sub_category'] as $sub_cat)
<li>
<label class="pull-left">
<input type="checkbox" checked value="1"> {{ $sub_cat->name }} (7)
</label>
</li>
@endforeach
```
in case this didnt work can you share you controller code too?
**EDIT :** in your controller try to convert the array to a collection (there are simpler why like using eloquent
```
$collection = collect($myarray);
``` | Try this..
```
@if($category->sub_category)
@foreach($category->sub_category as $sub_cat)
<li>
<label class="pull-left">
<input type="checkbox" checked value="1"> {{ $sub_cat->name }} (7)
</label>
</li>
@endforeach
@endif
``` |
120,561 | If I rotate my button by -180 on the Y axis I can't even click on it. If for example I rotate it 180 on the Z axis everything is fine. Why does this happen and how can I fix it ? | 2016/04/26 | [
"https://gamedev.stackexchange.com/questions/120561",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/81690/"
] | This also works, Canvas > Graphics Raycaster > Uncheck Ignore Reverse Graphics | Easy fix is to set your Source Image to None, reset y rotation to 0, Color full transparent, Raycast Target Check. Then you add your Image as a child, set rotation y 180 and Uncheck Raycast Target (not needed anymore because the image is flipped, the raycast will pass trought it anyway). Set your child Image as Target Graphic in the Button component and there you go. |
31,510,756 | I have html body with this button:
```
<div tabindex="0" class="image-copy-to-clipboard image-copy-to-clipboard-icon" role="button" data-placement="bottom" data-toggle="popover" data-trigger="focus" data-container="body">
<div class="head hide">Press Ctrl+C to copy user info</div>
<div class="content hide">
<input id="userInfo" type="text" placeholder="" value="#{{user.Id}} : {{user.Name}}" autofocus="autofocus" />
</div>
</div>
```
And this script to make it works:
```
$('[data-toggle="popover"]').popover({
html: true,
title: function() {
return $(this).parent().find('.head').html();
},
content: function() {
return $(this).parent().find('.content').html();
}
});
$('#userInfo').focus(function (event) {
var self = $(this);
setTimeout(function() {
self.select();
}, 100);
});
$(document).on('click', function(event) {
if (event.target.nodeName == 'HTML') {
$('.popover.fade').hide().remove();
}
});
```
When popup window shown I need to focus on input field and all text must be selected. I tried a lot of issues but nothing works normally. Please help me solve this problem.
[JSFiddle](https://jsfiddle.net/HUSTLIN/b991st3m/1/) | 2015/07/20 | [
"https://Stackoverflow.com/questions/31510756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5129766/"
] | Just use them together without FETCH statement inside the CTE
```
;WITH cte AS
(
SELECT Id, Name
FROM #tbl
ORDER BY Id
OFFSET 0 ROWS
)
SELECT TOP 3 WITH TIES *
FROM cte
ORDER BY Id
```
See [`SQLFiddle`](http://sqlfiddle.com/#!6/9eecb7/1239)
Example with offset 3 [SQLFiddle](http://sqlfiddle.com/#!6/9eecb7/1241)
```
;WITH cte AS
(
SELECT Id, Name
FROM #tbl
ORDER BY Id
OFFSET 3 ROWS
)
SELECT TOP 3 WITH TIES *
FROM cte
ORDER BY Id
``` | ```
SELECT *
FROM #tbl
ORDER BY Id
OFFSET 0 ROWS
FETCH NEXT 3 ROWS WITH TIES
``` |
64,564 | I have a cheap velo cycle computer made by cateye. It is a simple read out of velocity and clock and has no fancy functions at all.
It worked fine for months, and then started "blipping" to double my speed.
That is, if I was doing about 20 km/h it would blip to 30 or 40 or 60 and then drop back to my real speed. I disregarded this and keep riding.
A month later it starts cutting out, reading 0 km/h or numbers like 6 or 9, where I am riding at about 20 km/h on the flat road.
I check closely - battery is okay but I change it anyway. No water anywhere, no rust, no damage, nothing wrong.
Now it stops completely - only shows a speed for a few seconds then back to 0.
The clock works fine, shows the correct time all the time. Head unit has not been dropped. Yes it has been ridden in the rain but that is what these are designed for and there is not water mist inside the screen.
How do I troubleshoot my bike computer? I know is not a Garmin or wahoo or any flash thing, but is only a year old. Probably out of warranty and I want to learn how tofix it. Or to stop from breaking the next one.
Computer is like this one <https://www.chainreactioncycles.com/nz/en/cateye-velo-5-function-computer/rp-prod26194> with wires, not cellphone or GPS. | 2019/10/06 | [
"https://bicycles.stackexchange.com/questions/64564",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/26620/"
] | First of all, try changing the distance and vertical alignment between the sensor and the wheel-mounted magnet.
If that doesn’t help, the sensor (or its cable) mounted to the fork is probably broken. Check the cable for any visible damage. I think the sensors are usually cheap&simple reed switches to detect the magnet. If you have a multimeter you could try measuring the resistance between the two contacts of the cycle computer’s mount. It should toggle between zero and infinity when you pass the magnet in front of the sensor. If it doesn’t do that it confirms a sensor or cable defect.
Your best choice is a replacement part, but if you are handy you could try replacing the cable and/or the reed contact. | I've been through this exact situation with a Cateye Velo 7 and it did very similar things. I'd be riding along at 30 km/h and the speedo would flash to 45 or 60 and rarely 90, and I never saw it but the MAX SPEED was at 120 km/h.
The curious thing about those numbers is they're some multiple of the speed I was travelling.
>
> Firstly, start by checking the magnet. Its probably fine, but this is far and away the easiest thing to check. Most sensors have a line that is the middle of the sensor, so that's where the wheel magnet should be centered.
>
>
>
Otherwise, your description tells me the wiring is mostly working but the head unit is getting multiple signals. The possible causes here are
1. a break in the conductor inside the wire
2. an intermittent connection to the head unit inside the socket on your bars
3. poor quality soldering at either end of the wire - a cold joint
4. a faulty sensor
5. extra magnets on your wheels.
The extra pulses mean that something is blipping more than once per wheel rotation. I'm not sure exactly how many blips the headunit requires to calculate a speed, but from manual testing its at least 3, maybe 4.
---
If you think the head unit might be acting weird on its own, test it out of the harness using anything metallic to short the two pads on the back. (note the pictured connectors are dirty and need a clean.)
[](https://i.stack.imgur.com/bKhEb.png)
Rapid shorting of these pinheads should make the computer see wheel rotations, and give an approximate speed.
---
You can troubleshoot the harness too - connect a continuity sensor (either a multimeter with a beeper, or an ohmmetermm or a small lightbulb and battery) to the pads on the receiver socket, the plastic holder that stays clamped to your bars.
The reading should be infinite ohms, which means no connection.
Move a magnet past the sensor, and this will close the internal reed switch, which will make your meter beep, or the ohmmeter read a number, probably about 1 ohm. This should go open circuit again when the magnet is removed.
If this doesn't work, examine the wire for any bumps or sharp folds or abrasions. Any should be repaired and then continue troubleshooting.
---
Down at the sensor, if you can pop the unit open and see the reed switch then do so. There may be fasteners or clips or perhaps simple friction holds it shut. In mine, there was a small black plastic version of a "guttering downpipe standoff" which clipped over two plastic studs and held a tiny circuit board in place.
I did not get a photo sadly, but the only component on the board was a through-hole reed switch and two holes for the wire to attach. My reed switch was faulty, so I replaced it with a $2.50 item from the local electronics supplier and it worked fine. A dab of solder and some glue were the only other parts used.
---
Note when reassembling, use glue to provide sealing from moisture, and to reinforce where the wires come out of plastic - generally these are prone to breaking here.
Use creative wrapping around a brake cable or similar to get your wire up to the handlebars while supported.
---
I do not think its your battery, because the screen will start going dim when the battery needs replacing.
Most of the wired cateyes use the same mount and sensor, which is available as a spare part. Downside of this is the spare part is $18NZ from Wiggle, whereas the whole unit is only $22. For the difference I'd rather have a spare headunit for $4. |
64,564 | I have a cheap velo cycle computer made by cateye. It is a simple read out of velocity and clock and has no fancy functions at all.
It worked fine for months, and then started "blipping" to double my speed.
That is, if I was doing about 20 km/h it would blip to 30 or 40 or 60 and then drop back to my real speed. I disregarded this and keep riding.
A month later it starts cutting out, reading 0 km/h or numbers like 6 or 9, where I am riding at about 20 km/h on the flat road.
I check closely - battery is okay but I change it anyway. No water anywhere, no rust, no damage, nothing wrong.
Now it stops completely - only shows a speed for a few seconds then back to 0.
The clock works fine, shows the correct time all the time. Head unit has not been dropped. Yes it has been ridden in the rain but that is what these are designed for and there is not water mist inside the screen.
How do I troubleshoot my bike computer? I know is not a Garmin or wahoo or any flash thing, but is only a year old. Probably out of warranty and I want to learn how tofix it. Or to stop from breaking the next one.
Computer is like this one <https://www.chainreactioncycles.com/nz/en/cateye-velo-5-function-computer/rp-prod26194> with wires, not cellphone or GPS. | 2019/10/06 | [
"https://bicycles.stackexchange.com/questions/64564",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/26620/"
] | First of all, try changing the distance and vertical alignment between the sensor and the wheel-mounted magnet.
If that doesn’t help, the sensor (or its cable) mounted to the fork is probably broken. Check the cable for any visible damage. I think the sensors are usually cheap&simple reed switches to detect the magnet. If you have a multimeter you could try measuring the resistance between the two contacts of the cycle computer’s mount. It should toggle between zero and infinity when you pass the magnet in front of the sensor. If it doesn’t do that it confirms a sensor or cable defect.
Your best choice is a replacement part, but if you are handy you could try replacing the cable and/or the reed contact. | My experience with cateye computers (admittedly only with a small sample size of 2) is that the mounts are not very sturdy, and after a few months develop enough play that the unit can 'rattle' within the mount when going over less than perfect surfaces.
In the case of this particular model, that would cause the contacts to make/break and potentially create 'fake' sensor pulses. In my case I resolved it by padding out the bracket to create a tighter fit, but it wasn't a great solution and I replaced it with a gps computer (which have their own issues) shortly after. |
64,564 | I have a cheap velo cycle computer made by cateye. It is a simple read out of velocity and clock and has no fancy functions at all.
It worked fine for months, and then started "blipping" to double my speed.
That is, if I was doing about 20 km/h it would blip to 30 or 40 or 60 and then drop back to my real speed. I disregarded this and keep riding.
A month later it starts cutting out, reading 0 km/h or numbers like 6 or 9, where I am riding at about 20 km/h on the flat road.
I check closely - battery is okay but I change it anyway. No water anywhere, no rust, no damage, nothing wrong.
Now it stops completely - only shows a speed for a few seconds then back to 0.
The clock works fine, shows the correct time all the time. Head unit has not been dropped. Yes it has been ridden in the rain but that is what these are designed for and there is not water mist inside the screen.
How do I troubleshoot my bike computer? I know is not a Garmin or wahoo or any flash thing, but is only a year old. Probably out of warranty and I want to learn how tofix it. Or to stop from breaking the next one.
Computer is like this one <https://www.chainreactioncycles.com/nz/en/cateye-velo-5-function-computer/rp-prod26194> with wires, not cellphone or GPS. | 2019/10/06 | [
"https://bicycles.stackexchange.com/questions/64564",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/26620/"
] | I've been through this exact situation with a Cateye Velo 7 and it did very similar things. I'd be riding along at 30 km/h and the speedo would flash to 45 or 60 and rarely 90, and I never saw it but the MAX SPEED was at 120 km/h.
The curious thing about those numbers is they're some multiple of the speed I was travelling.
>
> Firstly, start by checking the magnet. Its probably fine, but this is far and away the easiest thing to check. Most sensors have a line that is the middle of the sensor, so that's where the wheel magnet should be centered.
>
>
>
Otherwise, your description tells me the wiring is mostly working but the head unit is getting multiple signals. The possible causes here are
1. a break in the conductor inside the wire
2. an intermittent connection to the head unit inside the socket on your bars
3. poor quality soldering at either end of the wire - a cold joint
4. a faulty sensor
5. extra magnets on your wheels.
The extra pulses mean that something is blipping more than once per wheel rotation. I'm not sure exactly how many blips the headunit requires to calculate a speed, but from manual testing its at least 3, maybe 4.
---
If you think the head unit might be acting weird on its own, test it out of the harness using anything metallic to short the two pads on the back. (note the pictured connectors are dirty and need a clean.)
[](https://i.stack.imgur.com/bKhEb.png)
Rapid shorting of these pinheads should make the computer see wheel rotations, and give an approximate speed.
---
You can troubleshoot the harness too - connect a continuity sensor (either a multimeter with a beeper, or an ohmmetermm or a small lightbulb and battery) to the pads on the receiver socket, the plastic holder that stays clamped to your bars.
The reading should be infinite ohms, which means no connection.
Move a magnet past the sensor, and this will close the internal reed switch, which will make your meter beep, or the ohmmeter read a number, probably about 1 ohm. This should go open circuit again when the magnet is removed.
If this doesn't work, examine the wire for any bumps or sharp folds or abrasions. Any should be repaired and then continue troubleshooting.
---
Down at the sensor, if you can pop the unit open and see the reed switch then do so. There may be fasteners or clips or perhaps simple friction holds it shut. In mine, there was a small black plastic version of a "guttering downpipe standoff" which clipped over two plastic studs and held a tiny circuit board in place.
I did not get a photo sadly, but the only component on the board was a through-hole reed switch and two holes for the wire to attach. My reed switch was faulty, so I replaced it with a $2.50 item from the local electronics supplier and it worked fine. A dab of solder and some glue were the only other parts used.
---
Note when reassembling, use glue to provide sealing from moisture, and to reinforce where the wires come out of plastic - generally these are prone to breaking here.
Use creative wrapping around a brake cable or similar to get your wire up to the handlebars while supported.
---
I do not think its your battery, because the screen will start going dim when the battery needs replacing.
Most of the wired cateyes use the same mount and sensor, which is available as a spare part. Downside of this is the spare part is $18NZ from Wiggle, whereas the whole unit is only $22. For the difference I'd rather have a spare headunit for $4. | My experience with cateye computers (admittedly only with a small sample size of 2) is that the mounts are not very sturdy, and after a few months develop enough play that the unit can 'rattle' within the mount when going over less than perfect surfaces.
In the case of this particular model, that would cause the contacts to make/break and potentially create 'fake' sensor pulses. In my case I resolved it by padding out the bracket to create a tighter fit, but it wasn't a great solution and I replaced it with a gps computer (which have their own issues) shortly after. |
20,288,784 | I'm trying to use the bootstrap collapse navbar, I can expanded but I can't collapse the navigation.
And I can't find anything wrong with it:
```
<nav class="navbar navbar-inverse nav-justified">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="nav-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="http://revad.dev/news/">News</a>
</li>
</ul>
<ul id="menu-menu" class=" nav navbar-nav">
<li id="menu-item-5" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-5"><a href="http://revad.dev/">Accueil</a>
</li>
<li id="menu-item-290" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-290"><a href="http://revad.dev/#le-projet">Le Projet</a>
</li>
<li id="menu-item-291" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-291"><a href="http://revad.dev/#partenaires">Partenaires</a>
</li>
<li id="menu-item-292" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-292"><a href="http://revad.dev/#lavenir-du-projet">L’avenir</a>
</li>
<li id="menu-item-293" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home menu-item-293"><a href="http://revad.dev/#contact">Contact</a>
</li>
</ul>
</div>
</nav>
``` | 2013/11/29 | [
"https://Stackoverflow.com/questions/20288784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2050847/"
] | Was just using Bootstrap v3 CSS but v2 JS.
Updated javascript files to v3 and it worked all fine.
Thanks for your help | It appears that you have a few classes called `current_*`. If you have multiple active classes the collapse function would not work since it needs one or a sub set of items to activate and deactivate.
Making sure that `items` are only active when they should be will ensure that bootstrap's jquery can select and hide the appropriate `items`. |
22,066,017 | I want to calculate how many slides in a slideshow.
in JS:
```
var slides = $('document.getElementById("slide").getAttribute("data-slide").slide-new');
```
And in My HTML
```
<div class="slide" id="slide1" data-slide="0" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
<div class="slide" id="slide1" data-slide="1" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
```
I want to calculate How Many "Slide-new" there is "slide" variable.
In 'slides' variable I want 3 for first slideshow and 4 for second slideshow. But I can't get it...
Thanks | 2014/02/27 | [
"https://Stackoverflow.com/questions/22066017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3359925/"
] | `rawQuery()` doesn't actually run the SQL. Use `execSQL()` instead:
```
db.execSQL("update status SET column1 = '"+prms+"' ");
```
(See [What is the correct way to do inserts/updates/deletes in Android SQLiteDatabase using a query string?](https://stackoverflow.com/questions/20110274/what-is-the-correct-way-to-do-inserts-updates-deletes-in-android-sqlitedatabase/20118910#20118910) to learn more how `rawQuery()` and `execSQL()` work under the hood.) | db.execSQL("update status SET column1 = '"+prms+"' ", null); |
22,066,017 | I want to calculate how many slides in a slideshow.
in JS:
```
var slides = $('document.getElementById("slide").getAttribute("data-slide").slide-new');
```
And in My HTML
```
<div class="slide" id="slide1" data-slide="0" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
<div class="slide" id="slide1" data-slide="1" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
```
I want to calculate How Many "Slide-new" there is "slide" variable.
In 'slides' variable I want 3 for first slideshow and 4 for second slideshow. But I can't get it...
Thanks | 2014/02/27 | [
"https://Stackoverflow.com/questions/22066017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3359925/"
] | `rawQuery()` doesn't actually run the SQL. Use `execSQL()` instead:
```
db.execSQL("update status SET column1 = '"+prms+"' ");
```
(See [What is the correct way to do inserts/updates/deletes in Android SQLiteDatabase using a query string?](https://stackoverflow.com/questions/20110274/what-is-the-correct-way-to-do-inserts-updates-deletes-in-android-sqlitedatabase/20118910#20118910) to learn more how `rawQuery()` and `execSQL()` work under the hood.) | Update your following line code,
```
Cursor cursor = db.rawQuery("update status SET column1 = '"+prms+"' ", null);
```
to this line
```
db.execSQL( "update status SET column1 = '"+prms+"' " );
```
So your method will look like this,
```
public void sample(String prms)
{
Log.d("sucess",prms);
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("update status SET column1 = '"+prms+"'WHERE id = '5' " ); // remove second param from here.
}
```
Caution : This query is going to update all the row of Column1; You should include `where` clause |
22,066,017 | I want to calculate how many slides in a slideshow.
in JS:
```
var slides = $('document.getElementById("slide").getAttribute("data-slide").slide-new');
```
And in My HTML
```
<div class="slide" id="slide1" data-slide="0" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
<div class="slide" id="slide1" data-slide="1" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
```
I want to calculate How Many "Slide-new" there is "slide" variable.
In 'slides' variable I want 3 for first slideshow and 4 for second slideshow. But I can't get it...
Thanks | 2014/02/27 | [
"https://Stackoverflow.com/questions/22066017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3359925/"
] | `rawQuery()` doesn't actually run the SQL. Use `execSQL()` instead:
```
db.execSQL("update status SET column1 = '"+prms+"' ");
```
(See [What is the correct way to do inserts/updates/deletes in Android SQLiteDatabase using a query string?](https://stackoverflow.com/questions/20110274/what-is-the-correct-way-to-do-inserts-updates-deletes-in-android-sqlitedatabase/20118910#20118910) to learn more how `rawQuery()` and `execSQL()` work under the hood.) | Follow this code,it return no. of rows effected while updating.
```
SQLiteHelper helper;
public int updateName(String oldName,String newName)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(this.NAME, newName);
String [] whereArgs={oldName};
int count = db.update(helper.TABLE_NAME, values, helper.NAME+" =? ",whereArgs);
return count;
}
```
where helper is an object of class that extends `SQLiteOpenHelper` like the code below..
```
static class SQLiteHelper extends SQLiteOpenHelper
{
....////
private static final String DATABASE_NAME = "databaseName";
private static final String TABLE_NAME = "TABLENAME";
private static final int DATABASE_VERSION = 1;
private static final String UID = "_id";
private static final String NAME = "Name";
private static final String PASSWORD = "Password";
private static final String CREATE_TABLE ="CREATE TABLE "+ TABLE_NAME +"(" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT," + NAME + " VARCHAR(255)," + PASSWORD + " VARCHAR(255));";
public SQLiteHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Message.Message(context, "Constructor Called");
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try {
Message.Message(context, "OnCreate Called");
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Message.Message(context, "" + e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
try {
Message.Message(context, "onUpgrade Called");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
// TODO Auto-generated catch block
Message.Message(context, ""+e);
}
}
}
``` |
22,066,017 | I want to calculate how many slides in a slideshow.
in JS:
```
var slides = $('document.getElementById("slide").getAttribute("data-slide").slide-new');
```
And in My HTML
```
<div class="slide" id="slide1" data-slide="0" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
<div class="slide" id="slide1" data-slide="1" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
```
I want to calculate How Many "Slide-new" there is "slide" variable.
In 'slides' variable I want 3 for first slideshow and 4 for second slideshow. But I can't get it...
Thanks | 2014/02/27 | [
"https://Stackoverflow.com/questions/22066017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3359925/"
] | You can Directly `Execute` this Query like:
```
db.execSQL("update status SET column1 = '"+prms+"' ", null);
```
You should replace your code
```
Cursor cursor = db.execSQL("update status SET column1 = '"+prms+"' ", null);
```
With
```
db.execSQL("update status SET column1 = '"+prms+"' ", null);
```
**void execSQL(String sql)**
Execute a single **SQL** statement that is NOT a SELECT or any other **SQL** statement that returns data.
It has no means to return any data (such as the number of affected rows). Instead, you're encouraged to use **insert(String, String, ContentValues**, **update(String, ContentValues, String, String[])**, et al, when possible. | db.execSQL("update status SET column1 = '"+prms+"' ", null); |
22,066,017 | I want to calculate how many slides in a slideshow.
in JS:
```
var slides = $('document.getElementById("slide").getAttribute("data-slide").slide-new');
```
And in My HTML
```
<div class="slide" id="slide1" data-slide="0" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
<div class="slide" id="slide1" data-slide="1" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
```
I want to calculate How Many "Slide-new" there is "slide" variable.
In 'slides' variable I want 3 for first slideshow and 4 for second slideshow. But I can't get it...
Thanks | 2014/02/27 | [
"https://Stackoverflow.com/questions/22066017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3359925/"
] | You can Directly `Execute` this Query like:
```
db.execSQL("update status SET column1 = '"+prms+"' ", null);
```
You should replace your code
```
Cursor cursor = db.execSQL("update status SET column1 = '"+prms+"' ", null);
```
With
```
db.execSQL("update status SET column1 = '"+prms+"' ", null);
```
**void execSQL(String sql)**
Execute a single **SQL** statement that is NOT a SELECT or any other **SQL** statement that returns data.
It has no means to return any data (such as the number of affected rows). Instead, you're encouraged to use **insert(String, String, ContentValues**, **update(String, ContentValues, String, String[])**, et al, when possible. | Update your following line code,
```
Cursor cursor = db.rawQuery("update status SET column1 = '"+prms+"' ", null);
```
to this line
```
db.execSQL( "update status SET column1 = '"+prms+"' " );
```
So your method will look like this,
```
public void sample(String prms)
{
Log.d("sucess",prms);
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("update status SET column1 = '"+prms+"'WHERE id = '5' " ); // remove second param from here.
}
```
Caution : This query is going to update all the row of Column1; You should include `where` clause |
22,066,017 | I want to calculate how many slides in a slideshow.
in JS:
```
var slides = $('document.getElementById("slide").getAttribute("data-slide").slide-new');
```
And in My HTML
```
<div class="slide" id="slide1" data-slide="0" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
<div class="slide" id="slide1" data-slide="1" data-stellar-background-ratio="0.5">
<div id="slideshow" >
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
<div class="slide-new">Some Text</div>
</div>
</div>
```
I want to calculate How Many "Slide-new" there is "slide" variable.
In 'slides' variable I want 3 for first slideshow and 4 for second slideshow. But I can't get it...
Thanks | 2014/02/27 | [
"https://Stackoverflow.com/questions/22066017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3359925/"
] | You can Directly `Execute` this Query like:
```
db.execSQL("update status SET column1 = '"+prms+"' ", null);
```
You should replace your code
```
Cursor cursor = db.execSQL("update status SET column1 = '"+prms+"' ", null);
```
With
```
db.execSQL("update status SET column1 = '"+prms+"' ", null);
```
**void execSQL(String sql)**
Execute a single **SQL** statement that is NOT a SELECT or any other **SQL** statement that returns data.
It has no means to return any data (such as the number of affected rows). Instead, you're encouraged to use **insert(String, String, ContentValues**, **update(String, ContentValues, String, String[])**, et al, when possible. | Follow this code,it return no. of rows effected while updating.
```
SQLiteHelper helper;
public int updateName(String oldName,String newName)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(this.NAME, newName);
String [] whereArgs={oldName};
int count = db.update(helper.TABLE_NAME, values, helper.NAME+" =? ",whereArgs);
return count;
}
```
where helper is an object of class that extends `SQLiteOpenHelper` like the code below..
```
static class SQLiteHelper extends SQLiteOpenHelper
{
....////
private static final String DATABASE_NAME = "databaseName";
private static final String TABLE_NAME = "TABLENAME";
private static final int DATABASE_VERSION = 1;
private static final String UID = "_id";
private static final String NAME = "Name";
private static final String PASSWORD = "Password";
private static final String CREATE_TABLE ="CREATE TABLE "+ TABLE_NAME +"(" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT," + NAME + " VARCHAR(255)," + PASSWORD + " VARCHAR(255));";
public SQLiteHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Message.Message(context, "Constructor Called");
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try {
Message.Message(context, "OnCreate Called");
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Message.Message(context, "" + e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
try {
Message.Message(context, "onUpgrade Called");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
// TODO Auto-generated catch block
Message.Message(context, ""+e);
}
}
}
``` |
5,028,263 | Is there any library that can be used to decode Shift JIS text on Silverlight? | 2011/02/17 | [
"https://Stackoverflow.com/questions/5028263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41283/"
] | I was able to port Mono's implementation to .NET in less than an hour. This is the (minimal?) set of classes that needs to be ported (sorted by dependency):
1. [`I18N.Common.Strings`](https://github.com/mono/mono/blob/master/mcs/class/I18N/Common/Strings.cs)
2. [`I18N.Common.MonoEncoding`](https://github.com/mono/mono/blob/master/mcs/class/I18N/Common/MonoEncoding.cs)
3. [`I18N.CJK.CodeTable`](https://github.com/mono/mono/blob/master/mcs/class/I18N/CJK/CodeTable.cs)
4. [`I18N.CJK.DbcsConvert`](https://github.com/mono/mono/blob/master/mcs/class/I18N/CJK/DbcsConvert.cs)
5. [`I18N.CJK.DbcsEncoding`](https://github.com/mono/mono/blob/master/mcs/class/I18N/CJK/DbcsEncoding.cs)
6. [`I18N.CJK.JISConvert`](https://github.com/mono/mono/blob/master/mcs/class/I18N/CJK/JISConvert.cs)
7. [`I18N.CJK.CP932`](https://github.com/mono/mono/blob/master/mcs/class/I18N/CJK/CP932.cs)
Additionally, the following file needs to be copied (loaded in the constructor of `I18N.CJK.CodeTable`):
* [jis.table](https://github.com/mono/mono/blob/master/mcs/class/I18N/CJK/jis.table)
The class that implements the "shift\_jis" encoding is `I18N.CJK.CP932`. Note that it must be instantiated manually, ***not*** through `Encoding.GetEncoding()`. | I found some info here:
<http://www.eggheadcafe.com/community/aspnet/14/14621/covert-shiftjis-to-unicode.aspx>
This is the sample C# code from the link above (credits to Peter Bromberg). I cannot say for sure that it will work in Silverlight. I suppose it all depends on whether Encoding.GetEncoding("shift-jis") is available in SL:
```
public class FileConverter
{
const int BufferSize = 8096;
public static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine
("Usage: FileConverter <input file> <output file>");
return;
}
//NOTE: you may need to use " Encoding enc = Encoding.GetEncoding("shift-jis"); " for non-standard code pages
// Open a TextReader for the appropriate file
using (TextReader input = new StreamReader
(new FileStream (args[0], FileMode.Open),
Encoding.UTF8))
{
// Open a TextWriter for the appropriate file
using (TextWriter output = new StreamWriter
(new FileStream (args[1], FileMode.Create),
Encoding.Unicode))
{
// Create the buffer
char[] buffer = new char[BufferSize];
int len;
// Repeatedly copy data until we've finished
while ( (len = input.Read (buffer, 0, BufferSize)) > 0)
{
output.Write (buffer, 0, len);
}
}
}
}
}
``` |
326,887 | Could one use the word "wifey" instead of "wife"? I found many conflicting definitions online, Macmillan dictionary says it can be referred to as on'e wife in a humorous way or insulting way. Another meaning- It's referred to an old woman. I am not sure if the native US or UK speakers recognize this word and use it. | 2022/11/07 | [
"https://ell.stackexchange.com/questions/326887",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/160198/"
] | It's a recognised word, but its use is either old fashioned, or humorous, or occasionally affectionate.
In normal, modern, usage, on most locations, no one would use the term as a common synonym for 'wife'.
There are some areas where it would be considered nothing more than an informal, affectionate, term for the speaker's wife. | Although 'wifey' can be used affectionately, many people in English-speaking countries see the word as misogynist, sexist, and infantilising. There may be slight nuances of meaning, e.g. in American English, a single woman may be considered 'wifey' if she is stereotypically suitable marriage material for a sexist type of man, and in the UK, it may be a word used casually by husbands to refer to their wives.
Either way, it is **insulting**.
>
> ...why does this insult still hang around? And why does it infuriate
> so acutely?
>
>
> For me, it’s the reduction of my complex identity to a label that has
> the condescending, infantilizing singsong tenor with which you might
> speak to a child. Wifey. Baby. Honey. Sweetie.
>
>
>
[The term ‘wifey’ is sexist and infantilizing. (Washington Post)](https://www.washingtonpost.com/news/soloish/wp/2018/05/01/the-term-wifey-is-sexist-and-infantilizing-when-can-we-finally-get-rid-of-it/)
>
> wifey
>
>
> NOUN COUNTABLE BRITISH INFORMAL
>
>
> 1 an insulting or humorous word used for referring to someone’s wife
>
>
> 1a a woman, especially an old woman.
> This word is sometimes considered to be insulting.
>
>
>
[Wifey (Macmillan Dictionary)](https://www.macmillandictionary.com/dictionary/british/wifey) |
18,310 | I have created a program that searches through every player of a particular online game, visits their information webpage and extracts pieces of information about them (ie. their stats).
The problem is that there are several millions of players. By my initial calculations, it may take over 10 days to complete, and will use up over 30gbs of data traffic. This is less than ideal when you have a 40gb monthly allowance and you want to run the program weekly.
My question is this. How can I run my program quickly and cheaply. For instance, is it possible to buy some webspace with a webhosting company and run my java program somehow from there? I have seen some webhosting for around $2 per month, which seems pretty reasonable.
Or is it a webserver I would be after. Although they seem rather expensive. I am only doing this for my own interest and wouldn't want to spent more than a few dollars.
Thanks | 2011/08/16 | [
"https://webmasters.stackexchange.com/questions/18310",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/9620/"
] | Also you have to consider that you will also eat up 30GB x 4 of the websites data traffic per month, depending on the website this can be a huge problem for the operator and they will probably detect the bandwidth usage spike as an attack on their website. | Yes, you can purchase the use of a remote computer that would allow you to use that computer's access to the Internet to collect your data.
Here are some difficulties you will still face even if you go this route:
1. You will need to set up, configure and manage a remote computer, probably from a SSH command line interface.
2. The info you collected is still stored on a remote computer, you will face the same bandwidth issues you faced before in attempting to move that data to your local computer.
3. You will need to pay for the bandwidth your new server will use to access the data you are after.
It is probably much easier and more cost effective to purchase additional bandwidth for your local computer which is already configured |
237,570 | I am trying to merge two shapefiles from a zip obtained here:
<http://wsgw.mass.gov/data/gispub/shape/l3parcels/L3_SHP_M351_YARMOUTH.zip>
The two shapefiles contain different attributes for the same town in Massachusetts. I want to join the two shapefiles into one consolidated shapefile with all the attribute information from both files.
I can achieve this on QGIS, however something goes wrong when I try to do this on the command line.
On the command when I do this:
```
$ ls *.shp
M351OthLeg.shp M351TaxPar.shp
$ ogr2ogr -f "ESRI Shapefile" consolidated.shp M351TaxPar.shp
$ ogr2ogr -f "ESRI Shapefile" -update -append consolidated.shp M351OthLeg.shp
```
It does produce a consolidated file that is larger than the first two:
```
$ ls -al *.shp
-rwxr-xr-x@ 1 ssikdar 600 249940 Feb 15 2012 M351OthLeg.shp
-rwxr-xr-x@ 1 ssikdar 600 10765676 Feb 15 2012 M351TaxPar.shp
-rw-r--r-- 1 ssikdar 600 11015516 Apr 20 21:55 consolidated.shp
```
But the new file is missing attributes of the second file.
When I do an ogrinfo:
```
$ ogrinfo -so -al consolidated.shp
INFO: Open of `consolidated.shp'
using driver `ESRI Shapefile' successful.
...
SHAPE_Leng: Real (19.11)
SHAPE_Area: Real (19.11)
MAP_PAR_ID: String (26.0)
LOC_ID: String (18.0)
POLY_TYPE: String (15.0)
MAP_NO: String (4.0)
SOURCE: String (15.0)
PLAN_ID: String (40.0)
LAST_EDIT: Integer (9.0)
BND_CHK: String (2.0)
NO_MATCH: String (1.0)
TOWN_ID: Integer (4.0)
```
It doesn't seem to have the attributes of the last file I tried to merge with it.
```
$ ogrinfo -so -al M351OthLeg.shp
...
MAP_PAR_ID: String (26.0)
LEGAL_TYPE: String (15.0)
LS_BOOK: String (16.0)
LS_PAGE: String (14.0)
REG_ID: String (15.0)
SHAPE_Leng: Real (19.11)
SHAPE_Area: Real (19.11)
TOWN_ID: Integer (4.0)
TAXPAR_ID: String (18.0)
```
As a test I merged the two shapefile in Quantum GIS. When I do an ogrinfo on that file, the additional attributes are there:
```
$ ogrinfo -so -al ~/Documents/m351_qgis.shp
...
MAP_PAR_ID: String (254.0)
LEGAL_TYPE: String (254.0)
LS_BOOK: String (254.0)
LS_PAGE: String (254.0)
REG_ID: String (254.0)
SHAPE_Leng: Real (21.5)
SHAPE_Area: Real (21.5)
TOWN_ID: Integer (10.0)
TAXPAR_ID: String (254.0)
LOC_ID: String (254.0)
POLY_TYPE: String (254.0)
MAP_NO: String (254.0)
SOURCE: String (254.0)
PLAN_ID: String (254.0)
LAST_EDIT: Integer (10.0)
BND_CHK: String (254.0)
NO_MATCH: String (254.0)
```
Is there something I'm missing in my command line arguments that's giving me a different result than QGIS? | 2017/04/21 | [
"https://gis.stackexchange.com/questions/237570",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/25106/"
] | The value is incorrect in your underlying data, not just in your symbology. To correct this properly and not just work-around it with a different label, you will need to modify the value in your data. It appears that the incorrect value is in your `rock_class` field.
To modify this value, first you need to select all instances of that value in your layer, and then use field calculator to populate with the correct value.
1. Select all instances of value:
Open your attribute table (right-click on layer and select Open Attribute Table) and click on the Select by Attributes
[](https://i.stack.imgur.com/aLLHT.png)
In the `SELECT * FROM <layer name> WHERE:` box enter
```
rock_class = 'Metasedimenary'
```
(where `rock_class` is the name of your field and `Metasedimenary` is the value you want to select). Click Apply and Close. You should now see your rows selected in the table.
[](https://i.stack.imgur.com/lI14o.png)
2. Right-click on your `rock_class` field and select Field Calculator
[](https://i.stack.imgur.com/luXoQ.png)
In the field calculator window enter the value you want to change the values in your selected features to:
```
"Metasedimentary"
```
[](https://i.stack.imgur.com/M97M6.png)
Click OK to run the calculation and close the field calculator. You will now see that the selected values have been updated to your new correct value.
[](https://i.stack.imgur.com/LfNLy.png)
3. You will now need to update your symbology (as it will still be trying to symbolise on the old value that no longer exists). In your layer symbology tab you can either Remove All and then Add All Values - this will possibly reset all your symbol colours - or you can selectively remove the incorrect values by just selecting the problem values and clicking "Remove" and then click "Add" and add the new correct values in from the selection.
[](https://i.stack.imgur.com/dkLrD.png)
[](https://i.stack.imgur.com/CeUWE.png) | You can select that value in your table, and using field calculator, change it into the correct spelling. Then when you use that field in your symbology, the spelling will be correct |
52,913 | (Question) Suppose two individuals form an economy where each devotes $10$ hours of labour to produce goods $x$ and $y$. The utilities of the agents $S$ and $J$ are $U\_S(x,y) = x^{0.3}y^{0.7}$ and $U\_J(x,y)=x^{0.5}y^{0.5}$. If the individuals do not care whether they produce $x$ or $y$ and the production function for each good is given by $x=2l$ and $y=3l$ where $l$ is the total labour devoted to production of each good, find the price ratio $\frac{p\_x}{p\_y}$.
I have two different solutions for this:
1. (Solution 1) Suppose the price of labour is $p\_l$ in the economy. To maximize profits on $x$, $$\pi\_x(l\_x^J, l\_x^S, p\_x,p\_l) = p\_xx - p\_ll = 2p\_x(l\_x^J+l\_x^S)-p\_l(l\_x^J+l\_x^S)$$
Differentiation gives us $p\_l = 2p\_x$ and if we do the same on $y$'s maximization problem, we get $$p\_l = 2p\_x = 3p\_y$$ The price ratio can derived from this as $3/2$.
2. (Solution 2) Given $x$, the production possibility frontier is given by the equation $x/2 + y/3 = l\_x + l\_y = 20$. The slope of this equation at the optimal point gives us the price ratio and it's very clearly $3$.
My questions regarding this problem:
* Are both my solutions correct?
* Why is the slope of the Production-Possibility Frontier (PPF) at the optimal $(x^\*, y^\*)$ equal to the price ratio? It appears to be a a cost maximization problem subject to the PPF.
* Once I know the PPF, how do I find the optimal $(x^\*, y^\*)$, let's say for this problem? I am aware of the usual way of equating the demand and supply and also maximizing the profits. But is there any way our knowledge of the PPF can be used to find $(x^\*, y^\*)$? | 2022/09/30 | [
"https://economics.stackexchange.com/questions/52913",
"https://economics.stackexchange.com",
"https://economics.stackexchange.com/users/42380/"
] | To find competitive equilibrium prices $(p\_X, p\_Y, w=1)$, we need to find the supply of $X$ and $Y$ and labor $L$ demand of the two firms:
$\displaystyle\max\_{x\geq 0,l\_X\geq 0} p\_Xx - l\_X$ subject to $x \leq 2l\_X$
$\displaystyle\max\_{y\geq 0,l\_Y\geq 0} p\_Yy - l\_Y$ subject to $y \leq 3l\_Y$
Solving the above problems give the supply of $X$ and $Y$ as:
\begin{eqnarray\*} x^s \in \begin{cases} \emptyset &\text{if } p\_X > \frac{1}{2} \\ [0,\infty) &\text{if } p\_X = \frac{1}{2} \\ \{0\} &\text{if } p\_X < \frac{1}{2} \end{cases} \end{eqnarray\*}
and corresponding labor demand for $X$ is $l^d\_X = \dfrac{x^s}{2}$.
\begin{eqnarray\*} y^s \in \begin{cases} \emptyset &\text{if } p\_Y > \frac{1}{3} \\ [0,\infty) &\text{if } p\_Y = \frac{1}{3} \\ \{0\} &\text{if } p\_Y < \frac{1}{3} \end{cases} \end{eqnarray\*}
and corresponding labor demand for $Y$ is $l^d\_Y = \dfrac{y^s}{3}$.
This rules out the possibility that $p\_X > \frac{1}{2}$ or $p\_Y > \frac{1}{3}$ in equilibrium. Therefore, if the equilibrium exists, optimal profits will be $0$.
Now we can find the demand for $X$ and $Y$ by solving the following problems:
$\displaystyle\max\_{x\geq 0,y\geq 0} x^{0.3}y^{0.7} $ subject to $p\_Xx + p\_Yy \leq 10 $
$\displaystyle\max\_{x\geq 0,y\geq 0} x^{0.5}y^{0.5} $ subject to $p\_Xx + p\_Yy \leq 10 $
Solving the above problems give the demand for $X$ and $Y$ as:
$(x^d\_S, y^d\_S) = \left(\dfrac{3}{p\_X}, \dfrac{7}{p\_Y}\right)$
$(x^d\_J, y^d\_J) = \left(\dfrac{5}{p\_X}, \dfrac{5}{p\_Y}\right)$
Since demands for both the goods are always strictly positive, observing the supply rules out the possibility of $p\_X < \frac{1}{2}$ or $p\_Y < \frac{1}{3}$ in equilibrium.
Therefore, if the equilibrium exists, it must be the case that $p\_X = \frac{1}{2}$ and $p\_Y = \frac{1}{3}$. We can now verify that it is indeed the equilibrium.
Equilibrium prices are $(p\_X=\frac{1}{2}, p\_Y=\frac{1}{3}, w=1)$, and the corresponding equilibrium quantities of $X$, $Y$ and $L$ are:
$x^d\_S + x^d\_J = 6 + 10 = 16 = x^s$
$y^d\_S + y^d\_J = 21 + 15 = 36 = y^s$
$l^d\_X + l^d\_Y = \dfrac{x^s}{2} + \dfrac{y^s}{3} = 8 + 12 = 20 = 10+10=l^s\_S + l^s\_J$ | $\frac{p\_x}{p\_y}=\frac{3}{2}$
Because if $\frac{p\_x}{p\_y}>\frac{3}{2}$, both the persons will have an incentive to produce only x and then use the income to purchase y from the market. This will result in a rise in $p\_y$. The process will continue until $\frac{p\_x}{p\_y}=\frac{3}{2}$.
Analogously, if $\frac{p\_x}{p\_y}<\frac{3}{2}$, every-one has an incentive to produce only y and use the income to purchase x from the market. This will result in a rise in $p\_x$ until we reach the ratio $\frac{p\_x}{p\_y}=\frac{3}{2}$
This explanation says why the price ratio must be the slope of the PPC.
Both the solutions are correct except that in the second one you have probably made a typo, the slope of PPC is $\frac{3}{2}$. |
10,883,711 | I know this is a very newbie C# question but I am implementing a small program which does the following:
```
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
bool isRun = false;
int number = 0;
while (isRun = (true) && number < 3)
{
++number;
Console.WriteLine("Number = {0}", number.ToString());
Console.WriteLine();
}
Console.WriteLine(isRun.ToString());
Console.ReadLine();
}
}
}
```
At the end of the while loop, I would have expected the `bool` value to be true, but is is printed to be `false`. Why is that? Is this different from C++ where I would have done something like and the same thing in C# is giving me false
```
while(number<3)
{
is = true;
}
if(is){
cout<<true;
}
``` | 2012/06/04 | [
"https://Stackoverflow.com/questions/10883711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1240679/"
] | The reason you're seeing this behavior is due to the operator precedence involved. Here the `&&` binds more strongly than `=` so the code in the loop is actually bound as the following
```
while (isRun = (true && number < 3)) {
...
}
```
Once `number > 3` the `&&` expression is `false` and is assigned into the `isRun` value and simultaneously terminates the loop. Hence once the loop exits you will see `isRun` as `false`
To get the behavior you are looking for you will need to manually correct the precedence with parens.
```
while ((isRun = (true)) && number < 3) {
...
}
```
Note: In general, as @Servey pointed out, the assignment of locals to expressions inside the loop predicate is considered bad practice. Many C# users would actually be surprised that code compiles at all because they've been conditioned to only use `==` in loops.
It's more idiomatic to simply set `isRun` to `true` on the first line of the loop for this pattern.
```
while (number < 3) {
isRun = true;
...
}
``` | The problem is that you have set you `boolean` variable to `false` and without assigning it back to `true`, in while loop you are `matching` it against the `value true`, thus it `fails` in `every` case. |
3,448,520 | I'm running a site powered by WordPress with extra pages...
To integrate these pages with the WordPress theme I use this code:
```
<?php
$blog_longd='Title'; // page title
define('WP_USE_THEMES', false);
require('wp-blog-header.php');
get_header();
?>
html code
<?php
get_sidebar();
get_footer();
?>
```
This works fine, however page title shows always 404 Error Page (not "Title").
It seems that $wp-query->is\_404 is always set to true. I tried overriding this value but it doesn't seem to work. I tried fixing it by putting header status 200 above function get\_header()..also it doesn't work.
Any suggestions?
Thanks | 2010/08/10 | [
"https://Stackoverflow.com/questions/3448520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391684/"
] | I know it has been a long time since you asked but I had the problem and here is the solution.
```
<?php
require('./wp-config.php');
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
$wp->send_headers();
get_header();
echo "HELLO WORLD";
get_footer();
?>
``` | Maybe clumsy, but if you implement the `wp_title` filter, you can change the title to what you want. You can add this code to the header of each custom page:
```
add_filter('wp_title', 'replace_title');
function replace_title() {
return 'My new title';
}
```
If you want it a bit cleaner, use a smarter version of this filter to a plugin, and set only the global variable (here `$override_title`) in your page:
```
add_filter('wp_title', 'replace_title_if_global');
function replace_title_if_global($title) {
global $override_title;
if ($override_title) {
return $override_title;
}
return $title;
}
``` |
3,448,520 | I'm running a site powered by WordPress with extra pages...
To integrate these pages with the WordPress theme I use this code:
```
<?php
$blog_longd='Title'; // page title
define('WP_USE_THEMES', false);
require('wp-blog-header.php');
get_header();
?>
html code
<?php
get_sidebar();
get_footer();
?>
```
This works fine, however page title shows always 404 Error Page (not "Title").
It seems that $wp-query->is\_404 is always set to true. I tried overriding this value but it doesn't seem to work. I tried fixing it by putting header status 200 above function get\_header()..also it doesn't work.
Any suggestions?
Thanks | 2010/08/10 | [
"https://Stackoverflow.com/questions/3448520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391684/"
] | Maybe clumsy, but if you implement the `wp_title` filter, you can change the title to what you want. You can add this code to the header of each custom page:
```
add_filter('wp_title', 'replace_title');
function replace_title() {
return 'My new title';
}
```
If you want it a bit cleaner, use a smarter version of this filter to a plugin, and set only the global variable (here `$override_title`) in your page:
```
add_filter('wp_title', 'replace_title_if_global');
function replace_title_if_global($title) {
global $override_title;
if ($override_title) {
return $override_title;
}
return $title;
}
``` | There is code in the file class-wp.php:
```
function handle_404() {
...
// Don't 404 for these queries if they matched an object.
if ( ( is_tag() || is_category() || is_tax() || is_author() || is_post_type_archive() ) && $wp_query->get_queried_object() ) {
status_header( 200 );
return;
}
...
}
```
that handles 404 status for various of pages.
The stack of functions of this code is:
```
1) wp-blog-header.php:14, require()
2) function.php:775, wp()
3) class-wp.php:525, WP->main()
4) class-wp.php:491, handle_404()
```
So you have two ways to handle the situation:
1)
```
require('wp-blog-header.php');
function status_header( 200 );
```
2) more correct would be insert your own function here
```
if ( your_own_function() || ((is_tag() || is_category() || is_tax() || is_author() || is_post_type_archive() ) && $wp_query->get_queried_object()) ) {
```
that returns `true` when your custom page is requested |
3,448,520 | I'm running a site powered by WordPress with extra pages...
To integrate these pages with the WordPress theme I use this code:
```
<?php
$blog_longd='Title'; // page title
define('WP_USE_THEMES', false);
require('wp-blog-header.php');
get_header();
?>
html code
<?php
get_sidebar();
get_footer();
?>
```
This works fine, however page title shows always 404 Error Page (not "Title").
It seems that $wp-query->is\_404 is always set to true. I tried overriding this value but it doesn't seem to work. I tried fixing it by putting header status 200 above function get\_header()..also it doesn't work.
Any suggestions?
Thanks | 2010/08/10 | [
"https://Stackoverflow.com/questions/3448520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391684/"
] | I know it has been a long time since you asked but I had the problem and here is the solution.
```
<?php
require('./wp-config.php');
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
$wp->send_headers();
get_header();
echo "HELLO WORLD";
get_footer();
?>
``` | There is code in the file class-wp.php:
```
function handle_404() {
...
// Don't 404 for these queries if they matched an object.
if ( ( is_tag() || is_category() || is_tax() || is_author() || is_post_type_archive() ) && $wp_query->get_queried_object() ) {
status_header( 200 );
return;
}
...
}
```
that handles 404 status for various of pages.
The stack of functions of this code is:
```
1) wp-blog-header.php:14, require()
2) function.php:775, wp()
3) class-wp.php:525, WP->main()
4) class-wp.php:491, handle_404()
```
So you have two ways to handle the situation:
1)
```
require('wp-blog-header.php');
function status_header( 200 );
```
2) more correct would be insert your own function here
```
if ( your_own_function() || ((is_tag() || is_category() || is_tax() || is_author() || is_post_type_archive() ) && $wp_query->get_queried_object()) ) {
```
that returns `true` when your custom page is requested |
11,305,308 | `duplicated()` gives `TRUE` or `FALSE` statement depending if that position is duplicated previously in the vector. What if I wanted to remove not only the duplicated position, but also all the previous position that it is a duplicate of.
```
a <- c("A", "B", "C")
b <- c("A", "B", "C", "D")
```
`a` contains all the values that will be duplicated and `b` contains the values of `a` and some other values that are not duplicated.
How do I only extract `"D"`? | 2012/07/03 | [
"https://Stackoverflow.com/questions/11305308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144724/"
] | If what you really have is a single vector in which some elements are duplicated and some (which you want to keep) aren't, you could try either of these:
```
## Constructing an example that fits your narrative description of the situation
a <- c("A", "B", "C")
b <- c("A", "B", "C", "D")
ab <- c(a,b)
# Approach #1
setdiff(ab, ab[duplicated(ab)])
# [1] "D"
# Approach #2
ab[!(duplicated(ab) | rev(duplicated(rev(ab))))]
# [1] "D"
``` | ```
> table(c(a, b))
# A B C D
# 2 2 2 1
> names(table(c(a, b)))[table(c(a, b)) == 1]
# [1] "D"
``` |
11,305,308 | `duplicated()` gives `TRUE` or `FALSE` statement depending if that position is duplicated previously in the vector. What if I wanted to remove not only the duplicated position, but also all the previous position that it is a duplicate of.
```
a <- c("A", "B", "C")
b <- c("A", "B", "C", "D")
```
`a` contains all the values that will be duplicated and `b` contains the values of `a` and some other values that are not duplicated.
How do I only extract `"D"`? | 2012/07/03 | [
"https://Stackoverflow.com/questions/11305308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144724/"
] | Here is another one:
```
b[!b %in% a]
[1] "D"
``` | If what you really have is a single vector in which some elements are duplicated and some (which you want to keep) aren't, you could try either of these:
```
## Constructing an example that fits your narrative description of the situation
a <- c("A", "B", "C")
b <- c("A", "B", "C", "D")
ab <- c(a,b)
# Approach #1
setdiff(ab, ab[duplicated(ab)])
# [1] "D"
# Approach #2
ab[!(duplicated(ab) | rev(duplicated(rev(ab))))]
# [1] "D"
``` |
11,305,308 | `duplicated()` gives `TRUE` or `FALSE` statement depending if that position is duplicated previously in the vector. What if I wanted to remove not only the duplicated position, but also all the previous position that it is a duplicate of.
```
a <- c("A", "B", "C")
b <- c("A", "B", "C", "D")
```
`a` contains all the values that will be duplicated and `b` contains the values of `a` and some other values that are not duplicated.
How do I only extract `"D"`? | 2012/07/03 | [
"https://Stackoverflow.com/questions/11305308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144724/"
] | Here is another one:
```
b[!b %in% a]
[1] "D"
``` | ```
> table(c(a, b))
# A B C D
# 2 2 2 1
> names(table(c(a, b)))[table(c(a, b)) == 1]
# [1] "D"
``` |
11,305,308 | `duplicated()` gives `TRUE` or `FALSE` statement depending if that position is duplicated previously in the vector. What if I wanted to remove not only the duplicated position, but also all the previous position that it is a duplicate of.
```
a <- c("A", "B", "C")
b <- c("A", "B", "C", "D")
```
`a` contains all the values that will be duplicated and `b` contains the values of `a` and some other values that are not duplicated.
How do I only extract `"D"`? | 2012/07/03 | [
"https://Stackoverflow.com/questions/11305308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144724/"
] | Here are some timings to show how solutions posted by @Josh O'Brien, @cogitovita, and @jmsigner perform with a larger dataset:
```
set.seed(123)
a = sample(paste("ID_", seq(1e6), sep=""))
b = sample(a, 9e5, replace=TRUE)
ab = sample(c(a, b))
system.time(res1 <- setdiff(ab, ab[duplicated(ab)]))
# user system elapsed
# 1.543 0.030 1.563
system.time(res2 <- ab[!(duplicated(ab) | rev(duplicated(rev(ab))))])
# user system elapsed
# 0.537 0.042 0.575
system.time(res3 <- names(table(ab))[table(ab) == 1])
# user system elapsed
# 52.208 0.255 52.218
system.time(b[!b %in% a])
#user system elapsed
#0.098 0.002 0.100
setequal(res1, res2)
# [1] TRUE
setequal(res1, res3)
# [1] TRUE
``` | ```
> table(c(a, b))
# A B C D
# 2 2 2 1
> names(table(c(a, b)))[table(c(a, b)) == 1]
# [1] "D"
``` |
11,305,308 | `duplicated()` gives `TRUE` or `FALSE` statement depending if that position is duplicated previously in the vector. What if I wanted to remove not only the duplicated position, but also all the previous position that it is a duplicate of.
```
a <- c("A", "B", "C")
b <- c("A", "B", "C", "D")
```
`a` contains all the values that will be duplicated and `b` contains the values of `a` and some other values that are not duplicated.
How do I only extract `"D"`? | 2012/07/03 | [
"https://Stackoverflow.com/questions/11305308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1144724/"
] | Here is another one:
```
b[!b %in% a]
[1] "D"
``` | Here are some timings to show how solutions posted by @Josh O'Brien, @cogitovita, and @jmsigner perform with a larger dataset:
```
set.seed(123)
a = sample(paste("ID_", seq(1e6), sep=""))
b = sample(a, 9e5, replace=TRUE)
ab = sample(c(a, b))
system.time(res1 <- setdiff(ab, ab[duplicated(ab)]))
# user system elapsed
# 1.543 0.030 1.563
system.time(res2 <- ab[!(duplicated(ab) | rev(duplicated(rev(ab))))])
# user system elapsed
# 0.537 0.042 0.575
system.time(res3 <- names(table(ab))[table(ab) == 1])
# user system elapsed
# 52.208 0.255 52.218
system.time(b[!b %in% a])
#user system elapsed
#0.098 0.002 0.100
setequal(res1, res2)
# [1] TRUE
setequal(res1, res3)
# [1] TRUE
``` |
113,446 | I am confused about the exact location of the (departures) entrance to the Zagreb airport.
[Searching for Google Maps direction](https://www.google.com/maps/dir/Zagreb,+Croatia/Franjo+Tu%C4%91man+Airport+Zagreb+(ZAG),+Ul.+Rudolfa+Fizira+1,+10150,+Zagreb,+Croatia/@45.7395349,16.0787281,16.75z/data=!4m14!4m13!1m5!1m1!1s0x4765d692c902cc39:0x3a45249628fbc28a!2m2!1d15.9819189!2d45.8150108!1m5!1m1!1s0x47667ee85c7fab29:0x9ef60b3c28e288f6!2m2!1d16.0674366!2d45.7407504!3e2) to the airport places the destination point somewhere around (45.741151, 16.081114). This is also the part of the map that is shown on their official site when searching for driving directions to the airport *and* it is also close to the official airport's address, Ulica Rudolfa Fizira 21.
However, the satellite imagery does not show the roads sketched out on the map of this part and the terminal location seems to be somewhere around [(45.732079, 16.060357)](https://www.google.com/maps/place/45%C2%B043'55.5%22N+16%C2%B003'37.3%22E/@45.7315981,16.0598425,372m/data=!3m1!1e3!4m6!3m5!1s0x0:0x0!7e2!8m2!3d45.7320792!4d16.0603573).
I remember that the entrance is overlooking the park seen at these coordinates. I thought that the terminal perhaps moved, [having found this piece of news about the new terminal](https://www.total-croatia-news.com/business/17655-new-terminal-at-zagreb-airport-officially-opened). To add to my confusion, I realized this must have been already built the last time I was at the airport, but the photos do not ring a bell.
I would like to know the precise location to estimate the feasibility of walking to the airport from a nearby hotel. The two points in question are more than 2 km apart according to Google Maps. | 2018/04/20 | [
"https://travel.stackexchange.com/questions/113446",
"https://travel.stackexchange.com",
"https://travel.stackexchange.com/users/49330/"
] | There seems to be [two terminals](http://openstreetmap.org/#map=15/45.7344/16.0617).
The old one is close to some built-up area. The new one is not walkable to anything. There's huge parking but nothing else.
What terminal is in your ticket? I assume that new terminal is used exclusively and you can't walk anywhere from there. Try to catch some shuttle. | After flying from the airport I can attest that the new terminal is in use. It's located at [45.741275, 16.081007](https://www.google.com/maps/place/45%C2%B044'28.6%22N+16%C2%B004'51.6%22E/@45.7412891,16.0722522,3540m/data=!3m2!1e3!4b1!4m6!3m5!1s0x0:0x0!7e2!8m2!3d45.7412745!4d16.0810068 "45.741275, 16.081007").
Nowhere was it specified that I should use the "new" terminal. However, the bus station in front of the old one says *The old passenger terminal* (hr. Stari putnički terminal), implying that it's not in use any more. Additionally, while the bus was passing it, it's doors seemed to be sealed.
As an aside: the satellite imagery of this location is already updated when using the map on an Android phone. From a PC browser, I cannot see the updated imagery. |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | A `document.write()` called after the page loads will overwrite the current document.
You want to set the text of some element within your document. If you add a
```
<p id="message"></p>
```
to the end of your body, then you can call
```
document.getElementById("message").innerHTML = "your text here";
```
Or with the jQuery library
```
$("#message").html("your text here");
``` | ```
var x = document.createElement("div")
document.body.appendChild(x)
``` |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | A `document.write()` called after the page loads will overwrite the current document.
You want to set the text of some element within your document. If you add a
```
<p id="message"></p>
```
to the end of your body, then you can call
```
document.getElementById("message").innerHTML = "your text here";
```
Or with the jQuery library
```
$("#message").html("your text here");
``` | you can use
```
alert("Checkbox is checked");
```
or if you will be displaying it on page, first create an element with an id "message" (you can write anything you want, but remember, id's have to be unique on the page) like
```
<div id="message"></div>
```
and then use
```
document.getElementById("message").innerHTML = "Checkbox is checked";
```
or if you are using jQuery:
```
$("#message").html("Checkbox is checked");
```
or if you are using a console enabled browser (Firefox, Chrome etc.)
```
console.log("Checkbox is checked");
```
instead of
```
document.write("Checkbox is checked");
``` |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | `document.write()` is used to write to the document *stream*.
In your case, the stream is most probably already closed when the onClick handler is called, because your document has finished loading.
Calling `document.write()` on a closed document stream automatically calls `document.open()`, which will clear the document. | `document.write` is not best way to go as if there is any, yes ANY, DOM manipulation happening or happened already then `document.write()` does not work very well as it modifies original document but ignores any changes to DOM tree.
Also remember that browser displays things primarily from DOM, not from original document. |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | Calling `document.write` *after* the document has been loaded implicitly calls `document.open`, which clears the current document. (Compare to calling `document.open` while the page is loading, which inserts the string into the document stream; it does not clear the document.)
`document.write` is one of the oldest vestiges of ancient JavaScript, and should generally be avoided. Instead, you probably want to use DOM manipluation methods to update the document. | you can use
```
alert("Checkbox is checked");
```
or if you will be displaying it on page, first create an element with an id "message" (you can write anything you want, but remember, id's have to be unique on the page) like
```
<div id="message"></div>
```
and then use
```
document.getElementById("message").innerHTML = "Checkbox is checked";
```
or if you are using jQuery:
```
$("#message").html("Checkbox is checked");
```
or if you are using a console enabled browser (Firefox, Chrome etc.)
```
console.log("Checkbox is checked");
```
instead of
```
document.write("Checkbox is checked");
``` |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | `document.write()` is used to write to the document *stream*.
In your case, the stream is most probably already closed when the onClick handler is called, because your document has finished loading.
Calling `document.write()` on a closed document stream automatically calls `document.open()`, which will clear the document. | A `document.write()` called after the page loads will overwrite the current document.
You want to set the text of some element within your document. If you add a
```
<p id="message"></p>
```
to the end of your body, then you can call
```
document.getElementById("message").innerHTML = "your text here";
```
Or with the jQuery library
```
$("#message").html("your text here");
``` |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | Calling `document.write` *after* the document has been loaded implicitly calls `document.open`, which clears the current document. (Compare to calling `document.open` while the page is loading, which inserts the string into the document stream; it does not clear the document.)
`document.write` is one of the oldest vestiges of ancient JavaScript, and should generally be avoided. Instead, you probably want to use DOM manipluation methods to update the document. | `document.write` is not best way to go as if there is any, yes ANY, DOM manipulation happening or happened already then `document.write()` does not work very well as it modifies original document but ignores any changes to DOM tree.
Also remember that browser displays things primarily from DOM, not from original document. |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | ```
var x = document.createElement("div")
document.body.appendChild(x)
``` | `document.write` is not best way to go as if there is any, yes ANY, DOM manipulation happening or happened already then `document.write()` does not work very well as it modifies original document but ignores any changes to DOM tree.
Also remember that browser displays things primarily from DOM, not from original document. |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | `document.write()` is used to write to the document *stream*.
In your case, the stream is most probably already closed when the onClick handler is called, because your document has finished loading.
Calling `document.write()` on a closed document stream automatically calls `document.open()`, which will clear the document. | ```
var x = document.createElement("div")
document.body.appendChild(x)
``` |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | `document.write()` is used to write to the document *stream*.
In your case, the stream is most probably already closed when the onClick handler is called, because your document has finished loading.
Calling `document.write()` on a closed document stream automatically calls `document.open()`, which will clear the document. | Calling `document.write` *after* the document has been loaded implicitly calls `document.open`, which clears the current document. (Compare to calling `document.open` while the page is loading, which inserts the string into the document stream; it does not clear the document.)
`document.write` is one of the oldest vestiges of ancient JavaScript, and should generally be avoided. Instead, you probably want to use DOM manipluation methods to update the document. |
10,873,942 | Why in the code below upon the call of `document.write` in the function `validator()` the form elements (the checkbox and button) are removed from screen?
```
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validator() {
if (document.myForm.thebox.checked)
document.write("checkBox is checked");
else
document.write("checkBox is NOT checked");
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name ="thebox"/>
<input type="button" onClick="validator()" name="validation" value="Press me for validation"/>
</form>
</body>
</html>
``` | 2012/06/03 | [
"https://Stackoverflow.com/questions/10873942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699559/"
] | A `document.write()` called after the page loads will overwrite the current document.
You want to set the text of some element within your document. If you add a
```
<p id="message"></p>
```
to the end of your body, then you can call
```
document.getElementById("message").innerHTML = "your text here";
```
Or with the jQuery library
```
$("#message").html("your text here");
``` | `document.write` is not best way to go as if there is any, yes ANY, DOM manipulation happening or happened already then `document.write()` does not work very well as it modifies original document but ignores any changes to DOM tree.
Also remember that browser displays things primarily from DOM, not from original document. |
1,169,622 | I have a Raspberry Pi 3 running a version of Raspbian 7 (wheezy). These devices have an Ethernet RJ45 port (eth0), and a wireless WiFi module (wlan0). I would like to set them up as on this image:
[my-rpi3-network.png](https://i.stack.imgur.com/jTovO.png)
Basically:
* I connect the Rpi3 via the wired eth0 to a switch, and I get Internet on it from another Ubuntu PC, which has Internet "Shared to other computers" on `eth0`, which makes the Ubuntu PC a DHCP server with address 10.42.0.1, assigning addresses to clients in the 10.42.0.X range. That is why I'd like to keep the `eth0` port on the Rpi3 as a DHCP client.
* I want to make the `wlan0` on the Rpi3 an access point - meaning that other machines could connect to it; I'm assuming this means that the Rpi3 must be a DHCP server on that interface, then (otherwise it would not be able to allocate a local IP to a client machine that had connected to it through WiFi).
So, I found this link: <https://frillip.com/using-your-raspberry-pi-3-as-a-wifi-access-point-with-hostapd/> - and I was trying to follow it; first my Raspbian did not have `dhcpcd`, so I installed:
```
sudo apt-get install dhcpcd5
```
(it is `dhcpcd5` that has `/etc/dhcpcd.conf` - otherwise the `dhcpcd` package is actually `dhcpcd3` and it has `/etc/dhcpcd.sh` instead)
Midway through the tutorial I tried doing this as per instructions:
```
$ sudo service dhcpcd restart
[FAIL] Not running dhcpcd because /etc/network/interfaces ... failed!
[FAIL] defines some interfaces that will use a DHCP client ... failed!
```
My current `/etc/network/interfaces` is like this:
```
auto lo
iface lo inet loopback
iface eth0 inet dhcp
allow-hotplug wlan0
iface wlan0 inet static
address 172.24.1.1
netmask 255.255.255.0
network 172.24.1.0
broadcast 172.24.1.255
# wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
```
Other resources like <https://raspberrypi.stackexchange.com/questions/34914/wifi-not-working-on-startup> mention that apparently the problem is that `/etc/network/interfaces` defines `eth0` to be a DHCP client:
>
> If you see this, then to correct, open a terminal:
>
>
>
> ```
> $ sudo nano /etc/network/interfaces
>
> ```
>
> and replace dhcp with manual. The two lines from your interfaces are:
>
>
>
> ```
> iface eth0 inet manual
> iface default inet manual
>
> ```
>
>
However, I do not want to do this - because unless the `eth0` on the Rpi3 is a DHCP client, then I cannot get the Internet Sharing from the Ubuntu PC to work!
So, what I gather is that it is impossible to run a DHCP server on a machine that has one of its network interfaces defined as a DHCP client?! Is this true? Or to formulate it as a question:
* Can I have one network interface (`eth0`) as a DHCP client, and another (`wlan0`) as a DHCP server, on the same machine - and if so, how? | 2017/01/20 | [
"https://superuser.com/questions/1169622",
"https://superuser.com",
"https://superuser.com/users/-1/"
] | If I were you, instead of creating another DHCP server and subnet, I would just create a bridge in your RPi, which bridges the wireless and wired networks in the same network.
This way wireless clients get IP addresses directly from your Ubuntu server.
You can accomplish this with the following configuration in `/etc/network/interfaces`:
```
auto br0
iface br0 inet dhcp
bridge_ports wlan0 eth0
auto wlan0
iface wlan0 inet manual
auto eth0
iface eth0 inet manual
```
`br0` will be the address of the bridge interface, which bridges `eth0` and `wlan0` interfaces together. Then we configure the interface to get IP address for the RPi via DHCP.
Using a bridge here instead of a another NAT layer prevents some issues that are caused by double-NAT. | OP here - well at first I thought that the designation `manual` means the same as `static`, but that seems to not be the case; I found:
<https://wiki.debian.org/NetworkConfiguration>
>
> To create a network interface without an IP address at all use the manual method and use pre-up and post-down commands to bring the interface up and down.
>
>
>
> ```
> iface eth0 inet manual
> pre-up ifconfig $IFACE up
> post-down ifconfig $IFACE down
>
> ```
>
>
... and so I copied those exact lines in `/etc/network/interfaces` (replacing the `iface eth0 inet dhcp`) - and it turned out, it works:
```
$ sudo service dhcpcd restart
dhcpcd[3253]: dhcpcd not running
dhcpcd[3254]: version 6.7.1 starting
dhcpcd[3254]: all: IPv6 kernel autoconf disabled
dhcpcd[3254]: eth0: adding address feXX::...
dhcpcd[3254]: if_addaddress6: Operation not supported
dhcpcd[3254]: DUID 00:XX:XX:...
dhcpcd[3254]: eth0: IAID eb:XX:....
dhcpcd[3254]: eth0: soliciting a DHCP lease
dhcpcd[3254]: eth0: offered 10.42.0.96 from 10.42.0.1
dhcpcd[3254]: eth0: leased 10.42.0.96 for 3600 seconds
dhcpcd[3254]: eth0: adding route to 10.42.0.0/24
dhcpcd[3254]: eth0: adding default route via 10.42.0.1
dhcpcd[3254]: forked to background, child pid 3307
```
So, as things work as expected (and they did so even after a reboot of the RPi3), I guess that is it, then... |
68,820,711 | For readability purpose, I want to set the value of a string on multiple lines but the result would show as a one ligne. I tried to contact using `+` but it does not work.
By the way, one of the lines (a part of the string) is resolved at apply time.
example:
```
output "variable" {
value = "First part "
+ ", then second part "
+ " and final part."
}
```
and the output.variable will show `"First part, then second part and final part."` | 2021/08/17 | [
"https://Stackoverflow.com/questions/68820711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8569928/"
] | you can use the [join](https://www.terraform.io/docs/language/functions/join.html) function:
```
output "variable" {
value = join("", ["First part ",
", then second part ",
" and final part."])
}
``` | Why don’t you try to concatenate adding a \n character at the end of every variable forming the string? Something like:
```
output “variable” {
value = “${var}\n${var2}\n”
}
``` |
10,632 | I have recently started reading about colour in organic molecules and come across conjugation of pi bonds. My question is pretty short... In transition metal ions I understand colour is caused by molecules jumping between the d sub orbitals as a result of ligand splitting them. The concept of excitation easily applies here. So what I want to know is. How do electrons get excited in a conjugated molecule? | 2014/05/11 | [
"https://chemistry.stackexchange.com/questions/10632",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/4833/"
] | This first picture shows what happens to the molecular orbitals of ethylene if we bring two ethylene molecules (the right and left sides of the molecular orbital vs. energy part of the diagram) close together and form 1,3 butadiene (center of the figure)
The next figure shows the result of adding a third ethylenic group to the molecule and form 1,3,5-hexatriene. Note how in each case the molecular orbitals combine (split) and generate a new set of molecular orbitals; and in each case the separation between the Highest Occupied Molecular Orbital (HOMO) and the Lowest Unoccupied Molecular Orbital (LUMO) decreases. When light is absorbed an electron is promoted from the HOMO to the LUMO. If we make the HOMO-LUMO separation small enough by extending conjugation, we can shift absorbtion into the visible region (longer wavelength, smaller HOMO-LUMO energy separation). We can add other groups too, like cyano, nitro, phenyl, carbonyl, etc. to extend the conjugation in our system.
 | To be able to show some color, the photons with wave length within visible light region have to be absorbed as the energy to make electron jump from lower orbital to higher orbital.
In the case of conjugated organic compound, electrons jumps between $\pi$ and $\pi^{\*}$ molecular orbitals happen to be within the visible light region. The key is the energy difference, the conjugation system has to be big enough or the energy gap between $\pi$ and $\pi^{\*}$ molecular orbitals is too big and the wave length will be too short to be visible. |
9,764,401 | how can I modify the user:group ownership of a s3fs mounted bucket?
I have a git installation that I would essentially like to store on my Amazon S3 account in a bucket, and then using Sparkleshare, via my web host, sync this data accross multiple machines.
**- I Have set up the sparkleshare to successfully sync three machines. Works like a charm.**
* This is syncing to a folder at /home/git/dropbox No problems there.
* I want the sync folder to me a mounted S3 bucket though
* I can mount the buckets right next to that dropbox folder, but no love changing ownership to git:git
Problem: when you create the mount with root:root user, only that user has access to the bucket.
I tried to create the mount with S3FS logged in as the GIT user, but no luck, it still mounts and assigns permissions as the root:root user.
Do I uninstall S3FS and re-install using the GIT user?
Any help would be greatly appreciated!
Rick | 2012/03/19 | [
"https://Stackoverflow.com/questions/9764401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/682223/"
] | You simply want to mount it as that user. You can also automount it by adding the uid and gid that you want it mounted as. For example, your /etc/fstab would have an entry such as the following:
```
s3fs#s3bucketName /mnt/point fuse defaults,noatime,allow_other,uid=500,gid=48,use_cache=/tmp,default_acl=public-read 0 0
``` | On Ubuntu I am finding that whichever user does the s3fs mount will own it, even though ls will show the owner as root:root, and in fact root cannot use it. When you did the mount as the git user are you sure you could not write to it? |
9,764,401 | how can I modify the user:group ownership of a s3fs mounted bucket?
I have a git installation that I would essentially like to store on my Amazon S3 account in a bucket, and then using Sparkleshare, via my web host, sync this data accross multiple machines.
**- I Have set up the sparkleshare to successfully sync three machines. Works like a charm.**
* This is syncing to a folder at /home/git/dropbox No problems there.
* I want the sync folder to me a mounted S3 bucket though
* I can mount the buckets right next to that dropbox folder, but no love changing ownership to git:git
Problem: when you create the mount with root:root user, only that user has access to the bucket.
I tried to create the mount with S3FS logged in as the GIT user, but no luck, it still mounts and assigns permissions as the root:root user.
Do I uninstall S3FS and re-install using the GIT user?
Any help would be greatly appreciated!
Rick | 2012/03/19 | [
"https://Stackoverflow.com/questions/9764401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/682223/"
] | On Ubuntu I am finding that whichever user does the s3fs mount will own it, even though ls will show the owner as root:root, and in fact root cannot use it. When you did the mount as the git user are you sure you could not write to it? | 1.69 seems to have fixed a uid/gid issue
<https://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.69.tar.gz&can=2&q=> |
9,764,401 | how can I modify the user:group ownership of a s3fs mounted bucket?
I have a git installation that I would essentially like to store on my Amazon S3 account in a bucket, and then using Sparkleshare, via my web host, sync this data accross multiple machines.
**- I Have set up the sparkleshare to successfully sync three machines. Works like a charm.**
* This is syncing to a folder at /home/git/dropbox No problems there.
* I want the sync folder to me a mounted S3 bucket though
* I can mount the buckets right next to that dropbox folder, but no love changing ownership to git:git
Problem: when you create the mount with root:root user, only that user has access to the bucket.
I tried to create the mount with S3FS logged in as the GIT user, but no luck, it still mounts and assigns permissions as the root:root user.
Do I uninstall S3FS and re-install using the GIT user?
Any help would be greatly appreciated!
Rick | 2012/03/19 | [
"https://Stackoverflow.com/questions/9764401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/682223/"
] | You simply want to mount it as that user. You can also automount it by adding the uid and gid that you want it mounted as. For example, your /etc/fstab would have an entry such as the following:
```
s3fs#s3bucketName /mnt/point fuse defaults,noatime,allow_other,uid=500,gid=48,use_cache=/tmp,default_acl=public-read 0 0
``` | 1.69 seems to have fixed a uid/gid issue
<https://code.google.com/p/s3fs/downloads/detail?name=s3fs-1.69.tar.gz&can=2&q=> |
12,532,398 | I'm trying for hours now to get the following working:
I'd like to have three divs in an container div.
1. They need to be stacked vertically (topDiv, middleDiv, bottomDiv)
2. the topDiv should be 20px tall (fixed)
3. the middleDiv should take the rest of space left (like \* in a table or \vfill in LaTeX)
4. the bottomDiv should be 50px tall (fixed)
that does not sound so hard does it? I just can't figure it out!
thanks for your help. | 2012/09/21 | [
"https://Stackoverflow.com/questions/12532398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638344/"
] | something like this may work for you:
<http://jsfiddle.net/nCrEc/1/>
edit:
this version scales with the browser window
<http://jsfiddle.net/nCrEc/2/>
html:
```
<div class="con">
<div class="top"></div>
<div class="middle"></div>
<div class="bottom"></div>
</div>
```
css:
```
.con{width:200px; top:0;bottom:0;left:0; position:absolute;background:#ff0;}
.top{width:200px;height:20px;position:absolute;top:0;left:0;background:#f60;}
.bottom{width:200px;height:50px;position:absolute;bottom:0;left:0;background:#f60;}
.middle{width:200px;min-height:1px; position:absolute;bottom:50px;top:20px;left:0;background:#06f;}
``` | I did something very similar on this website:
<http://www.probusllandudno.org.uk/>
click the dinners 2012 link (and, if using FF web developer, u can use view generated source)
The main points are putting the divs in order in the doc, assigning fixed width (in my case) or width=100%, top and botom divs have fixed height see the css
ADDENDUM
Another response offers a sophisticated solution that covers issues around most specifically padding.. You haven't specified how your content might influence the solution. My web page is just centered text |
12,532,398 | I'm trying for hours now to get the following working:
I'd like to have three divs in an container div.
1. They need to be stacked vertically (topDiv, middleDiv, bottomDiv)
2. the topDiv should be 20px tall (fixed)
3. the middleDiv should take the rest of space left (like \* in a table or \vfill in LaTeX)
4. the bottomDiv should be 50px tall (fixed)
that does not sound so hard does it? I just can't figure it out!
thanks for your help. | 2012/09/21 | [
"https://Stackoverflow.com/questions/12532398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638344/"
] | something like this may work for you:
<http://jsfiddle.net/nCrEc/1/>
edit:
this version scales with the browser window
<http://jsfiddle.net/nCrEc/2/>
html:
```
<div class="con">
<div class="top"></div>
<div class="middle"></div>
<div class="bottom"></div>
</div>
```
css:
```
.con{width:200px; top:0;bottom:0;left:0; position:absolute;background:#ff0;}
.top{width:200px;height:20px;position:absolute;top:0;left:0;background:#f60;}
.bottom{width:200px;height:50px;position:absolute;bottom:0;left:0;background:#f60;}
.middle{width:200px;min-height:1px; position:absolute;bottom:50px;top:20px;left:0;background:#06f;}
``` | It's easy with [Flexbox](http://dev.w3.org/csswg/css3-flexbox/#flex-direction-property) but it is still being developed and only really works in Chrome at the moment.
Otherwise, you can use [`* {box-sizing: border-box;}`](http://paulirish.com/2012/box-sizing-border-box-ftw/) to make your life easier. There is even an [IE6-7 polyfill](http://html5please.com/#box-sizing) if supporting old browsers is important to you.
Here is an [example](http://codepen.io/anon/pen/LAlxd).
```
*{-moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; margin:0; padding:0;}
html,body{width:100%; height:100%;}
div{width:100%; background:salmon;}
.middle {background:lightblue; height:100%; padding:100px 0;}
.top, .bottom {height:100px; position: absolute; left:0;}
.top {top:0; }
.bottom {bottom: 0;}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.