Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 1
70k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
115k
| response_k
stringlengths 0
60.5k
|
---|---|---|---|---|---|
143,774 | So, I installed the Android SDK, Eclipse, and the ADT. Upon firing up Eclipse the first time after setting up the ADT, this error popped up:
```
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
```
I'm not quite sure how this is. Feels weird that there's a missing library there. I'm using Ubuntu 12.04. No adb is a pretty big blow as an Android developer. How do I fix? | 2012/05/29 | [
"https://askubuntu.com/questions/143774",
"https://askubuntu.com",
"https://askubuntu.com/users/27601/"
] | Android SDK platform tools requires `ia32-libs`, which itself is a big package of libraries:
```
sudo apt-get install ia32-libs
```
---
**UPDATE:**
Below are the [latest instructions from Google](https://developer.android.com/sdk/installing/index.html?pkg=tools) on how to install Android SDK library dependencies:
>
> If you are running a 64-bit distribution on your development machine, you need to install additional packages first. For Ubuntu 13.10 (Saucy Salamander) and above, install the `libncurses5:i386`, `libstdc++6:i386`, and `zlib1g:i386` packages using `apt-get`:
>
>
>
> ```
> sudo dpkg --add-architecture i386
> sudo apt-get update
> sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
>
> ```
>
> For earlier versions of Ubuntu, install the `ia32-libs` package using `apt-get`:
>
>
>
> ```
> apt-get install ia32-libs
>
> ```
>
> | This solved my issue: <http://blog.timmattison.com/archives/2011/11/02/how-to-install-googles-android-eclipse-plugin-and-or-adb-on-64-bit-debian-ubuntu/> |
143,774 | So, I installed the Android SDK, Eclipse, and the ADT. Upon firing up Eclipse the first time after setting up the ADT, this error popped up:
```
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
```
I'm not quite sure how this is. Feels weird that there's a missing library there. I'm using Ubuntu 12.04. No adb is a pretty big blow as an Android developer. How do I fix? | 2012/05/29 | [
"https://askubuntu.com/questions/143774",
"https://askubuntu.com",
"https://askubuntu.com/users/27601/"
] | Android SDK platform tools requires `ia32-libs`, which itself is a big package of libraries:
```
sudo apt-get install ia32-libs
```
---
**UPDATE:**
Below are the [latest instructions from Google](https://developer.android.com/sdk/installing/index.html?pkg=tools) on how to install Android SDK library dependencies:
>
> If you are running a 64-bit distribution on your development machine, you need to install additional packages first. For Ubuntu 13.10 (Saucy Salamander) and above, install the `libncurses5:i386`, `libstdc++6:i386`, and `zlib1g:i386` packages using `apt-get`:
>
>
>
> ```
> sudo dpkg --add-architecture i386
> sudo apt-get update
> sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
>
> ```
>
> For earlier versions of Ubuntu, install the `ia32-libs` package using `apt-get`:
>
>
>
> ```
> apt-get install ia32-libs
>
> ```
>
> | If `libncurses` is not installed then install it and try again.
```
sudo apt-get install libncurses5
``` |
143,774 | So, I installed the Android SDK, Eclipse, and the ADT. Upon firing up Eclipse the first time after setting up the ADT, this error popped up:
```
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
```
I'm not quite sure how this is. Feels weird that there's a missing library there. I'm using Ubuntu 12.04. No adb is a pretty big blow as an Android developer. How do I fix? | 2012/05/29 | [
"https://askubuntu.com/questions/143774",
"https://askubuntu.com",
"https://askubuntu.com/users/27601/"
] | You need library ncurses 32 bit version installed in your system
```
sudo apt-get install libncurses5:i386
```
In addition to libncurses5, you may require libstdc++6.
```
sudo apt-get install libstdc++6:i386
```
With the command
```
sudo apt-get install ia32-libs
```
You install a lot of libraries that is not useful to solve your problem. | ```
sudo apt-get install ia32-libs
```
Solved my problem. This libraries collection can be useful for a lot of developer's programs also. |
143,774 | So, I installed the Android SDK, Eclipse, and the ADT. Upon firing up Eclipse the first time after setting up the ADT, this error popped up:
```
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
```
I'm not quite sure how this is. Feels weird that there's a missing library there. I'm using Ubuntu 12.04. No adb is a pretty big blow as an Android developer. How do I fix? | 2012/05/29 | [
"https://askubuntu.com/questions/143774",
"https://askubuntu.com",
"https://askubuntu.com/users/27601/"
] | Android SDK platform tools requires `ia32-libs`, which itself is a big package of libraries:
```
sudo apt-get install ia32-libs
```
---
**UPDATE:**
Below are the [latest instructions from Google](https://developer.android.com/sdk/installing/index.html?pkg=tools) on how to install Android SDK library dependencies:
>
> If you are running a 64-bit distribution on your development machine, you need to install additional packages first. For Ubuntu 13.10 (Saucy Salamander) and above, install the `libncurses5:i386`, `libstdc++6:i386`, and `zlib1g:i386` packages using `apt-get`:
>
>
>
> ```
> sudo dpkg --add-architecture i386
> sudo apt-get update
> sudo apt-get install libncurses5:i386 libstdc++6:i386 zlib1g:i386
>
> ```
>
> For earlier versions of Ubuntu, install the `ia32-libs` package using `apt-get`:
>
>
>
> ```
> apt-get install ia32-libs
>
> ```
>
> | I am running Ubuntu 13.10 and I was having the same problem. I tried adding `ia32libs` and it didn't recognize the repo, and recommended a couple others like `lib32z1`. Neither worked. Then I saw this comment,
You need library ncurses 32 bit version installed in your system
```
sudo apt-get install libncurses5:i386
```
In addition to libncurses5, you may require libstdc++6.
```
sudo apt-get install libstdc++6:i386
```
This worked great for me. :) |
143,774 | So, I installed the Android SDK, Eclipse, and the ADT. Upon firing up Eclipse the first time after setting up the ADT, this error popped up:
```
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] 'adb version' failed!
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
[2012-05-29 12:11:06 - adb] Failed to parse the output of 'adb version':
Standard Output was:
Error Output was:
/home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurses.so.5: cannot open shared object file: No such file or directory
```
I'm not quite sure how this is. Feels weird that there's a missing library there. I'm using Ubuntu 12.04. No adb is a pretty big blow as an Android developer. How do I fix? | 2012/05/29 | [
"https://askubuntu.com/questions/143774",
"https://askubuntu.com",
"https://askubuntu.com/users/27601/"
] | I am running Ubuntu 13.10 and I was having the same problem. I tried adding `ia32libs` and it didn't recognize the repo, and recommended a couple others like `lib32z1`. Neither worked. Then I saw this comment,
You need library ncurses 32 bit version installed in your system
```
sudo apt-get install libncurses5:i386
```
In addition to libncurses5, you may require libstdc++6.
```
sudo apt-get install libstdc++6:i386
```
This worked great for me. :) | For me `adb` was missing regardless of all activities.
Then I noticed useful hint shown in the terminal, which I've tried:
>
> `sudo apt-get install android-tools-adb`
>
>
>
After that, `adb` command was installed and now I can install on emulated devices whatever I want. |
149,592 | Till now I have used a following flow for training a random forest model.
```
create 10 folds of data.
for each fold i:
- use ith fold as validation data
- use remaining 9 folds as training data
- apply normalization on training and validation data
- # apply feature selection on training data
- # select same features from validation data
- train random forest on training data
- predict values for validation data
combine all predictions.
```
Now I want to do feature selection using `varImp()` function. I am confused as it is said that `varImp` itself trains a model on training data to find out best set of features.
How should I use `varImp` to get important features (say using `partial least squares`) and then again apply training model on training data? | 2015/05/04 | [
"https://stats.stackexchange.com/questions/149592",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/46224/"
] | This sounds a lot like recursive feature elimination. See the [caret help page for feature selection](http://topepo.github.io/caret/featureselection.html). | I'd suggest removing the least important/lowest varImp features using this criterion, then re-runing test and validation sets. In some cases, but not always, this would increase your success. Note that normalization is generally not recommended for this approach and may in fact result in a loss of valuable signals. |
4,487,189 | Taking the combintorialist point of view that a cycle of a permutation$~\sigma$ of a finite set $S$ is an orbit of the action of the subgroup generated by$~\sigma$ in its (natural) action on$~S$, it is known that whenever $S$ admits $k$-cycles at all (so $0<k\leq n$ where $n$ is the size of $S$), the expected number of $k$-cycles of$~\sigma$ where $\sigma$ is chosen uniformly at random among all permutations of$~S$, is precisely$~\frac1k$. Stated differently, the statistic "number of $k$-cycles" takes an average value of$~\frac1k$ when $\sigma$ runs over all permutations of$~S$. I am looking for nice, intuitive, transparent, proofs of this fact, notably where the fraction$~\frac1k$ comes about naturally, preferably as the probability of obtaining a specific value when choosing an element uniformly from a $k$-element set. While I know a few easy computations that prove the result, none I've seen so far have achieved this highest standard, though some arrive at the fraction after some very basic cancellations.
The cases $k=1$ (the expected number of fixed points of a permutation is precisely $1$) and $k=n$ (there are $(n-1)!$ distinct cyclic permutations of $S$, which is $\frac1n$ of all permutations) are very well known and with easy proofs, but I would like a proof that covers all allowed values of $k$ in a uniform manner.
I've seen quite a few questions on this site that come close to this one, but few state the result in isolation and none specifically ask for elegant arguments, so I don't feel this question is truly a duplicate of any of them.
---
This question was inspired by watching [this video](https://www.youtube.com/watch?v=iSNsgj1OCLA&t=706s) (with a rather click-bait title) where the deduction of the case for $k=n$ (from 8:17 on) is followed by the irrefutable argument "this is a general result" (implying it's validity for all $k$) with no mention of expectation (for $k=n$ the only possible numbers of cycles are $0$ and $1$, so the expected value is just a probability) and no explanation whatsoever. | 2022/07/06 | [
"https://math.stackexchange.com/questions/4487189",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/18880/"
] | One argument is that looking at a particular single element, the probability that the cycle that element is in is of length $k$ is $\frac1n$. (A *seats on a plane* argument justifies this.)
So the expected number of elements finding themselves in a cycle of length $k$ is $n\left(\frac1n\right)=1$, by linearity of expectation.
Since cycles of length $k$ have $k$ elements, the expected number of cycles of length $k$ is $\frac1k$. | So here is a straightforward approach (which a colleague suggested to me), in which the fraction $\frac1k$ unfortunately only comes out after simplification at the end. The idea is to simply count all distinct pairs of a permutation$~\sigma$ of $S$ and a specific $k$-cycle (a set of size $k$) that occurs as orbit for$~\sigma$; this number should turn out to be $\frac{n!}k$ which then proves that the expected number of $k$-cycles associated to a random$~\sigma$ is$~\frac1k$. Start with enumerating the possible $k$-subsets of$~S$ (candidates for orbits) of which there are obviously $\binom nk$. Then for each such $k$-subset $P$, enumerate the permutations for which $P$ occurs as an orbit: a cyclic permutation of $P$ can be chosen in $(k-1)!$ ways (as per the result mentioned in OP) while for the remaining $n-k$ elements an unconstrained permutation can be chosen in $(n-k)!$ ways (obviously independently of the choice of $P$). Multiply for the total number of pairs:
$$
\binom nk\times(k-1)!\times(n-k)!
= \frac{n!\times(k-1)!\times(n-k)!}{k!\times(n-k)!}
= \frac{n!}k
$$
as desired. Note that the condition $k\leq n$, which necessarily has to be used somewhere, is implicitly invoked when rewriting $\binom nk=\frac{n!}{k!\times(n-k)!}$; when the condition is not satisfied the left hand side is $0$ while $(n-k)!$ in the right hand side is not defined (of course the argument that there are $(n-k)!$ permutations of the "remaining" elements also goes awry). And to be complete, the presence of $(k-1)!$ makes the argument fail for $k=0$, and indeed the statement that a $k$-set admits $(k-1)!$ cyclic permutations needs the hypothesis $k>0$. |
4,487,189 | Taking the combintorialist point of view that a cycle of a permutation$~\sigma$ of a finite set $S$ is an orbit of the action of the subgroup generated by$~\sigma$ in its (natural) action on$~S$, it is known that whenever $S$ admits $k$-cycles at all (so $0<k\leq n$ where $n$ is the size of $S$), the expected number of $k$-cycles of$~\sigma$ where $\sigma$ is chosen uniformly at random among all permutations of$~S$, is precisely$~\frac1k$. Stated differently, the statistic "number of $k$-cycles" takes an average value of$~\frac1k$ when $\sigma$ runs over all permutations of$~S$. I am looking for nice, intuitive, transparent, proofs of this fact, notably where the fraction$~\frac1k$ comes about naturally, preferably as the probability of obtaining a specific value when choosing an element uniformly from a $k$-element set. While I know a few easy computations that prove the result, none I've seen so far have achieved this highest standard, though some arrive at the fraction after some very basic cancellations.
The cases $k=1$ (the expected number of fixed points of a permutation is precisely $1$) and $k=n$ (there are $(n-1)!$ distinct cyclic permutations of $S$, which is $\frac1n$ of all permutations) are very well known and with easy proofs, but I would like a proof that covers all allowed values of $k$ in a uniform manner.
I've seen quite a few questions on this site that come close to this one, but few state the result in isolation and none specifically ask for elegant arguments, so I don't feel this question is truly a duplicate of any of them.
---
This question was inspired by watching [this video](https://www.youtube.com/watch?v=iSNsgj1OCLA&t=706s) (with a rather click-bait title) where the deduction of the case for $k=n$ (from 8:17 on) is followed by the irrefutable argument "this is a general result" (implying it's validity for all $k$) with no mention of expectation (for $k=n$ the only possible numbers of cycles are $0$ and $1$, so the expected value is just a probability) and no explanation whatsoever. | 2022/07/06 | [
"https://math.stackexchange.com/questions/4487189",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/18880/"
] | So here is a straightforward approach (which a colleague suggested to me), in which the fraction $\frac1k$ unfortunately only comes out after simplification at the end. The idea is to simply count all distinct pairs of a permutation$~\sigma$ of $S$ and a specific $k$-cycle (a set of size $k$) that occurs as orbit for$~\sigma$; this number should turn out to be $\frac{n!}k$ which then proves that the expected number of $k$-cycles associated to a random$~\sigma$ is$~\frac1k$. Start with enumerating the possible $k$-subsets of$~S$ (candidates for orbits) of which there are obviously $\binom nk$. Then for each such $k$-subset $P$, enumerate the permutations for which $P$ occurs as an orbit: a cyclic permutation of $P$ can be chosen in $(k-1)!$ ways (as per the result mentioned in OP) while for the remaining $n-k$ elements an unconstrained permutation can be chosen in $(n-k)!$ ways (obviously independently of the choice of $P$). Multiply for the total number of pairs:
$$
\binom nk\times(k-1)!\times(n-k)!
= \frac{n!\times(k-1)!\times(n-k)!}{k!\times(n-k)!}
= \frac{n!}k
$$
as desired. Note that the condition $k\leq n$, which necessarily has to be used somewhere, is implicitly invoked when rewriting $\binom nk=\frac{n!}{k!\times(n-k)!}$; when the condition is not satisfied the left hand side is $0$ while $(n-k)!$ in the right hand side is not defined (of course the argument that there are $(n-k)!$ permutations of the "remaining" elements also goes awry). And to be complete, the presence of $(k-1)!$ makes the argument fail for $k=0$, and indeed the statement that a $k$-set admits $(k-1)!$ cyclic permutations needs the hypothesis $k>0$. | Assume $n\ge k$. We will be working in the symmetric group $S\_n$ of permutations of $[n]=\{1,2,...,n\}$.
Observation 1: Given a fixed $k$-cycle, it appears in exactly $(n-k)!$ elements of $S\_n$. (This comes from all the permutations of the remaining $n-k$ elements of $[n]$.)
Observation 2: There are ${n\choose k}\cdot \frac{k!}{k}$ cycles of length $k$ that can be made with elements of $[n]$. (Choose $k$ elements of $[n]$ to form a $k$-cycle, and then choose a cyclic permutation of these elements.)
So counting over all of $S\_n$, there will be a total of $(n-k)!\cdot {n\choose k}\cdot \frac{k!}{k}=\frac{n!}{k}$ cycles of length $k$ appearing in all of $S\_n$.
So the expected number of cycles of length $k$ appearing in elements of $S\_n$ is given by $\frac{\frac{n!}{k}}{{n!}}=\frac1k$
This value of $\frac1k$ comes about because a cycle of length $k$ can be expressed in $k$ different ways (depending on where you want to 'start' the cycle). |
4,487,189 | Taking the combintorialist point of view that a cycle of a permutation$~\sigma$ of a finite set $S$ is an orbit of the action of the subgroup generated by$~\sigma$ in its (natural) action on$~S$, it is known that whenever $S$ admits $k$-cycles at all (so $0<k\leq n$ where $n$ is the size of $S$), the expected number of $k$-cycles of$~\sigma$ where $\sigma$ is chosen uniformly at random among all permutations of$~S$, is precisely$~\frac1k$. Stated differently, the statistic "number of $k$-cycles" takes an average value of$~\frac1k$ when $\sigma$ runs over all permutations of$~S$. I am looking for nice, intuitive, transparent, proofs of this fact, notably where the fraction$~\frac1k$ comes about naturally, preferably as the probability of obtaining a specific value when choosing an element uniformly from a $k$-element set. While I know a few easy computations that prove the result, none I've seen so far have achieved this highest standard, though some arrive at the fraction after some very basic cancellations.
The cases $k=1$ (the expected number of fixed points of a permutation is precisely $1$) and $k=n$ (there are $(n-1)!$ distinct cyclic permutations of $S$, which is $\frac1n$ of all permutations) are very well known and with easy proofs, but I would like a proof that covers all allowed values of $k$ in a uniform manner.
I've seen quite a few questions on this site that come close to this one, but few state the result in isolation and none specifically ask for elegant arguments, so I don't feel this question is truly a duplicate of any of them.
---
This question was inspired by watching [this video](https://www.youtube.com/watch?v=iSNsgj1OCLA&t=706s) (with a rather click-bait title) where the deduction of the case for $k=n$ (from 8:17 on) is followed by the irrefutable argument "this is a general result" (implying it's validity for all $k$) with no mention of expectation (for $k=n$ the only possible numbers of cycles are $0$ and $1$, so the expected value is just a probability) and no explanation whatsoever. | 2022/07/06 | [
"https://math.stackexchange.com/questions/4487189",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/18880/"
] | So here is a straightforward approach (which a colleague suggested to me), in which the fraction $\frac1k$ unfortunately only comes out after simplification at the end. The idea is to simply count all distinct pairs of a permutation$~\sigma$ of $S$ and a specific $k$-cycle (a set of size $k$) that occurs as orbit for$~\sigma$; this number should turn out to be $\frac{n!}k$ which then proves that the expected number of $k$-cycles associated to a random$~\sigma$ is$~\frac1k$. Start with enumerating the possible $k$-subsets of$~S$ (candidates for orbits) of which there are obviously $\binom nk$. Then for each such $k$-subset $P$, enumerate the permutations for which $P$ occurs as an orbit: a cyclic permutation of $P$ can be chosen in $(k-1)!$ ways (as per the result mentioned in OP) while for the remaining $n-k$ elements an unconstrained permutation can be chosen in $(n-k)!$ ways (obviously independently of the choice of $P$). Multiply for the total number of pairs:
$$
\binom nk\times(k-1)!\times(n-k)!
= \frac{n!\times(k-1)!\times(n-k)!}{k!\times(n-k)!}
= \frac{n!}k
$$
as desired. Note that the condition $k\leq n$, which necessarily has to be used somewhere, is implicitly invoked when rewriting $\binom nk=\frac{n!}{k!\times(n-k)!}$; when the condition is not satisfied the left hand side is $0$ while $(n-k)!$ in the right hand side is not defined (of course the argument that there are $(n-k)!$ permutations of the "remaining" elements also goes awry). And to be complete, the presence of $(k-1)!$ makes the argument fail for $k=0$, and indeed the statement that a $k$-set admits $(k-1)!$ cyclic permutations needs the hypothesis $k>0$. | This bijective proof avoids the use of expectation, it is purely combinatorial:
We will show a bijection between the set $S$ of permutations and the set $\{1,2,\dots,k\}\times T$, where $T$ is the set of occurrences of $k$-cycles in $S$. Hence the number of occurrences of $k$-cycles divided by the number of permutations is $1/k$ as stated. The bijection is really simple, we just need to be careful with notation to make it clear.
The elements of $T$ are the pairs $(\tau,\sigma)$, meaning that $\tau$ is a $k$-cycle in the permutation $\sigma$. We'll adopt the usual cycle notation $\tau=(i\_1\,i\_2\, \dots \,i\_k)$ but the order notation $\sigma=(\sigma\_1,\sigma\_2, \dots, \sigma\_n)$ instead. That is, if these form $(\tau,\sigma)\in T$ then $\sigma\_{i\_1}=i\_2, \sigma\_{i\_2}=i\_3, \dots, \sigma\_{i\_k}=i\_1$. If, in the expression of $\tau$, $i\_1$ is the minimum of its $k$ elements we'll say it is in *primal* form).
For instance, for $n=6$ we have
$$(\tau,\sigma)\in T \quad {\rm for} \quad \tau=(2\, 4\, 6\, 3) \ {\rm and\ } \sigma=(5,4,2,6,1,3)\,,$$
and note that $\tau$ is in primal form.
Then we define our bijection as follows: for $\tau=(i\_1\,i\_2\, \dots \,i\_k)$ in primal form and $(\tau,\sigma)\in T$, the image of $(j,(\tau,\sigma))$ is $\tilde\sigma = (i\_j, i\_{j+1},\dots,i\_{j-1},\omega)\in S$, where $\omega$ is the list of the numbers not in $\tau$, keeping their relative order (and of course $j-1$ means $k$ if $j=1$).
For example, for $n=6$ and $\tau$ and $\sigma$ the same as before,
$$
(1,(\tau,\sigma)) \mapsto \tilde\sigma = (2,4,6,3,5,1) \quad {\rm and}\quad (3,(\tau,\sigma)) \mapsto \tilde\sigma = (6,3,2,4,5,1)\,.
$$
It is clear that the following is the inverse map: for $\tilde\sigma=(\tilde\sigma\_1, \tilde\sigma\_2, \dots, \tilde\sigma\_k,\omega)$ (where $\omega$ is the $n-k$ remaining numbers listed in any order) we get $(j,(\tau,\sigma))\in \{1,2,\dots, k\}\times T$, where $\tau=(\tilde\sigma\_1\,\tilde\sigma\_2\,\dots\,\tilde\sigma\_k)$, $j$ indicates the position of $\tilde\sigma\_1$ in the primal form of $\tau$, and $\sigma$ is the permutation which has $\tau$ as a cycle and the terms of $\omega$ are placed in the remaining positions, keeping their relative order.
For instance, if $n=7$, $k=3$ and $\tilde\sigma = (4,6,2,1,7,3,5)$ then $\tau=(4\,6\,2)=(2\,4\,6)$, so $j=2$ and $\sigma=(1,4,7,6,3,2,5)$.
Finally, please note that the special case $k=1$ (the average number of fixed points is 1 regardless of $n$) is much simpler to express. |
4,487,189 | Taking the combintorialist point of view that a cycle of a permutation$~\sigma$ of a finite set $S$ is an orbit of the action of the subgroup generated by$~\sigma$ in its (natural) action on$~S$, it is known that whenever $S$ admits $k$-cycles at all (so $0<k\leq n$ where $n$ is the size of $S$), the expected number of $k$-cycles of$~\sigma$ where $\sigma$ is chosen uniformly at random among all permutations of$~S$, is precisely$~\frac1k$. Stated differently, the statistic "number of $k$-cycles" takes an average value of$~\frac1k$ when $\sigma$ runs over all permutations of$~S$. I am looking for nice, intuitive, transparent, proofs of this fact, notably where the fraction$~\frac1k$ comes about naturally, preferably as the probability of obtaining a specific value when choosing an element uniformly from a $k$-element set. While I know a few easy computations that prove the result, none I've seen so far have achieved this highest standard, though some arrive at the fraction after some very basic cancellations.
The cases $k=1$ (the expected number of fixed points of a permutation is precisely $1$) and $k=n$ (there are $(n-1)!$ distinct cyclic permutations of $S$, which is $\frac1n$ of all permutations) are very well known and with easy proofs, but I would like a proof that covers all allowed values of $k$ in a uniform manner.
I've seen quite a few questions on this site that come close to this one, but few state the result in isolation and none specifically ask for elegant arguments, so I don't feel this question is truly a duplicate of any of them.
---
This question was inspired by watching [this video](https://www.youtube.com/watch?v=iSNsgj1OCLA&t=706s) (with a rather click-bait title) where the deduction of the case for $k=n$ (from 8:17 on) is followed by the irrefutable argument "this is a general result" (implying it's validity for all $k$) with no mention of expectation (for $k=n$ the only possible numbers of cycles are $0$ and $1$, so the expected value is just a probability) and no explanation whatsoever. | 2022/07/06 | [
"https://math.stackexchange.com/questions/4487189",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/18880/"
] | One argument is that looking at a particular single element, the probability that the cycle that element is in is of length $k$ is $\frac1n$. (A *seats on a plane* argument justifies this.)
So the expected number of elements finding themselves in a cycle of length $k$ is $n\left(\frac1n\right)=1$, by linearity of expectation.
Since cycles of length $k$ have $k$ elements, the expected number of cycles of length $k$ is $\frac1k$. | Here is a proof that exploits linearity of expectation, which is something that certainly comes to mind. I'll fix some value $s\in S$ and $k\in\{1,\ldots,n\}$, and let $\def\Sym{\operatorname{Sym}}\Sym(S)$ denote the set of permutations of $S$. Let $\chi\_{s,k}:M\to\{0,1\}$ be the characteristic function of the condition "the cycle of the permutation containing $s$ has length$~k$". The first step is to show that the expected value of$~\chi\_{s,k}$, viewed as a random variable on $\Sym(S)$ with uniform probability, is$~\frac1n$, independently of $s$ and of$~k$.
At this point I need to fix an order on $S$, which will allow met to write permutations of $S$ in two-line form; to avoid horribly complicated notation I will just assume that $S=\{1,\ldots,n\}$ (but still think of $s$ as element of $S$ and of $k$ as a number, a potential cycle length). Now
consider the bijection $f:\Sym(S)\to\Sym(S)$ defined as follows. Given $\sigma=({1\atop\sigma\_1}~\cdots~{n\atop\sigma\_n})$ in two-line form, locate the position $l=\sigma^{-1}\_s$ where $s$ occurs in the second line, and form the product$~\pi$ of the cycle $(s~\sigma\_1~\sigma\_2~\cdots~\sigma\_{l-1})$ (effectively reading the entry $\sigma\_l=s$ as a right parenthesis) and the permutation of the remaining entries $\{\sigma\_{l+1},\ldots,\sigma\_n\}$ with $2$-line form $({e\_1\atop\sigma\_{l+1}}~\cdots~{e\_{n-l}\atop\sigma\_n}))$ where $\{e\_1,\ldots,e\_{n-l}\}=\{\sigma\_{l+1},\ldots,\sigma\_n\}$ and $e\_1<\ldots<e\_{n-l}$ (which is a complicated way of saying the permutation of those elements suggested by the sequence $(\sigma\_{l+1},\ldots,\sigma\_n)$); now $f(\sigma)=\pi$. It is not hard to see that $f$ is invertible and therefore a bijection. Also it is clear that $\chi\_{s,k}(f(\sigma))$ is the characteristic function of the event $\sigma^{-1}\_s=k$, or $\sigma\_k=s$, and since $\sigma\_k$ could be any value in $S$ with equal probability, the average (or expected) value of that function is$~\frac1n$.
Now we apply linearity of expectation, forming the sum $\sum\_{s\in S}\chi\_{s,k}$ of the statistics (or random variables if you prefer) $\chi\_{s,k}$ for all $n$ values of $s$; clearly one gets that the expected value of this sum is $n\times\frac1n=1$, independently of $k$. But is is also clear that $\sum\_{s\in S}\chi\_{s,k}(\sigma)$ is the size of the union of $k$-cycles for$~\sigma$, or $k$ times the number of $k$-cycles for$~\sigma$; the expected value of that number is than $\frac1k$ QED.
---
This is of course the same answer as that of Henry, but written by someone who refuses to be concise (or as I would prefer to say, who refuses to sacrifice precision to conciseness). It was also strongly inspired by [this answer by joriki](https://math.stackexchange.com/a/165412/18880) to a closely related question. |
4,487,189 | Taking the combintorialist point of view that a cycle of a permutation$~\sigma$ of a finite set $S$ is an orbit of the action of the subgroup generated by$~\sigma$ in its (natural) action on$~S$, it is known that whenever $S$ admits $k$-cycles at all (so $0<k\leq n$ where $n$ is the size of $S$), the expected number of $k$-cycles of$~\sigma$ where $\sigma$ is chosen uniformly at random among all permutations of$~S$, is precisely$~\frac1k$. Stated differently, the statistic "number of $k$-cycles" takes an average value of$~\frac1k$ when $\sigma$ runs over all permutations of$~S$. I am looking for nice, intuitive, transparent, proofs of this fact, notably where the fraction$~\frac1k$ comes about naturally, preferably as the probability of obtaining a specific value when choosing an element uniformly from a $k$-element set. While I know a few easy computations that prove the result, none I've seen so far have achieved this highest standard, though some arrive at the fraction after some very basic cancellations.
The cases $k=1$ (the expected number of fixed points of a permutation is precisely $1$) and $k=n$ (there are $(n-1)!$ distinct cyclic permutations of $S$, which is $\frac1n$ of all permutations) are very well known and with easy proofs, but I would like a proof that covers all allowed values of $k$ in a uniform manner.
I've seen quite a few questions on this site that come close to this one, but few state the result in isolation and none specifically ask for elegant arguments, so I don't feel this question is truly a duplicate of any of them.
---
This question was inspired by watching [this video](https://www.youtube.com/watch?v=iSNsgj1OCLA&t=706s) (with a rather click-bait title) where the deduction of the case for $k=n$ (from 8:17 on) is followed by the irrefutable argument "this is a general result" (implying it's validity for all $k$) with no mention of expectation (for $k=n$ the only possible numbers of cycles are $0$ and $1$, so the expected value is just a probability) and no explanation whatsoever. | 2022/07/06 | [
"https://math.stackexchange.com/questions/4487189",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/18880/"
] | One argument is that looking at a particular single element, the probability that the cycle that element is in is of length $k$ is $\frac1n$. (A *seats on a plane* argument justifies this.)
So the expected number of elements finding themselves in a cycle of length $k$ is $n\left(\frac1n\right)=1$, by linearity of expectation.
Since cycles of length $k$ have $k$ elements, the expected number of cycles of length $k$ is $\frac1k$. | Assume $n\ge k$. We will be working in the symmetric group $S\_n$ of permutations of $[n]=\{1,2,...,n\}$.
Observation 1: Given a fixed $k$-cycle, it appears in exactly $(n-k)!$ elements of $S\_n$. (This comes from all the permutations of the remaining $n-k$ elements of $[n]$.)
Observation 2: There are ${n\choose k}\cdot \frac{k!}{k}$ cycles of length $k$ that can be made with elements of $[n]$. (Choose $k$ elements of $[n]$ to form a $k$-cycle, and then choose a cyclic permutation of these elements.)
So counting over all of $S\_n$, there will be a total of $(n-k)!\cdot {n\choose k}\cdot \frac{k!}{k}=\frac{n!}{k}$ cycles of length $k$ appearing in all of $S\_n$.
So the expected number of cycles of length $k$ appearing in elements of $S\_n$ is given by $\frac{\frac{n!}{k}}{{n!}}=\frac1k$
This value of $\frac1k$ comes about because a cycle of length $k$ can be expressed in $k$ different ways (depending on where you want to 'start' the cycle). |
4,487,189 | Taking the combintorialist point of view that a cycle of a permutation$~\sigma$ of a finite set $S$ is an orbit of the action of the subgroup generated by$~\sigma$ in its (natural) action on$~S$, it is known that whenever $S$ admits $k$-cycles at all (so $0<k\leq n$ where $n$ is the size of $S$), the expected number of $k$-cycles of$~\sigma$ where $\sigma$ is chosen uniformly at random among all permutations of$~S$, is precisely$~\frac1k$. Stated differently, the statistic "number of $k$-cycles" takes an average value of$~\frac1k$ when $\sigma$ runs over all permutations of$~S$. I am looking for nice, intuitive, transparent, proofs of this fact, notably where the fraction$~\frac1k$ comes about naturally, preferably as the probability of obtaining a specific value when choosing an element uniformly from a $k$-element set. While I know a few easy computations that prove the result, none I've seen so far have achieved this highest standard, though some arrive at the fraction after some very basic cancellations.
The cases $k=1$ (the expected number of fixed points of a permutation is precisely $1$) and $k=n$ (there are $(n-1)!$ distinct cyclic permutations of $S$, which is $\frac1n$ of all permutations) are very well known and with easy proofs, but I would like a proof that covers all allowed values of $k$ in a uniform manner.
I've seen quite a few questions on this site that come close to this one, but few state the result in isolation and none specifically ask for elegant arguments, so I don't feel this question is truly a duplicate of any of them.
---
This question was inspired by watching [this video](https://www.youtube.com/watch?v=iSNsgj1OCLA&t=706s) (with a rather click-bait title) where the deduction of the case for $k=n$ (from 8:17 on) is followed by the irrefutable argument "this is a general result" (implying it's validity for all $k$) with no mention of expectation (for $k=n$ the only possible numbers of cycles are $0$ and $1$, so the expected value is just a probability) and no explanation whatsoever. | 2022/07/06 | [
"https://math.stackexchange.com/questions/4487189",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/18880/"
] | One argument is that looking at a particular single element, the probability that the cycle that element is in is of length $k$ is $\frac1n$. (A *seats on a plane* argument justifies this.)
So the expected number of elements finding themselves in a cycle of length $k$ is $n\left(\frac1n\right)=1$, by linearity of expectation.
Since cycles of length $k$ have $k$ elements, the expected number of cycles of length $k$ is $\frac1k$. | This bijective proof avoids the use of expectation, it is purely combinatorial:
We will show a bijection between the set $S$ of permutations and the set $\{1,2,\dots,k\}\times T$, where $T$ is the set of occurrences of $k$-cycles in $S$. Hence the number of occurrences of $k$-cycles divided by the number of permutations is $1/k$ as stated. The bijection is really simple, we just need to be careful with notation to make it clear.
The elements of $T$ are the pairs $(\tau,\sigma)$, meaning that $\tau$ is a $k$-cycle in the permutation $\sigma$. We'll adopt the usual cycle notation $\tau=(i\_1\,i\_2\, \dots \,i\_k)$ but the order notation $\sigma=(\sigma\_1,\sigma\_2, \dots, \sigma\_n)$ instead. That is, if these form $(\tau,\sigma)\in T$ then $\sigma\_{i\_1}=i\_2, \sigma\_{i\_2}=i\_3, \dots, \sigma\_{i\_k}=i\_1$. If, in the expression of $\tau$, $i\_1$ is the minimum of its $k$ elements we'll say it is in *primal* form).
For instance, for $n=6$ we have
$$(\tau,\sigma)\in T \quad {\rm for} \quad \tau=(2\, 4\, 6\, 3) \ {\rm and\ } \sigma=(5,4,2,6,1,3)\,,$$
and note that $\tau$ is in primal form.
Then we define our bijection as follows: for $\tau=(i\_1\,i\_2\, \dots \,i\_k)$ in primal form and $(\tau,\sigma)\in T$, the image of $(j,(\tau,\sigma))$ is $\tilde\sigma = (i\_j, i\_{j+1},\dots,i\_{j-1},\omega)\in S$, where $\omega$ is the list of the numbers not in $\tau$, keeping their relative order (and of course $j-1$ means $k$ if $j=1$).
For example, for $n=6$ and $\tau$ and $\sigma$ the same as before,
$$
(1,(\tau,\sigma)) \mapsto \tilde\sigma = (2,4,6,3,5,1) \quad {\rm and}\quad (3,(\tau,\sigma)) \mapsto \tilde\sigma = (6,3,2,4,5,1)\,.
$$
It is clear that the following is the inverse map: for $\tilde\sigma=(\tilde\sigma\_1, \tilde\sigma\_2, \dots, \tilde\sigma\_k,\omega)$ (where $\omega$ is the $n-k$ remaining numbers listed in any order) we get $(j,(\tau,\sigma))\in \{1,2,\dots, k\}\times T$, where $\tau=(\tilde\sigma\_1\,\tilde\sigma\_2\,\dots\,\tilde\sigma\_k)$, $j$ indicates the position of $\tilde\sigma\_1$ in the primal form of $\tau$, and $\sigma$ is the permutation which has $\tau$ as a cycle and the terms of $\omega$ are placed in the remaining positions, keeping their relative order.
For instance, if $n=7$, $k=3$ and $\tilde\sigma = (4,6,2,1,7,3,5)$ then $\tau=(4\,6\,2)=(2\,4\,6)$, so $j=2$ and $\sigma=(1,4,7,6,3,2,5)$.
Finally, please note that the special case $k=1$ (the average number of fixed points is 1 regardless of $n$) is much simpler to express. |
4,487,189 | Taking the combintorialist point of view that a cycle of a permutation$~\sigma$ of a finite set $S$ is an orbit of the action of the subgroup generated by$~\sigma$ in its (natural) action on$~S$, it is known that whenever $S$ admits $k$-cycles at all (so $0<k\leq n$ where $n$ is the size of $S$), the expected number of $k$-cycles of$~\sigma$ where $\sigma$ is chosen uniformly at random among all permutations of$~S$, is precisely$~\frac1k$. Stated differently, the statistic "number of $k$-cycles" takes an average value of$~\frac1k$ when $\sigma$ runs over all permutations of$~S$. I am looking for nice, intuitive, transparent, proofs of this fact, notably where the fraction$~\frac1k$ comes about naturally, preferably as the probability of obtaining a specific value when choosing an element uniformly from a $k$-element set. While I know a few easy computations that prove the result, none I've seen so far have achieved this highest standard, though some arrive at the fraction after some very basic cancellations.
The cases $k=1$ (the expected number of fixed points of a permutation is precisely $1$) and $k=n$ (there are $(n-1)!$ distinct cyclic permutations of $S$, which is $\frac1n$ of all permutations) are very well known and with easy proofs, but I would like a proof that covers all allowed values of $k$ in a uniform manner.
I've seen quite a few questions on this site that come close to this one, but few state the result in isolation and none specifically ask for elegant arguments, so I don't feel this question is truly a duplicate of any of them.
---
This question was inspired by watching [this video](https://www.youtube.com/watch?v=iSNsgj1OCLA&t=706s) (with a rather click-bait title) where the deduction of the case for $k=n$ (from 8:17 on) is followed by the irrefutable argument "this is a general result" (implying it's validity for all $k$) with no mention of expectation (for $k=n$ the only possible numbers of cycles are $0$ and $1$, so the expected value is just a probability) and no explanation whatsoever. | 2022/07/06 | [
"https://math.stackexchange.com/questions/4487189",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/18880/"
] | Here is a proof that exploits linearity of expectation, which is something that certainly comes to mind. I'll fix some value $s\in S$ and $k\in\{1,\ldots,n\}$, and let $\def\Sym{\operatorname{Sym}}\Sym(S)$ denote the set of permutations of $S$. Let $\chi\_{s,k}:M\to\{0,1\}$ be the characteristic function of the condition "the cycle of the permutation containing $s$ has length$~k$". The first step is to show that the expected value of$~\chi\_{s,k}$, viewed as a random variable on $\Sym(S)$ with uniform probability, is$~\frac1n$, independently of $s$ and of$~k$.
At this point I need to fix an order on $S$, which will allow met to write permutations of $S$ in two-line form; to avoid horribly complicated notation I will just assume that $S=\{1,\ldots,n\}$ (but still think of $s$ as element of $S$ and of $k$ as a number, a potential cycle length). Now
consider the bijection $f:\Sym(S)\to\Sym(S)$ defined as follows. Given $\sigma=({1\atop\sigma\_1}~\cdots~{n\atop\sigma\_n})$ in two-line form, locate the position $l=\sigma^{-1}\_s$ where $s$ occurs in the second line, and form the product$~\pi$ of the cycle $(s~\sigma\_1~\sigma\_2~\cdots~\sigma\_{l-1})$ (effectively reading the entry $\sigma\_l=s$ as a right parenthesis) and the permutation of the remaining entries $\{\sigma\_{l+1},\ldots,\sigma\_n\}$ with $2$-line form $({e\_1\atop\sigma\_{l+1}}~\cdots~{e\_{n-l}\atop\sigma\_n}))$ where $\{e\_1,\ldots,e\_{n-l}\}=\{\sigma\_{l+1},\ldots,\sigma\_n\}$ and $e\_1<\ldots<e\_{n-l}$ (which is a complicated way of saying the permutation of those elements suggested by the sequence $(\sigma\_{l+1},\ldots,\sigma\_n)$); now $f(\sigma)=\pi$. It is not hard to see that $f$ is invertible and therefore a bijection. Also it is clear that $\chi\_{s,k}(f(\sigma))$ is the characteristic function of the event $\sigma^{-1}\_s=k$, or $\sigma\_k=s$, and since $\sigma\_k$ could be any value in $S$ with equal probability, the average (or expected) value of that function is$~\frac1n$.
Now we apply linearity of expectation, forming the sum $\sum\_{s\in S}\chi\_{s,k}$ of the statistics (or random variables if you prefer) $\chi\_{s,k}$ for all $n$ values of $s$; clearly one gets that the expected value of this sum is $n\times\frac1n=1$, independently of $k$. But is is also clear that $\sum\_{s\in S}\chi\_{s,k}(\sigma)$ is the size of the union of $k$-cycles for$~\sigma$, or $k$ times the number of $k$-cycles for$~\sigma$; the expected value of that number is than $\frac1k$ QED.
---
This is of course the same answer as that of Henry, but written by someone who refuses to be concise (or as I would prefer to say, who refuses to sacrifice precision to conciseness). It was also strongly inspired by [this answer by joriki](https://math.stackexchange.com/a/165412/18880) to a closely related question. | Assume $n\ge k$. We will be working in the symmetric group $S\_n$ of permutations of $[n]=\{1,2,...,n\}$.
Observation 1: Given a fixed $k$-cycle, it appears in exactly $(n-k)!$ elements of $S\_n$. (This comes from all the permutations of the remaining $n-k$ elements of $[n]$.)
Observation 2: There are ${n\choose k}\cdot \frac{k!}{k}$ cycles of length $k$ that can be made with elements of $[n]$. (Choose $k$ elements of $[n]$ to form a $k$-cycle, and then choose a cyclic permutation of these elements.)
So counting over all of $S\_n$, there will be a total of $(n-k)!\cdot {n\choose k}\cdot \frac{k!}{k}=\frac{n!}{k}$ cycles of length $k$ appearing in all of $S\_n$.
So the expected number of cycles of length $k$ appearing in elements of $S\_n$ is given by $\frac{\frac{n!}{k}}{{n!}}=\frac1k$
This value of $\frac1k$ comes about because a cycle of length $k$ can be expressed in $k$ different ways (depending on where you want to 'start' the cycle). |
4,487,189 | Taking the combintorialist point of view that a cycle of a permutation$~\sigma$ of a finite set $S$ is an orbit of the action of the subgroup generated by$~\sigma$ in its (natural) action on$~S$, it is known that whenever $S$ admits $k$-cycles at all (so $0<k\leq n$ where $n$ is the size of $S$), the expected number of $k$-cycles of$~\sigma$ where $\sigma$ is chosen uniformly at random among all permutations of$~S$, is precisely$~\frac1k$. Stated differently, the statistic "number of $k$-cycles" takes an average value of$~\frac1k$ when $\sigma$ runs over all permutations of$~S$. I am looking for nice, intuitive, transparent, proofs of this fact, notably where the fraction$~\frac1k$ comes about naturally, preferably as the probability of obtaining a specific value when choosing an element uniformly from a $k$-element set. While I know a few easy computations that prove the result, none I've seen so far have achieved this highest standard, though some arrive at the fraction after some very basic cancellations.
The cases $k=1$ (the expected number of fixed points of a permutation is precisely $1$) and $k=n$ (there are $(n-1)!$ distinct cyclic permutations of $S$, which is $\frac1n$ of all permutations) are very well known and with easy proofs, but I would like a proof that covers all allowed values of $k$ in a uniform manner.
I've seen quite a few questions on this site that come close to this one, but few state the result in isolation and none specifically ask for elegant arguments, so I don't feel this question is truly a duplicate of any of them.
---
This question was inspired by watching [this video](https://www.youtube.com/watch?v=iSNsgj1OCLA&t=706s) (with a rather click-bait title) where the deduction of the case for $k=n$ (from 8:17 on) is followed by the irrefutable argument "this is a general result" (implying it's validity for all $k$) with no mention of expectation (for $k=n$ the only possible numbers of cycles are $0$ and $1$, so the expected value is just a probability) and no explanation whatsoever. | 2022/07/06 | [
"https://math.stackexchange.com/questions/4487189",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/18880/"
] | Here is a proof that exploits linearity of expectation, which is something that certainly comes to mind. I'll fix some value $s\in S$ and $k\in\{1,\ldots,n\}$, and let $\def\Sym{\operatorname{Sym}}\Sym(S)$ denote the set of permutations of $S$. Let $\chi\_{s,k}:M\to\{0,1\}$ be the characteristic function of the condition "the cycle of the permutation containing $s$ has length$~k$". The first step is to show that the expected value of$~\chi\_{s,k}$, viewed as a random variable on $\Sym(S)$ with uniform probability, is$~\frac1n$, independently of $s$ and of$~k$.
At this point I need to fix an order on $S$, which will allow met to write permutations of $S$ in two-line form; to avoid horribly complicated notation I will just assume that $S=\{1,\ldots,n\}$ (but still think of $s$ as element of $S$ and of $k$ as a number, a potential cycle length). Now
consider the bijection $f:\Sym(S)\to\Sym(S)$ defined as follows. Given $\sigma=({1\atop\sigma\_1}~\cdots~{n\atop\sigma\_n})$ in two-line form, locate the position $l=\sigma^{-1}\_s$ where $s$ occurs in the second line, and form the product$~\pi$ of the cycle $(s~\sigma\_1~\sigma\_2~\cdots~\sigma\_{l-1})$ (effectively reading the entry $\sigma\_l=s$ as a right parenthesis) and the permutation of the remaining entries $\{\sigma\_{l+1},\ldots,\sigma\_n\}$ with $2$-line form $({e\_1\atop\sigma\_{l+1}}~\cdots~{e\_{n-l}\atop\sigma\_n}))$ where $\{e\_1,\ldots,e\_{n-l}\}=\{\sigma\_{l+1},\ldots,\sigma\_n\}$ and $e\_1<\ldots<e\_{n-l}$ (which is a complicated way of saying the permutation of those elements suggested by the sequence $(\sigma\_{l+1},\ldots,\sigma\_n)$); now $f(\sigma)=\pi$. It is not hard to see that $f$ is invertible and therefore a bijection. Also it is clear that $\chi\_{s,k}(f(\sigma))$ is the characteristic function of the event $\sigma^{-1}\_s=k$, or $\sigma\_k=s$, and since $\sigma\_k$ could be any value in $S$ with equal probability, the average (or expected) value of that function is$~\frac1n$.
Now we apply linearity of expectation, forming the sum $\sum\_{s\in S}\chi\_{s,k}$ of the statistics (or random variables if you prefer) $\chi\_{s,k}$ for all $n$ values of $s$; clearly one gets that the expected value of this sum is $n\times\frac1n=1$, independently of $k$. But is is also clear that $\sum\_{s\in S}\chi\_{s,k}(\sigma)$ is the size of the union of $k$-cycles for$~\sigma$, or $k$ times the number of $k$-cycles for$~\sigma$; the expected value of that number is than $\frac1k$ QED.
---
This is of course the same answer as that of Henry, but written by someone who refuses to be concise (or as I would prefer to say, who refuses to sacrifice precision to conciseness). It was also strongly inspired by [this answer by joriki](https://math.stackexchange.com/a/165412/18880) to a closely related question. | This bijective proof avoids the use of expectation, it is purely combinatorial:
We will show a bijection between the set $S$ of permutations and the set $\{1,2,\dots,k\}\times T$, where $T$ is the set of occurrences of $k$-cycles in $S$. Hence the number of occurrences of $k$-cycles divided by the number of permutations is $1/k$ as stated. The bijection is really simple, we just need to be careful with notation to make it clear.
The elements of $T$ are the pairs $(\tau,\sigma)$, meaning that $\tau$ is a $k$-cycle in the permutation $\sigma$. We'll adopt the usual cycle notation $\tau=(i\_1\,i\_2\, \dots \,i\_k)$ but the order notation $\sigma=(\sigma\_1,\sigma\_2, \dots, \sigma\_n)$ instead. That is, if these form $(\tau,\sigma)\in T$ then $\sigma\_{i\_1}=i\_2, \sigma\_{i\_2}=i\_3, \dots, \sigma\_{i\_k}=i\_1$. If, in the expression of $\tau$, $i\_1$ is the minimum of its $k$ elements we'll say it is in *primal* form).
For instance, for $n=6$ we have
$$(\tau,\sigma)\in T \quad {\rm for} \quad \tau=(2\, 4\, 6\, 3) \ {\rm and\ } \sigma=(5,4,2,6,1,3)\,,$$
and note that $\tau$ is in primal form.
Then we define our bijection as follows: for $\tau=(i\_1\,i\_2\, \dots \,i\_k)$ in primal form and $(\tau,\sigma)\in T$, the image of $(j,(\tau,\sigma))$ is $\tilde\sigma = (i\_j, i\_{j+1},\dots,i\_{j-1},\omega)\in S$, where $\omega$ is the list of the numbers not in $\tau$, keeping their relative order (and of course $j-1$ means $k$ if $j=1$).
For example, for $n=6$ and $\tau$ and $\sigma$ the same as before,
$$
(1,(\tau,\sigma)) \mapsto \tilde\sigma = (2,4,6,3,5,1) \quad {\rm and}\quad (3,(\tau,\sigma)) \mapsto \tilde\sigma = (6,3,2,4,5,1)\,.
$$
It is clear that the following is the inverse map: for $\tilde\sigma=(\tilde\sigma\_1, \tilde\sigma\_2, \dots, \tilde\sigma\_k,\omega)$ (where $\omega$ is the $n-k$ remaining numbers listed in any order) we get $(j,(\tau,\sigma))\in \{1,2,\dots, k\}\times T$, where $\tau=(\tilde\sigma\_1\,\tilde\sigma\_2\,\dots\,\tilde\sigma\_k)$, $j$ indicates the position of $\tilde\sigma\_1$ in the primal form of $\tau$, and $\sigma$ is the permutation which has $\tau$ as a cycle and the terms of $\omega$ are placed in the remaining positions, keeping their relative order.
For instance, if $n=7$, $k=3$ and $\tilde\sigma = (4,6,2,1,7,3,5)$ then $\tau=(4\,6\,2)=(2\,4\,6)$, so $j=2$ and $\sigma=(1,4,7,6,3,2,5)$.
Finally, please note that the special case $k=1$ (the average number of fixed points is 1 regardless of $n$) is much simpler to express. |
37,522,050 | I didn't find a way to perform optimize.minimize from scipy with a multidimensional function. In nearly all examples an analytical function is optimized while my function is interpolated. The test data set looks like this:
```
x = np.array([2000,2500,3000,3500])
y = np.array([10,15,25,50])
z = np.array([10,12,17,19,13,13,16,20,17,60,25,25,8,35,15,20])
data = np.array([x,y,z])
```
While the function is like F(x,y) = z
What I want to know is what happens at f(2200,12) and what is the global maximum in the range of x (2000:3500) and y (10:50). The interpolation works fine. But finding the global maximum doesn't work so far.
The interpolation
```
self.F2 = interp2d(xx, -yy, z, kind, bounds_error=False)
```
yields
```
<scipy.interpolate.interpolate.interp2d object at 0x0000000002C3BBE0>
```
I tried to optimize via:
```
x0 = [(2000,3500),(10,50)]
res = scipy.optimize.minimize(self.F2, x0, method='Nelder-Mead')
```
An exception is thrown:
```
TypeError: __call__() missing 1 required positional argument: 'y'
```
I think that the optimizer can't handle the object from the interpolation. In the examples the people used lambda to get values from their function. What do I have to do in my case?
Best,
Alex | 2016/05/30 | [
"https://Stackoverflow.com/questions/37522050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4808110/"
] | First, to find global maximum (instead of minimum) you need to interpolate your function with opposite sign:
```
F2 = interp2d(x, y, -z)
```
Second, the callable in `minimize` takes a tuple of arguments, and `interp2d` object needs input coordinates to be given as separate positional arguments. Therefore, we cannot use `interp2d` object in `minimize` directly; we need a wrapper that will unpack a tuple of arguments from `minimize` and feed it to `interp2d`:
```
f = lambda x: F2(*x)
```
And third, to use `minimize` you need to specify an initial guess for minimum (and bounds, in your case). Any reasonable point will do:
```
x0 = (2200, 12)
bounds = [(2000,3500),(10,50)]
print minimize(f, x0, method='SLSQP', bounds=bounds)
```
This yields:
```
status: 0
success: True
njev: 43
nfev: 243
fun: array([-59.99999488])
x: array([ 2500.00002708, 24.99999931])
message: 'Optimization terminated successfully.'
jac: array([ 0.07000017, 1. , 0. ])
nit: 43
``` | One more possible solution (hope you get the idea):
One more function is created (f), and the minimized values are sent as arguments to this function.
```
from scipy.optimize import minimize
x = data.Height.values
y = data.Weight.values
def f(params):
w0, w1 = params
return mse(w0, w1, x, y)
optimum = minimize(f, (0,0), method = 'L-BFGS-B', bounds = ((-100, 100), (-5,5)) )
w0 = optimum.x[0]
w1 = optimum.x[1]
```
Also tried implementation with lambda function, but had no luck. |
17,881,115 | in my app i want to calculate the distance between two points that has a latitude and a longitude. i managed to get the equations used to calculate it from this website (<http://andrew.hedges.name/experiments/haversine/>) and here is the equations:
```
dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2
c = 2 * atan2( sqrt(a), sqrt(1-a) )
d = R * c (where R is the radius of the Earth
```
so i translate them as code, here it is:
```
float distanceLongitude = lon2 - lon1;
float distanceLatitude = lat2 - lat1;
float a = powf(sinf((distanceLatitude/2)), 2) + cosf(lat1) * cosf(lat2) * powf((sinf(distanceLongitude/2)),2);
float c = 2 * atan2f(sqrtf(a), sqrtf(1-a));
float d = 6373 * c; //6373 radius of earth
```
i tried the code with the following coordinates:
lat1 = 33.854025 lon1 = 35.506923
lat2 = 33.856835 lon2 = 35.506324
according to the website, the results are 0.317 km or 0.197 miles. however, my code's output is giving me 18.143757. how can i fix that? (please check the converter in the website to know what i'm talking about.
Note: d should be the final result. | 2013/07/26 | [
"https://Stackoverflow.com/questions/17881115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2176995/"
] | Why wouldn't you use the Apple API to calculate this distance? You could just perform something like this:
```
CLLocation *locA = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];
CLLocationDistance distance = [locA distanceFromLocation:locB];
```
Note that CLLLocationDistance it's just a typedef to a float, and the distance variable will have the value in meters. | The input to the `sinf` and `cosf` routines is in radians. You must convert angles from degrees to radians before calling them. To do this, multiply the angles by π/180º. |
17,881,115 | in my app i want to calculate the distance between two points that has a latitude and a longitude. i managed to get the equations used to calculate it from this website (<http://andrew.hedges.name/experiments/haversine/>) and here is the equations:
```
dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2
c = 2 * atan2( sqrt(a), sqrt(1-a) )
d = R * c (where R is the radius of the Earth
```
so i translate them as code, here it is:
```
float distanceLongitude = lon2 - lon1;
float distanceLatitude = lat2 - lat1;
float a = powf(sinf((distanceLatitude/2)), 2) + cosf(lat1) * cosf(lat2) * powf((sinf(distanceLongitude/2)),2);
float c = 2 * atan2f(sqrtf(a), sqrtf(1-a));
float d = 6373 * c; //6373 radius of earth
```
i tried the code with the following coordinates:
lat1 = 33.854025 lon1 = 35.506923
lat2 = 33.856835 lon2 = 35.506324
according to the website, the results are 0.317 km or 0.197 miles. however, my code's output is giving me 18.143757. how can i fix that? (please check the converter in the website to know what i'm talking about.
Note: d should be the final result. | 2013/07/26 | [
"https://Stackoverflow.com/questions/17881115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2176995/"
] | Why wouldn't you use the Apple API to calculate this distance? You could just perform something like this:
```
CLLocation *locA = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2];
CLLocationDistance distance = [locA distanceFromLocation:locB];
```
Note that CLLLocationDistance it's just a typedef to a float, and the distance variable will have the value in meters. | The latitude and lingitude is (most probably) given in decimal degrees, such as 52.09878 and 10.897934. But the sinf etc functions use radiants.
Try converting your `distanceLongitude` and `distanceLatitude` to radiants and then continue with a = ...
```
radiantLongitudeDistance = degreeLongitudeDistance * M_PI / 180.0
``` |
2,557,492 | I am in the UK, studying GCSE, if that means anything to you.
What would you recommend to me, to further my understanding of mathematics, of my current level or further?
Thanks. | 2017/12/08 | [
"https://math.stackexchange.com/questions/2557492",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/511660/"
] | I would recommend a two-pronged approach!
Strengthening your algebra and problem solving skills beyond what is covered in GCSE would be very valuable. Books such as 'Student Problems from the Mathematical Gazette', ISBN 0 906588 49 9, available from the Mathematical Association, would provide good challenges for you.
For general appreciation of Mathematics (which should whet your appetite for your future maths education) there are many good and popular books - for example '17 equations that changed the world' by Ian Stewart. | I recommend that you find a book that is both enjoyable **and** challenging but not too challenging. If it generates curiosity in mathematics everything else should be doable. I'm not saying easy, some things will come easily to you, others will be hard work but with curiosity you will persist and overcome. One view of math is that it is the art of solving problems so my suggestions will biased that way. Here are some suggestions; they may be a little on the old side. I'm sure there are newer books that I'm not as familiar with, on the other hand you may find inexpensive copies in second bookstores such as those run by Oxfam.
>
> ***How to Solve It*** by G. Polya
>
> **Problem books** by Martin Gardner
>
> ***The Lore of Large Numbers*** by Philip J. Davis
>
> ***Countdown*** by Steve Olson (This book is more about competitive math problem solving than the math per se. The math is only about 30% (rough) of the book.)
>
> ***The Mathematical Experience*** by Philip J. Davis and Rueben Hersh (The math may be only about 10% but there are many short essays that are fun to dip into.)
>
>
>
I will add to this list if I think of anything else. Other users may add newer books or completely disagree with me. |
51,273,604 | For example I'm writing an email (console) based application for fun. I was trying to incorporate files into it to read the information from it. For example if my txt format is as following how can I read each variable?
```
Server: gmail
User: [email protected]
Password: pass123
To: [email protected]
CC: [email protected], [email protected], [email protected]
BCC: [email protected], [email protected]
Subject: subject
Body: 123
454
6464
This is still part of the body
File: filename.zip
```
However, the CC and BCC should be a string array I believe, right? | 2018/07/10 | [
"https://Stackoverflow.com/questions/51273604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7833897/"
] | * Create 2 layers using `::before` and `::after`pseudo elements having same heights equal to 50% height of the parent element.
* Apply `background`, `border-radius` and other necessary CSS properties on these layers.
* Use `skewX()` transformation on hover to create the triangular effect.
**Demo:**
```css
*, *::before, *::after { box-sizing: border-box; }
body {
background: #333 url("https://k39.kn3.net/A01CCB6AE.jpg") no-repeat;
background-size: cover;
height: 100vh;
padding: 10px;
margin: 0;
}
.nav {
font-family: Arial, sans-serif;
list-style: none;
padding: 0;
margin: 0;
}
.nav li + li {
margin-top: 3px;
}
.nav li a {
text-decoration: none;
border-radius: 2px;
position: relative;
padding: 12px 18px;
overflow: hidden;
display: block;
color: #000;
}
.nav li a::before,
.nav li a::after {
transition: transform .2s linear;
transform-origin: left top;
background-color: #dcdcdc;
position: absolute;
opacity: 0.5;
content: '';
height: 50%;
z-index: -1;
right: 0;
left: 0;
top: 0;
}
.nav li a::after {
transform-origin: left bottom;
top: auto;
bottom: 0;
}
.nav li a:hover::before {
transform: skewX(30deg);
}
.nav li a:hover::after {
transform: skewX(-30deg);
}
```
```html
<ul class="nav">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
<li><a href="#">Item 4</a></li>
</ul>
``` | I am posting my answer using `bootstrap4` but the key point here is not relevant whether `bootstrap3` or `bootstrap4` is used. The key point here is how you can make a triangle.
Demo: <http://jsfiddle.net/aq9Laaew/81019/>
### CSS Triangle
I am not going to explain here since it's already been explained well: <https://css-tricks.com/snippets/css/css-triangle/>
The idea here is to use `:before` of the active `nav-link` to make a triangle with white background.
### Calculations
[![enter image description here](https://i.stack.imgur.com/DqLef.png)](https://i.stack.imgur.com/DqLef.png)
If you want the tip of the triangle right in the middle of the menu, you need to calculate its total height.
```
Total height = border top (1px) +
padding top (1rem) +
line height (1.5 x 1rem = 1.5rem) +
padding bottom (1rem) +
border bottom (1px)
```
And then you divide it by 2 for the width of the border top and bottom. |
51,273,604 | For example I'm writing an email (console) based application for fun. I was trying to incorporate files into it to read the information from it. For example if my txt format is as following how can I read each variable?
```
Server: gmail
User: [email protected]
Password: pass123
To: [email protected]
CC: [email protected], [email protected], [email protected]
BCC: [email protected], [email protected]
Subject: subject
Body: 123
454
6464
This is still part of the body
File: filename.zip
```
However, the CC and BCC should be a string array I believe, right? | 2018/07/10 | [
"https://Stackoverflow.com/questions/51273604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7833897/"
] | Use [box-shadow](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow) and [Pseudo-elements](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements)
```css
*{
box-sizing:border-box
}
body {
width: 100wh;
height: 100vh;
background: linear-gradient(-45deg, #EE7752, #E73C7E, #23A6D5, #23D5AB);
background-size: 400% 400%;
animation: Gradient 15s ease infinite;
}
@keyframes Gradient {
0%,100% { background-position: 0% 50% }
50% { background-position: 100% 50% }
}
menu{
margin: 40px auto;
position: relative;
max-width: 320px
}
menu li{
position: relative;
list-style: none;
overflow: hidden;
margin-bottom: 2px
}
menu li:before{
content: "";
position: absolute;
top: 0;
left: 0;
z-index:-1;
height: 40px;
width: 40px;
opacity:0;
margin-left: -30px;
box-shadow: 0px 0px 0px 480px #d1e3ab;
transform-origin: center;
transform: rotate(45deg);
}
menu a{
display: block;
text-decoration: none;
color:#5e5e5e;
font-size: 14px;
background-color: #e1e1e1;
padding: 12px 10px;
text-indent: 24px;
}
menu li:hover a{
background-color: transparent;
}
menu li:hover:before{
opacity:1
}
```
```html
<menu>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a></li>
<li><a href="#">Item 4</a></li>
</menu>
``` | I am posting my answer using `bootstrap4` but the key point here is not relevant whether `bootstrap3` or `bootstrap4` is used. The key point here is how you can make a triangle.
Demo: <http://jsfiddle.net/aq9Laaew/81019/>
### CSS Triangle
I am not going to explain here since it's already been explained well: <https://css-tricks.com/snippets/css/css-triangle/>
The idea here is to use `:before` of the active `nav-link` to make a triangle with white background.
### Calculations
[![enter image description here](https://i.stack.imgur.com/DqLef.png)](https://i.stack.imgur.com/DqLef.png)
If you want the tip of the triangle right in the middle of the menu, you need to calculate its total height.
```
Total height = border top (1px) +
padding top (1rem) +
line height (1.5 x 1rem = 1.5rem) +
padding bottom (1rem) +
border bottom (1px)
```
And then you divide it by 2 for the width of the border top and bottom. |
64,362,029 | Given a **string** resembling HTML **(but not actually HTML)**, how can I use JavaScript to remove all 'HTML tags' except a specific 'tag' (and its 'children')?
For instance, if I have the following **string**:
```
'<p><span>Sample data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><strong>hello world</strong><math><msqrt><mo>x</mo></msqrt></math></div></p>'
```
And I only want to keep raw text & 'math tags' (and everything inside each 'math tag'), how would I go about doing that?
```
const html = '<p><span>Sample data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><strong>hello world</strong><math><msqrt><mo>x</mo></msqrt></math></div></p>';
const result = stripNonSpecifiedHTML(html, 'math');
// expected result:
// 'Sample data: <math><msqrt><mo>y</mo></msqrt></math>hello world<math><msqrt><mo>x</mo></msqrt></math>'
function stripNonSpecifiedHTML(html, tagNameToKeep) {
// ...
}
``` | 2020/10/14 | [
"https://Stackoverflow.com/questions/64362029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9935570/"
] | You could do something along the lines of:
```
html.split('<math>')[1].split('</math>')[0]
``` | While not `html`, this string can be parsed as `xml`.
```
const html = '<p><span>Initial data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><math><msqrt><mo>x</mo></msqrt></math></div></p>';
let parser = new DOMParser(),
xmlDoc = parser.parseFromString(html, 'text/xml');
```
Then from there, you can loop over all the `<math>` tags.
```
let mathTags = xmlDoc.getElementsByTagName('math');
Array.from(mathTags).forEach(math => {
let data = math.innerHTML,
content = math.textContent;
});
``` |
64,362,029 | Given a **string** resembling HTML **(but not actually HTML)**, how can I use JavaScript to remove all 'HTML tags' except a specific 'tag' (and its 'children')?
For instance, if I have the following **string**:
```
'<p><span>Sample data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><strong>hello world</strong><math><msqrt><mo>x</mo></msqrt></math></div></p>'
```
And I only want to keep raw text & 'math tags' (and everything inside each 'math tag'), how would I go about doing that?
```
const html = '<p><span>Sample data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><strong>hello world</strong><math><msqrt><mo>x</mo></msqrt></math></div></p>';
const result = stripNonSpecifiedHTML(html, 'math');
// expected result:
// 'Sample data: <math><msqrt><mo>y</mo></msqrt></math>hello world<math><msqrt><mo>x</mo></msqrt></math>'
function stripNonSpecifiedHTML(html, tagNameToKeep) {
// ...
}
``` | 2020/10/14 | [
"https://Stackoverflow.com/questions/64362029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9935570/"
] | It looks rather awful, but it woks (with some limitations):
* split the string by `<math>` and `</math>`
* remove all html tags in every second element
* add `<math>` and `</math>` around every second element
* join the array back into a string
```js
const html =
'<p><span>Initial data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><strong>hello world</strong><math><msqrt><mo>x</mo></msqrt></math></div></p>'
var text = html.split('<math>')
.map(t => t.split('</math>')).flat()
.map((t, i) => {return (i % 2==0 ) ? t.replace(/<.+?>/g,''): t })
.map((t, i) => {return (i % 2==0 ) ? t : '<math>' + t + '</math>' })
.join('');
console.log(text);
// OUTPUT: Initial data: <math><msqrt><mo>y</mo></msqrt></math> hello world<math><msqrt><mo>x</mo></msqrt></math>
``` | While not `html`, this string can be parsed as `xml`.
```
const html = '<p><span>Initial data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><math><msqrt><mo>x</mo></msqrt></math></div></p>';
let parser = new DOMParser(),
xmlDoc = parser.parseFromString(html, 'text/xml');
```
Then from there, you can loop over all the `<math>` tags.
```
let mathTags = xmlDoc.getElementsByTagName('math');
Array.from(mathTags).forEach(math => {
let data = math.innerHTML,
content = math.textContent;
});
``` |
64,362,029 | Given a **string** resembling HTML **(but not actually HTML)**, how can I use JavaScript to remove all 'HTML tags' except a specific 'tag' (and its 'children')?
For instance, if I have the following **string**:
```
'<p><span>Sample data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><strong>hello world</strong><math><msqrt><mo>x</mo></msqrt></math></div></p>'
```
And I only want to keep raw text & 'math tags' (and everything inside each 'math tag'), how would I go about doing that?
```
const html = '<p><span>Sample data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><strong>hello world</strong><math><msqrt><mo>x</mo></msqrt></math></div></p>';
const result = stripNonSpecifiedHTML(html, 'math');
// expected result:
// 'Sample data: <math><msqrt><mo>y</mo></msqrt></math>hello world<math><msqrt><mo>x</mo></msqrt></math>'
function stripNonSpecifiedHTML(html, tagNameToKeep) {
// ...
}
``` | 2020/10/14 | [
"https://Stackoverflow.com/questions/64362029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9935570/"
] | It looks rather awful, but it woks (with some limitations):
* split the string by `<math>` and `</math>`
* remove all html tags in every second element
* add `<math>` and `</math>` around every second element
* join the array back into a string
```js
const html =
'<p><span>Initial data: <math><msqrt><mo>y</mo></msqrt></math></span> <div><strong>hello world</strong><math><msqrt><mo>x</mo></msqrt></math></div></p>'
var text = html.split('<math>')
.map(t => t.split('</math>')).flat()
.map((t, i) => {return (i % 2==0 ) ? t.replace(/<.+?>/g,''): t })
.map((t, i) => {return (i % 2==0 ) ? t : '<math>' + t + '</math>' })
.join('');
console.log(text);
// OUTPUT: Initial data: <math><msqrt><mo>y</mo></msqrt></math> hello world<math><msqrt><mo>x</mo></msqrt></math>
``` | You could do something along the lines of:
```
html.split('<math>')[1].split('</math>')[0]
``` |
23,794,049 | In my application I `$watch` if the form is valid before doing some stuff. The problem is that ngForm won't compile `models` before I use it.
Exemple : <http://plnkr.co/edit/Y7dL67Fn7SaSEkjiFf2q?p=preview>
**JS**
```
$scope.results = [];
$scope.$watch(function() {
return $scope.testForm.$valid;
},
function( valid ) {
$scope.results.push( valid );
}
)
```
**HTML**
```
<ng-form name="testForm" ng-init="test = 1">
<input ng-model="test" required>
</ng-form>
<p ng-repeat="result in results track by $index" ng-class="{'false': !result, 'true': result}">{{ result }}</p>
```
**Results :**
```
false // Wrong
true
```
The form shouldn't be invalid at first because `$scope.test` is set to 1.
Any clue ? | 2014/05/21 | [
"https://Stackoverflow.com/questions/23794049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2099829/"
] | According to **[the docs](https://docs.angularjs.org/api/ng/type/%24rootScope.Scope#%24watch)**:
>
> After a watcher is registered with the scope, the listener `fn` is called asynchronously (via `$evalAsync`) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of `watchExpression` didn't change. To detect this scenario within the listener `fn`, you can compare the `newVal` and `oldVal`. If these two values are identical (===) then the listener was called due to initialization.
>
>
>
---
It (almost always) makes sense to ignore this first call using a check:
```
$scope.$watch('testForm.$valid', function (newValue, oldValue) {
if (newValue === oldValue) { return; }
$scope.results.push(newValue);
});
```
See, also, this **[short demo](http://plnkr.co/edit/UDPcJQtQcXaFnJKmuuoM?p=preview)**. | Not sure if correctly understand, but it could be that the first time AngularJS checks,
```
$scope.results = [];
```
is empty, therefore result evaluating to false before you push anything in it.
If you start with an non-empty result, say:
```
$scope.results = [1];
```
First evaluation is truey.
I don't think $watch is the proper method. I think your issue has to do with how $watch works, and the digest cycle of Angular. |
51,561,762 | I am writing the code below in VBA macro excel, my problem is that I get the object our of range error in the line (107, col 10) and I don't know why.
the line I get the error
```
.Range(.Cells(x, "A"), .Cells(x, "AC")).Select
```
my code is below
```
Sub MRP()
'
' Macro1 Macro
'
'
Dim wks As Worksheet
Dim OPwks As Worksheet
Dim MRPwks As Worksheet
Dim OPDwks As Worksheet
Dim DbCwks As Worksheet
Dim x As Long
Dim p As Integer, i As Long, q As Long
Dim a As Integer, m As Integer, k As Long
Dim rowRange As Range
Dim colRange As Range
Dim LastCol As Long
Dim LastRowOPwks As Long
Dim LastRowMRPwks As Long
Dim LastRowDBCwks As Long
Set MRPwks = Worksheets("MRP")
Set OPwks = Worksheets("OpenPOsReport")
Set DbCwks = Worksheets("CompDB")
Set wks = ActiveSheet
Worksheets("OpenPOsReport").Activate
LastRowMRPwks = MRPwks.Cells(MRPwks.Rows.Count, "A").End(xlUp).Row
LastRowOPwks = OPwks.Cells(OPwks.Rows.Count, "A").End(xlUp).Row
LastRowDBCwks = DbCwks.Cells(DbCwks.Rows.Count, "A").End(xlUp).Row
'Set rowRange = wks.Range("A1:A" & LastRow)
'For m = 8 To LastRow
'Cells(m, "N") = 0
'Next m
For i = 2 To LastRowDBCwks
p = 0
For q = 8 To LastRowOPwks
If DbCwks.Cells(i, "V") = 0 Then k = 0 Else: k = p / Cells(i, "V")
If OPwks.Cells(q, "A") = DbCwks.Cells(i, "A") Then
If OPwks.Cells(q, "D") = 0 Or OPwks.Cells(q, "B") < 1 / 1 / 18
Then GoTo Nextiteration Else
If (OPwks.Cells(q, "C") + DbCwks.Cells(i, "C")) >=
(DbCwks.Cells(i, "F") + k) Then
OPwks.Cells(q, "N").Value = 1
OPwks.Range(Cells(q, "A"), Cells(q, "N")).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Else
p = p + OPwks.Cells(q, "D").Value
OPwks.Cells(q, "N").Value = 0
OPwks.Range(Cells(q, "A"), Cells(q, "O")).Select
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
End If
Nextiteration:
Next q
Next i
'For q = 8 To LastRow
' If Cells(q, "N") = 1 Then
' End If
' Next
With MRPwks
For x = 5 To LastRowMRPwks
If .Cells(x, "AC").Value > 0 Then
.Range(.Cells(x, "A"), .Cells(x, "AC")).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
If .Cells(x, "AC") = 0 Then
.Range(.Cells(x, "A"), .Cells(x, "AC")).Select
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next x
End With
End Sub
```
I dont know why I get the Object out of range error in the first part of the code. | 2018/07/27 | [
"https://Stackoverflow.com/questions/51561762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9317553/"
] | You have `Worksheets("OpenPOsReport").Activate` in your code, then you try to select `.Range(.Cells(x, "A"), .Cells(x, "AC")).Select` on `MRPwks` which is not active at that time. This is not possible.
Change your code to
```
With MRPwks
For x = 5 To LastRowMRPwks
If .Cells(x, "AC").Value > 0 Then
With .Range(.Cells(x, "A"), .Cells(x, "AC")).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
If .Cells(x, "AC") = 0 Then
With .Range(.Cells(x, "A"), .Cells(x, "AC")).Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next x
End With
```
It is not neccessary to select the range first. | You can avoid this error if you don't try to `Select` the range (because you cannot select a range on a sheet that's inactive). One common mistake is to say "OK, well, then I'll just add a `.Activate` to make sure the right sheet is active. But that leads to spaghetti code, as you constantly need to keep track of which sheet in which workbook is active, makes the code hard to read and harder to debug.
[Selecting/Activating things in Excel is almost *never* necessary](https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba?s=1%7C315.9629), and when you do it this way it tends to cause all sorts of difficult-to-troubleshoot errors, like the one you have.
```
Dim rngToFormat as Range
For x = 5 To LastRowMRPwks
Set rngToFormat = .Cells(x, "A").Resize(1,29)
If rngToFormat.Cells(29).Value > 0 Then
With rngToFormat.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Else
With rngToFormat.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next x
``` |
39,018,272 | I have a task to carry out 3 times a day on a WS2012R2 to get the Disk size, total number of files and folders including subdirectories from a folder on a remote server.
Currently I get this information by RDP'ing to the target, navigating to the folder and right clicking the folder to copy the info:
[![enter image description here](https://i.stack.imgur.com/JxXFY.png)](https://i.stack.imgur.com/JxXFY.png)
I have already tried the PowerShell script :
```
Get-ChildItem E:\Data -Recurse -File | Measure-Object | %{$_.Count}
```
and other PowerShell scripts.
Which produced countless errors pertaining to not having permissions for some sub directories or simply gave results I didn't want such.
I have tried VBscript but VBscript simply cannot get this information. | 2016/08/18 | [
"https://Stackoverflow.com/questions/39018272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5142580/"
] | You can just access the count property:
```
$items = Get-ChildItem E:\Data -Recurse -File
($items | Where { -not $_.PSIsContainer}).Count #files
($items | Where $_.PSIsContainer).Count #folders
``` | **To summarise the comments so far.**
You can get the size of the C drive with:
```
$Drive = "C"
Get-PSDrive -Name $Drive | Select-Object @{N="Used Space on $Drive Drive (GB)"; E={[Math]::Round($_.Used/1GB)}}
```
But you cannot use something like the code below to count the files & folders for the whole C drive, but it works for simple filestructures and simple drives.
I use the code to calculate my other drives and for my homepath, just change $Path to e.g "$Env:Homepath".
>
> There's the path length problem which is a .NET thing and won't be
> fixed until everyone (and PowerShell) is using .NET 4.6.2. Then
> there's that you're acting as you counting it, not the operating
> system counting.
>
>
>
```
[Int]$NumFolders = 0
[Int]$NumFiles = 0
$Path = "C:\"
$Objects = Get-ChildItem $Path -Recurse
$Size = Get-ChildItem $Path -Recurse | Measure-Object -property length -sum
$NumFiles = ($Objects | Where { -not $_.PSIsContainer}).Count
$NumFolders = ($Objects | Where {$_.PSIsContainer}).Count
$Summary = New-Object PSCustomObject -Property @{"Path" = $Path ; "Files" = $NumFiles ; "Folders" = $NumFolders ; "Size in MB" = ([Math]::Round($Size.sum /1MB))}
$Summary | Format-list
```
To run this on remote computers, I would recommend using New-PsSession to the computer/computers, then Invoke-Command to run the code using the new sessions. |
23,338,038 | I've tried to give my "get\_threads" variable some additional content, based on the actual case. But it doesn't work as expected, the query isn't executing at all.
It looks like there are some blanks that are missing in the "final" variable.
But when i add them to the value, the output completely dissapears.
The output query is:
```
SELECT id, main_forum_id, icon_id, title, description, author_id, closed, views, posts, date_created, last_post_author_id, last_replyTime FROM forum_thread WHERE main_forum_id= ('1') ORDER BY views ASC LIMIT 0, 20
```
And that's the code:
```
$get_threads = "SELECT id, main_forum_id, icon_id, title, description, author_id, closed, views, posts, date_created, last_post_author_id, last_replyTime FROM forum_thread WHERE main_forum_id= ('" . $actualBoard . "')";
if (isset($_GET[ 'sortField' ])) {
switch ($_GET[ 'sortField' ]) {
case topic:
$get_threads .= " ORDER BY title ASC ";
break;
case rating:
$get_threads .= " ORDER BY rating ASC ";
break;
case replies:
$get_threads .= " ORDER BY replies ASC ";
break;
case views:
$get_threads .= " ORDER BY views ASC ";
break;
case lastReply:
$get_threads .= " ORDER BY last_replyTime DESC ";
break;
}
} else {
$lastReplyClass = 'columnLastPost active';
$get_threads .= " ORDER BY last_replyTime ASC ";
}
$get_threads .= " LIMIT $start, $perPage";
```
SOLUTION:
Okay, i'm such an idiot..
Had a format function for the time and deleted it. That caused the error:
```
Fatal error: Call to undefined function formatDateString()
``` | 2014/04/28 | [
"https://Stackoverflow.com/questions/23338038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3580759/"
] | ```
SELECT id, main_forum_id, icon_id, title, description, author_id, closed, views, posts, date_created, last_post_author_id, last_replyTime FROM forum_thread WHERE main_forum_id= ('1') ORDER BY last_replyTime ASCLIMIT 20, 20
```
ASCLIMIT ?
There has to be a space.
You should add a space before your LIMIT and before your ORDER BY
```
$get_threads .= " ORDER BY last_replyTime ASC";
}
$get_threads .= " LIMIT $start, $perPage";
``` | Give the space between `ORDER BY last_replyTime ASC` and `LIMIT 20 20`
Also `switch case` surrounded with single`(')` or double`("")` quotes.
For example,
```
case "topic":
break;
case "views":
break;
``` |
23,338,038 | I've tried to give my "get\_threads" variable some additional content, based on the actual case. But it doesn't work as expected, the query isn't executing at all.
It looks like there are some blanks that are missing in the "final" variable.
But when i add them to the value, the output completely dissapears.
The output query is:
```
SELECT id, main_forum_id, icon_id, title, description, author_id, closed, views, posts, date_created, last_post_author_id, last_replyTime FROM forum_thread WHERE main_forum_id= ('1') ORDER BY views ASC LIMIT 0, 20
```
And that's the code:
```
$get_threads = "SELECT id, main_forum_id, icon_id, title, description, author_id, closed, views, posts, date_created, last_post_author_id, last_replyTime FROM forum_thread WHERE main_forum_id= ('" . $actualBoard . "')";
if (isset($_GET[ 'sortField' ])) {
switch ($_GET[ 'sortField' ]) {
case topic:
$get_threads .= " ORDER BY title ASC ";
break;
case rating:
$get_threads .= " ORDER BY rating ASC ";
break;
case replies:
$get_threads .= " ORDER BY replies ASC ";
break;
case views:
$get_threads .= " ORDER BY views ASC ";
break;
case lastReply:
$get_threads .= " ORDER BY last_replyTime DESC ";
break;
}
} else {
$lastReplyClass = 'columnLastPost active';
$get_threads .= " ORDER BY last_replyTime ASC ";
}
$get_threads .= " LIMIT $start, $perPage";
```
SOLUTION:
Okay, i'm such an idiot..
Had a format function for the time and deleted it. That caused the error:
```
Fatal error: Call to undefined function formatDateString()
``` | 2014/04/28 | [
"https://Stackoverflow.com/questions/23338038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3580759/"
] | ```
SELECT id, main_forum_id, icon_id, title, description, author_id, closed, views, posts, date_created, last_post_author_id, last_replyTime FROM forum_thread WHERE main_forum_id= ('1') ORDER BY last_replyTime ASCLIMIT 20, 20
```
ASCLIMIT ?
There has to be a space.
You should add a space before your LIMIT and before your ORDER BY
```
$get_threads .= " ORDER BY last_replyTime ASC";
}
$get_threads .= " LIMIT $start, $perPage";
``` | ```
$get_threads = "SELECT id, main_forum_id, icon_id, title, description, author_id, closed, views, posts, date_created, last_post_author_id, last_replyTime FROM forum_thread WHERE main_forum_id= ('" . $actualBoard . "') ";
$sortField = (isset($_GET[ 'sortField' ])) ? $_GET[ 'sortField' ] : '';
switch ($sortField) {
case 'topic':
$get_threads .= " ORDER BY title ASC ";
break;
case 'rating':
$get_threads .= " ORDER BY rating ASC ";
break;
case 'replies':
$get_threads .= " ORDER BY replies ASC ";
break;
case 'views':
$get_threads .= " ORDER BY views ASC ";
break;
case 'lastReply':
$get_threads .= " ORDER BY last_replyTime DESC ";
break;
default:{
$lastReplyClass = 'columnLastPost active';
$get_threads .= " ORDER BY last_replyTime ASC ";
}
break;
}
$get_threads .= " LIMIT $start, $perPage";
``` |
45,326,201 | I am trying to get the current path of my Angular app. However, this is always returned empty.
```
constructor(
private route: ActivatedRoute
) {
this.route.url.subscribe(segments => {
var currentPath = segments[0].path;
console.log("Current Route: ", currentPath);
});
}
```
No matter where I navigate, this is always empty:
[![enter image description here](https://i.stack.imgur.com/lXcwk.png)](https://i.stack.imgur.com/lXcwk.png)
What am I doing wrong here? | 2017/07/26 | [
"https://Stackoverflow.com/questions/45326201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2814241/"
] | If you want to get current route url , you can use this code :
```js
import { Router, ActivatedRoute } from '@angular/router';
constructor(
private router: Router,
private activatedRoute: ActivatedRoute) {
console.log(activatedRoute.snapshot.url[0].path);
}
```
If you want to get full url of web app . you should use this :
```js
window.location.pathname
``` | `ActivatedRoute` doesn't have a path. You should consult the router which you can inject along with the constructor.
A common way is to provide location used to navigate to the activated route but it uses additional services that you might not adhere. |
46,329,195 | i would like to ask, how to get file(image) from my form.php ,then move file in another folder and get path of picture in Controller.php.
I am not sure how to get that file from post.
form.php
```
<form method="post">
<input name="image" type="file"><br>
<input type="submit" value="Uložit článok" />
</form>
```
Controller.php
```
$folder_path "images/" . $_FILES["image"]["name"]
$folder = "images/";
move_uploaded_file($_FILES["image"]["tmp_name"], "$folder" . $_FILES["image"]["name"]);
$Manager->AddPhoto($folder); //this is just adding into database
``` | 2017/09/20 | [
"https://Stackoverflow.com/questions/46329195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8588611/"
] | Once you set your response field on successful sending, call next() as a last step, so the next middleware gets the request and sends the response back. So basically:
```
...
res.json(yourResponse);
next();
...
```
Or, if this is the last middleware, send the response back to client:
```
res.send(yourResponse);
``` | I solved it in this way. The emailExistence didn't let me to use promises, so I used email-ckeck instead of it:
```
const router = require('express').Router();
const nodemailer = require('nodemailer');
const emailExistence= require('email-existence');
var emailCheck = require('email-check');
module.exports = router;
router.post('/forgetPass', (req, res, next) => {
if(!req.body.email){
next(new Error("Email is required."));
return;
}
// Check the req.body.email with email pattern regex
var patt = new RegExp (process.env.EMAIL_PATTERN__REGEX),
isEmail = patt.test(req.body.email);
if(!isEmail){
next(new Error("The email does'nt seem to be a valid email. If you are sure about your email validity contact the website admin."));
return;
}
return emailCheck(req.body.email)
.then(function(result){
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL,
pass: process.env.EMAILPASSWORD
}
});
let mailOptions = {
from: process.env.EMAIL,
to: req.body.email,
subject: 'Link for setting a new password',
html: 'Set a new password from <a href="http://www.example.com/newpass">this link</a>.'
};
return transporter.sendMail(mailOptions)
.then(function (result2) {
res.status(200).json(Object.assign(req.base, {
message: "The email has been sent successfully.",
data: null
}));
return;
},
function(error2){
next(new Error("Error in sending email."));
return;
});
},
function(error) {
next(new Error("The email does'nt seem to be a valid email. If you are sure about your email validity contact the website admin."));
return;
});
});
``` |
8,694,492 | I was reading Foursquare API and trying to find how to use it for places search (as alternative to Google Places). However I was surprised that it requires the client secret key to be provided always!.
I'm using it in the browser, and the only way to get a response is to provide both client secret and client id in the request. It's "Client Secret" there should be another way of doing this, without using the client secret. Google API checks for the referring url and client id. Do Foursquare supports something like this?
I know that I can make the request in my server to foursquare and call it from my JavaScript client code. But that would be very ugly (IMO) since user have to wait for doubled response time `user -> my-server -> foursquare-api` instead of just `user -> foursquare-api`.
A page in my Web Application that would use it: [Where can I a great place in the city to see Christmas lights in Boston, MA?](http://www.tipntag.com/q/719/where-can-i-a-great-place-in-the-city-to-see-christmas-lights-in-boston-ma), try to share a tip in order to find out (you don't have to really post it!). | 2012/01/01 | [
"https://Stackoverflow.com/questions/8694492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161278/"
] | It's ugly, yes. But my two cents:
If your needs for security greatly outweigh your needs for speed, then use a server-side proxy… It's basically what everyone does, most proxies are disguised in one way or another some are 3rd party services, some are tiny stand-alone rails/express/etc apps, some are just a endpoint on your existing app, some use google appengine, but kid yourself not, most people use a proxy.
If your need for speed greatly outweighs your need for security: Then go the "unsafe" way of exposing your key. It's not that bad really as along as you decouple data that's sensitive for your users that does not come from foursquare from data accessed via foursquare. You're only sharing some potentially fake geo data, some potentially fake place data and well, you get picture: it's not your user's financial statements, it's a big game called Foursquare. Worse comes to worse, change your API key once in a while.
IMO, in situations like these there is no middle ground, you have to balance it in your head so that one greatly outweighs the other (security vs speed). I have yet to see a situation where both are truly and honestly equally important and nothing can be traded-off. | A proxy approach really helped me. My app is running on embedded jetty and I used a ProxyServelt to approach this problem:
```
import java.net.URI;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.UriBuilder;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.proxy.ProxyServlet;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FoursquareProxyServlet extends ProxyServlet {
public static final String FOURSQUARE_API_PREFIX = "foursquare";
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(FoursquareProxyServlet.class);
private static final String FOURSQUARE_API_VERSION = "20141026";
private String apiURL;
private String clientId;
private String clientSecret;
public void init() throws ServletException {
super.init();
ServletConfig config = getServletConfig();
apiURL = config.getInitParameter("foursquare.apiUrl");
clientId = config.getInitParameter("foursquare.clientId");
clientSecret = config.getInitParameter("foursquare.clientSecret");
}
@Override
protected void customizeProxyRequest(Request proxyRequest, HttpServletRequest request) {
proxyRequest.getHeaders().remove("Host");
}
@Override
protected URI rewriteURI(HttpServletRequest request) {
URI uri = UriBuilder.fromUri(this.apiURL)
.path(request.getRequestURI().replaceAll("/foursquare", ""))
.replaceQuery(request.getQueryString().trim())
.queryParam("client_id", this.clientId)
.queryParam("client_secret", this.clientSecret)
.queryParam("v", FOURSQUARE_API_VERSION)
.build();
return uri;
}
protected HttpClient newHttpClient() {
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(sslContextFactory);
return httpClient;
}
}
```
Then you just need to plug it into your server:
```
protected ServletContextHandler createFoursquareProxy() {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/"+FoursquareProxyServlet.FOURSQUARE_API_PREFIX+"/*");
ServletHolder foursquareProxy = new ServletHolder("foursquare", new FoursquareProxyServlet());
foursquareProxy.setInitParameter("foursquare.apiUrl", this.foursquareApiUrl);
foursquareProxy.setInitParameter("foursquare.clientId", this.foursquareClientId);
foursquareProxy.setInitParameter("foursquare.clientSecret", this.foursquareClientSecret);
context.addServlet(foursquareProxy, "/*");
return context;
}
```
Your request in this case would look like this:
```
GET http://{host}:{port}/foursquare/venues/search?&ll=40.7,-74%20&query=sushi
```
I'm sure you will be able to figure out something similar with your stack. |
8,694,492 | I was reading Foursquare API and trying to find how to use it for places search (as alternative to Google Places). However I was surprised that it requires the client secret key to be provided always!.
I'm using it in the browser, and the only way to get a response is to provide both client secret and client id in the request. It's "Client Secret" there should be another way of doing this, without using the client secret. Google API checks for the referring url and client id. Do Foursquare supports something like this?
I know that I can make the request in my server to foursquare and call it from my JavaScript client code. But that would be very ugly (IMO) since user have to wait for doubled response time `user -> my-server -> foursquare-api` instead of just `user -> foursquare-api`.
A page in my Web Application that would use it: [Where can I a great place in the city to see Christmas lights in Boston, MA?](http://www.tipntag.com/q/719/where-can-i-a-great-place-in-the-city-to-see-christmas-lights-in-boston-ma), try to share a tip in order to find out (you don't have to really post it!). | 2012/01/01 | [
"https://Stackoverflow.com/questions/8694492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161278/"
] | *This is a trick I learned from a fellow developer.*
It's not a proxy, yet similar. It will still make the requests from your IP address (not the server) yet the signing happens on the server. It doesn't create massive network traffic.
Basically it's a signing endpoint only. You create a page on your server that only signs the request but doesn't actually execute it. You then use the `Location: https://api.foursquare.com/...` header to redirect the user to a signed version of the page.
Note that all the signing happens on the server but the actual request is made by the client. No secrets are exposed since they're only used on the server. | A proxy approach really helped me. My app is running on embedded jetty and I used a ProxyServelt to approach this problem:
```
import java.net.URI;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.UriBuilder;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.proxy.ProxyServlet;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FoursquareProxyServlet extends ProxyServlet {
public static final String FOURSQUARE_API_PREFIX = "foursquare";
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(FoursquareProxyServlet.class);
private static final String FOURSQUARE_API_VERSION = "20141026";
private String apiURL;
private String clientId;
private String clientSecret;
public void init() throws ServletException {
super.init();
ServletConfig config = getServletConfig();
apiURL = config.getInitParameter("foursquare.apiUrl");
clientId = config.getInitParameter("foursquare.clientId");
clientSecret = config.getInitParameter("foursquare.clientSecret");
}
@Override
protected void customizeProxyRequest(Request proxyRequest, HttpServletRequest request) {
proxyRequest.getHeaders().remove("Host");
}
@Override
protected URI rewriteURI(HttpServletRequest request) {
URI uri = UriBuilder.fromUri(this.apiURL)
.path(request.getRequestURI().replaceAll("/foursquare", ""))
.replaceQuery(request.getQueryString().trim())
.queryParam("client_id", this.clientId)
.queryParam("client_secret", this.clientSecret)
.queryParam("v", FOURSQUARE_API_VERSION)
.build();
return uri;
}
protected HttpClient newHttpClient() {
SslContextFactory sslContextFactory = new SslContextFactory();
HttpClient httpClient = new HttpClient(sslContextFactory);
return httpClient;
}
}
```
Then you just need to plug it into your server:
```
protected ServletContextHandler createFoursquareProxy() {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/"+FoursquareProxyServlet.FOURSQUARE_API_PREFIX+"/*");
ServletHolder foursquareProxy = new ServletHolder("foursquare", new FoursquareProxyServlet());
foursquareProxy.setInitParameter("foursquare.apiUrl", this.foursquareApiUrl);
foursquareProxy.setInitParameter("foursquare.clientId", this.foursquareClientId);
foursquareProxy.setInitParameter("foursquare.clientSecret", this.foursquareClientSecret);
context.addServlet(foursquareProxy, "/*");
return context;
}
```
Your request in this case would look like this:
```
GET http://{host}:{port}/foursquare/venues/search?&ll=40.7,-74%20&query=sushi
```
I'm sure you will be able to figure out something similar with your stack. |
33,539,774 | How can I create Global Helper functions in `react-native`?
I would like to use for accessing `sqlite` database or fetching data from server. Can I create a `JavaScript` file with functions and call that functions from multiple views? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33539774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714480/"
] | The way we've done it in the past:
1. Create a file that exports a function:
```js
module.exports = function(variable) {
console.log(variable);
}
```
2. Require the file when you want to use it, in a variable:
```js
var func = require('./pathtofile');
```
3. Use function:
```js
func('myvariable');
``` | 2 methods, not sure which one is better:
1. Method
Use:
```
window.foo = function(val) {
alert(val);
}
```
2. (Not really global) Inside your `class` where you export and require in the `need-to-use` file, you can define your function.
See this:
```
var React = require('react-native');
var {
View,
} = React;
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
var MoviesScreen = React.createClass({
foo : function(val) {
alert(val);
},
render: function() {
return (
<View style={styles.container}>
</View>
);
},
});
module.exports = MoviesScreen;
``` |
33,539,774 | How can I create Global Helper functions in `react-native`?
I would like to use for accessing `sqlite` database or fetching data from server. Can I create a `JavaScript` file with functions and call that functions from multiple views? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33539774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714480/"
] | **global variable**
```js
class MainActivity extends Component {
constructor(){
super();
// Creating Global Variable.
global.SampleVar = 'This is Global Variable.';
}
}
```
in second activity
```js
class SecondActivity extends Component {
render(){
return(
<View>
<Text> {global.SampleVar} </Text>
</View>
);
}
}
```
But if you want to have a **global function**
```js
export function TestFunc1() {
}
export function TestFunc2() {
}
```
Then import and use
```js
import { TestFunc1 } from './path_to_file'
``` | 2 methods, not sure which one is better:
1. Method
Use:
```
window.foo = function(val) {
alert(val);
}
```
2. (Not really global) Inside your `class` where you export and require in the `need-to-use` file, you can define your function.
See this:
```
var React = require('react-native');
var {
View,
} = React;
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
var MoviesScreen = React.createClass({
foo : function(val) {
alert(val);
},
render: function() {
return (
<View style={styles.container}>
</View>
);
},
});
module.exports = MoviesScreen;
``` |
33,539,774 | How can I create Global Helper functions in `react-native`?
I would like to use for accessing `sqlite` database or fetching data from server. Can I create a `JavaScript` file with functions and call that functions from multiple views? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33539774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714480/"
] | 2 methods, not sure which one is better:
1. Method
Use:
```
window.foo = function(val) {
alert(val);
}
```
2. (Not really global) Inside your `class` where you export and require in the `need-to-use` file, you can define your function.
See this:
```
var React = require('react-native');
var {
View,
} = React;
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
var MoviesScreen = React.createClass({
foo : function(val) {
alert(val);
},
render: function() {
return (
<View style={styles.container}>
</View>
);
},
});
module.exports = MoviesScreen;
``` | I did in a simple way like this:
1. I created a `helpers.js` file that will contain all the helper functions for my project & placed it like this: `./src/helpers.js`(you can place anywhere you like).
2. Exported the function like this from `helpers.js`:
`export function GlobalLogout(str) {.....}`
3. Then I imported the function like this:
`import { GlobalLogout } from '../src/helpers';`
4. And finally use the function in the file like this:
`GlobalLogout(data);`
Hope this helps anyone! |
33,539,774 | How can I create Global Helper functions in `react-native`?
I would like to use for accessing `sqlite` database or fetching data from server. Can I create a `JavaScript` file with functions and call that functions from multiple views? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33539774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714480/"
] | The way we've done it in the past:
1. Create a file that exports a function:
```js
module.exports = function(variable) {
console.log(variable);
}
```
2. Require the file when you want to use it, in a variable:
```js
var func = require('./pathtofile');
```
3. Use function:
```js
func('myvariable');
``` | I have this helper function:
```
function myfunction(foo)
```
I declare it globally as:
```
global.myfunction = function myfunction(foo) {...};
``` |
33,539,774 | How can I create Global Helper functions in `react-native`?
I would like to use for accessing `sqlite` database or fetching data from server. Can I create a `JavaScript` file with functions and call that functions from multiple views? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33539774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714480/"
] | The way we've done it in the past:
1. Create a file that exports a function:
```js
module.exports = function(variable) {
console.log(variable);
}
```
2. Require the file when you want to use it, in a variable:
```js
var func = require('./pathtofile');
```
3. Use function:
```js
func('myvariable');
``` | **global variable**
```js
class MainActivity extends Component {
constructor(){
super();
// Creating Global Variable.
global.SampleVar = 'This is Global Variable.';
}
}
```
in second activity
```js
class SecondActivity extends Component {
render(){
return(
<View>
<Text> {global.SampleVar} </Text>
</View>
);
}
}
```
But if you want to have a **global function**
```js
export function TestFunc1() {
}
export function TestFunc2() {
}
```
Then import and use
```js
import { TestFunc1 } from './path_to_file'
``` |
33,539,774 | How can I create Global Helper functions in `react-native`?
I would like to use for accessing `sqlite` database or fetching data from server. Can I create a `JavaScript` file with functions and call that functions from multiple views? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33539774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714480/"
] | The way we've done it in the past:
1. Create a file that exports a function:
```js
module.exports = function(variable) {
console.log(variable);
}
```
2. Require the file when you want to use it, in a variable:
```js
var func = require('./pathtofile');
```
3. Use function:
```js
func('myvariable');
``` | I did in a simple way like this:
1. I created a `helpers.js` file that will contain all the helper functions for my project & placed it like this: `./src/helpers.js`(you can place anywhere you like).
2. Exported the function like this from `helpers.js`:
`export function GlobalLogout(str) {.....}`
3. Then I imported the function like this:
`import { GlobalLogout } from '../src/helpers';`
4. And finally use the function in the file like this:
`GlobalLogout(data);`
Hope this helps anyone! |
33,539,774 | How can I create Global Helper functions in `react-native`?
I would like to use for accessing `sqlite` database or fetching data from server. Can I create a `JavaScript` file with functions and call that functions from multiple views? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33539774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714480/"
] | **global variable**
```js
class MainActivity extends Component {
constructor(){
super();
// Creating Global Variable.
global.SampleVar = 'This is Global Variable.';
}
}
```
in second activity
```js
class SecondActivity extends Component {
render(){
return(
<View>
<Text> {global.SampleVar} </Text>
</View>
);
}
}
```
But if you want to have a **global function**
```js
export function TestFunc1() {
}
export function TestFunc2() {
}
```
Then import and use
```js
import { TestFunc1 } from './path_to_file'
``` | I have this helper function:
```
function myfunction(foo)
```
I declare it globally as:
```
global.myfunction = function myfunction(foo) {...};
``` |
33,539,774 | How can I create Global Helper functions in `react-native`?
I would like to use for accessing `sqlite` database or fetching data from server. Can I create a `JavaScript` file with functions and call that functions from multiple views? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33539774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714480/"
] | I have this helper function:
```
function myfunction(foo)
```
I declare it globally as:
```
global.myfunction = function myfunction(foo) {...};
``` | I did in a simple way like this:
1. I created a `helpers.js` file that will contain all the helper functions for my project & placed it like this: `./src/helpers.js`(you can place anywhere you like).
2. Exported the function like this from `helpers.js`:
`export function GlobalLogout(str) {.....}`
3. Then I imported the function like this:
`import { GlobalLogout } from '../src/helpers';`
4. And finally use the function in the file like this:
`GlobalLogout(data);`
Hope this helps anyone! |
33,539,774 | How can I create Global Helper functions in `react-native`?
I would like to use for accessing `sqlite` database or fetching data from server. Can I create a `JavaScript` file with functions and call that functions from multiple views? | 2015/11/05 | [
"https://Stackoverflow.com/questions/33539774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714480/"
] | **global variable**
```js
class MainActivity extends Component {
constructor(){
super();
// Creating Global Variable.
global.SampleVar = 'This is Global Variable.';
}
}
```
in second activity
```js
class SecondActivity extends Component {
render(){
return(
<View>
<Text> {global.SampleVar} </Text>
</View>
);
}
}
```
But if you want to have a **global function**
```js
export function TestFunc1() {
}
export function TestFunc2() {
}
```
Then import and use
```js
import { TestFunc1 } from './path_to_file'
``` | I did in a simple way like this:
1. I created a `helpers.js` file that will contain all the helper functions for my project & placed it like this: `./src/helpers.js`(you can place anywhere you like).
2. Exported the function like this from `helpers.js`:
`export function GlobalLogout(str) {.....}`
3. Then I imported the function like this:
`import { GlobalLogout } from '../src/helpers';`
4. And finally use the function in the file like this:
`GlobalLogout(data);`
Hope this helps anyone! |
52,090,080 | so I have this code to send data unto the backend
```
var $word = "minds & brains";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText);
}
xhttp.open("GET", 'http://mywebsite.com/controller/sample_controller?keyword='+$word, true);
xhttp.send();
```
but on my php it only gets the mind
```
<?php
echo $_GET['keyword'];
```
any ideas, help on how to acquire the exactly word "minds & brains"? | 2018/08/30 | [
"https://Stackoverflow.com/questions/52090080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1292042/"
] | You need to use [encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) to escape the `&` character:
```
xhttp.open("GET", 'http://mywebsite.com/controller/sample_controller?keyword='+ encodeURIComponent($word), true);
``` | try usung urlencode($word)
xhttp.open("GET", '<http://mywebsite.com/controller/sample_controller?keyword=>'+urlencode($word), true); |
78,584 | I have 12 volt and 135 ampere battery. Now I want to connect a device approximately 300 feet away from the battery.
When I connect it at this distance, my device does not work. When I connect the same device to the same battery at a shorter distance, the device does work.
What can I do? | 2013/08/10 | [
"https://electronics.stackexchange.com/questions/78584",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/27347/"
] | The battery is too far away. The voltage drop seems to big. You should have a bigger voltage on the battery side (DC-DC boos converter) or thicker cables.
Voltage drop is affected by the current flowing through the cables, length of the cables and cable thickens. You can look for more info here <http://www.buildmyowncabin.com/electrical/copper-wire-resistance.html> . It even has a calculator, so you can just put your values in and get the voltage drop. | As others have mentioned we need more info to be exact, but assuming your "internet cable" means something like CAT5, and assuming you are only using one pair, then you probably have a serious voltage drop at 900mA.
A rough calculation based on a [typical CAT5 cable](http://www.farnell.com/datasheets/1504872.pdf) with 24AWG conductors, using the typical loop resistance of 16Ω for 100m. We will estimate the routers load as 12Ω for a max of 1A:
300ft = 91.44m, so loop resistance = 16Ω \* (91.44/100) = 14.63Ω
Total circuit resistance = 14.63Ω + 12Ω = 26.63Ω
Circuit current = 12V / 26.63Ω = 451mA
Cable voltage drop = 0.451A \* 14.63Ω = 6.59V
Voltage available at router = 0.451A / 12Ω = 5.4V
So, although this is just a rough estimate (ignoring temperature effects, inductance/capacitance. Also we don't know what kind of regulation circuitry the router uses or it's input range) we can see that there is nowhere near enough power getting through to the router.
I would use at least 18AWG or thicker cable, preferably with some shielding and e.g. a ferrite bead. You can try using multiple conductors to lower the resistance. Also placing a largish capacitor (e.g. > 100uF) across the wires at the router end may help a little. |
78,584 | I have 12 volt and 135 ampere battery. Now I want to connect a device approximately 300 feet away from the battery.
When I connect it at this distance, my device does not work. When I connect the same device to the same battery at a shorter distance, the device does work.
What can I do? | 2013/08/10 | [
"https://electronics.stackexchange.com/questions/78584",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/27347/"
] | Any real conductor has an effective resistance per unit length. The voltage drop over that length of conductor, and the power dissipated in that conductor, is dependent on the amount of current you draw through that conductor. For a current draw of **I**, and a Resistance per Meter **R** you will experience:
(I^2 \* R) watts per meter of power lost as heat in the conductor
and
(I \* R) voltage drop per meter of conductor
If your endpoints cannot tolerate the worst case voltage drop, or if your power budget does not account for the losses in the cable, you can expect them not to function as intended.
[This PDF](http://www.seas.gwu.edu/~ecelabs/appnotes/PDF/techdat/swc.pdf) is a reference I have used for stranded wire. | As others have mentioned we need more info to be exact, but assuming your "internet cable" means something like CAT5, and assuming you are only using one pair, then you probably have a serious voltage drop at 900mA.
A rough calculation based on a [typical CAT5 cable](http://www.farnell.com/datasheets/1504872.pdf) with 24AWG conductors, using the typical loop resistance of 16Ω for 100m. We will estimate the routers load as 12Ω for a max of 1A:
300ft = 91.44m, so loop resistance = 16Ω \* (91.44/100) = 14.63Ω
Total circuit resistance = 14.63Ω + 12Ω = 26.63Ω
Circuit current = 12V / 26.63Ω = 451mA
Cable voltage drop = 0.451A \* 14.63Ω = 6.59V
Voltage available at router = 0.451A / 12Ω = 5.4V
So, although this is just a rough estimate (ignoring temperature effects, inductance/capacitance. Also we don't know what kind of regulation circuitry the router uses or it's input range) we can see that there is nowhere near enough power getting through to the router.
I would use at least 18AWG or thicker cable, preferably with some shielding and e.g. a ferrite bead. You can try using multiple conductors to lower the resistance. Also placing a largish capacitor (e.g. > 100uF) across the wires at the router end may help a little. |
47,026,927 | I am making a Choose Your Own Story game just as a little project to help me learn Java, and I don't know why this loop is behaving the way it is.
The issue is if you enter B when it prompts you to choose an option, it repeats the prompt, "Choose a response:". And if you enter B again, it outputs the right thing. If you enter A, it works fine the first time. I don't know why it takes two times for B to work.
I know the code is probably pretty bad other than that as well, so any other advice is also welcome.
Here's the code:
```
import java.util.Scanner;
import java.util.ArrayList;
public class Game {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String storyBlock = "one";
String option;
ArrayList<Choices> choiceRepo = new ArrayList<>();
ArrayList<Story> storyRepo = new ArrayList<>();
boolean continueFlag = true;
Story one = new Story("one", "The many rolling fields within Argonia are ideal for\n" +
"raising sheep, which is what my family has done for generations. In my grandfather's\n" +
"day, our village was known all round for having some of the best sheep in the land.\n" +
"It's not anymore. For years we've barely had enough sheep to help keep our family fe\n " +
"and clothed. It's been tough ever since the Ostians invaded our land and pillaged our towns\n" +
"and villages. After years of teetering on the edge of warfare, our countries finally clashed.\n" +
"We lost, obviously. Ostia is a much rougher country than ours, and it didn't take long for our\n" +
"peace seeking king to surrender his country. Though naive, I have to respect him for doing\n" +
"what he thought would save the most lives. And maybe it did save the most lives, but at the\n" +
"steep price of our freedom and well being. My village has struggled, but it hasn't been as\n" +
"bad as some of the villages that aren't as far out in the hills as we are. I've heard rumors that\n" +
"the Dark Hordes have taken to ravaging the countryside again, though, so it's only a matter\n" +
"of time until something very bad happens.\n" +
"The thought of them coming to my village and having to defend it makes me...\n");
storyRepo.add(one);
Choices ch1ChoiceA = new Choices("one", "A",
"frightened", "twoA");
choiceRepo.add(ch1ChoiceA);
Choices ch1ChoiceB = new Choices("one", "B",
"faintly excited at the notion of getting to fight", "twoB");
choiceRepo.add(ch1ChoiceB);
Story twoA = new Story("twoA", "...frightened. The Dark Horde is notorious for their savagery,\n" +
" and the king lets them loose to keep the populous of our country in fear of him. Their warriors\n" +
"are cold blooded killers, and their mages are even worse. Just thinking of coming into contact\n" +
"with them makes me stir from the place I have been sitting on the hill. I look up and after a\n" +
"quick count I realize that Pud has gone missing. That fluffer, always going over one hill or\n" +
"another. I just hope he hasn't gotten lost in the woods again. I might have to chase off another\n" +
"bear.");
storyRepo.add(twoA);
Story twoB = new Story("twoB", "...faintly excited at the notion of getting to fight. Though\n" +
" the Dark Horde is notorious for their savagery, I would almost welcome a chance to fight some\n" +
"of them. The king lets them loose to keep the populous of our country in fear of him. Their\n" +
"warriors are cold blooded killers, and their mages are even worse. This makes me concerned for\n" +
"my family and friends, but inside myself I can feel a craving for the adventure they would\n" +
"bring. While tending the flock I have fought bears, cougars, and even run into some roving hob\n" +
"goblins. My job has been to keep the flock safe, and I am very capable. And it also would give\n" +
"me a chance to practice the sword skills my father has been teaching me since he came back from\n" +
"the war that we lost. After a quick count realize that Pud has gone missing. That fluffer,\n" +
"always going over one hill or another. I just hope he hasn't gotten lost in the woods again.");
storyRepo.add(twoB);
Choices ch2Choice = new Choices("twoA", "A", "Continue", "three");
choiceRepo.add(ch2Choice);
while (continueFlag) {
ArrayList<Choices> specificChoices = new ArrayList<>();
for (Story story : storyRepo) {
if (story.storyName.equals(storyBlock)) {
story.printStory();
for (Choices choice : choiceRepo) {
if (choice.storyBlock.equals(storyBlock)) {
choice.printChoices();
specificChoices.add(choice);
}
}
}
System.out.println("Choose a response: ");
option = reader.nextLine();
if (!option.equals("A") &&
!option.equals("B") &&
!option.equals("Exit")) {
System.out.println("Invalid input. Enter A, B or Exit");
option = reader.nextLine();
}
if (option.equals("Exit")) {
continueFlag = false;
break;
}
for (Choices specificChoice : specificChoices) {
if (specificChoice.option.equals(option)) {
storyBlock = specificChoice.result;
}
}
}
}
}
}
``` | 2017/10/31 | [
"https://Stackoverflow.com/questions/47026927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7841544/"
] | I would suggest using `NumberFormatter` and setting its `maximumSignificantDigits` property:
```
let fmt = NumberFormatter()
fmt.numberStyle = .decimal
//fmt.minimumSignificantDigits = 5 // optional depending on needs
fmt.maximumSignificantDigits = 5
var n = 0.43578912
for _ in 0..<5 {
print(fmt.string(for: n)!)
n *= 10
}
```
Output:
>
> 0.43579
>
> 4.3579
>
> 43.579
>
> 435.79
>
> 4,357.9
>
>
>
You can specify other formatting options as desired such as disabling the grouping separator.
Setting `minimumSignificantDigits` will be useful if you want trailing zeros with numbers that have fewer digits. | Use the "g" format specifier:
```
var n = 0.4354345
for i in 0..<5 {
print(String(format: "%5g", n))
n = n * 10
}
```
will give you:
```
0.435435
4.35435
43.5435
435.435
4354.35
```
Your next best option is going to be to convert and then fix up by truncating the string. |
57,154,739 | I got an array like so
```
const array = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1]
```
and what I want is to just locate these ones and get the number of zeroes between these ones, and then return the biggest length of them so in this case it will return 5
and if the case was like so
```
const array = [1,0,0,0,0,0,1]
```
then the output should be 5 either
and if there wasn't but one one in the array like so
```
const array = [1,0,0,0]
```
I should get err
I have tried to locate the first one using .findIndex() like so
```
const firstOneIndex = intoArray.findIndex(el => el = 1);
``` | 2019/07/22 | [
"https://Stackoverflow.com/questions/57154739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10287480/"
] | ```js
const arr = [1, 0, 1, 1, 0, 0, 1];
function getDiff(array) {
// identify the 1's in the array
// strip the array down to a list of only the ones with values.
var mapped = array.map((v, i) => {
if (v == 1) return i;
}).filter(v => v != undefined);
var max = 0
var start;
var end;
// identify the largest gap between 1's
for (var ind in mapped) {
var gap = mapped[ind] - mapped[ind - 1];
// store largest gap start and stop indexs
if (gap > max) {
start = ind - 1;
end = ind;
max = gap;
}
}
// we do mapped[end] +1 because we want to include the last 1 in the splice, not exclude it.
var splice = array.splice(mapped[start], mapped[end] + 1);
return splice;
}
console.log(getDiff(arr));
``` | here is my attempt on it ,I have 2 solution one is the iteration solution and the other is using recursion
Solution #1
```
var array = [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]; // the original array
var index = array.indexOf(1); // store the index of the first 1
var diff = 0; // this will hold the max diff between the ones
// if exist at least one 1 and there is more than one 1
if( index != -1 || index != array.lastIndexOf(1)){
// if there is more than one 1 then store the index of the 2nd 1
var index2 = array.indexOf(1, index);
// start looping in the array and search for the mac diff by calculating the diff between the first 2 ones and do it again
while( index < array.length && index2 != -1 ){
// see if the last diff if bigger than the store the max of them in diff
diff = ((index2 - index) - 1) > diff ? ((index2 - index) - 1) : diff;
// adjust the indexs to continue doing the same
index = index2;
index2 = array.indexOf(1, index2 + 1);
}
console.log(diff = diff > 0 ? diff : 'error');
}
```
Solution #2 (recursion)
```
var array = [1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1]; // the original array
function howManyZeros(array){
var diff = 0;
console.log(array);
if( array.length > 1 ){
let index1 = array.indexOf(1);
let index2 = array.indexOf(1, index1 + 1);
if( index1 != -1 && index2 != -1){
diff = (index2 - index1) - 1;
return diff < howManyZeros(array.slice(index2)) ? howManyZeros(array.slice(index2)) : diff;
}
return diff;
}
return diff;
}
console.log(howManyZeros(array));
```
I hope this helps. |
41,554,125 | According to answers to this questions [Is overloading on all of the fundamental integer types is sufficient to capture all integers?](https://stackoverflow.com/questions/41552514/is-overloading-on-all-of-the-fundamental-integer-types-is-sufficient-to-capture) overloading of all fundamental types may not be able to handle types like `int8_t` `int64_t` etc. On another side according to documentation [std::ostream formatted output](http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt) and [std::istream formatted input](http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt) is implemented exactly by overloading all fundamental types. So on platform where `int8_t` and others could not be handled by such overloading how C++ streams would have to handle them? Would it fail to compile? Would standard library implementors have to provide additional undocumented methods? Something else? | 2017/01/09 | [
"https://Stackoverflow.com/questions/41554125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432358/"
] | For integer types, [istream] defines:
```
basic_istream<charT,traits>& operator>>(bool& n);
basic_istream<charT,traits>& operator>>(short& n);
basic_istream<charT,traits>& operator>>(unsigned short& n);
basic_istream<charT,traits>& operator>>(int& n);
basic_istream<charT,traits>& operator>>(unsigned int& n);
basic_istream<charT,traits>& operator>>(long& n);
basic_istream<charT,traits>& operator>>(unsigned long& n);
basic_istream<charT,traits>& operator>>(long long& n);
basic_istream<charT,traits>& operator>>(unsigned long long& n);
```
Any code of the form `is >> x` may fail to compile if `x` is an integer type that's not in that list.
As a quality of implementation issue, an implementation which offers extended integer types could add `operator>>` overloads for those types. This is permitted by [member.functions]/2 (as noted by hvd in comments), talking about classes in the standard library:
>
> An implementation may declare additional non-virtual member function signatures within a class:
>
>
> [...]
>
>
> * by adding a member function signature for a member function name.
>
>
> A call to a member function signature described in the C ++ standard library behaves as if the implementation declares no additional member function signatures.
>
>
>
This is a stronger guarantee than the general rule that implementations may add extensions that don't break conforming programs. The behaviour of conforming programs using SFINAE might be affected by the presence of the extra overloads.
---
For output, integer types not in the list will be implicitly convertible to another integer type which is in the list. | >
> So on platform where `int8_t` and others could not be handled by such overloading how C++ streams would have to handle them?
>
>
>
As far as integer insertion is concerned (operator<<), it would handle them in accord with standard C++ overload resolution. Extended integer types are *still* integer types and follow the rules of implicit conversion for the purpose of overload resolution.
For example, `int8_t` can be upconverted to any signed integer type large enough to hold it. So if `int8_t` is an extended integer type rather than an alias of the standard integer types, it can be upconverted to one of the standard ones, in accord with overload resolution rules.
For integer extraction (`operator>>`), this requires a non-`const` reference to a live integer, so conversion is not possible. Therefore, if you do not provide one of the explicit types that `operator>>` is overloaded for, your code should fail to compile.
The best you might get is if an implementation adds overloads specifically for those types, but you can't rely on that.
It should be noted that C++17's new `to_chars` and `from_chars` are explicitly stated by the standard to have overloads for *all* signed&unsigned integer types (and `char`). So that includes extended integer types.
>
> Would it fail to compile?
>
>
>
For insertion, that depends on the types used. `int8_t` is safe because there are standard integer types that are larger than it. It may have different behavior than you expect, but it will work.
By contrast, there is no guarantee that `int_least64_t` or `intmax_t` is not larger than `long long`. And implicit conversion can't go from larger to smaller. In those cases, you get a compile error.
For extraction, you get compilation failures if you don't match the types.
>
> Would standard library implementors have to provide additional undocumented methods?
>
>
>
No. They are permitted to do so, but that's not something you can rely on.
---
`int8_t` is a special case because of the treatment of how it can be implemented.
`char` serves double duty as a byte-sized type and a character type. Because it's a character type, iostream operations will treat uses of `char` differently from how it treats integer types. With integers, it will parse/generate integer strings. With a character, it assumes you mean to read a character.
A valid implementation of `int8_t` could be as an alias of `signed char` or just `char` if it is signed. As such, use of it with stream operations will *[treat it as a character](http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2)*.
A valid implementation of `int8_t` could be as an extended integer type, a type which is *distinct* from `char`. As such, the value will be upconverted to a larger integer type that matches one of the standard ones, in accord with overload resolution rules. And therefore, it will [call one of these](http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt). |
26,031,492 | What's the easiest way to authenticate into Google BigQuery when on a Google Compute Engine instance? | 2014/09/25 | [
"https://Stackoverflow.com/questions/26031492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132438/"
] | This is a interesting question, but I believe it doesn't. DI is more about automatic dependency injection. You declare the dependencies and someone, normally a Inversion of Control (IoC) container, injects those deps in your class.
Be aware that jsp is converted to a servlet class and `<jsp:include>` is a method call to another servlet class.
I suggest the above reading:
<http://www.martinfowler.com/articles/injection.html>
<http://misko.hevery.com/code-reviewers-guide/> | In `<jsp:include>` you have to specify what is the page name you are going to include. so that is kind of hard coding your dependency. Purpose of dependency injection is to separate dependent. That is not achieved through `<jsp:include>`. |
26,031,492 | What's the easiest way to authenticate into Google BigQuery when on a Google Compute Engine instance? | 2014/09/25 | [
"https://Stackoverflow.com/questions/26031492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132438/"
] | This is a interesting question, but I believe it doesn't. DI is more about automatic dependency injection. You declare the dependencies and someone, normally a Inversion of Control (IoC) container, injects those deps in your class.
Be aware that jsp is converted to a servlet class and `<jsp:include>` is a method call to another servlet class.
I suggest the above reading:
<http://www.martinfowler.com/articles/injection.html>
<http://misko.hevery.com/code-reviewers-guide/> | * In Dependency Injection or lesser used term Inversion of Control is actually *The the passing of a dependency (a service) to a dependent object (a client)* (Source:[Wikipedia](http://en.wikipedia.org/wiki/Dependency_injection)). But this responsibility of passing or association is not done by the two objects in question themselves but some third entity, let's say Dependency Injector.
* Now the very objective of DI is that the object to be associated with each other, do not do the association themselves but leave it to the Dependency Injector via some configuration.
* Any Dependency Injector OR DI framework (e.g. Spring) is responsible for **taking away the responsibility of creating and associating** the objects from object themselves so that Object worry only about the business logic and leave the creation/configuration to the framework.
* In the example of `<jsp:include>`, One JSP is including the other JSP, the JSPs themselves are assuming the responsibility of associating themselves hence *this is NOT a DI example*. |
5,103,113 | To create Button and its click event in run time I use:
```
Button b = new Button();
b.Name = "btn1";
b.Click += btn1_Click;
```
But now I have an array of Buttons to create in run time; how to set each button's event - I cannot interpolate because it's not a string.
```
Button[] b = new Button(Count);
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += ??????
}
```
what should I do for "?????" | 2011/02/24 | [
"https://Stackoverflow.com/questions/5103113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/529310/"
] | You can bind all buttons to the same event, so put the line like `b[i].Click += button_Click;`.
Then inside the `button_Click` event you can differentiate between the buttons, and take the proper actions.
For example:
```
public void button_Click(object sender, ButtonEventArgs e)
{
if( sender == b[0] )
{
//do what is appropriate for the first button
}
...
}
``` | It depends on what you want to do! If you want to have the same method called for all clicks, do this:
```
Button[] b = new Button[Count];
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += OnClick
}
private void OnClick(object sender, RoutedEventArgs e)
{
// do something
}
```
If you want to do something different for each button, e.g. depending on the index, you can do something like this:
```
Button[] b = new Button[Count];
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += (s, e) => { /*do something*/ };
}
``` |
5,103,113 | To create Button and its click event in run time I use:
```
Button b = new Button();
b.Name = "btn1";
b.Click += btn1_Click;
```
But now I have an array of Buttons to create in run time; how to set each button's event - I cannot interpolate because it's not a string.
```
Button[] b = new Button(Count);
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += ??????
}
```
what should I do for "?????" | 2011/02/24 | [
"https://Stackoverflow.com/questions/5103113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/529310/"
] | **Option 1:**
You can pass an lambda function, and create the handler based on the buttons index in the array like this:
```
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += (sender, args) =>
{
// your code
}
}
```
**Option 2:**
You can pass an anonymus delegate:
```
b[i].Click += delegate (sender, args) {
// your code
};
```
**Option 3:**
You can specify a handler function:
```
b[i].Click += YourHandlerFunction
// ....
// The handler signature also has to have the correct signature
void YourHandlerFunction(object sender, ButtonEventArgs args)
{
// your code
}
``` | It depends on what you want to do! If you want to have the same method called for all clicks, do this:
```
Button[] b = new Button[Count];
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += OnClick
}
private void OnClick(object sender, RoutedEventArgs e)
{
// do something
}
```
If you want to do something different for each button, e.g. depending on the index, you can do something like this:
```
Button[] b = new Button[Count];
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += (s, e) => { /*do something*/ };
}
``` |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | `array_pop` returns last value not remaining part.
so change this line `$fav = array_pop($fav);` to `array_pop($fav);` | array\_pop returns the remove element, not the array itself.
try this:
```
<pre>
<?php
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$last = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
?>
</pre>
``` |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | `array_pop` returns last value not remaining part.
so change this line `$fav = array_pop($fav);` to `array_pop($fav);` | you've overwritten the variable `$fav`.
you also might want to remove the last `|` from your string that you explode.
```
<?php
$fav = explode("|","0 | 1 | 2");
print_r($fav); // output should be: 0, 1, 2
$last_element = array_pop($fav);
echo "<br>after <br>";
print_r($fav); // output should be: 0, 1
?>
``` |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | Remove the assigment, so it looks like this:
```
array_pop($fav);
```
[array\_pop](http://php.net/manual/en/function.array-pop.php) returns the removed value and modifies the array in-place, so you must not assign the return value to the array variable. | you've overwritten the variable `$fav`.
you also might want to remove the last `|` from your string that you explode.
```
<?php
$fav = explode("|","0 | 1 | 2");
print_r($fav); // output should be: 0, 1, 2
$last_element = array_pop($fav);
echo "<br>after <br>";
print_r($fav); // output should be: 0, 1
?>
``` |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | ```
<?php
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$remove_last= array_pop($fav);
echo "<br>after <br>";
print_r($fav);
?>
output
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] =>
)
after
Array
(
[0] => 0
[1] => 1
[2] => 2
)
``` | array\_pop returns the remove element, not the array itself.
try this:
```
<pre>
<?php
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$last = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
?>
</pre>
``` |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | ```
<?php
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$remove_last= array_pop($fav);
echo "<br>after <br>";
print_r($fav);
?>
output
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] =>
)
after
Array
(
[0] => 0
[1] => 1
[2] => 2
)
``` | You're assigning the result of `array_pop` over the original array. Change that line to:
```
$removed = array_pop($fav);
``` |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | Remove the assigment, so it looks like this:
```
array_pop($fav);
```
[array\_pop](http://php.net/manual/en/function.array-pop.php) returns the removed value and modifies the array in-place, so you must not assign the return value to the array variable. | You're assigning the result of `array_pop` over the original array. Change that line to:
```
$removed = array_pop($fav);
``` |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | `array_pop` returns last value not remaining part.
so change this line `$fav = array_pop($fav);` to `array_pop($fav);` | ```
<?php
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$remove_last= array_pop($fav);
echo "<br>after <br>";
print_r($fav);
?>
output
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] =>
)
after
Array
(
[0] => 0
[1] => 1
[2] => 2
)
``` |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | `array_pop` returns last value not remaining part.
so change this line `$fav = array_pop($fav);` to `array_pop($fav);` | Remove the assigment, so it looks like this:
```
array_pop($fav);
```
[array\_pop](http://php.net/manual/en/function.array-pop.php) returns the removed value and modifies the array in-place, so you must not assign the return value to the array variable. |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | `array_pop` returns last value not remaining part.
so change this line `$fav = array_pop($fav);` to `array_pop($fav);` | You're assigning the result of `array_pop` over the original array. Change that line to:
```
$removed = array_pop($fav);
``` |
5,101,017 | ```
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$fav = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
```
what's the problem in my code? i want to remove the last value in the array `$fav`. | 2011/02/24 | [
"https://Stackoverflow.com/questions/5101017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612987/"
] | Remove the assigment, so it looks like this:
```
array_pop($fav);
```
[array\_pop](http://php.net/manual/en/function.array-pop.php) returns the removed value and modifies the array in-place, so you must not assign the return value to the array variable. | array\_pop returns the remove element, not the array itself.
try this:
```
<pre>
<?php
$fav = explode("|","0 | 1 | 2 | ");
print_r($fav);
$last = array_pop($fav);
echo "<br>after <br>";
print_r($fav);
?>
</pre>
``` |
42,341,537 | I have a list of gaming rooms which is created by Spring. Each rooms corresponds some rules (which is enum), and the code is:
```
@Bean
List<Room> rooms() {
return Arrays.stream(Rules.values())
.map(rule -> new Room(rule))
.collect(Collectors.toList());
}
```
But now I need the rooms to be `@Beans` too: I want Spring to process `@EventListener` annotation in them. However, I don't want to declare them manually in config as the `Rules` enum can be updated in the future. How can I solve this problem? Thanks. | 2017/02/20 | [
"https://Stackoverflow.com/questions/42341537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2572584/"
] | It can be accomplished by invoking another method which is marked with `@Bean` i.e. creates `Room` bean as shown below
```
@Bean
List<Room> rooms() {
return Arrays.stream(Rules.values())
.map(rule -> room(rule))
.collect(Collectors.toList());
}
@Bean
Room room(Rule rule) {
return new Room(rule);
}
```
This should suffice without need of `@EventListener`.
Let know in comments if any more information is required. | In my opinion, there is another option
```
@Bean
List<Room> rooms() {
return Arrays.stream(Rules.values())
.map(rule -> {
Room r = room(rule);
this.beanFactory.initializeBean(r, <some unique name>);
this.beanFactory.autowireBean(r);
this.beanFactory.registerSingleton(<same name>, r);
})
.collect(Collectors.toList());
}
private Room room(Rule rule) {
return new Room(rule);
}
```
within a @Configuration class having,
```
@Autowired
private ConfigurableListableBeanFactory beanFactory;
``` |
563,424 | What I'm trying to do is to display the third row first then the second row and then the first row, is there a way to do that? Thanks again in advance for your help.
```
\documentclass{beamer}
\begin{document}
\begin{frame}{test}
$\begin{bmatrix}
\pause
1 & -3 & 0 & 5 \\
\pause
-1 & 1 & 5 & 2 \\
\pause
0 & 0 & \tfrac{7}{2} & \tfrac{7}{2} \\
\end{bmatrix}$
\end{frame}
\end{document}
``` | 2020/09/20 | [
"https://tex.stackexchange.com/questions/563424",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/98778/"
] | You cal use the `calc` library.
```
\documentclass[border=1cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (3,1);
\fill (A) circle (0.1);
\fill (B) circle (0.1);
\draw (A) node[below] {A} -- (B) node[below] {B} -- ($ (B)!1!-90:(A) $) -- ($ (A)!1!90:(B) $) -- cycle;
\end{tikzpicture}
\end{document}
```
[![Square](https://i.stack.imgur.com/TwD3t.png)](https://i.stack.imgur.com/TwD3t.png) | Something like this? `tikz/turn` is a good choice.
[![enter image description here](https://i.stack.imgur.com/FcwTK.png)](https://i.stack.imgur.com/FcwTK.png)
```
\documentclass[tikz, border=1cm]{standalone}
\usepackage{xparse}
\makeatletter
\NewDocumentCommand { \mysquare } { s O{} D(){a} D(){b} }
{
\tikz@scan@one@point\pgf@process(#3)
\pgf@xa = \pgf@x
\pgf@ya = \pgf@y
\tikz@scan@one@point\pgf@process(#4)
\pgfmathsetmacro{\square@l}{
sqrt( (\pgf@x - \pgf@xa)^2 + (\pgf@y - \pgf@ya)^2 )
}
\def\square@sign{}
\IfBooleanT { #1 } { \def\square@sign{-} }
\draw[#2] (#3) -- (#4)
-- ([turn]\square@sign 90:\square@l pt)
-- ([turn]\square@sign 90:\square@l pt)
-- cycle;
}
\makeatother
\begin{document}
\begin{tikzpicture}
\coordinate [label=below left:$A$] (a) at (0, 0);
\coordinate [label=right:$B$] (b) at (2, 3);
\coordinate [label=above:$C$] (c) at (2, 1);
\mysquare[thick](a)(b)
\mysquare*[thick, red](a)(c)
\end{tikzpicture}
\end{document}
``` |
563,424 | What I'm trying to do is to display the third row first then the second row and then the first row, is there a way to do that? Thanks again in advance for your help.
```
\documentclass{beamer}
\begin{document}
\begin{frame}{test}
$\begin{bmatrix}
\pause
1 & -3 & 0 & 5 \\
\pause
-1 & 1 & 5 & 2 \\
\pause
0 & 0 & \tfrac{7}{2} & \tfrac{7}{2} \\
\end{bmatrix}$
\end{frame}
\end{document}
``` | 2020/09/20 | [
"https://tex.stackexchange.com/questions/563424",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/98778/"
] | You cal use the `calc` library.
```
\documentclass[border=1cm]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (3,1);
\fill (A) circle (0.1);
\fill (B) circle (0.1);
\draw (A) node[below] {A} -- (B) node[below] {B} -- ($ (B)!1!-90:(A) $) -- ($ (A)!1!90:(B) $) -- cycle;
\end{tikzpicture}
\end{document}
```
[![Square](https://i.stack.imgur.com/TwD3t.png)](https://i.stack.imgur.com/TwD3t.png) | The `tkz-euclide` package has a lot of features for making geometric constructions, including making a square from two previously defined coordinates:
```
\tkzDefSquare(A,B)
\tkzGetPoints{C}{D}
```
The first line defines the square based on `A` and `B`. The seconds gets the coordinates of the last two corners, and creates named coordinates `C` and `D`.
```
\documentclass[border=1cm]{standalone}
\usepackage{tkz-euclide}
\begin{document}
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (3,1);
\tkzDefSquare(A,B)
\tkzGetPoints{C}{D}
\tkzDrawPoints[size=8](A,B,C,D)
\tkzDrawPolygon(A,B,C,D)
\end{tikzpicture}
\end{document}
``` |
563,424 | What I'm trying to do is to display the third row first then the second row and then the first row, is there a way to do that? Thanks again in advance for your help.
```
\documentclass{beamer}
\begin{document}
\begin{frame}{test}
$\begin{bmatrix}
\pause
1 & -3 & 0 & 5 \\
\pause
-1 & 1 & 5 & 2 \\
\pause
0 & 0 & \tfrac{7}{2} & \tfrac{7}{2} \\
\end{bmatrix}$
\end{frame}
\end{document}
``` | 2020/09/20 | [
"https://tex.stackexchange.com/questions/563424",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/98778/"
] | The `tkz-euclide` package has a lot of features for making geometric constructions, including making a square from two previously defined coordinates:
```
\tkzDefSquare(A,B)
\tkzGetPoints{C}{D}
```
The first line defines the square based on `A` and `B`. The seconds gets the coordinates of the last two corners, and creates named coordinates `C` and `D`.
```
\documentclass[border=1cm]{standalone}
\usepackage{tkz-euclide}
\begin{document}
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (3,1);
\tkzDefSquare(A,B)
\tkzGetPoints{C}{D}
\tkzDrawPoints[size=8](A,B,C,D)
\tkzDrawPolygon(A,B,C,D)
\end{tikzpicture}
\end{document}
``` | Something like this? `tikz/turn` is a good choice.
[![enter image description here](https://i.stack.imgur.com/FcwTK.png)](https://i.stack.imgur.com/FcwTK.png)
```
\documentclass[tikz, border=1cm]{standalone}
\usepackage{xparse}
\makeatletter
\NewDocumentCommand { \mysquare } { s O{} D(){a} D(){b} }
{
\tikz@scan@one@point\pgf@process(#3)
\pgf@xa = \pgf@x
\pgf@ya = \pgf@y
\tikz@scan@one@point\pgf@process(#4)
\pgfmathsetmacro{\square@l}{
sqrt( (\pgf@x - \pgf@xa)^2 + (\pgf@y - \pgf@ya)^2 )
}
\def\square@sign{}
\IfBooleanT { #1 } { \def\square@sign{-} }
\draw[#2] (#3) -- (#4)
-- ([turn]\square@sign 90:\square@l pt)
-- ([turn]\square@sign 90:\square@l pt)
-- cycle;
}
\makeatother
\begin{document}
\begin{tikzpicture}
\coordinate [label=below left:$A$] (a) at (0, 0);
\coordinate [label=right:$B$] (b) at (2, 3);
\coordinate [label=above:$C$] (c) at (2, 1);
\mysquare[thick](a)(b)
\mysquare*[thick, red](a)(c)
\end{tikzpicture}
\end{document}
``` |
55,023 | Note: by external website I mean a website that we do not have access to the code. For example www.facebook.com
I want to record how many social share clicks we have from our customer newsletters. For example, when a customer receives a newsletter they can click "Share this on Facebook" which shares the hosted version of the newsletter.
If I wanted to record these newsletter clicks to our website I understand we'd use Google URL Builder (<https://support.google.com/analytics/answer/1033867?hl=en>) to create a UTM URL but because we're linking to an external site, how do we record this? | 2013/11/11 | [
"https://webmasters.stackexchange.com/questions/55023",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/10111/"
] | If you cannot insert Analytics Code at the target site then the easiest (and probably only) way would be to send them to a page on your own domain that records the click and then redirects to the intended URL. (This is how e-mail tracking in most professional newsletter software packages works in any case.) | You could embed a tracking pixel in your content. This is possible on Facebook (AFAIK) by using the power editor.
There are many online tracking pixel services providing Google Analytics integration, but you'll need one providing referral information in order to implement the scenario you described. |
63,302 | ![2:15 pm](https://i.stack.imgur.com/JlbBRm.png)
I have figured out the 1st box which is basic: *I Understand*.
What is the answer to the second box, circled in yellow? I am not sure if the circled 25 & 31 are part of the puzzle or just the number of the puzzle. | 2018/04/04 | [
"https://puzzling.stackexchange.com/questions/63302",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/47598/"
] | I think the one in yellow circle means.
>
> Equal Time
>
>
> | Is it
>
> 30 degrees which is the angle that is created between the hour and minute hand at 2:15
>
>
> |
12,700,708 | So this tutorial that I am using is not being as straight forward as I am hoping for. The next step requires the following:
"We need to create a class implementing abstract LocationListener class. This class will be registered with Location Manager to receive updates of location. We need to override all four methods of this class, namely onLocationChanged, onProviderDisabled/Enabled, and onStatusChanged. As we are just interested in getting location updates, we will modify the code of onLocationChanged to navigate to the new location received in the map view. This is achieved by calling animateTo method of MapController."
I would just like a little bit of advice as to if its a class I need to create on my own (new>Class) method, or is it just code I am supposed to add into another file. | 2012/10/03 | [
"https://Stackoverflow.com/questions/12700708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1715787/"
] | This is a new addition in [ServiceStack's New API](https://github.com/ServiceStack/ServiceStack/wiki/New-Api) which allows you to document the expected Response Type that the Request DTO will return, e.g. with
```
ReqDTO : IReturn<List<ResDTO>> { ... }
```
Which lets you call using any of the C# Service Clients with:
```
List<ResDTO> response = client.Get(new ReqDto());
```
If you didn't have the IReturn marker your client call would have to look like:
```
List<ResDTO> response = client.Get<List<ResDTO>>(new ReqDto());
```
Which is something the client/consumer of your service needs to know about. If you had the marker on the DTO the response type is already known.
The `IReturn<>` marker is also used to determine the Response DTO that's used in the HTTP Responses in ServiceStack's `/metadata` pages. | As far as I know, this is just a convenient way of defining your request/response DTOs.
You're free to use it, or not. |
12,700,708 | So this tutorial that I am using is not being as straight forward as I am hoping for. The next step requires the following:
"We need to create a class implementing abstract LocationListener class. This class will be registered with Location Manager to receive updates of location. We need to override all four methods of this class, namely onLocationChanged, onProviderDisabled/Enabled, and onStatusChanged. As we are just interested in getting location updates, we will modify the code of onLocationChanged to navigate to the new location received in the map view. This is achieved by calling animateTo method of MapController."
I would just like a little bit of advice as to if its a class I need to create on my own (new>Class) method, or is it just code I am supposed to add into another file. | 2012/10/03 | [
"https://Stackoverflow.com/questions/12700708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1715787/"
] | This is a new addition in [ServiceStack's New API](https://github.com/ServiceStack/ServiceStack/wiki/New-Api) which allows you to document the expected Response Type that the Request DTO will return, e.g. with
```
ReqDTO : IReturn<List<ResDTO>> { ... }
```
Which lets you call using any of the C# Service Clients with:
```
List<ResDTO> response = client.Get(new ReqDto());
```
If you didn't have the IReturn marker your client call would have to look like:
```
List<ResDTO> response = client.Get<List<ResDTO>>(new ReqDto());
```
Which is something the client/consumer of your service needs to know about. If you had the marker on the DTO the response type is already known.
The `IReturn<>` marker is also used to determine the Response DTO that's used in the HTTP Responses in ServiceStack's `/metadata` pages. | In the case where you define your DTOs in a portable class library, you won't be able to use IReturn. Perhaps IReturn should be defined in a PCL in ServiceStack. Just a thought. |
57,687,611 | I have written the below SQL query to join four tables and do the calculations based on criteria but throws an error. Will appreciate for any help. Thanks
Not sure where I am doing wrong or whether my logic is not right?
```
SELECT C.cust_name,
R.Reg_name,
sum(CASE WHEN P.Class = 'R' THEN T.Amount*.1 WHEN P.Class = 'P' THEN T.Amount*.2 ELSE T.Amount*.1 END) AS Calc_Amount
FROM Customers C,
Regions R,
transactions T,
customer_class P
WHERE C.reg_id = R.reg_id, C.cust_id = T.cust_id, C.cust_id = P.cust_id
AND P.class_id, P.class IN (SELECT max(class_id), class
FROM customer_class
GROUP BY cust_id)
AND T.Time, T.Amount IN (SELECT max(time),
Amount
FROM transactions
GROUP BY cust_id)
GROUP BY C.cust_name
ORDER BY C.cust_name
```
SQL command not properly ended | 2019/08/28 | [
"https://Stackoverflow.com/questions/57687611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10695168/"
] | You can't combine multiple conditions with an `,` in the WHERE clause. You probably want an and there:
```
WHERE C.reg_id = R.reg_id
AND C.cust_id = T.cust_id
AND C.cust_id = P.cust_id
```
But I strongly recommend to switch to an explicit `JOIN` in the FROM clause:
```
FROM Customers C
JOIN Regions R ON C.reg_id = R.reg_id
JOIN transactions T ON C.cust_id = T.cust_id
JOIN customer_class P ON C.cust_id = P.cust_id
```
Additionally, when you want to use multiple columns with an IN operator, you need to enclose the columns on the left hand side with parentheses, e.g. `(P.class_id, P.class)` instead of `P.class_id, P.class`.
You also need to include all columns that are not used in an aggregation in the `group by` clause.
So the complete query should look something like:
```sql
SELECT C.cust_name,
R.Reg_name,
sum(CASE WHEN P.Class = 'R' THEN T.Amount*.1 WHEN P.Class = 'P' THEN T.Amount*.2 ELSE T.Amount*.1 END) AS Calc_Amount
FROM Customers C
JOIN Regions R ON C.reg_id = R.reg_id
JOIN transactions T ON C.cust_id = T.cust_id
JOIN customer_class P ON C.cust_id = P.cust_id
WHERE (P.class_id, P.class) IN (SELECT max(class_id), class
FROM customer_class
GROUP BY cust_id)
AND (T.Time, T.Amount) IN (SELECT max(time), Amount
FROM transactions
GROUP BY cust_id)
GROUP BY C.cust_name, R.Reg_name
ORDER BY C.cust_name
``` | I would recommend proper `join` syntax *and* using window functions. I think you want something like this:
```
SELECT C.cust_name,
sum(CASE WHEN P.Class = 'R' THEN T.Amount*.1 WHEN P.Class = 'P' THEN T.Amount*.2 ELSE T.Amount*.1 END) AS Calc_Amount
FROM Customers C JOIN
Regions R
C.reg_id = R.reg_id JOIN
(SELECT T.*,
ROW_NUMBER() OVER (PARTITION BY T.cust_id ORDER BY T.Time DESC) as seqnum
FROM transactions T
) T
ON C.cust_id = T.cust_id AND seqnum = 1 JOIN
(SELECT P.*,
ROW_NUMBER() OVER (PARTITION BY P.cust_id ORDER BY P.class_id DESC) as seqnum
FROM customer_class P
) P
ON C.cust_id = P.cust_id
GROUP BY C.cust_name
ORDER BY C.cust_name;
```
However, I'm not sure that this logic does anything useful. You should probably ask a *new* question with sample data and desired results. |
57,687,611 | I have written the below SQL query to join four tables and do the calculations based on criteria but throws an error. Will appreciate for any help. Thanks
Not sure where I am doing wrong or whether my logic is not right?
```
SELECT C.cust_name,
R.Reg_name,
sum(CASE WHEN P.Class = 'R' THEN T.Amount*.1 WHEN P.Class = 'P' THEN T.Amount*.2 ELSE T.Amount*.1 END) AS Calc_Amount
FROM Customers C,
Regions R,
transactions T,
customer_class P
WHERE C.reg_id = R.reg_id, C.cust_id = T.cust_id, C.cust_id = P.cust_id
AND P.class_id, P.class IN (SELECT max(class_id), class
FROM customer_class
GROUP BY cust_id)
AND T.Time, T.Amount IN (SELECT max(time),
Amount
FROM transactions
GROUP BY cust_id)
GROUP BY C.cust_name
ORDER BY C.cust_name
```
SQL command not properly ended | 2019/08/28 | [
"https://Stackoverflow.com/questions/57687611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10695168/"
] | You can't combine multiple conditions with an `,` in the WHERE clause. You probably want an and there:
```
WHERE C.reg_id = R.reg_id
AND C.cust_id = T.cust_id
AND C.cust_id = P.cust_id
```
But I strongly recommend to switch to an explicit `JOIN` in the FROM clause:
```
FROM Customers C
JOIN Regions R ON C.reg_id = R.reg_id
JOIN transactions T ON C.cust_id = T.cust_id
JOIN customer_class P ON C.cust_id = P.cust_id
```
Additionally, when you want to use multiple columns with an IN operator, you need to enclose the columns on the left hand side with parentheses, e.g. `(P.class_id, P.class)` instead of `P.class_id, P.class`.
You also need to include all columns that are not used in an aggregation in the `group by` clause.
So the complete query should look something like:
```sql
SELECT C.cust_name,
R.Reg_name,
sum(CASE WHEN P.Class = 'R' THEN T.Amount*.1 WHEN P.Class = 'P' THEN T.Amount*.2 ELSE T.Amount*.1 END) AS Calc_Amount
FROM Customers C
JOIN Regions R ON C.reg_id = R.reg_id
JOIN transactions T ON C.cust_id = T.cust_id
JOIN customer_class P ON C.cust_id = P.cust_id
WHERE (P.class_id, P.class) IN (SELECT max(class_id), class
FROM customer_class
GROUP BY cust_id)
AND (T.Time, T.Amount) IN (SELECT max(time), Amount
FROM transactions
GROUP BY cust_id)
GROUP BY C.cust_name, R.Reg_name
ORDER BY C.cust_name
``` | Building on @a\_horse\_with\_no\_name's answer - the problem is with the `GROUP BY` expressions in the subqueries in the WHERE clause. It looks like you should be using
```
SELECT C.cust_name,
R.Reg_name,
sum(CASE WHEN P.Class = 'R' THEN T.Amount*.1 WHEN P.Class = 'P' THEN T.Amount*.2 ELSE T.Amount*.1 END) AS Calc_Amount
FROM Customers C
JOIN Regions R ON C.reg_id = R.reg_id
JOIN transactions T ON C.cust_id = T.cust_id
JOIN customer_class P ON C.cust_id = P.cust_id
WHERE (P.class_id, P.class) IN (SELECT max(class_id), class
FROM customer_class
GROUP BY class)
AND (T.Time, T.Amount) IN (SELECT max(time), Amount
FROM transactions
GROUP BY amount)
GROUP BY C.cust_name, R.Reg_name
ORDER BY C.cust_name
```
That will probably execute, but I'm not sure it'll give you the results you wanted. Another possibility is
```
SELECT C.cust_name,
R.Reg_name,
sum(CASE WHEN P.Class = 'R' THEN T.Amount*.1 WHEN P.Class = 'P' THEN T.Amount*.2 ELSE T.Amount*.1 END) AS Calc_Amount
FROM Customers C
JOIN Regions R ON C.reg_id = R.reg_id
JOIN transactions T ON C.cust_id = T.cust_id
JOIN customer_class P ON C.cust_id = P.cust_id
WHERE (P.class_id, P.class) IN (SELECT max(class_id), class
FROM customer_class
GROUP BY class)
AND (T.cust_id, T.Time, T.Amount) IN (SELECT cust_id, max(time), max(Amount)
FROM transactions
GROUP BY cust_id)
GROUP BY C.cust_name, R.Reg_name
ORDER BY C.cust_name
```
but I doubt the second sub-select does what you had in mind. But without test data and expected results it's impossible to understand what you're trying to do. You might consider editing the question and adding test data and expected results **as text, not as an image** so people can test their queries against the expected results. |
70,524,236 | I am trying to find specific digits in a Microsoft Word Document which contains text and digits, with VBA.
For example the text in the document is as follows;
(1) 52.203-19, This is a some text here
(2) 52.204-23, Quick brown fox jumped over the lazy dog 52 times.
(3) 52.204-25, I tried to search for a solution 52.204 times.
(4) 52.2, Could not find any luck though
(5) 52.203, this is blowing my mind away with mac 2.36
I wish to find the exact digits "**52.2**" as a whole.
I don't want to find instances where **52.2** is a part of another number like **52.2**03 or **52.2**04.
Also when I would like to find **52.203** then I want to exclude all instances like 52.203-xx where xx could be any two digit number.
In short I would like to find the exact number only as a whole and not in between the numbers, just like Excel's EXACT function.
Should I use RegEx or should I use Word's Advanced Find function with wildcards through VBA?
What I have finds all instances which I don't want.
```vb
Selection.Find.ClearFormatting
With Selection.Find
.Text = "52.2"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
``` | 2021/12/29 | [
"https://Stackoverflow.com/questions/70524236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17791302/"
] | Split the query into two queries for each part of the `OR`. Then combine them with `UNION`.
```
SELECT id, name, GROUP_CONCAT(DISTINCT externalDisplayID SEPARATOR ', ') AS tags
FROM (
SELECT c.id, c.name, tags.externalDisplayID
FROM checklist c
LEFT JOIN questionchecklistjoin qcheckj on qcheckj.checklistID = c.id
LEFT JOIN questioncategoryjoin qcatj ON qcatj.questionID = qcheckj.questionID
LEFT JOIN crosswalk cw on cw.fromQuestionCategoryJoinID = qcatj.id
LEFT JOIN questioncategoryjoin qcj1 on qcj1.id = cw.toQuestionCategoryJoinID
LEFT JOIN question tags on tags.id = qcj1.questionID
UNION ALL
SELECT c.id, c.name, tags.externalDisplayID
FROM checklist c
LEFT JOIN questionchecklistjoin qcheckj on qcheckj.checklistID = c.id
LEFT JOIN questioncategoryjoin qcatj ON qcatj.questionID = qcheckj.questionID
LEFT JOIN questioncategoryjoin qcatjsub on qcatjsub.parentQuestionID = qcatj.questionID
LEFT JOIN crosswalk cw on cw.fromQuestionCategoryJoinID = qcatjsub.id
LEFT JOIN questioncategoryjoin qcj1 on qcj1.id = cw.toQuestionCategoryJoinID
LEFT JOIN question tags on tags.id = qcj1.questionID
) AS x
GROUP BY x.id
ORDER BY x.name
```
Also, it doesn't make sense to include `externalDisplayID` in `ORDER BY`, because that will order by its value from a random row in the group. You could put `ORDER BY externalDisplayID` in the `GROUP_CONCAT()` arguments if that's what you want. | There is a second inefficiency going on here. I call it "explode-implode". First a bunch of `JOINs` (potentially) expand the number of rows in an intermediate table, then `GROUP BY c.id` collapses the number of rows back to what you started with (one row of output per row of `checkpoint`).
Before trying to help with that, please answer:
* Is `LEFT` really needed?
* How many rows in each table? (Especially in `cw`)
* Can you get rid of `DISTINCT`?
Barmar's answer can possibly be improved upon by delaying the `JOINs to` qcj1`and`tags`until after the`UNION`:
```
SELECT ...
FROM ( SELECT ...
FROM first few tables
UNION ALL
SELECT ...
FROM first few tables
) AS u
[LEFT] JOIN qcj1
[LEFT] JOIN tags
GROUP BY ...
ORDER BY ...
```
Another optimization (again building on Barmar's)
```
GROUP BY x.id
ORDER BY x.name
```
-->
```
GROUP BY x.name, x.id
ORDER BY x.name, x.id
```
When the items in `GROUP BY` and `ORDER BY` are the "same", they can be done in a single action, thereby saving (at least) a sort.
`x.name, x.id` is deterministic, where as `x.name` might put two rows with the same `name` in a different order, depending (perhaps) on the phase of the moon.
These indexes may help:
```
qcheckj: INDEX(checklistID, questionID)
qcatj: INDEX(questionID, id)
qcatjsub: INDEX(parentQuestionID, id)
cw: INDEX(fromQuestionCategoryJoinID, toQuestionCategoryJoinID)
``` |
54,555 | I have to write essays in two examinations which will be conducted soon. Those exams need essays to be written in 250 words. The topics are given on the time of the exams and are usually anything based on government schemes, matters of national and international importance, or anything that is often in news, etc. Last year (I think), they asked essays on Ethical banking, Influence of social media, Contribution of unorganised Sector in Indian economy, etc.
**Question:**
Essentially, this is a test of writing rather than that of knowledge. However, I think it's best if the essay essentially is somehow "complete" covering as many important aspect as possible even if in layman's terms. So, what structure may I follow to write good yet comprehensive essays in the word limits of 250 words? | 2021/01/20 | [
"https://writers.stackexchange.com/questions/54555",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/47115/"
] | I would take the standard 5 paragraph Essay format but modified for brevity. Your thesis or introduction answer should be your immediate answer to a writing prompt and should be no more than one sentance. Rephrase the question as your sentance (i.e. if the question is "What would be the platform you would run on if you were running for President of the United States?" then your response should be "If I were to run for President of the United States, my platform would address [item 1], [Item 2], and [item 3]."). Your conclusion paragraph should restate the thesis. The three paragraphs in between should briefly address best arguements for your thesis in order of strongest to weakest (for me, my answers would be economic improvement by reworking tax laws, foreign policy that would place the country in step with a more neutral pre-WWII dealing, and an infrastructure modernization program.). A good 3-4 paragraph argument would suffice for each.
Now before I give you my last piece of advise, do keep in mind that this was given to me by a teacher at an all boys high school, so it was tailored to it's audience of teenager boys who naturally have only one thing on their mind at any give momement. It still helps me to this day, and the somewhat crass nature of the analogy hammers it in:
>
> "A good essay should be like a girl's skirt: It should be long enough to cover everything but short enough to keep it interesting."
>
>
>
That is you shouldn't get far into the weeds on your point or points, especially on test essays. Also do not feel the need to hold strictly to the word count other than try to get the 250 word mark (most essays graders will judge by the eye, so a little wiggle room is allowed. Additionally most won't mark down if the essay goes over 250, though again, keep it close... they aren't asking for a Tolkien novel series. Obviously if you have a word counting program (assuming it's typed and not handwritten), don't short by a word and find a way you can squeeze in a fancy adjective that isn't going to be supferlous.
250 isn't a lot to work with. To get an idea, a 500 word essay assumes 5 paragraphs, each 3-4 sentances long and will fill about one 8X11 inche page on a word processor with a 12 inche font and double spaced. To give yourself a guestimate, google some writing prompts and try to answer them with 250 words but less than 300. | Here is one such format that you could use when constructing your essays:
1. Have a good opening statement and a little background information that makes the grader want to continue reading.
2. Once you have convinced your reader, state your thesis statement/claim. Because you only have 250 words and need to incorporate evidence, this would be the end of your introductory paragraph. (50 word intro)
3. State one way that your claim is supported by the evidence. (I have also found that my teachers have graded me better when I have put in a transition word) Then add a quote and a few lines of analysis, before restating your claim in a new way. (try to limit each body paragraph to 75 words)
4. Repeat for your second body paragraph. (75)
5. For the conclusion, keep it simple: you can save words here. Write an *extremely short* summary of your essay, including your claim, and then finish your piece with any new idea about the topic that shows that you have thought about it and are not just writing mindlessly. (The math would give you 50 words for the conclusion) |
6,037,996 | I need to implement a multi-agent system for an assignment. I have been brainstorming for ideas as to what I should implement, but I did not come up with anything great yet. I do not want it to be a traffic simulation application, but I need something just as useful. | 2011/05/17 | [
"https://Stackoverflow.com/questions/6037996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758257/"
] | I once saw an application of multiagent systems for studying/simulating fire evacuation plans in large buildings. Imagine a large building with thousands of people; in case of fire, you want these people to follow some rules for evacuating the building. To evaluate the effectiveness of your evacuation plan rules, you may want to simulate various scenarios using a multiagent system. I think it's a useful and interesting application. If you search the Web, you will find papers and works in this area, from which you might get further inspiration. | Not sure what you mean by "useful" but... you can always have a look at swarmbased AI (school of fish, flock of birds etc.) Each agent (boid) is very very simple in this case. Make the individual agents follow each other, stay away from a predator etc. |
6,037,996 | I need to implement a multi-agent system for an assignment. I have been brainstorming for ideas as to what I should implement, but I did not come up with anything great yet. I do not want it to be a traffic simulation application, but I need something just as useful. | 2011/05/17 | [
"https://Stackoverflow.com/questions/6037996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758257/"
] | A few come to mind:
1. Exploration and mapping: send a team of agents out into an environment to explore, then assimilate all of their observations into consistent maps (not an easy task!)
2. Elevator scheduling: how to service call requests during peak capacities considering the number and location of pending requests, car locations, and their capacities (not too far removed from traffic-light scheduling, though)
3. Air traffic control: consider landing priorities (i.e. fuel. number of passengers, emergency conditions,etc.), airplane position and speed, and landing conditions (ie. number of runways, etc). Then develop a set of rules so that each "agent" (i.e. airplane) assumes its place in a landing sequence. Note that this is a harder version of the flocking problem mentioned in another reply. | Not sure what you mean by "useful" but... you can always have a look at swarmbased AI (school of fish, flock of birds etc.) Each agent (boid) is very very simple in this case. Make the individual agents follow each other, stay away from a predator etc. |
6,037,996 | I need to implement a multi-agent system for an assignment. I have been brainstorming for ideas as to what I should implement, but I did not come up with anything great yet. I do not want it to be a traffic simulation application, but I need something just as useful. | 2011/05/17 | [
"https://Stackoverflow.com/questions/6037996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758257/"
] | I once saw an application of multiagent systems for studying/simulating fire evacuation plans in large buildings. Imagine a large building with thousands of people; in case of fire, you want these people to follow some rules for evacuating the building. To evaluate the effectiveness of your evacuation plan rules, you may want to simulate various scenarios using a multiagent system. I think it's a useful and interesting application. If you search the Web, you will find papers and works in this area, from which you might get further inspiration. | Its not quite multi-agent but have you considered a variation on ant colony optimisation ?
<http://en.wikipedia.org/wiki/Ant_colony_optimization_algorithms> |
6,037,996 | I need to implement a multi-agent system for an assignment. I have been brainstorming for ideas as to what I should implement, but I did not come up with anything great yet. I do not want it to be a traffic simulation application, but I need something just as useful. | 2011/05/17 | [
"https://Stackoverflow.com/questions/6037996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758257/"
] | I once saw an application of multiagent systems for studying/simulating fire evacuation plans in large buildings. Imagine a large building with thousands of people; in case of fire, you want these people to follow some rules for evacuating the building. To evaluate the effectiveness of your evacuation plan rules, you may want to simulate various scenarios using a multiagent system. I think it's a useful and interesting application. If you search the Web, you will find papers and works in this area, from which you might get further inspiration. | A few come to mind:
1. Exploration and mapping: send a team of agents out into an environment to explore, then assimilate all of their observations into consistent maps (not an easy task!)
2. Elevator scheduling: how to service call requests during peak capacities considering the number and location of pending requests, car locations, and their capacities (not too far removed from traffic-light scheduling, though)
3. Air traffic control: consider landing priorities (i.e. fuel. number of passengers, emergency conditions,etc.), airplane position and speed, and landing conditions (ie. number of runways, etc). Then develop a set of rules so that each "agent" (i.e. airplane) assumes its place in a landing sequence. Note that this is a harder version of the flocking problem mentioned in another reply. |
6,037,996 | I need to implement a multi-agent system for an assignment. I have been brainstorming for ideas as to what I should implement, but I did not come up with anything great yet. I do not want it to be a traffic simulation application, but I need something just as useful. | 2011/05/17 | [
"https://Stackoverflow.com/questions/6037996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758257/"
] | A few come to mind:
1. Exploration and mapping: send a team of agents out into an environment to explore, then assimilate all of their observations into consistent maps (not an easy task!)
2. Elevator scheduling: how to service call requests during peak capacities considering the number and location of pending requests, car locations, and their capacities (not too far removed from traffic-light scheduling, though)
3. Air traffic control: consider landing priorities (i.e. fuel. number of passengers, emergency conditions,etc.), airplane position and speed, and landing conditions (ie. number of runways, etc). Then develop a set of rules so that each "agent" (i.e. airplane) assumes its place in a landing sequence. Note that this is a harder version of the flocking problem mentioned in another reply. | Its not quite multi-agent but have you considered a variation on ant colony optimisation ?
<http://en.wikipedia.org/wiki/Ant_colony_optimization_algorithms> |
4,150 | StackExchange [continues to support TUG with corporate membership](https://tex.meta.stackexchange.com/questions/4140/should-we-keep-our-tex-user-group-membership) (many thanks). With that come eight individual memberships that can be given out to members of the community. The time has come to select our representatives for 2014. For reference, Eight top voted members during last year [TUG Membership: Names for 2013](https://tex.meta.stackexchange.com/q/2906/15717) who have enjoyed [TUG membership benefits](http://tug.org/aims_ben.html)
Following the model from previous years, I'd like to ask people to put themselves forward. There are no restrictions on standing other than having to be a member of the TeX StackExchange site: in particular, the existing 'representatives' are very welcome to put their names forward to continue. [Note: I've called the people we put forward 'representatives', but that's mainly because I can't think of a better term. Nominees should not feel the need to represent TeX-sx other than being members of the site and therefore interested in TeX in some way!]
The model for selection of representatives is as follows. We will have a two stage process, first 'nomination' then 'election'. The first phase runs for five days, until 1700 GMT on 2014-01-07. Each person who wishes to be considered should post an answer, where they can (if they wish) say what makes them a good choice. They should then immediately delete their answer.
The second phase will then begin. All of the answers will be undeleted, and everyone should take a look at these answers and vote for deserving candidates: remember there are eight places available! Again, there will be five days to vote, ending 1700 GMT on 2014-01-12. At that stage, the top eight names will be forwarded to the StackExchange community staff for notification to TUG.
In the event of a tie in number of votes, the mod team will decide which of the tied members are put forward to StackExchange. The mod team may also include additional names *if* at the end of the voting process there are fewer than eight nominees with positive scores.
---
At the end of the voting period, the tallies were as follows:
* [Harish Kumar](https://tex.stackexchange.com/users/11232/harish-kumar), 25
* [Sean Allred](https://tex.stackexchange.com/users/17423/sean-allred), 20
* [Ulrike Fischer](https://tex.stackexchange.com/users/2388/ulrike-fischer), 18
* [cgnieder](https://tex.stackexchange.com/users/5049/cgnieder), 18
* [azetina](https://tex.stackexchange.com/users/10898/azetina), 17
* [Torbjørn T.](https://tex.stackexchange.com/users/586/torbjorn-t), 17
* [Henri Menke](https://tex.stackexchange.com/users/10995/henri-menke), 17
* [morbusg](https://tex.stackexchange.com/users/1410/morbusg), 17
* [Fran](https://tex.stackexchange.com/users/11604/fran), 16
* [Stefan Kottwitz](https://tex.stackexchange.com/users/213/stefan-kottwitz), 13
Our representatives for 2014 are therefore Harish Kumar, Sean Allred, Ulrike Fischer, cgnieder, azetina, Torbjørn T., Henri Menke, and morbusg. Congratulations! | 2014/01/02 | [
"https://tex.meta.stackexchange.com/questions/4150",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/73/"
] | *If* and *only if*, there are free slots, and if nobody notices my nomination in other way, I would like to put my name just to have a taste of TUG membership. Though I have been in TeX world for long time, I was never a member (I just didn't think of it). If I like it I will go for an individual membership after this.
I have no specific goals/aims regarding what I do with the membership, hence feel free to downvote. :-) | I am very far from the merits, reputation and experience of many members of this site. And my knowledge about LaTeX and TUG is still superficial. Thus, certainly I will not a good 'representant' of TeX-sx. My membership could be surely of little utility in TUG (even less than here, if this is possible).
After this "self-promotion", it only remains to add that as I am still curious and I love LaTeX, so anyway, I present my candidacy for membership of TUG, just in case there is a stroke of luck and all the places are not covered with better candidates. |
4,150 | StackExchange [continues to support TUG with corporate membership](https://tex.meta.stackexchange.com/questions/4140/should-we-keep-our-tex-user-group-membership) (many thanks). With that come eight individual memberships that can be given out to members of the community. The time has come to select our representatives for 2014. For reference, Eight top voted members during last year [TUG Membership: Names for 2013](https://tex.meta.stackexchange.com/q/2906/15717) who have enjoyed [TUG membership benefits](http://tug.org/aims_ben.html)
Following the model from previous years, I'd like to ask people to put themselves forward. There are no restrictions on standing other than having to be a member of the TeX StackExchange site: in particular, the existing 'representatives' are very welcome to put their names forward to continue. [Note: I've called the people we put forward 'representatives', but that's mainly because I can't think of a better term. Nominees should not feel the need to represent TeX-sx other than being members of the site and therefore interested in TeX in some way!]
The model for selection of representatives is as follows. We will have a two stage process, first 'nomination' then 'election'. The first phase runs for five days, until 1700 GMT on 2014-01-07. Each person who wishes to be considered should post an answer, where they can (if they wish) say what makes them a good choice. They should then immediately delete their answer.
The second phase will then begin. All of the answers will be undeleted, and everyone should take a look at these answers and vote for deserving candidates: remember there are eight places available! Again, there will be five days to vote, ending 1700 GMT on 2014-01-12. At that stage, the top eight names will be forwarded to the StackExchange community staff for notification to TUG.
In the event of a tie in number of votes, the mod team will decide which of the tied members are put forward to StackExchange. The mod team may also include additional names *if* at the end of the voting process there are fewer than eight nominees with positive scores.
---
At the end of the voting period, the tallies were as follows:
* [Harish Kumar](https://tex.stackexchange.com/users/11232/harish-kumar), 25
* [Sean Allred](https://tex.stackexchange.com/users/17423/sean-allred), 20
* [Ulrike Fischer](https://tex.stackexchange.com/users/2388/ulrike-fischer), 18
* [cgnieder](https://tex.stackexchange.com/users/5049/cgnieder), 18
* [azetina](https://tex.stackexchange.com/users/10898/azetina), 17
* [Torbjørn T.](https://tex.stackexchange.com/users/586/torbjorn-t), 17
* [Henri Menke](https://tex.stackexchange.com/users/10995/henri-menke), 17
* [morbusg](https://tex.stackexchange.com/users/1410/morbusg), 17
* [Fran](https://tex.stackexchange.com/users/11604/fran), 16
* [Stefan Kottwitz](https://tex.stackexchange.com/users/213/stefan-kottwitz), 13
Our representatives for 2014 are therefore Harish Kumar, Sean Allred, Ulrike Fischer, cgnieder, azetina, Torbjørn T., Henri Menke, and morbusg. Congratulations! | 2014/01/02 | [
"https://tex.meta.stackexchange.com/questions/4150",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/73/"
] | *If* and *only if*, there are free slots, and if nobody notices my nomination in other way, I would like to put my name just to have a taste of TUG membership. Though I have been in TeX world for long time, I was never a member (I just didn't think of it). If I like it I will go for an individual membership after this.
I have no specific goals/aims regarding what I do with the membership, hence feel free to downvote. :-) | I'd like to join the election for a TUG membership.
* I hope I can stand a chance against the other, more trusted applicants. I'm a user for 1 year and 11 months now, but really started using this site about 1 year ago. My favourite tags are [tikz-pgf](https://tex.stackexchange.com/questions/tagged/tikz-pgf "show questions tagged 'tikz-pgf'") and [pstricks](https://tex.stackexchange.com/questions/tagged/pstricks "show questions tagged 'pstricks'").
* In the past, I read interesting TUGboat articles online, when they were available. I also read Die TeXnische Komödie as I am a member of dante.
* I advertise for TeX and TeX.SX in university.
* Currently I'm reading the TeXbook to become a better user and I believe, that a TUG membership will help me improving my skills.
* Hopefully, one day I can also publish in the TUGboat or in dante's Die TeXnische Komödie. |
4,150 | StackExchange [continues to support TUG with corporate membership](https://tex.meta.stackexchange.com/questions/4140/should-we-keep-our-tex-user-group-membership) (many thanks). With that come eight individual memberships that can be given out to members of the community. The time has come to select our representatives for 2014. For reference, Eight top voted members during last year [TUG Membership: Names for 2013](https://tex.meta.stackexchange.com/q/2906/15717) who have enjoyed [TUG membership benefits](http://tug.org/aims_ben.html)
Following the model from previous years, I'd like to ask people to put themselves forward. There are no restrictions on standing other than having to be a member of the TeX StackExchange site: in particular, the existing 'representatives' are very welcome to put their names forward to continue. [Note: I've called the people we put forward 'representatives', but that's mainly because I can't think of a better term. Nominees should not feel the need to represent TeX-sx other than being members of the site and therefore interested in TeX in some way!]
The model for selection of representatives is as follows. We will have a two stage process, first 'nomination' then 'election'. The first phase runs for five days, until 1700 GMT on 2014-01-07. Each person who wishes to be considered should post an answer, where they can (if they wish) say what makes them a good choice. They should then immediately delete their answer.
The second phase will then begin. All of the answers will be undeleted, and everyone should take a look at these answers and vote for deserving candidates: remember there are eight places available! Again, there will be five days to vote, ending 1700 GMT on 2014-01-12. At that stage, the top eight names will be forwarded to the StackExchange community staff for notification to TUG.
In the event of a tie in number of votes, the mod team will decide which of the tied members are put forward to StackExchange. The mod team may also include additional names *if* at the end of the voting process there are fewer than eight nominees with positive scores.
---
At the end of the voting period, the tallies were as follows:
* [Harish Kumar](https://tex.stackexchange.com/users/11232/harish-kumar), 25
* [Sean Allred](https://tex.stackexchange.com/users/17423/sean-allred), 20
* [Ulrike Fischer](https://tex.stackexchange.com/users/2388/ulrike-fischer), 18
* [cgnieder](https://tex.stackexchange.com/users/5049/cgnieder), 18
* [azetina](https://tex.stackexchange.com/users/10898/azetina), 17
* [Torbjørn T.](https://tex.stackexchange.com/users/586/torbjorn-t), 17
* [Henri Menke](https://tex.stackexchange.com/users/10995/henri-menke), 17
* [morbusg](https://tex.stackexchange.com/users/1410/morbusg), 17
* [Fran](https://tex.stackexchange.com/users/11604/fran), 16
* [Stefan Kottwitz](https://tex.stackexchange.com/users/213/stefan-kottwitz), 13
Our representatives for 2014 are therefore Harish Kumar, Sean Allred, Ulrike Fischer, cgnieder, azetina, Torbjørn T., Henri Menke, and morbusg. Congratulations! | 2014/01/02 | [
"https://tex.meta.stackexchange.com/questions/4150",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/73/"
] | *If* and *only if*, there are free slots, and if nobody notices my nomination in other way, I would like to put my name just to have a taste of TUG membership. Though I have been in TeX world for long time, I was never a member (I just didn't think of it). If I like it I will go for an individual membership after this.
I have no specific goals/aims regarding what I do with the membership, hence feel free to downvote. :-) | I humbly put myself on the list. I already am a member of [dante](http://www.dante.de/) and would like get the opportunity to help me decide if I pay for a joint membership in the future. (I've been tempted for a while now...)
If I get the chance I promise to write the article about chemistry and LaTeX for TUGboat Karl Berry asked me for about two years ago... (I'll probably be using my yet unfinished [series of blog posts](http://texwelt.de/blog/tag/chemie/) on TeXwelt.de as a basis.) |
4,150 | StackExchange [continues to support TUG with corporate membership](https://tex.meta.stackexchange.com/questions/4140/should-we-keep-our-tex-user-group-membership) (many thanks). With that come eight individual memberships that can be given out to members of the community. The time has come to select our representatives for 2014. For reference, Eight top voted members during last year [TUG Membership: Names for 2013](https://tex.meta.stackexchange.com/q/2906/15717) who have enjoyed [TUG membership benefits](http://tug.org/aims_ben.html)
Following the model from previous years, I'd like to ask people to put themselves forward. There are no restrictions on standing other than having to be a member of the TeX StackExchange site: in particular, the existing 'representatives' are very welcome to put their names forward to continue. [Note: I've called the people we put forward 'representatives', but that's mainly because I can't think of a better term. Nominees should not feel the need to represent TeX-sx other than being members of the site and therefore interested in TeX in some way!]
The model for selection of representatives is as follows. We will have a two stage process, first 'nomination' then 'election'. The first phase runs for five days, until 1700 GMT on 2014-01-07. Each person who wishes to be considered should post an answer, where they can (if they wish) say what makes them a good choice. They should then immediately delete their answer.
The second phase will then begin. All of the answers will be undeleted, and everyone should take a look at these answers and vote for deserving candidates: remember there are eight places available! Again, there will be five days to vote, ending 1700 GMT on 2014-01-12. At that stage, the top eight names will be forwarded to the StackExchange community staff for notification to TUG.
In the event of a tie in number of votes, the mod team will decide which of the tied members are put forward to StackExchange. The mod team may also include additional names *if* at the end of the voting process there are fewer than eight nominees with positive scores.
---
At the end of the voting period, the tallies were as follows:
* [Harish Kumar](https://tex.stackexchange.com/users/11232/harish-kumar), 25
* [Sean Allred](https://tex.stackexchange.com/users/17423/sean-allred), 20
* [Ulrike Fischer](https://tex.stackexchange.com/users/2388/ulrike-fischer), 18
* [cgnieder](https://tex.stackexchange.com/users/5049/cgnieder), 18
* [azetina](https://tex.stackexchange.com/users/10898/azetina), 17
* [Torbjørn T.](https://tex.stackexchange.com/users/586/torbjorn-t), 17
* [Henri Menke](https://tex.stackexchange.com/users/10995/henri-menke), 17
* [morbusg](https://tex.stackexchange.com/users/1410/morbusg), 17
* [Fran](https://tex.stackexchange.com/users/11604/fran), 16
* [Stefan Kottwitz](https://tex.stackexchange.com/users/213/stefan-kottwitz), 13
Our representatives for 2014 are therefore Harish Kumar, Sean Allred, Ulrike Fischer, cgnieder, azetina, Torbjørn T., Henri Menke, and morbusg. Congratulations! | 2014/01/02 | [
"https://tex.meta.stackexchange.com/questions/4150",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/73/"
] | *If* and *only if*, there are free slots, and if nobody notices my nomination in other way, I would like to put my name just to have a taste of TUG membership. Though I have been in TeX world for long time, I was never a member (I just didn't think of it). If I like it I will go for an individual membership after this.
I have no specific goals/aims regarding what I do with the membership, hence feel free to downvote. :-) | I'll, uh, hereby nominate myself. I'm not sure what's expected of the representatives, but I'll cope in case I'm lucky. I haven't done so much answering / editing / voting / reviewing last year because of being so busy busy busy, but hopefully I'll have more time this year.
I'll let you in on a little secret about me: My favorite past time is taking a random article from arXiv and re-TeXing it with plain XeTeX/LuaTeX. I haven't got the faintest clue what most of them are talking about, but I find it somehow relaxing – therapeutic, even.
Weird? Maybe. Fun? Definitely! Weird? Hey, you asked that already! |
4,150 | StackExchange [continues to support TUG with corporate membership](https://tex.meta.stackexchange.com/questions/4140/should-we-keep-our-tex-user-group-membership) (many thanks). With that come eight individual memberships that can be given out to members of the community. The time has come to select our representatives for 2014. For reference, Eight top voted members during last year [TUG Membership: Names for 2013](https://tex.meta.stackexchange.com/q/2906/15717) who have enjoyed [TUG membership benefits](http://tug.org/aims_ben.html)
Following the model from previous years, I'd like to ask people to put themselves forward. There are no restrictions on standing other than having to be a member of the TeX StackExchange site: in particular, the existing 'representatives' are very welcome to put their names forward to continue. [Note: I've called the people we put forward 'representatives', but that's mainly because I can't think of a better term. Nominees should not feel the need to represent TeX-sx other than being members of the site and therefore interested in TeX in some way!]
The model for selection of representatives is as follows. We will have a two stage process, first 'nomination' then 'election'. The first phase runs for five days, until 1700 GMT on 2014-01-07. Each person who wishes to be considered should post an answer, where they can (if they wish) say what makes them a good choice. They should then immediately delete their answer.
The second phase will then begin. All of the answers will be undeleted, and everyone should take a look at these answers and vote for deserving candidates: remember there are eight places available! Again, there will be five days to vote, ending 1700 GMT on 2014-01-12. At that stage, the top eight names will be forwarded to the StackExchange community staff for notification to TUG.
In the event of a tie in number of votes, the mod team will decide which of the tied members are put forward to StackExchange. The mod team may also include additional names *if* at the end of the voting process there are fewer than eight nominees with positive scores.
---
At the end of the voting period, the tallies were as follows:
* [Harish Kumar](https://tex.stackexchange.com/users/11232/harish-kumar), 25
* [Sean Allred](https://tex.stackexchange.com/users/17423/sean-allred), 20
* [Ulrike Fischer](https://tex.stackexchange.com/users/2388/ulrike-fischer), 18
* [cgnieder](https://tex.stackexchange.com/users/5049/cgnieder), 18
* [azetina](https://tex.stackexchange.com/users/10898/azetina), 17
* [Torbjørn T.](https://tex.stackexchange.com/users/586/torbjorn-t), 17
* [Henri Menke](https://tex.stackexchange.com/users/10995/henri-menke), 17
* [morbusg](https://tex.stackexchange.com/users/1410/morbusg), 17
* [Fran](https://tex.stackexchange.com/users/11604/fran), 16
* [Stefan Kottwitz](https://tex.stackexchange.com/users/213/stefan-kottwitz), 13
Our representatives for 2014 are therefore Harish Kumar, Sean Allred, Ulrike Fischer, cgnieder, azetina, Torbjørn T., Henri Menke, and morbusg. Congratulations! | 2014/01/02 | [
"https://tex.meta.stackexchange.com/questions/4150",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/73/"
] | *If* and *only if*, there are free slots, and if nobody notices my nomination in other way, I would like to put my name just to have a taste of TUG membership. Though I have been in TeX world for long time, I was never a member (I just didn't think of it). If I like it I will go for an individual membership after this.
I have no specific goals/aims regarding what I do with the membership, hence feel free to downvote. :-) | If there are free slots I'm putting my name on the list with the same reason as cgnieder: I'm already member of dante and I would like get the opportunity to help me decide if I pay for a joint membership in the future. But I can't promise an article or something like this as I haven't currently the time to write it. |
4,150 | StackExchange [continues to support TUG with corporate membership](https://tex.meta.stackexchange.com/questions/4140/should-we-keep-our-tex-user-group-membership) (many thanks). With that come eight individual memberships that can be given out to members of the community. The time has come to select our representatives for 2014. For reference, Eight top voted members during last year [TUG Membership: Names for 2013](https://tex.meta.stackexchange.com/q/2906/15717) who have enjoyed [TUG membership benefits](http://tug.org/aims_ben.html)
Following the model from previous years, I'd like to ask people to put themselves forward. There are no restrictions on standing other than having to be a member of the TeX StackExchange site: in particular, the existing 'representatives' are very welcome to put their names forward to continue. [Note: I've called the people we put forward 'representatives', but that's mainly because I can't think of a better term. Nominees should not feel the need to represent TeX-sx other than being members of the site and therefore interested in TeX in some way!]
The model for selection of representatives is as follows. We will have a two stage process, first 'nomination' then 'election'. The first phase runs for five days, until 1700 GMT on 2014-01-07. Each person who wishes to be considered should post an answer, where they can (if they wish) say what makes them a good choice. They should then immediately delete their answer.
The second phase will then begin. All of the answers will be undeleted, and everyone should take a look at these answers and vote for deserving candidates: remember there are eight places available! Again, there will be five days to vote, ending 1700 GMT on 2014-01-12. At that stage, the top eight names will be forwarded to the StackExchange community staff for notification to TUG.
In the event of a tie in number of votes, the mod team will decide which of the tied members are put forward to StackExchange. The mod team may also include additional names *if* at the end of the voting process there are fewer than eight nominees with positive scores.
---
At the end of the voting period, the tallies were as follows:
* [Harish Kumar](https://tex.stackexchange.com/users/11232/harish-kumar), 25
* [Sean Allred](https://tex.stackexchange.com/users/17423/sean-allred), 20
* [Ulrike Fischer](https://tex.stackexchange.com/users/2388/ulrike-fischer), 18
* [cgnieder](https://tex.stackexchange.com/users/5049/cgnieder), 18
* [azetina](https://tex.stackexchange.com/users/10898/azetina), 17
* [Torbjørn T.](https://tex.stackexchange.com/users/586/torbjorn-t), 17
* [Henri Menke](https://tex.stackexchange.com/users/10995/henri-menke), 17
* [morbusg](https://tex.stackexchange.com/users/1410/morbusg), 17
* [Fran](https://tex.stackexchange.com/users/11604/fran), 16
* [Stefan Kottwitz](https://tex.stackexchange.com/users/213/stefan-kottwitz), 13
Our representatives for 2014 are therefore Harish Kumar, Sean Allred, Ulrike Fischer, cgnieder, azetina, Torbjørn T., Henri Menke, and morbusg. Congratulations! | 2014/01/02 | [
"https://tex.meta.stackexchange.com/questions/4150",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/73/"
] | *If* and *only if*, there are free slots, and if nobody notices my nomination in other way, I would like to put my name just to have a taste of TUG membership. Though I have been in TeX world for long time, I was never a member (I just didn't think of it). If I like it I will go for an individual membership after this.
I have no specific goals/aims regarding what I do with the membership, hence feel free to downvote. :-) | I don't really like nominating myself for anything, but I'll make an exception.
Not really sure what to say though. I'm a mere user, my contributions to the TeX world so far are mainly those on this site. I've been a TUG member for two years I think. My main reason for joining was to give a little bit back, and I'll renew my membership if I'm not 'awarded' one here. (For that reason I'll place myself last in line.) |
4,150 | StackExchange [continues to support TUG with corporate membership](https://tex.meta.stackexchange.com/questions/4140/should-we-keep-our-tex-user-group-membership) (many thanks). With that come eight individual memberships that can be given out to members of the community. The time has come to select our representatives for 2014. For reference, Eight top voted members during last year [TUG Membership: Names for 2013](https://tex.meta.stackexchange.com/q/2906/15717) who have enjoyed [TUG membership benefits](http://tug.org/aims_ben.html)
Following the model from previous years, I'd like to ask people to put themselves forward. There are no restrictions on standing other than having to be a member of the TeX StackExchange site: in particular, the existing 'representatives' are very welcome to put their names forward to continue. [Note: I've called the people we put forward 'representatives', but that's mainly because I can't think of a better term. Nominees should not feel the need to represent TeX-sx other than being members of the site and therefore interested in TeX in some way!]
The model for selection of representatives is as follows. We will have a two stage process, first 'nomination' then 'election'. The first phase runs for five days, until 1700 GMT on 2014-01-07. Each person who wishes to be considered should post an answer, where they can (if they wish) say what makes them a good choice. They should then immediately delete their answer.
The second phase will then begin. All of the answers will be undeleted, and everyone should take a look at these answers and vote for deserving candidates: remember there are eight places available! Again, there will be five days to vote, ending 1700 GMT on 2014-01-12. At that stage, the top eight names will be forwarded to the StackExchange community staff for notification to TUG.
In the event of a tie in number of votes, the mod team will decide which of the tied members are put forward to StackExchange. The mod team may also include additional names *if* at the end of the voting process there are fewer than eight nominees with positive scores.
---
At the end of the voting period, the tallies were as follows:
* [Harish Kumar](https://tex.stackexchange.com/users/11232/harish-kumar), 25
* [Sean Allred](https://tex.stackexchange.com/users/17423/sean-allred), 20
* [Ulrike Fischer](https://tex.stackexchange.com/users/2388/ulrike-fischer), 18
* [cgnieder](https://tex.stackexchange.com/users/5049/cgnieder), 18
* [azetina](https://tex.stackexchange.com/users/10898/azetina), 17
* [Torbjørn T.](https://tex.stackexchange.com/users/586/torbjorn-t), 17
* [Henri Menke](https://tex.stackexchange.com/users/10995/henri-menke), 17
* [morbusg](https://tex.stackexchange.com/users/1410/morbusg), 17
* [Fran](https://tex.stackexchange.com/users/11604/fran), 16
* [Stefan Kottwitz](https://tex.stackexchange.com/users/213/stefan-kottwitz), 13
Our representatives for 2014 are therefore Harish Kumar, Sean Allred, Ulrike Fischer, cgnieder, azetina, Torbjørn T., Henri Menke, and morbusg. Congratulations! | 2014/01/02 | [
"https://tex.meta.stackexchange.com/questions/4150",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/73/"
] | *If* and *only if*, there are free slots, and if nobody notices my nomination in other way, I would like to put my name just to have a taste of TUG membership. Though I have been in TeX world for long time, I was never a member (I just didn't think of it). If I like it I will go for an individual membership after this.
I have no specific goals/aims regarding what I do with the membership, hence feel free to downvote. :-) | At Alan's heartwarming insistence, I'd like to nominate myself if there are free slots.
It seems everyone else has given a little tidbit about why, so here goes:
I've almost exploded in my interest of TeX and TeX systems,
and I would be excited to see what other people are talking about and doing.
I'm not privy to the full benefits of a TUG membership, but I would be excited and frankly honored to find out about it personally. |
4,150 | StackExchange [continues to support TUG with corporate membership](https://tex.meta.stackexchange.com/questions/4140/should-we-keep-our-tex-user-group-membership) (many thanks). With that come eight individual memberships that can be given out to members of the community. The time has come to select our representatives for 2014. For reference, Eight top voted members during last year [TUG Membership: Names for 2013](https://tex.meta.stackexchange.com/q/2906/15717) who have enjoyed [TUG membership benefits](http://tug.org/aims_ben.html)
Following the model from previous years, I'd like to ask people to put themselves forward. There are no restrictions on standing other than having to be a member of the TeX StackExchange site: in particular, the existing 'representatives' are very welcome to put their names forward to continue. [Note: I've called the people we put forward 'representatives', but that's mainly because I can't think of a better term. Nominees should not feel the need to represent TeX-sx other than being members of the site and therefore interested in TeX in some way!]
The model for selection of representatives is as follows. We will have a two stage process, first 'nomination' then 'election'. The first phase runs for five days, until 1700 GMT on 2014-01-07. Each person who wishes to be considered should post an answer, where they can (if they wish) say what makes them a good choice. They should then immediately delete their answer.
The second phase will then begin. All of the answers will be undeleted, and everyone should take a look at these answers and vote for deserving candidates: remember there are eight places available! Again, there will be five days to vote, ending 1700 GMT on 2014-01-12. At that stage, the top eight names will be forwarded to the StackExchange community staff for notification to TUG.
In the event of a tie in number of votes, the mod team will decide which of the tied members are put forward to StackExchange. The mod team may also include additional names *if* at the end of the voting process there are fewer than eight nominees with positive scores.
---
At the end of the voting period, the tallies were as follows:
* [Harish Kumar](https://tex.stackexchange.com/users/11232/harish-kumar), 25
* [Sean Allred](https://tex.stackexchange.com/users/17423/sean-allred), 20
* [Ulrike Fischer](https://tex.stackexchange.com/users/2388/ulrike-fischer), 18
* [cgnieder](https://tex.stackexchange.com/users/5049/cgnieder), 18
* [azetina](https://tex.stackexchange.com/users/10898/azetina), 17
* [Torbjørn T.](https://tex.stackexchange.com/users/586/torbjorn-t), 17
* [Henri Menke](https://tex.stackexchange.com/users/10995/henri-menke), 17
* [morbusg](https://tex.stackexchange.com/users/1410/morbusg), 17
* [Fran](https://tex.stackexchange.com/users/11604/fran), 16
* [Stefan Kottwitz](https://tex.stackexchange.com/users/213/stefan-kottwitz), 13
Our representatives for 2014 are therefore Harish Kumar, Sean Allred, Ulrike Fischer, cgnieder, azetina, Torbjørn T., Henri Menke, and morbusg. Congratulations! | 2014/01/02 | [
"https://tex.meta.stackexchange.com/questions/4150",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/73/"
] | *If* and *only if*, there are free slots, and if nobody notices my nomination in other way, I would like to put my name just to have a taste of TUG membership. Though I have been in TeX world for long time, I was never a member (I just didn't think of it). If I like it I will go for an individual membership after this.
I have no specific goals/aims regarding what I do with the membership, hence feel free to downvote. :-) | Since the list is not yet full (7 at the start of writing), I gladly reapply. My connection to TUG was for example
* [initiating our institutional membership](https://tex.meta.stackexchange.com/questions/1528/do-we-want-stack-exchange-to-become-an-institutional-member-of-the-tug),
* [visiting a TUG meeting](https://tex.meta.stackexchange.com/questions/1915/going-to-a-conference-the-tug-2011-experience) and making a [TeX.SX related presentation](http://texblog.net/latex-archive/events/tex-online/) there,
* writing a [TeX.SX related article](http://tug.org/TUGboat/tb32-3/tb102kottwitz.pdf) for the TUGboat from it.
That was fun, I wish the same fun for our fellow members, I already enjoyed 2 years. And if it happens that it might continue for me so I'd be happy. |
4,150 | StackExchange [continues to support TUG with corporate membership](https://tex.meta.stackexchange.com/questions/4140/should-we-keep-our-tex-user-group-membership) (many thanks). With that come eight individual memberships that can be given out to members of the community. The time has come to select our representatives for 2014. For reference, Eight top voted members during last year [TUG Membership: Names for 2013](https://tex.meta.stackexchange.com/q/2906/15717) who have enjoyed [TUG membership benefits](http://tug.org/aims_ben.html)
Following the model from previous years, I'd like to ask people to put themselves forward. There are no restrictions on standing other than having to be a member of the TeX StackExchange site: in particular, the existing 'representatives' are very welcome to put their names forward to continue. [Note: I've called the people we put forward 'representatives', but that's mainly because I can't think of a better term. Nominees should not feel the need to represent TeX-sx other than being members of the site and therefore interested in TeX in some way!]
The model for selection of representatives is as follows. We will have a two stage process, first 'nomination' then 'election'. The first phase runs for five days, until 1700 GMT on 2014-01-07. Each person who wishes to be considered should post an answer, where they can (if they wish) say what makes them a good choice. They should then immediately delete their answer.
The second phase will then begin. All of the answers will be undeleted, and everyone should take a look at these answers and vote for deserving candidates: remember there are eight places available! Again, there will be five days to vote, ending 1700 GMT on 2014-01-12. At that stage, the top eight names will be forwarded to the StackExchange community staff for notification to TUG.
In the event of a tie in number of votes, the mod team will decide which of the tied members are put forward to StackExchange. The mod team may also include additional names *if* at the end of the voting process there are fewer than eight nominees with positive scores.
---
At the end of the voting period, the tallies were as follows:
* [Harish Kumar](https://tex.stackexchange.com/users/11232/harish-kumar), 25
* [Sean Allred](https://tex.stackexchange.com/users/17423/sean-allred), 20
* [Ulrike Fischer](https://tex.stackexchange.com/users/2388/ulrike-fischer), 18
* [cgnieder](https://tex.stackexchange.com/users/5049/cgnieder), 18
* [azetina](https://tex.stackexchange.com/users/10898/azetina), 17
* [Torbjørn T.](https://tex.stackexchange.com/users/586/torbjorn-t), 17
* [Henri Menke](https://tex.stackexchange.com/users/10995/henri-menke), 17
* [morbusg](https://tex.stackexchange.com/users/1410/morbusg), 17
* [Fran](https://tex.stackexchange.com/users/11604/fran), 16
* [Stefan Kottwitz](https://tex.stackexchange.com/users/213/stefan-kottwitz), 13
Our representatives for 2014 are therefore Harish Kumar, Sean Allred, Ulrike Fischer, cgnieder, azetina, Torbjørn T., Henri Menke, and morbusg. Congratulations! | 2014/01/02 | [
"https://tex.meta.stackexchange.com/questions/4150",
"https://tex.meta.stackexchange.com",
"https://tex.meta.stackexchange.com/users/73/"
] | *If* and *only if*, there are free slots, and if nobody notices my nomination in other way, I would like to put my name just to have a taste of TUG membership. Though I have been in TeX world for long time, I was never a member (I just didn't think of it). If I like it I will go for an individual membership after this.
I have no specific goals/aims regarding what I do with the membership, hence feel free to downvote. :-) | TeX.SX and TUGboat have been invaluable resources for me. To be honest, I feel really welcomed here and even when I have asked several questions, I am glad, that at times, I am able to answer a few here and there. I am learning and similar to my last submission for selection, I am moving forward the TeX voice here in my country, Belize. Currently I am tutoring two of my students in LaTeX. One of the projects that I have initiated is writing a Mathematics book and so far, with all the resources from TUGboat and TeX.SX I have managed to achieve 2 chapters.
Therefore, I would gladly reapply for a TUGboat membership. |
23,058 | I am a new cyclist who is on my 2nd year of biking. I bought a cheapo Schwinn MTB at Walmart to start with but now I want a real road bike. I currently have $2k saved up and am looking into a Specialized Secteur Exprt Disc which is aluminum. I did pick up a carbon frame bike at the shop and although it is lighter, not by much. How sturdy are these carbon frames? From what I've read they can crack if you get in a tumble, and at that point you are done. Vs an aluminum frame will more likely than not be OK. I'd have to spend over $1000 more to get a carbon frame and as good components (Shimano 105 or above) so I don't know if its worth it or not. I'm just a casual cyclist who likes to go on long solo rides for fitness/fun. | 2014/06/16 | [
"https://bicycles.stackexchange.com/questions/23058",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/12641/"
] | There's no reason to worry about carbon fibre durability. I'm riding on a 20 year old Specialized Epic Allez (CF tubes with Al lugs), and it's just as light and stiff as it was when new.
If you have a serious accident CF may break in a non-repairable way, but the same is more-or-less true about aluminium as well, although it may take more of a tumble to break it. (In theory Al can be welded, but you have to be very careful, as the welding will wreck the heat treatment.)
At the same time, CF *is* more expensive. If I would buy a new bike today I would probably get a decent aluminium frame and instead spend more money on the components, rather than an expensive frame with sub-par groupset. | For a 2k budget, you can get either a mediocre new carbon frame, or a high-quality aluminium frame like a Cannondale CAAD 10.
Newer aluminium frames ride significantly better than their predecessors of even as recently as 5 years ago. The best aluminium frames can rival their carbon counterparts on weight and ride quality, while providing (in most cases) upgraded components.
I'd recommend buying a new aluminium bike over a lower-end carbon bicycle any day. |
201,042 | I am extending this post following from [here](https://codereview.stackexchange.com/questions/200861/generic-single-linked-list-using-smart-pointers/200988?noredirect=1#comment387172_200988). I made some of the changes that I could make in the previous post. Although, I have not been successful in creating iterators for my class.
The reason for the new post is to see if there is any additional changes I need to make to my code. As well as steps in creating iterators for this class. Should I perhaps follow what is done [here](https://www.geeksforgeeks.org/implementing-iterator-pattern-of-a-single-linked-list/)?
I am still in the learning process with smart pointers and there is still much I need to learn, I find it useful when people post detailed answers instead of computer science jargon that my ears are still new to.
Here is my header file:
```
#ifndef SingleLinkedList_h
#define SingleLinkedList_h
template <class T>
class SingleLinkedList {
private:
struct Node {
T data;
std::unique_ptr<Node> next = nullptr;
// disable if noncopyable<T> for cleaner error msgs
explicit Node(const T& x, std::unique_ptr<Node>&& p = nullptr)
: data(x)
, next(std::move(p)) {}
// disable if nonmovable<T> for cleaner error msgs
explicit Node(T&& x, std::unique_ptr<Node>&& p = nullptr)
: data(std::move(x))
, next(std::move(p)) {}
};
std::unique_ptr<Node> head = nullptr;
Node* tail = nullptr;
void do_pop_front() {
head = std::move(head->next);
}
public:
// Constructors
SingleLinkedList() = default; // empty constructor
SingleLinkedList(SingleLinkedList const &source); // copy constructor
// Rule of 5
SingleLinkedList(SingleLinkedList &&move) noexcept; // move constructor
SingleLinkedList& operator=(SingleLinkedList &&move) noexcept; // move assignment operator
~SingleLinkedList();
// Overload operators
SingleLinkedList& operator=(SingleLinkedList const &rhs);
// This function is for the overloaded operator <<
void display(std::ostream &str) const {
for (Node* loop = head.get(); loop != nullptr; loop = loop->next.get()) {
str << loop->data << "\t";
}
str << "\n";
}
friend std::ostream& operator<<(std::ostream &str, SingleLinkedList &data) {
data.display(str);
return str;
}
// Memeber functions
void swap(SingleLinkedList &other) noexcept;
bool empty() const { return head.get() == nullptr; }
int size() const;
void push_back(const T &theData);
void push_back(T &&theData);
void push_front(const T &theData);
void insertPosition(int pos, const T &theData);
void clear();
void pop_front();
void pop_back();
void deleteSpecific(int delValue);
bool search(const T &x);
};
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T> const &source) {
for(Node* loop = source.head.get(); loop != nullptr; loop = loop->next.get()) {
push_back(loop->data);
}
}
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T>&& move) noexcept {
move.swap(*this);
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
SingleLinkedList<T>::~SingleLinkedList() {
clear();
}
template <class T>
void SingleLinkedList<T>::clear() {
while (head) {
do_pop_front();
}
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList const &rhs) {
SingleLinkedList copy{ rhs };
swap(copy);
return *this;
}
template <class T>
void SingleLinkedList<T>::swap(SingleLinkedList &other) noexcept {
using std::swap;
swap(head, other.head);
swap(tail, other.tail);
}
template <class T>
int SingleLinkedList<T>::size() const {
int size = 0;
for (auto current = head.get(); current != nullptr; current = current->next.get()) {
size++;
}
return size;
}
template <class T>
void SingleLinkedList<T>::push_back(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
if (!head) {
head = std::move(newNode);
tail = head.get();
}
else {
tail->next = std::move(newNode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::push_back(T &&thedata) {
std::unique_ptr<Node> newnode = std::make_unique<Node>(std::move(thedata));
if (!head) {
head = std::move(newnode);
tail = head.get();
}
else {
tail->next = std::move(newnode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::push_front(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
newNode->next = std::move(head);
head = std::move(newNode);
}
template <class T>
void SingleLinkedList<T>::insertPosition(int pos, const T &theData) {
if (pos > size() || pos < 0) {
throw std::out_of_range("The insert location is invalid.");
}
auto node = head.get();
int i = 0;
for (; node && node->next && i < pos; node = node->next.get(), i++);
if (i != pos) {
throw std::out_of_range("Parameter 'pos' is out of range.");
}
auto newNode = std::make_unique<Node>(theData);
if (node) {
newNode->next = std::move(node->next);
node->next = std::move(newNode);
}
else {
head = std::move(newNode);
}
}
template <class T>
void SingleLinkedList<T>::pop_front() {
if (empty()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
do_pop_front();
}
template <class T>
void SingleLinkedList<T>::pop_back() {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto current = head.get();
Node* previous = nullptr;
while (current->next != nullptr) {
previous = current;
current = current->next.get();
}
tail = previous;
previous->next = nullptr;
}
template <class T>
void SingleLinkedList<T>::deleteSpecific(int delValue) {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto temp1 = head.get();
Node* temp2 = nullptr;
while (temp1->data != delValue) {
if (temp1->next == nullptr) {
throw std::invalid_argument("Given node not found in the list!!!");
}
temp2 = temp1;
temp1 = temp1->next.get();
}
temp2->next = std::move(temp1->next);
}
template <class T>
bool SingleLinkedList<T>::search(const T &x) {
auto current = head.get();
while (current) {
if (current->data == x) {
return true;
}
current = current->next.get();
}
return false;
}
#endif /* SingleLinkedList_h*/
```
Here is the main.cpp file:
```
//
// main.cpp
// Data Structure - LinkedList
//
// Created by Morgan Weiss on 7/24/2018
// Copyright © 2018 Morgan Weiss. All rights reserved.
//
#include <algorithm>
#include <cassert>
#include <iostream>
#include <memory>
#include <utility>
#include <stdexcept>
#include <ostream>
#include <iosfwd>
#include <stdexcept>
#include "SingleLinkedList.h"
int main(int argc, const char * argv[]) {
///////////////////////////////////////////////////////////////////////
///////////////////////////// Single Linked List //////////////////////
///////////////////////////////////////////////////////////////////////
SingleLinkedList<int> obj;
obj.push_back(2);
obj.push_back(4);
obj.push_back(6);
obj.push_back(8);
obj.push_back(10);
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------displaying all nodes---------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Inserting At Start----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.push_front(50);
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-------------inserting at particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertPosition(5,60);
std::cout << obj << "\n";
std::cout << "\n--------------------------------------------------\n";
std::cout << "-------------Get current size ---=--------------------";
std::cout << "\n--------------------------------------------------\n";
std::cout << obj.size() << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at start-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_front();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at end-----------------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_back();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"--------------Deleting At Particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteSpecific(4);
std::cout << obj << "\n";
obj.search(8) ? printf("yes"):printf("no");
std::cout << "\n--------------------------------------------------\n";
std::cout << "--------------Testing copy----------------------------";
std::cout << "\n--------------------------------------------------\n";
SingleLinkedList<int> obj1 = obj;
std::cout << obj1 << "\n";
//std::cout << "\n-------------------------------------------------------------------------\n";
//std::cout << "--------------Testing to insert in an empty list----------------------------";
//std::cout << "\n-------------------------------------------------------------------------\n";
//SingleLinkedList<int> obj2;
//obj2.insertPosition(5, 60);
//std::cout << obj2 << "\n";
std::cin.get();
}
``` | 2018/08/05 | [
"https://codereview.stackexchange.com/questions/201042",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/150820/"
] | ### Move `public` section of the class to the top
I prefer, and suggest others, to put the `public` section of a class before the `protected` and `private` sections.
The rationale for it is that users of the class want to see the `public` section of the class. It is less important to them to see what's in the `protected` and `private` sections. It does not make sense that they will have to wade through less important sections of the class before they get to the most important section.
```
template <class T>
class SingleLinkedList {
public:
// Constructors
SingleLinkedList() = default; // empty constructor
...
protected:
private:
struct Node {
...
};
...
};
```
### Remove `display(std::ostream &str)`
I understand that you need the function at the moment to display the contents of an object. However, it's too tightly coupled with the class. Different users may want to display an object of the class differently. You can't support that easily if `display` is the only function the user has access to.
This should be motivation for you to implement the iterator class. When you have the iterator class ready, the `operator<<(std::ostream&, SingleLinkedList const&)` function can be moved out of the class and the `friend`-ship won't be necessary. The current functionality can be moved to a non-member function.
Also note that the list object should be a `const&`.
```
template <typename T>
std::ostream& operator<<(std::ostream &str, SingleLinkedList<T> const& list)
{
// This will work as soon as you have begin() and end() member functions
for ( auto const& item : list )
{
str << item << "\t";
}
return str;
}
```
### `insertPosition` needs a better name
You are not inserting a position. You are inserting an item at a position. For that reason, I think `insert_at_position` is more appropriate and follows the naming convention of other functions.
If `insert_at_position` is too verbose, the simpler name, `insert` will be better than `insertPosition`, IMO.
### `deleteSpecific` needs a better name
I think the simpler name `remove()` will be better.
If you decide to keep `deleteSpecific`, I would suggest changing it to `delete_specific` to keep the function names consistent. | * **`push_front`** does not update `tail`. Usually no problem, unless applied to an empty list (`tail` remains `nullptr`, which `push_back` doesn't check, etc).
* Ditto for `insertPosition`.
* Ditto for `pop_back`. Popping the last element from the list shall update `head`.
* `push_front(const T &&theData)` is missing.
* **`insertPosition`** looks too cautious. You immediately know that `pos <= size()`; there is no point to not trust yourself. `i != pos` is impossible.
As a side note, the interface doesn't look clear. I'd expect `insertPosition(0, ...) be _always_ equivalent to`push\_front`.
* `size()` shall return `size_t`. In any case, there is no reason to return a signed value. Similarly, the position arguments shall be `size_t`, or at least unsigned. |
201,042 | I am extending this post following from [here](https://codereview.stackexchange.com/questions/200861/generic-single-linked-list-using-smart-pointers/200988?noredirect=1#comment387172_200988). I made some of the changes that I could make in the previous post. Although, I have not been successful in creating iterators for my class.
The reason for the new post is to see if there is any additional changes I need to make to my code. As well as steps in creating iterators for this class. Should I perhaps follow what is done [here](https://www.geeksforgeeks.org/implementing-iterator-pattern-of-a-single-linked-list/)?
I am still in the learning process with smart pointers and there is still much I need to learn, I find it useful when people post detailed answers instead of computer science jargon that my ears are still new to.
Here is my header file:
```
#ifndef SingleLinkedList_h
#define SingleLinkedList_h
template <class T>
class SingleLinkedList {
private:
struct Node {
T data;
std::unique_ptr<Node> next = nullptr;
// disable if noncopyable<T> for cleaner error msgs
explicit Node(const T& x, std::unique_ptr<Node>&& p = nullptr)
: data(x)
, next(std::move(p)) {}
// disable if nonmovable<T> for cleaner error msgs
explicit Node(T&& x, std::unique_ptr<Node>&& p = nullptr)
: data(std::move(x))
, next(std::move(p)) {}
};
std::unique_ptr<Node> head = nullptr;
Node* tail = nullptr;
void do_pop_front() {
head = std::move(head->next);
}
public:
// Constructors
SingleLinkedList() = default; // empty constructor
SingleLinkedList(SingleLinkedList const &source); // copy constructor
// Rule of 5
SingleLinkedList(SingleLinkedList &&move) noexcept; // move constructor
SingleLinkedList& operator=(SingleLinkedList &&move) noexcept; // move assignment operator
~SingleLinkedList();
// Overload operators
SingleLinkedList& operator=(SingleLinkedList const &rhs);
// This function is for the overloaded operator <<
void display(std::ostream &str) const {
for (Node* loop = head.get(); loop != nullptr; loop = loop->next.get()) {
str << loop->data << "\t";
}
str << "\n";
}
friend std::ostream& operator<<(std::ostream &str, SingleLinkedList &data) {
data.display(str);
return str;
}
// Memeber functions
void swap(SingleLinkedList &other) noexcept;
bool empty() const { return head.get() == nullptr; }
int size() const;
void push_back(const T &theData);
void push_back(T &&theData);
void push_front(const T &theData);
void insertPosition(int pos, const T &theData);
void clear();
void pop_front();
void pop_back();
void deleteSpecific(int delValue);
bool search(const T &x);
};
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T> const &source) {
for(Node* loop = source.head.get(); loop != nullptr; loop = loop->next.get()) {
push_back(loop->data);
}
}
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T>&& move) noexcept {
move.swap(*this);
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
SingleLinkedList<T>::~SingleLinkedList() {
clear();
}
template <class T>
void SingleLinkedList<T>::clear() {
while (head) {
do_pop_front();
}
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList const &rhs) {
SingleLinkedList copy{ rhs };
swap(copy);
return *this;
}
template <class T>
void SingleLinkedList<T>::swap(SingleLinkedList &other) noexcept {
using std::swap;
swap(head, other.head);
swap(tail, other.tail);
}
template <class T>
int SingleLinkedList<T>::size() const {
int size = 0;
for (auto current = head.get(); current != nullptr; current = current->next.get()) {
size++;
}
return size;
}
template <class T>
void SingleLinkedList<T>::push_back(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
if (!head) {
head = std::move(newNode);
tail = head.get();
}
else {
tail->next = std::move(newNode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::push_back(T &&thedata) {
std::unique_ptr<Node> newnode = std::make_unique<Node>(std::move(thedata));
if (!head) {
head = std::move(newnode);
tail = head.get();
}
else {
tail->next = std::move(newnode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::push_front(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
newNode->next = std::move(head);
head = std::move(newNode);
}
template <class T>
void SingleLinkedList<T>::insertPosition(int pos, const T &theData) {
if (pos > size() || pos < 0) {
throw std::out_of_range("The insert location is invalid.");
}
auto node = head.get();
int i = 0;
for (; node && node->next && i < pos; node = node->next.get(), i++);
if (i != pos) {
throw std::out_of_range("Parameter 'pos' is out of range.");
}
auto newNode = std::make_unique<Node>(theData);
if (node) {
newNode->next = std::move(node->next);
node->next = std::move(newNode);
}
else {
head = std::move(newNode);
}
}
template <class T>
void SingleLinkedList<T>::pop_front() {
if (empty()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
do_pop_front();
}
template <class T>
void SingleLinkedList<T>::pop_back() {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto current = head.get();
Node* previous = nullptr;
while (current->next != nullptr) {
previous = current;
current = current->next.get();
}
tail = previous;
previous->next = nullptr;
}
template <class T>
void SingleLinkedList<T>::deleteSpecific(int delValue) {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto temp1 = head.get();
Node* temp2 = nullptr;
while (temp1->data != delValue) {
if (temp1->next == nullptr) {
throw std::invalid_argument("Given node not found in the list!!!");
}
temp2 = temp1;
temp1 = temp1->next.get();
}
temp2->next = std::move(temp1->next);
}
template <class T>
bool SingleLinkedList<T>::search(const T &x) {
auto current = head.get();
while (current) {
if (current->data == x) {
return true;
}
current = current->next.get();
}
return false;
}
#endif /* SingleLinkedList_h*/
```
Here is the main.cpp file:
```
//
// main.cpp
// Data Structure - LinkedList
//
// Created by Morgan Weiss on 7/24/2018
// Copyright © 2018 Morgan Weiss. All rights reserved.
//
#include <algorithm>
#include <cassert>
#include <iostream>
#include <memory>
#include <utility>
#include <stdexcept>
#include <ostream>
#include <iosfwd>
#include <stdexcept>
#include "SingleLinkedList.h"
int main(int argc, const char * argv[]) {
///////////////////////////////////////////////////////////////////////
///////////////////////////// Single Linked List //////////////////////
///////////////////////////////////////////////////////////////////////
SingleLinkedList<int> obj;
obj.push_back(2);
obj.push_back(4);
obj.push_back(6);
obj.push_back(8);
obj.push_back(10);
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------displaying all nodes---------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Inserting At Start----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.push_front(50);
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-------------inserting at particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertPosition(5,60);
std::cout << obj << "\n";
std::cout << "\n--------------------------------------------------\n";
std::cout << "-------------Get current size ---=--------------------";
std::cout << "\n--------------------------------------------------\n";
std::cout << obj.size() << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at start-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_front();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at end-----------------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_back();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"--------------Deleting At Particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteSpecific(4);
std::cout << obj << "\n";
obj.search(8) ? printf("yes"):printf("no");
std::cout << "\n--------------------------------------------------\n";
std::cout << "--------------Testing copy----------------------------";
std::cout << "\n--------------------------------------------------\n";
SingleLinkedList<int> obj1 = obj;
std::cout << obj1 << "\n";
//std::cout << "\n-------------------------------------------------------------------------\n";
//std::cout << "--------------Testing to insert in an empty list----------------------------";
//std::cout << "\n-------------------------------------------------------------------------\n";
//SingleLinkedList<int> obj2;
//obj2.insertPosition(5, 60);
//std::cout << obj2 << "\n";
std::cin.get();
}
``` | 2018/08/05 | [
"https://codereview.stackexchange.com/questions/201042",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/150820/"
] | ### Move `public` section of the class to the top
I prefer, and suggest others, to put the `public` section of a class before the `protected` and `private` sections.
The rationale for it is that users of the class want to see the `public` section of the class. It is less important to them to see what's in the `protected` and `private` sections. It does not make sense that they will have to wade through less important sections of the class before they get to the most important section.
```
template <class T>
class SingleLinkedList {
public:
// Constructors
SingleLinkedList() = default; // empty constructor
...
protected:
private:
struct Node {
...
};
...
};
```
### Remove `display(std::ostream &str)`
I understand that you need the function at the moment to display the contents of an object. However, it's too tightly coupled with the class. Different users may want to display an object of the class differently. You can't support that easily if `display` is the only function the user has access to.
This should be motivation for you to implement the iterator class. When you have the iterator class ready, the `operator<<(std::ostream&, SingleLinkedList const&)` function can be moved out of the class and the `friend`-ship won't be necessary. The current functionality can be moved to a non-member function.
Also note that the list object should be a `const&`.
```
template <typename T>
std::ostream& operator<<(std::ostream &str, SingleLinkedList<T> const& list)
{
// This will work as soon as you have begin() and end() member functions
for ( auto const& item : list )
{
str << item << "\t";
}
return str;
}
```
### `insertPosition` needs a better name
You are not inserting a position. You are inserting an item at a position. For that reason, I think `insert_at_position` is more appropriate and follows the naming convention of other functions.
If `insert_at_position` is too verbose, the simpler name, `insert` will be better than `insertPosition`, IMO.
### `deleteSpecific` needs a better name
I think the simpler name `remove()` will be better.
If you decide to keep `deleteSpecific`, I would suggest changing it to `delete_specific` to keep the function names consistent. | Just small addition to great answers.
Commenting obvious stuff
========================
I would delete all comments, really. You can safely assume that people who read you code will know what constructor etc is.
Such commenting is really distracting.
```
// Constructors
SingleLinkedList() = default; // empty constructor
SingleLinkedList(SingleLinkedList const &source); // copy constructor
```
Small inconsistency
===================
In one case you are using `auto` (correct)
```
for (auto current = head.get(); current != nullptr; current = current->next.get()) {
size++;
}
```
In other case you don't.
```
for (Node* loop = head.get(); loop != nullptr; loop = loop->next.get()) {
str << loop->data << "\t";
}
```
It is really important (especially in big projects with millions LOC) to keep things as much consistent as you can. |
201,042 | I am extending this post following from [here](https://codereview.stackexchange.com/questions/200861/generic-single-linked-list-using-smart-pointers/200988?noredirect=1#comment387172_200988). I made some of the changes that I could make in the previous post. Although, I have not been successful in creating iterators for my class.
The reason for the new post is to see if there is any additional changes I need to make to my code. As well as steps in creating iterators for this class. Should I perhaps follow what is done [here](https://www.geeksforgeeks.org/implementing-iterator-pattern-of-a-single-linked-list/)?
I am still in the learning process with smart pointers and there is still much I need to learn, I find it useful when people post detailed answers instead of computer science jargon that my ears are still new to.
Here is my header file:
```
#ifndef SingleLinkedList_h
#define SingleLinkedList_h
template <class T>
class SingleLinkedList {
private:
struct Node {
T data;
std::unique_ptr<Node> next = nullptr;
// disable if noncopyable<T> for cleaner error msgs
explicit Node(const T& x, std::unique_ptr<Node>&& p = nullptr)
: data(x)
, next(std::move(p)) {}
// disable if nonmovable<T> for cleaner error msgs
explicit Node(T&& x, std::unique_ptr<Node>&& p = nullptr)
: data(std::move(x))
, next(std::move(p)) {}
};
std::unique_ptr<Node> head = nullptr;
Node* tail = nullptr;
void do_pop_front() {
head = std::move(head->next);
}
public:
// Constructors
SingleLinkedList() = default; // empty constructor
SingleLinkedList(SingleLinkedList const &source); // copy constructor
// Rule of 5
SingleLinkedList(SingleLinkedList &&move) noexcept; // move constructor
SingleLinkedList& operator=(SingleLinkedList &&move) noexcept; // move assignment operator
~SingleLinkedList();
// Overload operators
SingleLinkedList& operator=(SingleLinkedList const &rhs);
// This function is for the overloaded operator <<
void display(std::ostream &str) const {
for (Node* loop = head.get(); loop != nullptr; loop = loop->next.get()) {
str << loop->data << "\t";
}
str << "\n";
}
friend std::ostream& operator<<(std::ostream &str, SingleLinkedList &data) {
data.display(str);
return str;
}
// Memeber functions
void swap(SingleLinkedList &other) noexcept;
bool empty() const { return head.get() == nullptr; }
int size() const;
void push_back(const T &theData);
void push_back(T &&theData);
void push_front(const T &theData);
void insertPosition(int pos, const T &theData);
void clear();
void pop_front();
void pop_back();
void deleteSpecific(int delValue);
bool search(const T &x);
};
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T> const &source) {
for(Node* loop = source.head.get(); loop != nullptr; loop = loop->next.get()) {
push_back(loop->data);
}
}
template <class T>
SingleLinkedList<T>::SingleLinkedList(SingleLinkedList<T>&& move) noexcept {
move.swap(*this);
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList<T> &&move) noexcept {
move.swap(*this);
return *this;
}
template <class T>
SingleLinkedList<T>::~SingleLinkedList() {
clear();
}
template <class T>
void SingleLinkedList<T>::clear() {
while (head) {
do_pop_front();
}
}
template <class T>
SingleLinkedList<T>& SingleLinkedList<T>::operator=(SingleLinkedList const &rhs) {
SingleLinkedList copy{ rhs };
swap(copy);
return *this;
}
template <class T>
void SingleLinkedList<T>::swap(SingleLinkedList &other) noexcept {
using std::swap;
swap(head, other.head);
swap(tail, other.tail);
}
template <class T>
int SingleLinkedList<T>::size() const {
int size = 0;
for (auto current = head.get(); current != nullptr; current = current->next.get()) {
size++;
}
return size;
}
template <class T>
void SingleLinkedList<T>::push_back(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
if (!head) {
head = std::move(newNode);
tail = head.get();
}
else {
tail->next = std::move(newNode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::push_back(T &&thedata) {
std::unique_ptr<Node> newnode = std::make_unique<Node>(std::move(thedata));
if (!head) {
head = std::move(newnode);
tail = head.get();
}
else {
tail->next = std::move(newnode);
tail = tail->next.get();
}
}
template <class T>
void SingleLinkedList<T>::push_front(const T &theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
newNode->next = std::move(head);
head = std::move(newNode);
}
template <class T>
void SingleLinkedList<T>::insertPosition(int pos, const T &theData) {
if (pos > size() || pos < 0) {
throw std::out_of_range("The insert location is invalid.");
}
auto node = head.get();
int i = 0;
for (; node && node->next && i < pos; node = node->next.get(), i++);
if (i != pos) {
throw std::out_of_range("Parameter 'pos' is out of range.");
}
auto newNode = std::make_unique<Node>(theData);
if (node) {
newNode->next = std::move(node->next);
node->next = std::move(newNode);
}
else {
head = std::move(newNode);
}
}
template <class T>
void SingleLinkedList<T>::pop_front() {
if (empty()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
do_pop_front();
}
template <class T>
void SingleLinkedList<T>::pop_back() {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto current = head.get();
Node* previous = nullptr;
while (current->next != nullptr) {
previous = current;
current = current->next.get();
}
tail = previous;
previous->next = nullptr;
}
template <class T>
void SingleLinkedList<T>::deleteSpecific(int delValue) {
if (!head.get()) {
throw std::out_of_range("List is Empty!!! Deletion is not possible.");
}
auto temp1 = head.get();
Node* temp2 = nullptr;
while (temp1->data != delValue) {
if (temp1->next == nullptr) {
throw std::invalid_argument("Given node not found in the list!!!");
}
temp2 = temp1;
temp1 = temp1->next.get();
}
temp2->next = std::move(temp1->next);
}
template <class T>
bool SingleLinkedList<T>::search(const T &x) {
auto current = head.get();
while (current) {
if (current->data == x) {
return true;
}
current = current->next.get();
}
return false;
}
#endif /* SingleLinkedList_h*/
```
Here is the main.cpp file:
```
//
// main.cpp
// Data Structure - LinkedList
//
// Created by Morgan Weiss on 7/24/2018
// Copyright © 2018 Morgan Weiss. All rights reserved.
//
#include <algorithm>
#include <cassert>
#include <iostream>
#include <memory>
#include <utility>
#include <stdexcept>
#include <ostream>
#include <iosfwd>
#include <stdexcept>
#include "SingleLinkedList.h"
int main(int argc, const char * argv[]) {
///////////////////////////////////////////////////////////////////////
///////////////////////////// Single Linked List //////////////////////
///////////////////////////////////////////////////////////////////////
SingleLinkedList<int> obj;
obj.push_back(2);
obj.push_back(4);
obj.push_back(6);
obj.push_back(8);
obj.push_back(10);
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"---------------displaying all nodes---------------";
std::cout<<"\n--------------------------------------------------\n";
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------Inserting At Start----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.push_front(50);
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"-------------inserting at particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.insertPosition(5,60);
std::cout << obj << "\n";
std::cout << "\n--------------------------------------------------\n";
std::cout << "-------------Get current size ---=--------------------";
std::cout << "\n--------------------------------------------------\n";
std::cout << obj.size() << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at start-----------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_front();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"----------------deleting at end-----------------------";
std::cout<<"\n--------------------------------------------------\n";
obj.pop_back();
std::cout << obj << "\n";
std::cout<<"\n--------------------------------------------------\n";
std::cout<<"--------------Deleting At Particular--------------";
std::cout<<"\n--------------------------------------------------\n";
obj.deleteSpecific(4);
std::cout << obj << "\n";
obj.search(8) ? printf("yes"):printf("no");
std::cout << "\n--------------------------------------------------\n";
std::cout << "--------------Testing copy----------------------------";
std::cout << "\n--------------------------------------------------\n";
SingleLinkedList<int> obj1 = obj;
std::cout << obj1 << "\n";
//std::cout << "\n-------------------------------------------------------------------------\n";
//std::cout << "--------------Testing to insert in an empty list----------------------------";
//std::cout << "\n-------------------------------------------------------------------------\n";
//SingleLinkedList<int> obj2;
//obj2.insertPosition(5, 60);
//std::cout << obj2 << "\n";
std::cin.get();
}
``` | 2018/08/05 | [
"https://codereview.stackexchange.com/questions/201042",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/150820/"
] | ### Move `public` section of the class to the top
I prefer, and suggest others, to put the `public` section of a class before the `protected` and `private` sections.
The rationale for it is that users of the class want to see the `public` section of the class. It is less important to them to see what's in the `protected` and `private` sections. It does not make sense that they will have to wade through less important sections of the class before they get to the most important section.
```
template <class T>
class SingleLinkedList {
public:
// Constructors
SingleLinkedList() = default; // empty constructor
...
protected:
private:
struct Node {
...
};
...
};
```
### Remove `display(std::ostream &str)`
I understand that you need the function at the moment to display the contents of an object. However, it's too tightly coupled with the class. Different users may want to display an object of the class differently. You can't support that easily if `display` is the only function the user has access to.
This should be motivation for you to implement the iterator class. When you have the iterator class ready, the `operator<<(std::ostream&, SingleLinkedList const&)` function can be moved out of the class and the `friend`-ship won't be necessary. The current functionality can be moved to a non-member function.
Also note that the list object should be a `const&`.
```
template <typename T>
std::ostream& operator<<(std::ostream &str, SingleLinkedList<T> const& list)
{
// This will work as soon as you have begin() and end() member functions
for ( auto const& item : list )
{
str << item << "\t";
}
return str;
}
```
### `insertPosition` needs a better name
You are not inserting a position. You are inserting an item at a position. For that reason, I think `insert_at_position` is more appropriate and follows the naming convention of other functions.
If `insert_at_position` is too verbose, the simpler name, `insert` will be better than `insertPosition`, IMO.
### `deleteSpecific` needs a better name
I think the simpler name `remove()` will be better.
If you decide to keep `deleteSpecific`, I would suggest changing it to `delete_specific` to keep the function names consistent. | Optimization
============
Getting the best performance for any operation is the Holy Grail for any programmer - but is this always required?
There's this famous quote by Donald Knuth:
>
> Premature optimization is the root of all evil.
>
>
>
While this is sometimes taken out of context, he basically wanted to express that you shouldn't worry about small inefficiencies in the code, **unless you know that extra performance is needed** (e.g. by profiling performance afterwards, or by design requirements beforehand). The extra complexity added by those optimizations usually makes debugging and maintaining the code much harder.
And this can be observed in the implementation: There is an optimization to allow for \$\mathcal{O}(1)\$ tail insertion by storing a `tail` pointer. As other answers have pointed out, that `tail` pointer isn't updated correctly in all places.
After getting OP's reasoning for the optimization (i.e. none), it seems like this one had been done prematurely.
### Know thy data structures
>
> Note: In the following, I'm assuming a forward singly linked list (`head` and `next` pointers). Similar arguments apply for reverse singly linked lists (`tail` and `prev` pointers).
>
>
>
Operations on a singly linked lists tail are usually one of its worst case ones, as finding the tail requires a full traversal of the list.
If it is known beforehand that operations on the tail will be critical, you'd normally not consider a singly linked list (other than maybe the reverse one), as other data structures like a doubly linked list or even a dynamically growing array (`std::vector`) inherently provide better performance characteristics for that use case.
>
> The only special case I can think of where this **might** be useful is that the program
>
>
> * runs on a platform with heavy memory constraints
> * and has lots of tail insertions, but few to none tail deletions,
>
>
> like a queue for an embedded device (where the extra memory overhead of a doubly linked list is too much) - but even then I'd still want to know why this is better than a circular buffer (which has even less memory overhead, as it needs no `next` pointers).
>
>
>
Design
======
Currently, the `SingleLinkedList` allows for move- and copy-constructable types, but doesn't provide any support for types that aren't (like `std::mutex`). If `SingleLinkedList` should also support those types (which require in-place construction), I'd suggest adding `emplace`, `emplace_front` and `emplace_back` member functions (corresponding to `insert`, `push_front` and `push_back` respectively).
>
> Note that this will require an additional `Node` constructor:
>
>
>
> ```
> template<typename... Args, typename = std::enable_if_t<std::is_constructible_v<T, Args&&...>>>
> Node(std::unique_ptr<Node>&& next, Args&&... args) noexcept(std::is_nothrow_constructible_v<T, Args&&...>)
> : data{std::forward<Args>(args)...}, next{std::move(next)} {}
>
> ```
>
> Some necessary changes:
>
>
> * `next` cannot be at the end of the parameter list ([explanation](https://stackoverflow.com/q/14768951/6467688))
> * `next` cannot have a default value (since it isn't at the end of the parameter list), nor can the constructor be overloaded regarding the presence of `next` (it either has to always be there or always be absent, anything else would result in ambiguities). I chose "It has to be there", YMMV.
>
>
> (Technically not the whole truth, as you could e.g. use tag types to choose the correct overload. This was meant as a *simple* example.)
> * This requires the `<type_traits>` header for, well, type traits.
>
>
> The type traits help constricting the constructor to only accept arguments that are valid for `T`, so instantiation fails as early as possible (the `std::make_unique<Node>(...)` call). As a bonus, the constructor is automatically gets the same exception specification as the internally called `T` constructor.
>
>
> This constructor can replace the existing ones in cases where `next != nullptr`. For consistency, I'd suggest dropping the `next` parameter from those constructors so there is only one order of parameters to pass a `next` node (having both `(value, node)` and `(node, value)` work can be confusing).
>
>
>
An implementation of `emplace_front` can be as simple as this:
```
template <class T>
template <typename... Args>
void SingleLinkedList<T>::emplace_front(Args&&... args) {
head = std::make_unique<Node>(std::move(head), std::forward<Args>(args)...);
if(!tail) tail = head.get(); // update tail if list was empty before
}
```
>
> This has been carefully crafted to have the same strong exception guarantee as the original `push_front`:
>
>
> * If the allocation fails in `std::make_unique`, the `head` isn't changed (because it is passed as `std::unique_ptr<Node>&&`).
> * Inside the `Node`, `data` gets constructed first. If that throws, `next` (in this case `head`) will not be moved from yet, i.e. it's still valid.
>
>
> It's subtleties like these that makes writing code with a strong exception guarantee hard to get right. You can simply adapt the original `push_front` implementation if that makes you more comfortable, as it's more robust regarding other changes (e.g. changing the constructors `next` parameter's type to `std::unique_ptr<Node>`, or reordering `Node::data` after `Node::next`).
>
>
>
Of course, `push_front` can now be reimplemented in terms of `emplace_front`:
```
template <class T>
void SingleLinkedList<T>::push_front(const T &theData) {
emplace_front(theData);
}
template <class T>
void SingleLinkedList<T>::push_front(T&& theData) {
emplace_front(std::move(theData));
}
``` |
473,683 | I am looking for a word or phrase which can be used in the sentence:
>
> It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology.
>
>
>
The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve. | 2018/11/19 | [
"https://english.stackexchange.com/questions/473683",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/324928/"
] | I don't know of a technology that cannot be improved, but we often use the term ***mature*** to describe technology that's deemed developed enough to be left alone:
>
> A **[mature technology](https://en.wikipedia.org/wiki/Mature_technology)** is a technology that has been in use for long enough that most of its initial faults and inherent problems have been removed or reduced by further development. In some contexts, it may also refer to technology that has not seen widespread use, but whose scientific background is well understood.
>
> *Wikipedia*
>
>
>
>
> **[mature](https://www.thefreedictionary.com/mature)**
>
> 6. No longer subject to great expansion or development. Used of an industry, market, or product.
>
> *American Heritage® Dictionary*
>
>
> | The word that first came to mind for me was ***robust***, which a previous poster had used in describing the meaning of the word they were suggesting ("foolproof").
>
> [**robust**](https://www.merriam-webster.com/dictionary/robust)
>
>
> 1d : capable of performing without failure under a wide range of
> conditions
>
>
> * *robust software*
>
>
> |
473,683 | I am looking for a word or phrase which can be used in the sentence:
>
> It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology.
>
>
>
The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve. | 2018/11/19 | [
"https://english.stackexchange.com/questions/473683",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/324928/"
] | In the same vein as the good *tried and true* or *mature* is [**seasoned.**](https://www.merriam-webster.com/dictionary/seasoned) The Merriam-Webster entry gives "to make fit by experience" as one of the meanings of the transitive verb. It is used in expressions like *seasoned advice* or *seasoned veterans* or *seasoned strategic planning consultants*.
I think *seasoned* implies that something or somebody functions *properly*, without fault. This likely includes sufficient efficiency but does not necessarily mean strictly *optimally,* so it's only a partial fit.
But it fits your word search nicely nevertheless because it already encompasses the "rather old" aspect. You can simply omit the "It is rather old" and say "It is a seasoned technology." | Nobody so far has suggested **commodity** (noun) / **commoditised** (verb). Where something is so well-understood that anyone can make a new one cheaply, that won't be any better than the other options.
I work in the development of new technology and we often refer to things that aren't interesting to us any more as having been commoditised.
The Merriam Webster [definition of commodity](https://www.merriam-webster.com/dictionary/commodity) covers it under heading 3:
>
> 3: a good or service whose wide availability typically leads to smaller
> profit margins and diminishes the importance of factors (such as brand
> name) other than price
>
>
> |
473,683 | I am looking for a word or phrase which can be used in the sentence:
>
> It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology.
>
>
>
The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve. | 2018/11/19 | [
"https://english.stackexchange.com/questions/473683",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/324928/"
] | **tried and tested**
>
> adjective - recognized as reliable; found to be successful
>
>
> tried-and-tested in British (ˈtraɪdəndˈtɛstɪd), tried-and-trusted
> (ˈtraɪdəndˈtrʌstɪd) or US and Canadian **tried-and-true** (ˈtraɪdəndˈtruː)
> adjective recognized as reliable; found to be successful
>
>
> <https://www.collinsdictionary.com/dictionary/english/tried-and-tested>
>
>
>
As noted the expression varies somewhat according to location. All of the above versions would be understandable to a British person. | In a technical context, you want [this definition](https://www.merriam-webster.com/dictionary/understood) of the word **understood**, which carries more weight than the way it is used colloquially:
*un·der·stood | \ˌən-dər-ˈstu̇d*
----------------------------------
### adjective
1. fully apprehended
The reason is *understood* is meant to be complete. If it is 100%, totally investigated, researched into detail, thoroughly optimised so there is nothing more to find out or improve, in science it is referred to as *understood*. Examples include:
>
> These are all interesting mathematical properties that are relevant to the description of physical systems, but they cannot be used as a catch-all, by saying that eventually all (un-**understood**) physical systems will be **understood** in terms of non-linearity.
>
>
>
*[Source](https://books.google.com/books?id=tbqfAgAAQBAJ&pg=PA292&lpg=PA292&dq=%22understood%22%20physical%20systems)*
And
>
> On the other hand, it has been found that many effects occuring in natural and man-made system of propagating waves can be best characterized and **understood** as parametric interactions of waves.
>
>
>
[Source](https://books.google.com/books?id=DRQjAQAAMAAJ&pg=PA777&lpg=PA777&dq=%22understood%22)
In both the these examples, the *understood* concept is a fully studied one that can be safely used as a building block for more complicated models because there is nothing more to learn about it. |
473,683 | I am looking for a word or phrase which can be used in the sentence:
>
> It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology.
>
>
>
The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve. | 2018/11/19 | [
"https://english.stackexchange.com/questions/473683",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/324928/"
] | I don't know of a technology that cannot be improved, but we often use the term ***mature*** to describe technology that's deemed developed enough to be left alone:
>
> A **[mature technology](https://en.wikipedia.org/wiki/Mature_technology)** is a technology that has been in use for long enough that most of its initial faults and inherent problems have been removed or reduced by further development. In some contexts, it may also refer to technology that has not seen widespread use, but whose scientific background is well understood.
>
> *Wikipedia*
>
>
>
>
> **[mature](https://www.thefreedictionary.com/mature)**
>
> 6. No longer subject to great expansion or development. Used of an industry, market, or product.
>
> *American Heritage® Dictionary*
>
>
> | There is a common acronym for this, used in computing and engineering, which is
**COTS** - "commercial off-the-shelf" - i.e. you can buy it ready made without having to do any research to invent it yourself, and without needing to understand every detail of how it works.
>
> It is rather old, but COTS technology.
>
>
>
<https://en.wiktionary.org/wiki/COTS> |
473,683 | I am looking for a word or phrase which can be used in the sentence:
>
> It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology.
>
>
>
The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve. | 2018/11/19 | [
"https://english.stackexchange.com/questions/473683",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/324928/"
] | Might I suggest that the technology has been **vetted**?
>
> vet: to subject to usually expert appraisal or correction
>
>
> | In a technical context, you want [this definition](https://www.merriam-webster.com/dictionary/understood) of the word **understood**, which carries more weight than the way it is used colloquially:
*un·der·stood | \ˌən-dər-ˈstu̇d*
----------------------------------
### adjective
1. fully apprehended
The reason is *understood* is meant to be complete. If it is 100%, totally investigated, researched into detail, thoroughly optimised so there is nothing more to find out or improve, in science it is referred to as *understood*. Examples include:
>
> These are all interesting mathematical properties that are relevant to the description of physical systems, but they cannot be used as a catch-all, by saying that eventually all (un-**understood**) physical systems will be **understood** in terms of non-linearity.
>
>
>
*[Source](https://books.google.com/books?id=tbqfAgAAQBAJ&pg=PA292&lpg=PA292&dq=%22understood%22%20physical%20systems)*
And
>
> On the other hand, it has been found that many effects occuring in natural and man-made system of propagating waves can be best characterized and **understood** as parametric interactions of waves.
>
>
>
[Source](https://books.google.com/books?id=DRQjAQAAMAAJ&pg=PA777&lpg=PA777&dq=%22understood%22)
In both the these examples, the *understood* concept is a fully studied one that can be safely used as a building block for more complicated models because there is nothing more to learn about it. |
473,683 | I am looking for a word or phrase which can be used in the sentence:
>
> It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology.
>
>
>
The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve. | 2018/11/19 | [
"https://english.stackexchange.com/questions/473683",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/324928/"
] | I would offer **battle-tested**
Often used figuratively to imply its been used hard and been put through its paces and hardships - yet still remained viable.
[Battle tested](https://www.merriam-webster.com/dictionary/battle-tested)
As the dictionary example:
>
> —often used figuratively
> The Yankees' pen, moreover, is battle-tested. Rivera, and his setup men, lefty Mike Stanton and righties Jeff Nelson and Ramiro Mendoza, have a combined 1.45 ERA over 105 2/3 innings of postseason experience.
> — Tom Verducci, Sports Illustrated, 20 Sept. 1999
>
>
>
For your example:
>
> It is rather old, but **battle-tested** technology.
>
>
>
This would give the impression that the software has been put through its paces under considerable duress, unexpected uses and intense situations - and each time, came out still working! | **Streamlined** may fit your needs.
>
> It is rather old, but *streamlined* technology.
>
>
>
adjective - designed or organized to give maximum efficiency; compact.
<https://www.dictionary.com/browse/streamlined>
I somewhat prefer this since it doesn't speak to the "newness" of the technology but it does imply that it is optimized or researched/planned in detail. |
473,683 | I am looking for a word or phrase which can be used in the sentence:
>
> It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology.
>
>
>
The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve. | 2018/11/19 | [
"https://english.stackexchange.com/questions/473683",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/324928/"
] | All of these answers, mature, well established, proven are absolutely correct in my opinion, but have become euphemisms for "out dated". Whenever someone tries to sell me "mature" technology, I immediately think "barely usable in today's environment".
I would then describe this as [stable](https://en.oxforddictionaries.com/definition/stable):
>
> Not likely to change or fail
> ; firmly established
>
>
>
or [fit for purpose](https://en.oxforddictionaries.com/definition/fit_for_purpose):
>
> well equipped or well suited for its designated role or purpose
>
>
> | May I suggest the adjective [**fully fledged**](https://www.collinsdictionary.com/dictionary/english/fully-fledged):
>
> **Fully fledged** means complete or fully developed.
>
>
>
This adjective comes from the idea that when a young bird has acquired its adult feathers, it is able to fly.
So, the OP's original example sentence is going to look like this:
>
> It is rather old, but **fully-fledged** technology.
>
>
> |
473,683 | I am looking for a word or phrase which can be used in the sentence:
>
> It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology.
>
>
>
The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve. | 2018/11/19 | [
"https://english.stackexchange.com/questions/473683",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/324928/"
] | **tried and tested**
>
> adjective - recognized as reliable; found to be successful
>
>
> tried-and-tested in British (ˈtraɪdəndˈtɛstɪd), tried-and-trusted
> (ˈtraɪdəndˈtrʌstɪd) or US and Canadian **tried-and-true** (ˈtraɪdəndˈtruː)
> adjective recognized as reliable; found to be successful
>
>
> <https://www.collinsdictionary.com/dictionary/english/tried-and-tested>
>
>
>
As noted the expression varies somewhat according to location. All of the above versions would be understandable to a British person. | perfected
---------
As an adjective, "perfect" describes a thing as *having* the qualities you're looking for; as a verb, it refers to *the activity or process of giving* it those qualities.
So as the past-tense of that verb, "perfected" says not just that a thing *is* in a state of perfection, but that it has been *brought* to this state -- with the connotation that it got there as the result of a rigorous, painstaking, iterative process, as opposed to a single act. Thus:
>
> It is rather old, but **perfected**, technology.
>
>
>
Ref:
<https://www.dictionary.com/browse/perfected>
**perfect** [ *adjective, noun* **pur**-fikt; *verb* per-**fekt** ]
[...]
*verb (used with object)*
* to bring to completion; finish.
* to bring to perfection; make flawless or faultless:
*He has succeeded in perfecting his recipe for chicken Kiev.* |
473,683 | I am looking for a word or phrase which can be used in the sentence:
>
> It is a rather old, but \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ technology.
>
>
>
The word or phrase should address a technology that is totally investigated, researched in detail, and thoroughly optimised, so there is nothing more to find out or improve. | 2018/11/19 | [
"https://english.stackexchange.com/questions/473683",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/324928/"
] | Might I suggest that the technology has been **vetted**?
>
> vet: to subject to usually expert appraisal or correction
>
>
> | Nobody so far has suggested **commodity** (noun) / **commoditised** (verb). Where something is so well-understood that anyone can make a new one cheaply, that won't be any better than the other options.
I work in the development of new technology and we often refer to things that aren't interesting to us any more as having been commoditised.
The Merriam Webster [definition of commodity](https://www.merriam-webster.com/dictionary/commodity) covers it under heading 3:
>
> 3: a good or service whose wide availability typically leads to smaller
> profit margins and diminishes the importance of factors (such as brand
> name) other than price
>
>
> |