qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
510,518 | Install 14.04 through live usb to external-hdd on ASUS 105E-DS02, currently running 12.04 with broken wifi. The 8GB live usb and 3 dvds from PRIZX will provide the software. Have read through many answers and web sites, did note the need for internet connection which is not available until thats fixed. Hoping that wifi Atheros ath9k, internal, external Ralink and external rt2800usb Realtek rtl8192 are included in the software. The wifi issue is a seperate question (awaiting answers). Either way I wish to fix 12.04 and install 14.04 on external-hdd. The external-hdd is recognised in 12.04 , and there appears to the ability to boot external drive (recognised WD passport (750 GB) as such in BIOS) and to boot bootable (live) usb (also in BIOS) Any additional help will be much appreciated. Sure miss my now gone linux/bsd library and four servers. | 2014/08/12 | [
"https://askubuntu.com/questions/510518",
"https://askubuntu.com",
"https://askubuntu.com/users/315054/"
]
| Overall just start the installation but when it gets to the page where it asks you to select install location and such select "something else" then set the bootloader install location to the external hdd and the / mount point on it as well. | You should be able to do this quite easily using manual partitioning. See [this answer](https://askubuntu.com/a/343352/205638) and make sure you're installing to your external, which will likely be `/dev/sdb` and not internal, which will likely be `/dev/sda`. You also have to choose your external for Bootloader Installation as in [this guide](http://www.linuxbsdos.com/2013/10/23/how-to-install-ubuntu-13-10-on-an-external-hard-drive/). You'll most likely have to boot using your BIOS boot menu to choose USB device, since your grub installation on your internal hard drive won't know about the external and vice versa. |
28,678,095 | I have an excel sheet named InputData. I have 9 different columns present at the moment. I want to have a loop which counts the number of columns in the excel sheet. Also, for each value of the counter, I want to select that individual column and the last column (to be selected default for each iteration). Once I have selected the necessary columns, the idea is to do a pivot table and draw a bar chart. Then again dynamically goto the next column via the counter value and the last column(to be selected default for each iteration) and so on. I am not able to figure out how to go about it. Any help in this matter is highly appreciated. Thanks in advance!!
```
For i = 1 To lastColno
' Pivot Table Code
Range("B1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Paste
Sheets("BuildData").Select
Range("J1").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Sheet1").Select
Range("B1").Select
ActiveSheet.Paste
Range("A1").Select
Application.CutCopyMode = False
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Sheet1!R1C1:R2641C2", Version:=xlPivotTableVersion14).CreatePivotTable _
TableDestination:="Sheet2!R3C1", TableName:="PivotTable1", DefaultVersion _
:=xlPivotTableVersion14
Sheets("Sheet2").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("_KOLA_5SX")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Claim?")
.Orientation = xlColumnField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
"PivotTable1").PivotFields("Claim?"), "Count of Claim?", xlCount
Next i
``` | 2015/02/23 | [
"https://Stackoverflow.com/questions/28678095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4597187/"
]
| I am going to assume you've attempted a few things know the basics of excel-vba (for future questions and maybe this one as well, show the work you've done so far).
I would create a formula cell that counts how many columns there. Put it in another sheet so the formula is `=COUNTA('InputData'!1:1)`. COUNTA counts the number of cells that aren't empty in the range. Assuming there are no blank columns, this will give you the location of the last column. You can then use that in your VBA loop.
If your formula field is in cell "A1" then the loop might look like:
```
Dim lastColumn As Integer
lastColumn = Range("A2").Value
For i = 1 To lastColumn
# rest of your code here
Next i
```
Try this [vba tutorial](http://www.excel-easy.com/vba.html) for tips on how to grab the columns and go about making your pivot table. Good luck. Hope this helps you get started. | Unfortunately I will not be able to provide you your answer however following code can guide you through your start. Following code will find your last column and repeat your code until "i" hits your column number. In between you can add your code which you want to repeat.
```
Sub rowvscol()
Dim lastColno As Long
Dim lastCol As Range
lastColno = Cells(1, Columns.Count).End(xlToLeft).Column
Set lastCol = Range(lastColno & ":" & lastColno).EntireColumn
For i = 1 To lastColno
' Pivot Table Code Goes here
Next i
End Sub
```
Good luck. |
26,746,253 | How can I express the following without the nested case statements? Specifically, I would like to do the steps in order, and call fail if any of the steps hit the "bad" branch.
```
loadData :: IO [Market]
loadData = do
filedata <- B.readFile "markets.json"
case parseData filedata of
Left err -> fail err
Right v -> do
case fromJSON v of
Error err -> fail err
Success a -> return a
``` | 2014/11/04 | [
"https://Stackoverflow.com/questions/26746253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105678/"
]
| You probably want the exception monad transformer here. Something like this (utterly untested):
```
import Control.Monad.Trans
import Control.Monad.Except
type MyMonadStack a = ExceptT String IO a
loadData :: MyMonadStack [Market]
loadData = do filedata <- lift $ B.readFile "markets.json"
v <- ExceptT $ parseData filedata
a <- ExceptT $ toEither $ fromJSON v
return a
toEither :: WhateverTypeFromJSONReturns a b -> Either a b
toEither (Error a) = Left a
toEither (Success b) = Right b
``` | If `parseData` and `fromJSON` both have `Either Err a` as their codomain, where `Err` is a fixed type (maybe defined by you), then you can use the `Either e` monad instance like so:
```
loadData :: IO (Either Err [Market])
loadData = do
filedata <- B.readFile "markets.json"
return $ parseData filedata >>= fromJSON
```
Or, if you want to be extra slick, you can use a particular [monad transformer](http://hackage.haskell.org/package/either-3.0.2) to do the same thing. |
336,364 | I would like to ask some help on how I can get the Mod 10 check digit of Contact.DonorID.
the result should be
```
Contact.CRN__c = Contact.DonorID + CheckDigit
```
Just like this:
>
> Check Digit is **2**
>
>
> CRN: 0018457**2**
>
>
>
It is my first time to do it and I don't have any idea, I've been struggling for 3 days searching about it. I found this link -- [Luhn algorithm check digit in formula field](https://salesforce.stackexchange.com/questions/79536/luhn-algorithm-check-digit-in-formula-field) but it is using formula field, so, it can't help me.
Thank you in advance! | 2021/03/10 | [
"https://salesforce.stackexchange.com/questions/336364",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/93802/"
]
| I found that to add a button to a list view, navigate to "Search Layouts for Salesforce Classic" (right below Search Layouts) and add the button to the List View Layout there.
Note that the button will not appear in the "Recently Viewed" list view, but it will appear in all the other list views. | Setup > Object Manager > Case > In the sidebar > ListView Page Layout > Edit List View then in the custom button section add your list button, And Save it.
You see the list button on the list views other than recently view. |
56,840,971 | I am trying to create a function that prints each word on a new line. The argument given is a string with words that aren't separated by a space but capitalized except the first word i.e. "helloMyNameIsMark". I have something that works but wondering if there's a better way of doing this in javaScript.
```
separateWords = (string) => {
const letters = string.split('');
let word = "";
const words = letters.reduce((acc, letter, idx) => {
if (letter === letter.toUpperCase()) {
acc.push(word);
word = "";
word = word.concat(letter);
} else if (idx === letters.length - 1) {
word = word.concat(letter);
acc.push(word);
} else {
word = word.concat(letter)
}
return acc
}, []);
words.forEach(word => {
console.log(word)
})
}
``` | 2019/07/01 | [
"https://Stackoverflow.com/questions/56840971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11725805/"
]
| You could use the regex `[A-Z]` and [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) each upper case letter with `\n` prefix
```js
const separateWords = str => str.replace(/[A-Z]/g, m => '\n' + m)
console.log(separateWords('helloMyNameIsMark'))
```
Or you could use a lookahead `(?=[A-Z])` to `split` at each upper case letter to get an array of words. Then loop through the array to log each word:
```js
const separateWords = str => str.split(/(?=[A-Z])/g)
separateWords('helloMyNameIsMark').forEach(w => console.log(w))
``` | I would separate the breaking of words into an array and the printing of that array into two distinct functions. Regular expressions make that first part much easier than your `reduce` call. (But that `reduce` is a good thought if you don't see a regex solution.)
My version might look like this:
```js
const separateWords = (str) => str .replace (/([A-Z])/g, " $1") .split (' ')
const printSeparateWords = (str) => separateWords (str) .forEach (word => console.log (word) )
printSeparateWords ("helloMyNameIsMark")
``` |
56,840,971 | I am trying to create a function that prints each word on a new line. The argument given is a string with words that aren't separated by a space but capitalized except the first word i.e. "helloMyNameIsMark". I have something that works but wondering if there's a better way of doing this in javaScript.
```
separateWords = (string) => {
const letters = string.split('');
let word = "";
const words = letters.reduce((acc, letter, idx) => {
if (letter === letter.toUpperCase()) {
acc.push(word);
word = "";
word = word.concat(letter);
} else if (idx === letters.length - 1) {
word = word.concat(letter);
acc.push(word);
} else {
word = word.concat(letter)
}
return acc
}, []);
words.forEach(word => {
console.log(word)
})
}
``` | 2019/07/01 | [
"https://Stackoverflow.com/questions/56840971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11725805/"
]
| You could use the regex `[A-Z]` and [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) each upper case letter with `\n` prefix
```js
const separateWords = str => str.replace(/[A-Z]/g, m => '\n' + m)
console.log(separateWords('helloMyNameIsMark'))
```
Or you could use a lookahead `(?=[A-Z])` to `split` at each upper case letter to get an array of words. Then loop through the array to log each word:
```js
const separateWords = str => str.split(/(?=[A-Z])/g)
separateWords('helloMyNameIsMark').forEach(w => console.log(w))
``` | Very similar to adiga's answer, but it can actually be simpler:
```
const separateWords = str => str.replace(/[A-Z]/g, '\n$&');
```
This will also benefit from improved performance (might matter if used at scale). |
56,840,971 | I am trying to create a function that prints each word on a new line. The argument given is a string with words that aren't separated by a space but capitalized except the first word i.e. "helloMyNameIsMark". I have something that works but wondering if there's a better way of doing this in javaScript.
```
separateWords = (string) => {
const letters = string.split('');
let word = "";
const words = letters.reduce((acc, letter, idx) => {
if (letter === letter.toUpperCase()) {
acc.push(word);
word = "";
word = word.concat(letter);
} else if (idx === letters.length - 1) {
word = word.concat(letter);
acc.push(word);
} else {
word = word.concat(letter)
}
return acc
}, []);
words.forEach(word => {
console.log(word)
})
}
``` | 2019/07/01 | [
"https://Stackoverflow.com/questions/56840971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11725805/"
]
| You could use the regex `[A-Z]` and [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace) each upper case letter with `\n` prefix
```js
const separateWords = str => str.replace(/[A-Z]/g, m => '\n' + m)
console.log(separateWords('helloMyNameIsMark'))
```
Or you could use a lookahead `(?=[A-Z])` to `split` at each upper case letter to get an array of words. Then loop through the array to log each word:
```js
const separateWords = str => str.split(/(?=[A-Z])/g)
separateWords('helloMyNameIsMark').forEach(w => console.log(w))
``` | Here's a more literal interpretation of your stated requirement: *prints each word* on a new line.
```js
function separateWords(str){
let currentWord = '';
for (let chr of str){
if (chr == chr.toUpperCase()){
console.log(currentWord);
currentWord = chr;
} else {
currentWord += chr;
}
}
if (currentWord)
console.log(currentWord);
}
separateWords('helloMyNameIsMark');
``` |
1,561,193 | I get the Extended Euclidean Algorithm but I don't understand what this question is asking me:
In this question we consider arithmetic modulo 60 ("clock arithmetic" on the clock with numbers {0,1,2,3,...,58,59}).
Which of the following statements apply?
a. 50 X 50 = 40 modulo 60
b. 17 + 50 = 3 modulo 60
c. 4100 x 10 = 0 modulo 60
d. 1/17 = 53 modulo 60
e. 37 + 50 = modulo 60
f. 1/10 is undefined modulo 60
g. 17 - 35 = 42 modulo 60
h. 17 - 25 = 18 modulo 60
I have to pick the right ones but I'm not sure how to work it out? Like if they gave something like
17x = 1 mod(43) I could solve it but I'm not sure how you would solve the other question
P.S I have the answers I just dont want to look at them as I'd rather try to understand first as this is revision for my exam. thanks | 2015/12/05 | [
"https://math.stackexchange.com/questions/1561193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242148/"
]
| You need to differentiate between two different questions:
Q1: Does the right road lead to the ruins?
Q2: Would you say "yes" to question Q1?
If the right road does lead to the ruins, the liar will say "No" to Q1, and *therefore* say "Yes" to Q2! | You have to consider each of the cases separately. First, let us assume that right path leads to the ruins. Then a villager telling the truth would answer "Yes". A lying villager would answer "Yes" as well, since his answer to the question "Does the right path lead to the ruins?" would be "No".
On the other hand, if the right path leads into the jungle, the answer from the villager telling the truth would be "No". The lying villager would also say "No", because his answer to the question "Does the right path lead to the ruins?" would be "Yes".
Thus, in both cases a "Yes" means that the right path leads to the ruins, and a "No" means that the left path leads to the ruins. |
1,561,193 | I get the Extended Euclidean Algorithm but I don't understand what this question is asking me:
In this question we consider arithmetic modulo 60 ("clock arithmetic" on the clock with numbers {0,1,2,3,...,58,59}).
Which of the following statements apply?
a. 50 X 50 = 40 modulo 60
b. 17 + 50 = 3 modulo 60
c. 4100 x 10 = 0 modulo 60
d. 1/17 = 53 modulo 60
e. 37 + 50 = modulo 60
f. 1/10 is undefined modulo 60
g. 17 - 35 = 42 modulo 60
h. 17 - 25 = 18 modulo 60
I have to pick the right ones but I'm not sure how to work it out? Like if they gave something like
17x = 1 mod(43) I could solve it but I'm not sure how you would solve the other question
P.S I have the answers I just dont want to look at them as I'd rather try to understand first as this is revision for my exam. thanks | 2015/12/05 | [
"https://math.stackexchange.com/questions/1561193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242148/"
]
| If you ask a liar a question the answer will be lie.
If you ask a liar what his answer will be, he will lie about his answer being a lie and he will say that his answer is the truth.
So if the path leads to ruins and you ask if the path leads to ruins he will lie and say "no". If you ask him if he will answer "yes" he will lie and answer.... "yes".
....
To get the truth out of a liar ask him "What would you say if I asked you..." the liar will lie about lying and give the true answer....[1]
[1](assuming the question was binary yes/no... otherwise he could give a second lie; the lie he \*wouldn't give.)
====
Or you could parse it from the top down:
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" LIAR: "NO"
That's a lie. He would answer yes.
* "Does the right branch leads to the ruins" LIAR: "YES"
* That's a lie. The right branch does not lead to the ruins.
* Conclusion: The left branch lead to the ruins.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" TRUTHTELLER: "NO"
That's the truth. He would answer no.
* "Does the right branch leads to the ruins" TRUTHTELLER : "NO"
* That's the truth. The right branch does not lead to the ruins.
* Conclusion: The left branch lead to the ruins.
Hence "NO" means left branch.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" LIAR: "YES"
That's a lie. He would answer no.
* "Does the right branch leads to the ruins" LIAR: "NO"
* That's a lie. The right branch does lead to the ruins.
* Conclusion: The right branch lead to the ruins.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" TRUTHTELLER: "YES"
That's the truth. He would answer yes.
* "Does the right branch leads to the ruins" TRUTHTELLER : "YES"
* That's the truth. The right branch does lead to the ruins.
* Conclusion: The right branch lead to the ruins.
Hence "YES" means right branch. | You have to consider each of the cases separately. First, let us assume that right path leads to the ruins. Then a villager telling the truth would answer "Yes". A lying villager would answer "Yes" as well, since his answer to the question "Does the right path lead to the ruins?" would be "No".
On the other hand, if the right path leads into the jungle, the answer from the villager telling the truth would be "No". The lying villager would also say "No", because his answer to the question "Does the right path lead to the ruins?" would be "Yes".
Thus, in both cases a "Yes" means that the right path leads to the ruins, and a "No" means that the left path leads to the ruins. |
1,561,193 | I get the Extended Euclidean Algorithm but I don't understand what this question is asking me:
In this question we consider arithmetic modulo 60 ("clock arithmetic" on the clock with numbers {0,1,2,3,...,58,59}).
Which of the following statements apply?
a. 50 X 50 = 40 modulo 60
b. 17 + 50 = 3 modulo 60
c. 4100 x 10 = 0 modulo 60
d. 1/17 = 53 modulo 60
e. 37 + 50 = modulo 60
f. 1/10 is undefined modulo 60
g. 17 - 35 = 42 modulo 60
h. 17 - 25 = 18 modulo 60
I have to pick the right ones but I'm not sure how to work it out? Like if they gave something like
17x = 1 mod(43) I could solve it but I'm not sure how you would solve the other question
P.S I have the answers I just dont want to look at them as I'd rather try to understand first as this is revision for my exam. thanks | 2015/12/05 | [
"https://math.stackexchange.com/questions/1561193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242148/"
]
| You need to differentiate between two different questions:
Q1: Does the right road lead to the ruins?
Q2: Would you say "yes" to question Q1?
If the right road does lead to the ruins, the liar will say "No" to Q1, and *therefore* say "Yes" to Q2! | If I were in this situation in real life, I will ask them about a different place different from the two in the fork, The truth teller will always say "no". On the other hand the liar will say "yes". For that I can identify whether the person is a truth-teller or not, then I will ask him the direct question.
For example, if I am walking in the street and I know one of the branches leads to Ali's house and the other leads to Yasser's house and I seek Ali's house. I would first ask if the right path leads to (some name other than the expected) for example Omar's house which isn't existent. the truth-teller will say "no" while the liar, will say "yes". So I will proceed with the question of interest and determine the result based upon the previous response?
I hope this helps!
If something is wrong or ambiguous, correct me. |
1,561,193 | I get the Extended Euclidean Algorithm but I don't understand what this question is asking me:
In this question we consider arithmetic modulo 60 ("clock arithmetic" on the clock with numbers {0,1,2,3,...,58,59}).
Which of the following statements apply?
a. 50 X 50 = 40 modulo 60
b. 17 + 50 = 3 modulo 60
c. 4100 x 10 = 0 modulo 60
d. 1/17 = 53 modulo 60
e. 37 + 50 = modulo 60
f. 1/10 is undefined modulo 60
g. 17 - 35 = 42 modulo 60
h. 17 - 25 = 18 modulo 60
I have to pick the right ones but I'm not sure how to work it out? Like if they gave something like
17x = 1 mod(43) I could solve it but I'm not sure how you would solve the other question
P.S I have the answers I just dont want to look at them as I'd rather try to understand first as this is revision for my exam. thanks | 2015/12/05 | [
"https://math.stackexchange.com/questions/1561193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242148/"
]
| If you ask a liar a question the answer will be lie.
If you ask a liar what his answer will be, he will lie about his answer being a lie and he will say that his answer is the truth.
So if the path leads to ruins and you ask if the path leads to ruins he will lie and say "no". If you ask him if he will answer "yes" he will lie and answer.... "yes".
....
To get the truth out of a liar ask him "What would you say if I asked you..." the liar will lie about lying and give the true answer....[1]
[1](assuming the question was binary yes/no... otherwise he could give a second lie; the lie he \*wouldn't give.)
====
Or you could parse it from the top down:
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" LIAR: "NO"
That's a lie. He would answer yes.
* "Does the right branch leads to the ruins" LIAR: "YES"
* That's a lie. The right branch does not lead to the ruins.
* Conclusion: The left branch lead to the ruins.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" TRUTHTELLER: "NO"
That's the truth. He would answer no.
* "Does the right branch leads to the ruins" TRUTHTELLER : "NO"
* That's the truth. The right branch does not lead to the ruins.
* Conclusion: The left branch lead to the ruins.
Hence "NO" means left branch.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" LIAR: "YES"
That's a lie. He would answer no.
* "Does the right branch leads to the ruins" LIAR: "NO"
* That's a lie. The right branch does lead to the ruins.
* Conclusion: The right branch lead to the ruins.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" TRUTHTELLER: "YES"
That's the truth. He would answer yes.
* "Does the right branch leads to the ruins" TRUTHTELLER : "YES"
* That's the truth. The right branch does lead to the ruins.
* Conclusion: The right branch lead to the ruins.
Hence "YES" means right branch. | If I were in this situation in real life, I will ask them about a different place different from the two in the fork, The truth teller will always say "no". On the other hand the liar will say "yes". For that I can identify whether the person is a truth-teller or not, then I will ask him the direct question.
For example, if I am walking in the street and I know one of the branches leads to Ali's house and the other leads to Yasser's house and I seek Ali's house. I would first ask if the right path leads to (some name other than the expected) for example Omar's house which isn't existent. the truth-teller will say "no" while the liar, will say "yes". So I will proceed with the question of interest and determine the result based upon the previous response?
I hope this helps!
If something is wrong or ambiguous, correct me. |
1,561,193 | I get the Extended Euclidean Algorithm but I don't understand what this question is asking me:
In this question we consider arithmetic modulo 60 ("clock arithmetic" on the clock with numbers {0,1,2,3,...,58,59}).
Which of the following statements apply?
a. 50 X 50 = 40 modulo 60
b. 17 + 50 = 3 modulo 60
c. 4100 x 10 = 0 modulo 60
d. 1/17 = 53 modulo 60
e. 37 + 50 = modulo 60
f. 1/10 is undefined modulo 60
g. 17 - 35 = 42 modulo 60
h. 17 - 25 = 18 modulo 60
I have to pick the right ones but I'm not sure how to work it out? Like if they gave something like
17x = 1 mod(43) I could solve it but I'm not sure how you would solve the other question
P.S I have the answers I just dont want to look at them as I'd rather try to understand first as this is revision for my exam. thanks | 2015/12/05 | [
"https://math.stackexchange.com/questions/1561193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242148/"
]
| If you ask a liar a question the answer will be lie.
If you ask a liar what his answer will be, he will lie about his answer being a lie and he will say that his answer is the truth.
So if the path leads to ruins and you ask if the path leads to ruins he will lie and say "no". If you ask him if he will answer "yes" he will lie and answer.... "yes".
....
To get the truth out of a liar ask him "What would you say if I asked you..." the liar will lie about lying and give the true answer....[1]
[1](assuming the question was binary yes/no... otherwise he could give a second lie; the lie he \*wouldn't give.)
====
Or you could parse it from the top down:
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" LIAR: "NO"
That's a lie. He would answer yes.
* "Does the right branch leads to the ruins" LIAR: "YES"
* That's a lie. The right branch does not lead to the ruins.
* Conclusion: The left branch lead to the ruins.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" TRUTHTELLER: "NO"
That's the truth. He would answer no.
* "Does the right branch leads to the ruins" TRUTHTELLER : "NO"
* That's the truth. The right branch does not lead to the ruins.
* Conclusion: The left branch lead to the ruins.
Hence "NO" means left branch.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" LIAR: "YES"
That's a lie. He would answer no.
* "Does the right branch leads to the ruins" LIAR: "NO"
* That's a lie. The right branch does lead to the ruins.
* Conclusion: The right branch lead to the ruins.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" TRUTHTELLER: "YES"
That's the truth. He would answer yes.
* "Does the right branch leads to the ruins" TRUTHTELLER : "YES"
* That's the truth. The right branch does lead to the ruins.
* Conclusion: The right branch lead to the ruins.
Hence "YES" means right branch. | You need to differentiate between two different questions:
Q1: Does the right road lead to the ruins?
Q2: Would you say "yes" to question Q1?
If the right road does lead to the ruins, the liar will say "No" to Q1, and *therefore* say "Yes" to Q2! |
1,561,193 | I get the Extended Euclidean Algorithm but I don't understand what this question is asking me:
In this question we consider arithmetic modulo 60 ("clock arithmetic" on the clock with numbers {0,1,2,3,...,58,59}).
Which of the following statements apply?
a. 50 X 50 = 40 modulo 60
b. 17 + 50 = 3 modulo 60
c. 4100 x 10 = 0 modulo 60
d. 1/17 = 53 modulo 60
e. 37 + 50 = modulo 60
f. 1/10 is undefined modulo 60
g. 17 - 35 = 42 modulo 60
h. 17 - 25 = 18 modulo 60
I have to pick the right ones but I'm not sure how to work it out? Like if they gave something like
17x = 1 mod(43) I could solve it but I'm not sure how you would solve the other question
P.S I have the answers I just dont want to look at them as I'd rather try to understand first as this is revision for my exam. thanks | 2015/12/05 | [
"https://math.stackexchange.com/questions/1561193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242148/"
]
| You need to differentiate between two different questions:
Q1: Does the right road lead to the ruins?
Q2: Would you say "yes" to question Q1?
If the right road does lead to the ruins, the liar will say "No" to Q1, and *therefore* say "Yes" to Q2! | Since the liar always lies, the only way to extract a truth from a liar is to make him lie a lie, as $\neg (\neg T) = T$.
Let $p$ be the case that the villager tells the truth.
Let $q$ be the case that the right branch leads to the ruins.
We shall prove this by taking cases:
1. The right branch leads to the ruins. (i.e $q$)
1.1 If $p$, then the answer will be yes and you are good to go.
1.2 If $\neg p$, if you had asked the liar a question whether $q$, he would say "No" as he wants to lie. However since you've asked him whether he'll answer "yes", if he were not lying then he would have answered "no" but as he always lies, he will answer $\neg$no$=$yes. Thus, you are good to go.
2. The left branch leads to the ruins. (i.e $\neg q$)
1.1 If $p$, then the answer would be "no" and you should thus take the left branch.
1.2 If $\neg p$ then the answer would be still be "no" as the villager will lie twice.
Thus if the answer is "no", you should always go left, and if it's "yes" then you should go right. |
1,561,193 | I get the Extended Euclidean Algorithm but I don't understand what this question is asking me:
In this question we consider arithmetic modulo 60 ("clock arithmetic" on the clock with numbers {0,1,2,3,...,58,59}).
Which of the following statements apply?
a. 50 X 50 = 40 modulo 60
b. 17 + 50 = 3 modulo 60
c. 4100 x 10 = 0 modulo 60
d. 1/17 = 53 modulo 60
e. 37 + 50 = modulo 60
f. 1/10 is undefined modulo 60
g. 17 - 35 = 42 modulo 60
h. 17 - 25 = 18 modulo 60
I have to pick the right ones but I'm not sure how to work it out? Like if they gave something like
17x = 1 mod(43) I could solve it but I'm not sure how you would solve the other question
P.S I have the answers I just dont want to look at them as I'd rather try to understand first as this is revision for my exam. thanks | 2015/12/05 | [
"https://math.stackexchange.com/questions/1561193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/242148/"
]
| If you ask a liar a question the answer will be lie.
If you ask a liar what his answer will be, he will lie about his answer being a lie and he will say that his answer is the truth.
So if the path leads to ruins and you ask if the path leads to ruins he will lie and say "no". If you ask him if he will answer "yes" he will lie and answer.... "yes".
....
To get the truth out of a liar ask him "What would you say if I asked you..." the liar will lie about lying and give the true answer....[1]
[1](assuming the question was binary yes/no... otherwise he could give a second lie; the lie he \*wouldn't give.)
====
Or you could parse it from the top down:
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" LIAR: "NO"
That's a lie. He would answer yes.
* "Does the right branch leads to the ruins" LIAR: "YES"
* That's a lie. The right branch does not lead to the ruins.
* Conclusion: The left branch lead to the ruins.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" TRUTHTELLER: "NO"
That's the truth. He would answer no.
* "Does the right branch leads to the ruins" TRUTHTELLER : "NO"
* That's the truth. The right branch does not lead to the ruins.
* Conclusion: The left branch lead to the ruins.
Hence "NO" means left branch.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" LIAR: "YES"
That's a lie. He would answer no.
* "Does the right branch leads to the ruins" LIAR: "NO"
* That's a lie. The right branch does lead to the ruins.
* Conclusion: The right branch lead to the ruins.
Q: ""if i were to ask you whether the right branch leads to the ruins would you answer yes?"" TRUTHTELLER: "YES"
That's the truth. He would answer yes.
* "Does the right branch leads to the ruins" TRUTHTELLER : "YES"
* That's the truth. The right branch does lead to the ruins.
* Conclusion: The right branch lead to the ruins.
Hence "YES" means right branch. | Since the liar always lies, the only way to extract a truth from a liar is to make him lie a lie, as $\neg (\neg T) = T$.
Let $p$ be the case that the villager tells the truth.
Let $q$ be the case that the right branch leads to the ruins.
We shall prove this by taking cases:
1. The right branch leads to the ruins. (i.e $q$)
1.1 If $p$, then the answer will be yes and you are good to go.
1.2 If $\neg p$, if you had asked the liar a question whether $q$, he would say "No" as he wants to lie. However since you've asked him whether he'll answer "yes", if he were not lying then he would have answered "no" but as he always lies, he will answer $\neg$no$=$yes. Thus, you are good to go.
2. The left branch leads to the ruins. (i.e $\neg q$)
1.1 If $p$, then the answer would be "no" and you should thus take the left branch.
1.2 If $\neg p$ then the answer would be still be "no" as the villager will lie twice.
Thus if the answer is "no", you should always go left, and if it's "yes" then you should go right. |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| I hope he doesn't calculate it by adding all numbers ;)
\begin{align}
50 = \sum\_{k=0}^{100} (-1)^k k
\end{align}
And a last one, involving only $4$s and $9$s:
\begin{align}
4^9 \mod 49 + \sqrt{49}
\end{align} | You could go Roman with $$\Huge{L}$$
Or with $$\begin{array}{c} \\ \\ \end{array}$$
$$\begin{array}{ccccccccccccc} \Huge{X}&&&&&&&&&&&&\Huge{X}\\ \\ \\ \\
&&&&&&\Huge{X}\\ \\ \\ \\ \Huge{X}&&&&&&&&&&&&\Huge{X} \end{array}\\ $$ |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| We can use only two [famous numbers in mathematics](http://list25.com/25-famous-numbers-and-why-they-are-important/), [$\large\pi$](http://en.wikipedia.org/wiki/Pi) and [$\large e$](http://en.wikipedia.org/wiki/E_%28mathematical_constant%29), to produce number $50$.
[$$\bbox[8pt,border:3px #FF69B4 solid]{\color{red}{\Large \lfloor e^\pi \rfloor + \lfloor \pi^e \rfloor + \lfloor \pi \rfloor + \lfloor e \rfloor = 50}}
$$](http://wolfr.am/24dbxKEa)
Click the box to see Wolfram Alpha's output to confirm the result | $$\frac{2^{\frac{(2\cdot2)!}{2+2}}+22+2^{2^2}-\sqrt 2^2}{2^{2-\frac{2}{2}}}$$ |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| I hope he doesn't calculate it by adding all numbers ;)
\begin{align}
50 = \sum\_{k=0}^{100} (-1)^k k
\end{align}
And a last one, involving only $4$s and $9$s:
\begin{align}
4^9 \mod 49 + \sqrt{49}
\end{align} | The Complex Answers
===================
I'd suggest $4.471527458208!=50$, but this isn't readily solvable. You suggested summations, and I thought "Hey! Why not *nested* summations?" The product of my "why not" statement:
$$\sum \_{n=0}^4\sum \_{i=n}^7n=50$$
If you're okay with floor functions:
$$\left\lfloor\prod \_{n=1}^5\frac{\pi +e}{7}n\right\rfloor=50$$
A slightly more complicated one:
$$-1\left(\sum \_{n=-3}^{11}-n\right)-10=50$$
If you want to complicate that (for a bit of fun), try, using Euler's identity for $-1$ and $n-2n$ for $-n$:
$$e^{i\pi}\left(\sum \_{n=3e^{i\pi}}^{11}n-2n\right)-10=50$$
The Somewhat Easy Answers
=========================
Using only 5's and 0's:
$$5.5\frac{505}{5}-5.55=50$$
Something kind of neat, using a pattern 1...7,1:
$$1\cdot 2+3\cdot 4+5\cdot 6+7-1=50$$
Where $x\_n$ denotes $x$ in radix $n$:
$$302\_4=50$$
$$200\_5=50$$
$$32\_{16}=50$$
$$62\_8=50$$
Set Theory
==========
If $\alpha=\#A$ states that $\alpha$ is the cardinal of $A$, then:
$$\#\{x\in\mathbb{N}:5<x\leq55\}=50$$ |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| We can use only two [famous numbers in mathematics](http://list25.com/25-famous-numbers-and-why-they-are-important/), [$\large\pi$](http://en.wikipedia.org/wiki/Pi) and [$\large e$](http://en.wikipedia.org/wiki/E_%28mathematical_constant%29), to produce number $50$.
[$$\bbox[8pt,border:3px #FF69B4 solid]{\color{red}{\Large \lfloor e^\pi \rfloor + \lfloor \pi^e \rfloor + \lfloor \pi \rfloor + \lfloor e \rfloor = 50}}
$$](http://wolfr.am/24dbxKEa)
Click the box to see Wolfram Alpha's output to confirm the result | Some solutions:
$$\dfrac{50(-1)^{-i}}{i^{i^{2}}}=50$$
$$50=\sum\_{n=1}^{10}(2n-1) \mod 10$$
$$50=1212\_3$$
$$\left(4+\frac{4}{4}\right)\dfrac{\binom{4}{4-\frac{4}{4}}}{0.4}=50$$ |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| Whenever one of my friends has a birthday, I find out how old they get and then I visit [their number on Wikipedia](http://en.wikipedia.org/wiki/50_%28number%29)
For your friend, I would write something like this:
>
> 50 is the smallest number that is the sum of two non-zero square numbers in two distinct ways: $1^2 + 7^2$ and $5^2 + 5^2$. It is also the sum of three squares, $3^2 + 4^2 + 5^2$. It is also a Harshad number and a nontotient and a noncototient. 50 is the aliquot sum of 40 and 94. 50 is also the atomic number of tin and fifth magic number in nuclear physics.
>
>
>
While many of the things on Wikipedia are not Mathematical expressions, and some of it is way too long to write on a cake, I am certain that this will brighten his day if you tell him this stuff!
As for a mathematical expression, I'd go with either $3^2 + 4^2 + 5^2$ because I find it simple but elegant, or fill the cake with stuff like "Harshad number, 5th magic number in nuclear physics, nontotient", etc. and see if he can figure out how old he is. | Some solutions:
$$\dfrac{50(-1)^{-i}}{i^{i^{2}}}=50$$
$$50=\sum\_{n=1}^{10}(2n-1) \mod 10$$
$$50=1212\_3$$
$$\left(4+\frac{4}{4}\right)\dfrac{\binom{4}{4-\frac{4}{4}}}{0.4}=50$$ |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| Quoting [Wikipedia](http://en.wikipedia.org/wiki/50_(number))
>
> Fifty is the smallest number that is the sum of two non-zero square
> numbers in two distinct ways: $50 = 1^2 + 7^2 = 5^2 + 5^2$.
>
>
>
So you could write something like
\begin{align}
50 = \min\_{n\in \mathbb{N}}\{n =p\_i^2+p\_j^2=p\_k^2+p\_l^2 \quad | \quad p\_i,p\_j,p\_k,p\_l\in\mathbb{N} \quad \wedge\quad p\_k \not =p\_i \not = p\_l \}
\end{align}
I like it, because it doesn't involve some sort of scaling and is not obvious (at least not for me). | $$
\begin{align}
&50 = \frac{5}{24} \zeta(-7)\\
&50 = \frac{ 1600 \sqrt{2} }{3 \pi ^3}\int\_0^{\infty } \frac{x^2 \log ^2(x)}{x^4+1} \, dx
\end{align}
$$ |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| No fancy math here, but if you want to emphasize how old your friend is getting, nothing says it better than implying he's halfway to the century mark:
$$100\over2$$ | Compute the smallest positive integer $n$ such that the first two digits of $n^2$ is $\frac{n}{2}$. |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| We also have
\begin{align\*}
50 &= 11+12+13+14 \\
&= (8+4)+(8-4)+(8\cdot 4)+(8/4) \\
&= 4^2 + 4^2 + 3^2 + 3^2\\
&= 6^2 + 3^2 + 2^2 + 1^2\\
&= (7+i)(7-i) \\
&= (10-\color{red}{5})(10-\color{red}{0})\\
&= 10(\color{red}{5}+\color{red}{0})\\
&= \sqrt{30^2+40^2}\\
&= \sqrt[3]{170^2+310^2}\\
&= \sqrt[3]{146^2+322^2}\\
&= \sqrt[3]{50^2+350^2}\\
\end{align\*}
Finally $50= 2 + 4 + 8 + 12 + 24$ and $\frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \frac{1}{12} + \frac{1}{24} = 1$. | Some solutions:
$$\dfrac{50(-1)^{-i}}{i^{i^{2}}}=50$$
$$50=\sum\_{n=1}^{10}(2n-1) \mod 10$$
$$50=1212\_3$$
$$\left(4+\frac{4}{4}\right)\dfrac{\binom{4}{4-\frac{4}{4}}}{0.4}=50$$ |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| $$
\begin{align}
&50 = \frac{5}{24} \zeta(-7)\\
&50 = \frac{ 1600 \sqrt{2} }{3 \pi ^3}\int\_0^{\infty } \frac{x^2 \log ^2(x)}{x^4+1} \, dx
\end{align}
$$ | $$50 = \int\_{\ln 1}^{3!+2^2}\frac{\Gamma(\frac{1}{2})^4}{6\sum\_{1}^{\infty}\frac{1}{n^2}}\sqrt{3^2+4^2}dx$$
can make it more complicated but it wont fit on a cake :) |
1,061,357 | A really good friend of mine is an elementary school math teacher. He is turning 50, and we want to put a mathematical expression that equals 50 on his birthday cake but goes beyond the typical "order of operations" problems. Some simple examples are
$$e^{\ln{50}}$$
$$100\sin{\frac{\pi}{6}}$$
$$25\sum\_{k=0}^\infty \frac{1}{2^k}$$
$$\frac{300}{\pi^2}\sum\_{k\in \mathbb{N}}\frac{1}{k^2}$$
What are some other creative ways I can top his cake?
I should note that he is an elementary school teacher. Now he LOVES math, and I can certainly show him a lot of expressions. I don't want them so difficult that it takes a masters degree to solve, but they should certainly be interesting enough to cause him to be wowed. Elementary functions are good, summations are also good, integrals can be explained, so this is the type of expression I'm looking for...
EDIT:: I would make a note that we are talking about a cake here, so use your judgement from here on out. Think of a normal rectangular cake and how big it is. Hence, long strings of numbers, complex integrals, and long summations are not going to work. I appreciate the answers but I need more compact expressions. | 2014/12/10 | [
"https://math.stackexchange.com/questions/1061357",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/61030/"
]
| Quoting [Wikipedia](http://en.wikipedia.org/wiki/50_(number))
>
> Fifty is the smallest number that is the sum of two non-zero square
> numbers in two distinct ways: $50 = 1^2 + 7^2 = 5^2 + 5^2$.
>
>
>
So you could write something like
\begin{align}
50 = \min\_{n\in \mathbb{N}}\{n =p\_i^2+p\_j^2=p\_k^2+p\_l^2 \quad | \quad p\_i,p\_j,p\_k,p\_l\in\mathbb{N} \quad \wedge\quad p\_k \not =p\_i \not = p\_l \}
\end{align}
I like it, because it doesn't involve some sort of scaling and is not obvious (at least not for me). | $$-\frac{12!! - 3^{10}}{705 \text{ mod } 101}-\int\_0^3 4x^3\;dx = 50$$
Or, if the double factorial is too weird:
$$\frac{9! - 2^{15}}{10000000\_2}-\sqrt[5]{243}^2 = 50$$ |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| I don't believe there is a way to *prevent* it from happening, apart from statically assigning the DNS servers on the VPN connection.
To change the order in which DNS servers are queried, one is supposed to be able to change the interface binding order as per <https://superuser.com/a/314379/120267>, but that doesn't seem to affect VPN connections in my personal testing on Windows 7; I've confirmed that my VPN connection is consistently added to the top of the `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Linkage\Bind` list, regardless of the interface binding order settings.
However, you can reset the DNS changes after the VPN connection is established.
Collecting Information
======================
Open up a command prompt (`Start` -> `Run...` -> `cmd`) and then run `netsh interface ipv4 show dnsservers`. You will see output similar to the following:
```
Configuration for interface "My VPN"
Statically Configured DNS Servers: 11.22.33.44
55.66.77.88
...
Configuration for interface "Local Network Connection"
DNS servers configured through DHCP: 192.168.0.1
192.168.0.2
...
```
You need the **interface name** for the VPN, and optionally your non-VPN connection's first **DNS server**. In this example, they are *My VPN* and *192.168.0.1*, respectively.
---
Setting It All Up
=================
Option 1: Disable VPN DNS
-------------------------
Assuming you don't need your VPN's DNS servers at all, you can simply run the following in the command prompt:
```
netsh interface ipv4 delete dnsservers name="<Interface Name>" address=all validate=no
Eg: netsh interface ipv4 delete dnsservers name="My VPN" address=all validate=no
```
If you run `netsh interface ipv4 show dnsservers` again, you will see that the DNS servers associated with the VPN have been removed; your non-VPN connection's DNS servers will be used to resolve hostnames.
---
Option 2: Supplement VPN DNS
----------------------------
If you need your VPN's DNS servers to resolve intranet hostnames, you can run the following in the command prompt:
```
netsh interface ipv4 add dnsservers name="<Interface Name>" address=<Non-VPN DNS server> index=1 validate=no
Eg: netsh interface ipv4 add dnsservers name="My VPN" address=192.168.0.1 index=1 validate=no
```
In this case, `netsh interface ipv4 show dnsservers` will show that your non-VPN connection's first DNS server has been added to the top of the list of your VPN's DNS servers. It will be used to resolve hostnames first, and if unsuccessful, fall back to using your VPN's regular DNS servers. | As of 2017 this is now possible if its based on **OpenVPN**
Add a line to your client config file of
>
> pull-filter ignore "dhcp-option DNS "
>
>
>
and it will ignore all pushed config lines that start with the quoted text.
The three action keywords are `accept` `ignore` `reject`.
I have not discovered a use case for reject. |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| Unfortunately netsh can not delete dns servers assigned by dhcp. But this can be done by clearing DhcpNameServer parameter in
```
HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{id}
```
registry key. | >
> Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
>
>
>
At least there is no easy way to do that.
>
> Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
>
>
>
You can add entries to the hosts file (`C:\Windows\System32\drivers\etc\hosts`). This file contains mappings from host names to IP addresses and is preferred over DNS requests. |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| Unfortunately netsh can not delete dns servers assigned by dhcp. But this can be done by clearing DhcpNameServer parameter in
```
HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{id}
```
registry key. | Can you check the status of the 'Use default gateway on remote network' checkbox. This is found by opening the properties of your VPN connection and go to Networking tab and select either TCP/IP v4 or TCP/IP V6 and then select properties and then advanced.
This may be enabled which could mean that all internet traffic is routed over the VPN connection.it is not always possible to disabled this and still do what you want with the VPN, but it can be disabled, it might speed up internet access.
If that doesn't help, there is a DNS tab there and you could try adding your DNS servers there. I have tried this, but I would expect these settings to override the automatic settings. |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| I don't believe there is a way to *prevent* it from happening, apart from statically assigning the DNS servers on the VPN connection.
To change the order in which DNS servers are queried, one is supposed to be able to change the interface binding order as per <https://superuser.com/a/314379/120267>, but that doesn't seem to affect VPN connections in my personal testing on Windows 7; I've confirmed that my VPN connection is consistently added to the top of the `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Linkage\Bind` list, regardless of the interface binding order settings.
However, you can reset the DNS changes after the VPN connection is established.
Collecting Information
======================
Open up a command prompt (`Start` -> `Run...` -> `cmd`) and then run `netsh interface ipv4 show dnsservers`. You will see output similar to the following:
```
Configuration for interface "My VPN"
Statically Configured DNS Servers: 11.22.33.44
55.66.77.88
...
Configuration for interface "Local Network Connection"
DNS servers configured through DHCP: 192.168.0.1
192.168.0.2
...
```
You need the **interface name** for the VPN, and optionally your non-VPN connection's first **DNS server**. In this example, they are *My VPN* and *192.168.0.1*, respectively.
---
Setting It All Up
=================
Option 1: Disable VPN DNS
-------------------------
Assuming you don't need your VPN's DNS servers at all, you can simply run the following in the command prompt:
```
netsh interface ipv4 delete dnsservers name="<Interface Name>" address=all validate=no
Eg: netsh interface ipv4 delete dnsservers name="My VPN" address=all validate=no
```
If you run `netsh interface ipv4 show dnsservers` again, you will see that the DNS servers associated with the VPN have been removed; your non-VPN connection's DNS servers will be used to resolve hostnames.
---
Option 2: Supplement VPN DNS
----------------------------
If you need your VPN's DNS servers to resolve intranet hostnames, you can run the following in the command prompt:
```
netsh interface ipv4 add dnsservers name="<Interface Name>" address=<Non-VPN DNS server> index=1 validate=no
Eg: netsh interface ipv4 add dnsservers name="My VPN" address=192.168.0.1 index=1 validate=no
```
In this case, `netsh interface ipv4 show dnsservers` will show that your non-VPN connection's first DNS server has been added to the top of the list of your VPN's DNS servers. It will be used to resolve hostnames first, and if unsuccessful, fall back to using your VPN's regular DNS servers. | I had a similar problem; connecting to a VPN server would override my workstation's (remote VPN client) DNS so that the local LAN DNS would be obscured. I described the problem more in detail on [Stackoverflow side](https://stackoverflow.com/questions/14078824/how-to-prevent-openvpn-from-overriding-local-dns) before I was pointed out that I should've posted it here instead.
Having read through this thread it is apparent that the override can't be prevented using the OpenVPN client configuration. My solution was to add a batch file in the OpenVPN config directory that executes when the OpenVPN connection is formed. If the OVPN file is called company.ovpn, the file that is run on connect needs to be named company\_up.bat.
I've augmented the file some since the version I posted to my question in StackOverflow earlier tonight. Now it looks like this:
```
1: ping 127.0.0.1 -n 2 > nul
2: netsh interface ip set dns "Local Area Connection 4" static 127.0.0.1
3: route delete 0.0.0.0
4: route add -p 0.0.0.0/0 172.20.20.1 metric 1000
5: exit 0
```
**1:** A hack to wait for couple of seconds before proceeding. The latest version (2.3) of OpenVPN client would ignore the DNS and route changes if executed without a delay.
**2:** Set the DNS of the VPN connection to point to the localhost. I have a resolver (I use [SimpleDNS Plus](http://www.simpledns.com/)) running on the localhost that forwards the queries to the company domain to the company DNS server over the VPN, and everything else to the local LAN DNS server. Note that I could not use a local LAN resolver to forward the queries for the company domain to the company DNS over the VPN since the VPN endpoint is on the localhost. The connection name ("Local Area Connection 4") was determined at command prompt via "ipconfig /all".
**3:** The company VPN server is configured to route *all* the outbound traffic through the VPN while at the same time restricting outbound (to the Internet) SSH connections. This conflicted with my workflow, and I'm first deleting the "0.0.0.0 netmask 0.0.0.0" route...
**4:** .. and then I re-add the 0.0.0.0/0 route to point to the local LAN gateway, and set its metric (weight) to 1000 as a catch-all for all traffic that is not routed otherwise.
**5:** Without "exit 0" OpenVPN spits out an error warning of the script failed (with an exit status 1).
Hopefully this is useful for someone.. it's working reasonably well for me (no need to make route or DNS adjustments manually every time I open a connection). |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| I don't believe there is a way to *prevent* it from happening, apart from statically assigning the DNS servers on the VPN connection.
To change the order in which DNS servers are queried, one is supposed to be able to change the interface binding order as per <https://superuser.com/a/314379/120267>, but that doesn't seem to affect VPN connections in my personal testing on Windows 7; I've confirmed that my VPN connection is consistently added to the top of the `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Linkage\Bind` list, regardless of the interface binding order settings.
However, you can reset the DNS changes after the VPN connection is established.
Collecting Information
======================
Open up a command prompt (`Start` -> `Run...` -> `cmd`) and then run `netsh interface ipv4 show dnsservers`. You will see output similar to the following:
```
Configuration for interface "My VPN"
Statically Configured DNS Servers: 11.22.33.44
55.66.77.88
...
Configuration for interface "Local Network Connection"
DNS servers configured through DHCP: 192.168.0.1
192.168.0.2
...
```
You need the **interface name** for the VPN, and optionally your non-VPN connection's first **DNS server**. In this example, they are *My VPN* and *192.168.0.1*, respectively.
---
Setting It All Up
=================
Option 1: Disable VPN DNS
-------------------------
Assuming you don't need your VPN's DNS servers at all, you can simply run the following in the command prompt:
```
netsh interface ipv4 delete dnsservers name="<Interface Name>" address=all validate=no
Eg: netsh interface ipv4 delete dnsservers name="My VPN" address=all validate=no
```
If you run `netsh interface ipv4 show dnsservers` again, you will see that the DNS servers associated with the VPN have been removed; your non-VPN connection's DNS servers will be used to resolve hostnames.
---
Option 2: Supplement VPN DNS
----------------------------
If you need your VPN's DNS servers to resolve intranet hostnames, you can run the following in the command prompt:
```
netsh interface ipv4 add dnsservers name="<Interface Name>" address=<Non-VPN DNS server> index=1 validate=no
Eg: netsh interface ipv4 add dnsservers name="My VPN" address=192.168.0.1 index=1 validate=no
```
In this case, `netsh interface ipv4 show dnsservers` will show that your non-VPN connection's first DNS server has been added to the top of the list of your VPN's DNS servers. It will be used to resolve hostnames first, and if unsuccessful, fall back to using your VPN's regular DNS servers. | I simply remove this option from the client VPN config
*setenv opt block-outside-dns*
It resolved the issue |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| I don't believe there is a way to *prevent* it from happening, apart from statically assigning the DNS servers on the VPN connection.
To change the order in which DNS servers are queried, one is supposed to be able to change the interface binding order as per <https://superuser.com/a/314379/120267>, but that doesn't seem to affect VPN connections in my personal testing on Windows 7; I've confirmed that my VPN connection is consistently added to the top of the `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Linkage\Bind` list, regardless of the interface binding order settings.
However, you can reset the DNS changes after the VPN connection is established.
Collecting Information
======================
Open up a command prompt (`Start` -> `Run...` -> `cmd`) and then run `netsh interface ipv4 show dnsservers`. You will see output similar to the following:
```
Configuration for interface "My VPN"
Statically Configured DNS Servers: 11.22.33.44
55.66.77.88
...
Configuration for interface "Local Network Connection"
DNS servers configured through DHCP: 192.168.0.1
192.168.0.2
...
```
You need the **interface name** for the VPN, and optionally your non-VPN connection's first **DNS server**. In this example, they are *My VPN* and *192.168.0.1*, respectively.
---
Setting It All Up
=================
Option 1: Disable VPN DNS
-------------------------
Assuming you don't need your VPN's DNS servers at all, you can simply run the following in the command prompt:
```
netsh interface ipv4 delete dnsservers name="<Interface Name>" address=all validate=no
Eg: netsh interface ipv4 delete dnsservers name="My VPN" address=all validate=no
```
If you run `netsh interface ipv4 show dnsservers` again, you will see that the DNS servers associated with the VPN have been removed; your non-VPN connection's DNS servers will be used to resolve hostnames.
---
Option 2: Supplement VPN DNS
----------------------------
If you need your VPN's DNS servers to resolve intranet hostnames, you can run the following in the command prompt:
```
netsh interface ipv4 add dnsservers name="<Interface Name>" address=<Non-VPN DNS server> index=1 validate=no
Eg: netsh interface ipv4 add dnsservers name="My VPN" address=192.168.0.1 index=1 validate=no
```
In this case, `netsh interface ipv4 show dnsservers` will show that your non-VPN connection's first DNS server has been added to the top of the list of your VPN's DNS servers. It will be used to resolve hostnames first, and if unsuccessful, fall back to using your VPN's regular DNS servers. | Unfortunately netsh can not delete dns servers assigned by dhcp. But this can be done by clearing DhcpNameServer parameter in
```
HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{id}
```
registry key. |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| I don't believe there is a way to *prevent* it from happening, apart from statically assigning the DNS servers on the VPN connection.
To change the order in which DNS servers are queried, one is supposed to be able to change the interface binding order as per <https://superuser.com/a/314379/120267>, but that doesn't seem to affect VPN connections in my personal testing on Windows 7; I've confirmed that my VPN connection is consistently added to the top of the `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Linkage\Bind` list, regardless of the interface binding order settings.
However, you can reset the DNS changes after the VPN connection is established.
Collecting Information
======================
Open up a command prompt (`Start` -> `Run...` -> `cmd`) and then run `netsh interface ipv4 show dnsservers`. You will see output similar to the following:
```
Configuration for interface "My VPN"
Statically Configured DNS Servers: 11.22.33.44
55.66.77.88
...
Configuration for interface "Local Network Connection"
DNS servers configured through DHCP: 192.168.0.1
192.168.0.2
...
```
You need the **interface name** for the VPN, and optionally your non-VPN connection's first **DNS server**. In this example, they are *My VPN* and *192.168.0.1*, respectively.
---
Setting It All Up
=================
Option 1: Disable VPN DNS
-------------------------
Assuming you don't need your VPN's DNS servers at all, you can simply run the following in the command prompt:
```
netsh interface ipv4 delete dnsservers name="<Interface Name>" address=all validate=no
Eg: netsh interface ipv4 delete dnsservers name="My VPN" address=all validate=no
```
If you run `netsh interface ipv4 show dnsservers` again, you will see that the DNS servers associated with the VPN have been removed; your non-VPN connection's DNS servers will be used to resolve hostnames.
---
Option 2: Supplement VPN DNS
----------------------------
If you need your VPN's DNS servers to resolve intranet hostnames, you can run the following in the command prompt:
```
netsh interface ipv4 add dnsservers name="<Interface Name>" address=<Non-VPN DNS server> index=1 validate=no
Eg: netsh interface ipv4 add dnsservers name="My VPN" address=192.168.0.1 index=1 validate=no
```
In this case, `netsh interface ipv4 show dnsservers` will show that your non-VPN connection's first DNS server has been added to the top of the list of your VPN's DNS servers. It will be used to resolve hostnames first, and if unsuccessful, fall back to using your VPN's regular DNS servers. | Can you check the status of the 'Use default gateway on remote network' checkbox. This is found by opening the properties of your VPN connection and go to Networking tab and select either TCP/IP v4 or TCP/IP V6 and then select properties and then advanced.
This may be enabled which could mean that all internet traffic is routed over the VPN connection.it is not always possible to disabled this and still do what you want with the VPN, but it can be disabled, it might speed up internet access.
If that doesn't help, there is a DNS tab there and you could try adding your DNS servers there. I have tried this, but I would expect these settings to override the automatic settings. |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| Unfortunately netsh can not delete dns servers assigned by dhcp. But this can be done by clearing DhcpNameServer parameter in
```
HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{id}
```
registry key. | I simply remove this option from the client VPN config
*setenv opt block-outside-dns*
It resolved the issue |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| I had a similar problem; connecting to a VPN server would override my workstation's (remote VPN client) DNS so that the local LAN DNS would be obscured. I described the problem more in detail on [Stackoverflow side](https://stackoverflow.com/questions/14078824/how-to-prevent-openvpn-from-overriding-local-dns) before I was pointed out that I should've posted it here instead.
Having read through this thread it is apparent that the override can't be prevented using the OpenVPN client configuration. My solution was to add a batch file in the OpenVPN config directory that executes when the OpenVPN connection is formed. If the OVPN file is called company.ovpn, the file that is run on connect needs to be named company\_up.bat.
I've augmented the file some since the version I posted to my question in StackOverflow earlier tonight. Now it looks like this:
```
1: ping 127.0.0.1 -n 2 > nul
2: netsh interface ip set dns "Local Area Connection 4" static 127.0.0.1
3: route delete 0.0.0.0
4: route add -p 0.0.0.0/0 172.20.20.1 metric 1000
5: exit 0
```
**1:** A hack to wait for couple of seconds before proceeding. The latest version (2.3) of OpenVPN client would ignore the DNS and route changes if executed without a delay.
**2:** Set the DNS of the VPN connection to point to the localhost. I have a resolver (I use [SimpleDNS Plus](http://www.simpledns.com/)) running on the localhost that forwards the queries to the company domain to the company DNS server over the VPN, and everything else to the local LAN DNS server. Note that I could not use a local LAN resolver to forward the queries for the company domain to the company DNS over the VPN since the VPN endpoint is on the localhost. The connection name ("Local Area Connection 4") was determined at command prompt via "ipconfig /all".
**3:** The company VPN server is configured to route *all* the outbound traffic through the VPN while at the same time restricting outbound (to the Internet) SSH connections. This conflicted with my workflow, and I'm first deleting the "0.0.0.0 netmask 0.0.0.0" route...
**4:** .. and then I re-add the 0.0.0.0/0 route to point to the local LAN gateway, and set its metric (weight) to 1000 as a catch-all for all traffic that is not routed otherwise.
**5:** Without "exit 0" OpenVPN spits out an error warning of the script failed (with an exit status 1).
Hopefully this is useful for someone.. it's working reasonably well for me (no need to make route or DNS adjustments manually every time I open a connection). | I simply remove this option from the client VPN config
*setenv opt block-outside-dns*
It resolved the issue |
392,269 | I have a customer that uses a VPN connection, however it automatically configures my DNS settings to a non-existent DNS server, meaning every DNS resolution times out until the alternative is tried, which really slows down all Internet traffic.
Is there a way that I can prevent an application from overriding my DNS settings (without enabling UAC)?
Alternatively, is there a way that I can set up some kind of local routing that says 'when a DNS request for IP address A comes in, actually use IP address B'?
I'm using Windows 8 Developer preview (but I suspect it should work the same as Windows 7).
Thanks | 2012/02/21 | [
"https://superuser.com/questions/392269",
"https://superuser.com",
"https://superuser.com/users/23951/"
]
| Unfortunately netsh can not delete dns servers assigned by dhcp. But this can be done by clearing DhcpNameServer parameter in
```
HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{id}
```
registry key. | As of 2017 this is now possible if its based on **OpenVPN**
Add a line to your client config file of
>
> pull-filter ignore "dhcp-option DNS "
>
>
>
and it will ignore all pushed config lines that start with the quoted text.
The three action keywords are `accept` `ignore` `reject`.
I have not discovered a use case for reject. |
48,931,483 | I am using Laravel 5.6
I have 2 tables. User Table and Role Table in migration folder. Also installed Laravel Passport
When I ran this command `php artisan migrate`, I saw the auth tables created first and then role table and user table.
Can I run role and user table first because I want to put reference constraints in auth table? | 2018/02/22 | [
"https://Stackoverflow.com/questions/48931483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726802/"
]
| I don't know the exact stuff Laravel Passport does, but in general the Migrator classes are ran in alphabetic order. Given the fact that they are prefixed with the generation timestamp, it should be enough just renaming the role migrator, to having a timstamp before the user migrator.
When you do this, don't forget to regenerate the autoload files. | Laravel Migration run on the alpahbetical order .
Consider an example where you Auth table with the migration named as
```
2018_03_18_12_create_auth_tables.php
```
User table migration as
```
2018_03_18_13_create_users_tables.php
```
In this case the Auth table will run first and User table will run second due to their alpahbetical order . If you want to change the order of the migration then you can rename the file of users table as
```
2018_03_18_11_create_users_tables.php
```
After doing this the alphabetical order will change and the users table will run first.
I hope this helps |
30,654 | How would you describe the **Power Law** in simple words? The Wikipedia entry is too long and verbose. I would like to understand the concept of the power law and how and why it shows up everywhere.
For example, a recent Economist article **[Cry havoc! And let slip the maths of war](http://www.economist.com/node/18483411)**, shows that terrorist attacks follow an inverted power law curve. | 2011/04/03 | [
"https://math.stackexchange.com/questions/30654",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/8941/"
]
| Just to expand on Ross Millikan's answer. Power-laws are important and pop up all the time because they obey [scale-invariance](http://en.wikipedia.org/wiki/Scale_invariance). Scale-invariance is the property that a system behaves the same when all length-scales are multiplied with a common factor. System show scale invariance if there is no characteristic length scale associated which, e.g., happens at phase transitions. | The power law just is the equation $f(x)=ax^k$ (the Wikipedia article allows some deviation.) If $k \lt 0$ it says that big events get less likely than small events and how fast. It shows up many places in science, and finding the exponent is often a clue to the underlying laws. It also shows up in the real world. [This paper](http://www.hpl.hp.com/research/idl/papers/ranking/adamicglottometrics.pdf) discusses finding it in statistics on the internet. Of course, real world data doesn't fit a power law exactly, and how close is "close enough" may be in the eye of the beholder. It is also known as "Zipf's Law" if you want to search around for places it is found. |
30,654 | How would you describe the **Power Law** in simple words? The Wikipedia entry is too long and verbose. I would like to understand the concept of the power law and how and why it shows up everywhere.
For example, a recent Economist article **[Cry havoc! And let slip the maths of war](http://www.economist.com/node/18483411)**, shows that terrorist attacks follow an inverted power law curve. | 2011/04/03 | [
"https://math.stackexchange.com/questions/30654",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/8941/"
]
| As Ross Millikan points out, a function $p(x)$ obeys a power law if
$$p(x) \propto x^\alpha, \ \ \alpha \in \mathbb{R}$$
There are many real-world [examples](http://en.wikipedia.org/wiki/Power_law#Examples_of_power_law_functions) of power law functions. For example, [Newtonian gravity](http://en.wikipedia.org/wiki/Newton's_law_of_universal_gravitation) obeys a power law ($F = G \frac{m\_1 m\_2}{r^2}$, where $\alpha=2$ in this case), [Coulombs's law](http://en.wikipedia.org/wiki/Electrostatics#Coulomb.27s_law) of electrostatic potential ($F = \frac{Q\_1 Q\_2}{4 \pi r^2 \varepsilon\_0}$, again $\alpha=2$), critical exponents of phase transitions [near the critical point](http://en.wikipedia.org/wiki/Phase_transition#Critical_exponents_and_universality_classes) ($C \propto |T\_c - T|^\alpha$), [earthquake magnitude vs. frequency](http://scitation.aip.org/getpdf/servlet/GetPDFServlet?filetype=pdf&id=PHTOAD000054000006000034000001&idtype=cvips&prog=normal&bypassSSO=1) (this is why we measure earthquakes on a [Ricther-scale](http://en.wikipedia.org/wiki/Richter_magnitude_scale) ) and the [length of the coastline of Britain](http://en.wikipedia.org/wiki/How_Long_Is_the_Coast_of_Britain%3F_Statistical_Self-Similarity_and_Fractional_Dimension) ( $L(G) = M G^{1-D}$, where $1-D$ is the exponent in the power law), to name just a few.
There are many ways to generate power law distributions. [Reed and Hughes](http://www.angelfire.com/nv/telka/transfer/powerlaw_expl.pdf) show they can be
generated from killed exponential processes, [Simkin and Roychowdhury](http://arxiv.org/pdf/physics/0601192v3) give an overview of how power laws have been rediscovered many times and [Brian Hayes](http://www.americanscientist.org/issues/pub/fat-tails) gives a nice article on 'Fat-Tails'. See [Mitzenmacher](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.122.3769&rep=rep1&type=pdf) for a review of other generative models to create power law distributions.
Of the ways to generate power law distributions, I believe the one that is most descriptive as to why power laws are so pervasive is the [stability](http://en.wikipedia.org/wiki/Stable_distribution) of sums of identical and independently distributed random variables. If $X\_k$ are identical and independently distributed random variables, then their sum, $S$, will converge to a stable distribution:
$$ S\_n = \sum\_{k=0}^{n-1} X\_k $$
Under suitable conditions, the random variable has power law tails, i.e.:
$$ \Pr\{ S > x \} \propto x^{-\alpha}, \ \ x \to \infty $$
Alternatively, we can talk about its [probability density function](http://en.wikipedia.org/wiki/Probability_density_function) (abusing notation a bit):
$$ \Pr\{ S = x \} \propto x^{-(\alpha+1) }, \ \ x \to \infty $$
for some $\alpha \in (0, 2]$. The only exception is when the random variables $X\_k$ have finite second moment (or finite variance if you prefer), in which case $S$ converges to a [Normal distribution](http://en.wikipedia.org/wiki/Normal_distribution) (which is, incidentally, also a stable distribution).
The class of distributions that are stable are called [Levy $\alpha$-stable](http://en.wikipedia.org/wiki/L%C3%A9vy_distribution). See [Nolan's](http://academic2.american.edu/~jpnolan/stable/chap1.pdf) first chapter on his upcoming book for an introduction.
Incidentally, this is also why we often see power laws with exponent in the range of $(1,3]$. As $\alpha \to 1$, the distribution is no longer renormalizable (i.e. $\int\_{-\infty}^{\infty} x^{-\alpha} dx \to \infty$ as $\alpha \to 1$)) whereas when $\alpha \ge 3$ the distribution has finite variance and the conditions for it being a normal distribution apply.
The stability is why I believe power laws are so prevalent in nature: They are the limiting distributions of random processes, irrespective of the fine-grained details, when random processes are combined. Be it terrorist attacks, word distribution, galaxy cluster size, neuron connectivity or friend networks, under suitably weak conditions, if these are the result of the addition of some underlying processes, they will converge to a power law distribution as it is the limiting, stable, distribution. | The power law just is the equation $f(x)=ax^k$ (the Wikipedia article allows some deviation.) If $k \lt 0$ it says that big events get less likely than small events and how fast. It shows up many places in science, and finding the exponent is often a clue to the underlying laws. It also shows up in the real world. [This paper](http://www.hpl.hp.com/research/idl/papers/ranking/adamicglottometrics.pdf) discusses finding it in statistics on the internet. Of course, real world data doesn't fit a power law exactly, and how close is "close enough" may be in the eye of the beholder. It is also known as "Zipf's Law" if you want to search around for places it is found. |
30,654 | How would you describe the **Power Law** in simple words? The Wikipedia entry is too long and verbose. I would like to understand the concept of the power law and how and why it shows up everywhere.
For example, a recent Economist article **[Cry havoc! And let slip the maths of war](http://www.economist.com/node/18483411)**, shows that terrorist attacks follow an inverted power law curve. | 2011/04/03 | [
"https://math.stackexchange.com/questions/30654",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/8941/"
]
| The power law just is the equation $f(x)=ax^k$ (the Wikipedia article allows some deviation.) If $k \lt 0$ it says that big events get less likely than small events and how fast. It shows up many places in science, and finding the exponent is often a clue to the underlying laws. It also shows up in the real world. [This paper](http://www.hpl.hp.com/research/idl/papers/ranking/adamicglottometrics.pdf) discusses finding it in statistics on the internet. Of course, real world data doesn't fit a power law exactly, and how close is "close enough" may be in the eye of the beholder. It is also known as "Zipf's Law" if you want to search around for places it is found. | An easy to read article with data: <http://www.jmir.org/2015/6/e160/> |
30,654 | How would you describe the **Power Law** in simple words? The Wikipedia entry is too long and verbose. I would like to understand the concept of the power law and how and why it shows up everywhere.
For example, a recent Economist article **[Cry havoc! And let slip the maths of war](http://www.economist.com/node/18483411)**, shows that terrorist attacks follow an inverted power law curve. | 2011/04/03 | [
"https://math.stackexchange.com/questions/30654",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/8941/"
]
| As Ross Millikan points out, a function $p(x)$ obeys a power law if
$$p(x) \propto x^\alpha, \ \ \alpha \in \mathbb{R}$$
There are many real-world [examples](http://en.wikipedia.org/wiki/Power_law#Examples_of_power_law_functions) of power law functions. For example, [Newtonian gravity](http://en.wikipedia.org/wiki/Newton's_law_of_universal_gravitation) obeys a power law ($F = G \frac{m\_1 m\_2}{r^2}$, where $\alpha=2$ in this case), [Coulombs's law](http://en.wikipedia.org/wiki/Electrostatics#Coulomb.27s_law) of electrostatic potential ($F = \frac{Q\_1 Q\_2}{4 \pi r^2 \varepsilon\_0}$, again $\alpha=2$), critical exponents of phase transitions [near the critical point](http://en.wikipedia.org/wiki/Phase_transition#Critical_exponents_and_universality_classes) ($C \propto |T\_c - T|^\alpha$), [earthquake magnitude vs. frequency](http://scitation.aip.org/getpdf/servlet/GetPDFServlet?filetype=pdf&id=PHTOAD000054000006000034000001&idtype=cvips&prog=normal&bypassSSO=1) (this is why we measure earthquakes on a [Ricther-scale](http://en.wikipedia.org/wiki/Richter_magnitude_scale) ) and the [length of the coastline of Britain](http://en.wikipedia.org/wiki/How_Long_Is_the_Coast_of_Britain%3F_Statistical_Self-Similarity_and_Fractional_Dimension) ( $L(G) = M G^{1-D}$, where $1-D$ is the exponent in the power law), to name just a few.
There are many ways to generate power law distributions. [Reed and Hughes](http://www.angelfire.com/nv/telka/transfer/powerlaw_expl.pdf) show they can be
generated from killed exponential processes, [Simkin and Roychowdhury](http://arxiv.org/pdf/physics/0601192v3) give an overview of how power laws have been rediscovered many times and [Brian Hayes](http://www.americanscientist.org/issues/pub/fat-tails) gives a nice article on 'Fat-Tails'. See [Mitzenmacher](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.122.3769&rep=rep1&type=pdf) for a review of other generative models to create power law distributions.
Of the ways to generate power law distributions, I believe the one that is most descriptive as to why power laws are so pervasive is the [stability](http://en.wikipedia.org/wiki/Stable_distribution) of sums of identical and independently distributed random variables. If $X\_k$ are identical and independently distributed random variables, then their sum, $S$, will converge to a stable distribution:
$$ S\_n = \sum\_{k=0}^{n-1} X\_k $$
Under suitable conditions, the random variable has power law tails, i.e.:
$$ \Pr\{ S > x \} \propto x^{-\alpha}, \ \ x \to \infty $$
Alternatively, we can talk about its [probability density function](http://en.wikipedia.org/wiki/Probability_density_function) (abusing notation a bit):
$$ \Pr\{ S = x \} \propto x^{-(\alpha+1) }, \ \ x \to \infty $$
for some $\alpha \in (0, 2]$. The only exception is when the random variables $X\_k$ have finite second moment (or finite variance if you prefer), in which case $S$ converges to a [Normal distribution](http://en.wikipedia.org/wiki/Normal_distribution) (which is, incidentally, also a stable distribution).
The class of distributions that are stable are called [Levy $\alpha$-stable](http://en.wikipedia.org/wiki/L%C3%A9vy_distribution). See [Nolan's](http://academic2.american.edu/~jpnolan/stable/chap1.pdf) first chapter on his upcoming book for an introduction.
Incidentally, this is also why we often see power laws with exponent in the range of $(1,3]$. As $\alpha \to 1$, the distribution is no longer renormalizable (i.e. $\int\_{-\infty}^{\infty} x^{-\alpha} dx \to \infty$ as $\alpha \to 1$)) whereas when $\alpha \ge 3$ the distribution has finite variance and the conditions for it being a normal distribution apply.
The stability is why I believe power laws are so prevalent in nature: They are the limiting distributions of random processes, irrespective of the fine-grained details, when random processes are combined. Be it terrorist attacks, word distribution, galaxy cluster size, neuron connectivity or friend networks, under suitably weak conditions, if these are the result of the addition of some underlying processes, they will converge to a power law distribution as it is the limiting, stable, distribution. | Just to expand on Ross Millikan's answer. Power-laws are important and pop up all the time because they obey [scale-invariance](http://en.wikipedia.org/wiki/Scale_invariance). Scale-invariance is the property that a system behaves the same when all length-scales are multiplied with a common factor. System show scale invariance if there is no characteristic length scale associated which, e.g., happens at phase transitions. |
30,654 | How would you describe the **Power Law** in simple words? The Wikipedia entry is too long and verbose. I would like to understand the concept of the power law and how and why it shows up everywhere.
For example, a recent Economist article **[Cry havoc! And let slip the maths of war](http://www.economist.com/node/18483411)**, shows that terrorist attacks follow an inverted power law curve. | 2011/04/03 | [
"https://math.stackexchange.com/questions/30654",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/8941/"
]
| Just to expand on Ross Millikan's answer. Power-laws are important and pop up all the time because they obey [scale-invariance](http://en.wikipedia.org/wiki/Scale_invariance). Scale-invariance is the property that a system behaves the same when all length-scales are multiplied with a common factor. System show scale invariance if there is no characteristic length scale associated which, e.g., happens at phase transitions. | An easy to read article with data: <http://www.jmir.org/2015/6/e160/> |
30,654 | How would you describe the **Power Law** in simple words? The Wikipedia entry is too long and verbose. I would like to understand the concept of the power law and how and why it shows up everywhere.
For example, a recent Economist article **[Cry havoc! And let slip the maths of war](http://www.economist.com/node/18483411)**, shows that terrorist attacks follow an inverted power law curve. | 2011/04/03 | [
"https://math.stackexchange.com/questions/30654",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/8941/"
]
| As Ross Millikan points out, a function $p(x)$ obeys a power law if
$$p(x) \propto x^\alpha, \ \ \alpha \in \mathbb{R}$$
There are many real-world [examples](http://en.wikipedia.org/wiki/Power_law#Examples_of_power_law_functions) of power law functions. For example, [Newtonian gravity](http://en.wikipedia.org/wiki/Newton's_law_of_universal_gravitation) obeys a power law ($F = G \frac{m\_1 m\_2}{r^2}$, where $\alpha=2$ in this case), [Coulombs's law](http://en.wikipedia.org/wiki/Electrostatics#Coulomb.27s_law) of electrostatic potential ($F = \frac{Q\_1 Q\_2}{4 \pi r^2 \varepsilon\_0}$, again $\alpha=2$), critical exponents of phase transitions [near the critical point](http://en.wikipedia.org/wiki/Phase_transition#Critical_exponents_and_universality_classes) ($C \propto |T\_c - T|^\alpha$), [earthquake magnitude vs. frequency](http://scitation.aip.org/getpdf/servlet/GetPDFServlet?filetype=pdf&id=PHTOAD000054000006000034000001&idtype=cvips&prog=normal&bypassSSO=1) (this is why we measure earthquakes on a [Ricther-scale](http://en.wikipedia.org/wiki/Richter_magnitude_scale) ) and the [length of the coastline of Britain](http://en.wikipedia.org/wiki/How_Long_Is_the_Coast_of_Britain%3F_Statistical_Self-Similarity_and_Fractional_Dimension) ( $L(G) = M G^{1-D}$, where $1-D$ is the exponent in the power law), to name just a few.
There are many ways to generate power law distributions. [Reed and Hughes](http://www.angelfire.com/nv/telka/transfer/powerlaw_expl.pdf) show they can be
generated from killed exponential processes, [Simkin and Roychowdhury](http://arxiv.org/pdf/physics/0601192v3) give an overview of how power laws have been rediscovered many times and [Brian Hayes](http://www.americanscientist.org/issues/pub/fat-tails) gives a nice article on 'Fat-Tails'. See [Mitzenmacher](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.122.3769&rep=rep1&type=pdf) for a review of other generative models to create power law distributions.
Of the ways to generate power law distributions, I believe the one that is most descriptive as to why power laws are so pervasive is the [stability](http://en.wikipedia.org/wiki/Stable_distribution) of sums of identical and independently distributed random variables. If $X\_k$ are identical and independently distributed random variables, then their sum, $S$, will converge to a stable distribution:
$$ S\_n = \sum\_{k=0}^{n-1} X\_k $$
Under suitable conditions, the random variable has power law tails, i.e.:
$$ \Pr\{ S > x \} \propto x^{-\alpha}, \ \ x \to \infty $$
Alternatively, we can talk about its [probability density function](http://en.wikipedia.org/wiki/Probability_density_function) (abusing notation a bit):
$$ \Pr\{ S = x \} \propto x^{-(\alpha+1) }, \ \ x \to \infty $$
for some $\alpha \in (0, 2]$. The only exception is when the random variables $X\_k$ have finite second moment (or finite variance if you prefer), in which case $S$ converges to a [Normal distribution](http://en.wikipedia.org/wiki/Normal_distribution) (which is, incidentally, also a stable distribution).
The class of distributions that are stable are called [Levy $\alpha$-stable](http://en.wikipedia.org/wiki/L%C3%A9vy_distribution). See [Nolan's](http://academic2.american.edu/~jpnolan/stable/chap1.pdf) first chapter on his upcoming book for an introduction.
Incidentally, this is also why we often see power laws with exponent in the range of $(1,3]$. As $\alpha \to 1$, the distribution is no longer renormalizable (i.e. $\int\_{-\infty}^{\infty} x^{-\alpha} dx \to \infty$ as $\alpha \to 1$)) whereas when $\alpha \ge 3$ the distribution has finite variance and the conditions for it being a normal distribution apply.
The stability is why I believe power laws are so prevalent in nature: They are the limiting distributions of random processes, irrespective of the fine-grained details, when random processes are combined. Be it terrorist attacks, word distribution, galaxy cluster size, neuron connectivity or friend networks, under suitably weak conditions, if these are the result of the addition of some underlying processes, they will converge to a power law distribution as it is the limiting, stable, distribution. | An easy to read article with data: <http://www.jmir.org/2015/6/e160/> |
3,513,134 | Suppose that $f : \mathbb{R} →\mathbb{R}$ and $\lim\_{x\to a} f(x) = L$ (L-finite). Show that $f$ must be bounded in an open interval centered at $x = a$.
---
By definition of function limits.
$\forall\epsilon >0$, there $\exists \delta \in \mathbb{R}$ s.t if $x\in D$ and $0<|x-a|< \delta$, then $|f(x)-L|<\epsilon$
consider the open interval $(a-\delta ,a+\delta)$ thus by above, f is bounded above by $max(L+\epsilon,f(a))$ and bounded below by $min(L-\epsilon,f(a))$ Q.E.D
---
My professor gave me some tips of how to get the end goal however there is still some strings I need to tie. I'm getting somewhat twisted when it says $x=a$. Does the open interval $(a-\delta ,a+\delta)$ have anything to do with the definition that is "$0<|x-a|< \delta$" or is the open interval separate from the definition at this point? and should I consider a variable change? | 2020/01/18 | [
"https://math.stackexchange.com/questions/3513134",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/553585/"
]
| The open interval is precisely the values of $x$ for which $|x-a|<\delta$; if you restrict it to positive absolute values, you punch a hole in the open interval at $a$. Since the function has a definite value at $a$, however, if you've shown that the function is bounded for the punctured interval, you can extend the bound to encompass $f(a)$. | If $|f(x)| \leq M$ for $0<|x-a|<\delta$ then $|f(x)| \leq C$ for all $x \in (a-\delta, a+\delta)$ where $C$ is the maximum of $M$ and $|f(a)|$. |
37,680,473 | I want to install a Hybris Commerce 5.7 on an Azure VM (Windows Server 2012, D13 configuration) for testing. The install.bat -r b2c\_acc command builds successfull, but on install.bat -r b2c\_acc **initialize** I get the following error:
```
[java] ERROR [main] [DefaultSolrServerService] de.hybris.platform.solrserver.SolrServerException: Error while executing Solr start command for instance: [name: default, port:
8983]
[java] WARN [main] [CloseAwareApplicationContext] Exception encountered during context initialization - cancelling refresh attempt
[java] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultSolrServerService' defined in class path resource [global-solrserver-spri
ng.xml]: Invocation of init method failed; nested exception is de.hybris.platform.solrserver.SolrServerException: Error while executing Solr start command for instance: [name: defa
ult, port: 8983]
[java] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
[java] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
[java] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
[java] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
[java] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
[java] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
[java] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
[java] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
[java] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
[java] at org.springframework.context.support.AbstractApplicationContext.refresh(AbsttApplicationContext.java:480)
[java] at de.hybris.platform.core.HybrisContextFactory.refreshContext(HybrisContextFactory.java:98)
[java] at de.hybris.platform.core.HybrisContextFactory$GlobalContextFactory.build(HybrisContextFactory.java:176)
[java] at de.hybris.platform.core.HybrisContextHolder.getGlobalInstanceCached(HybrisContextHolder.java:134)
[java] at de.hybris.platform.core.HybrisContextHolder.getGlobalInstance(HybrisContextHolder.java:113)
[java] at de.hybris.platform.core.Registry.getSingletonGlobalApplicationContext(Registry.java:1059)
[java] at de.hybris.platform.cache.impl.RegionCacheAdapter.getController(RegionCacheAdapter.java:76)
[java] at de.hybris.platform.cache.impl.RegionCacheAdapter.getOrAddUnit(RegionCacheAdapter.java:206)
[java] at de.hybris.platform.cache.AbstractCacheUnit.get(AbstractCacheUnit.java:180)
[java] at de.hybris.platform.persistence.type.ComposedType_HJMPWrapper$FindByCodeExact1FinderResult.getFinderResult(ComposedType_HJMPWrapper.java:1727)
[java] at de.hybris.platform.persistence.type.ComposedType_HJMPWrapper.ejbFindByCodeExact(ComposedType_HJMPWrapper.java:1786)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
[java] at java.lang.reflect.Method.invoke(Unknown Source)
[java] at de.hybris.platform.util.Utilities.callMethod(Utilities.java:1069)
[java] at de.hybris.platform.util.Utilities.callMethod(Utilities.java:1059)
[java] at de.hybris.platform.persistence.framework.HomeInvocationHandler.invoke(HomeInvocationHandler.java:93)
[java] at com.sun.proxy.$Proxy3.findByCodeExact(Unknown Source)
[java] at de.hybris.platform.persistence.type.TypeManagerEJB.findByCodeExact(TypeManagerEJB.java:271)
[java] at de.hybris.platform.persistence.type.TypeManagerEJB.getComposedType(TypeManagJB.java:459)
[java] at de.hybris.platform.util.migration.DeploymentMigrationUtil.migrateSelectedDeployments(DeploymentMigrationUtil.java:458)
[java] at de.hybris.platform.core.AbstractTenant.migrateCoreTypes(AbstractTenant.java:910)
[java] at de.hybris.platform.core.AbstractTenant.doStartupSafe(AbstractTenant.java:716)
[java] at de.hybris.platform.core.AbstractTenant.doStartUp(AbstractTenant.java:658)
[java] at de.hybris.platform.core.Registry.assureTenantStarted(Registry.java:639)
[java] at de.hybris.platform.core.Registry.activateTenant(Registry.java:700)
[java] at de.hybris.platform.core.Registry.setCurrentTenant(Registry.java:544)
[java] at de.hybris.platform.core.Registry.activateMasterTenantForInit(Registry.java:616)
[java] at de.hybris.platform.util.ClientExecuter.execute(ClientExecuter.java:36)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[java] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
[java] at java.lang.reflect.Method.invoke(Unknown Source)
[java] at de.hybris.bootstrap.loader.Loader.execute(Loader.java:145)
[java] at de.hybris.bootstrap.loader.Loader.main(Loader.java:121)
```
I added the 8983 port to the VM's endpoints, but that didn't help.
Any idea what causes this error? | 2016/06/07 | [
"https://Stackoverflow.com/questions/37680473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3629694/"
]
| I am pretty sure you have something using your port 8983, I would say it's probably another Solr instance. Try accessing
<http://localhost:8983/solr>
If you're able to access the solr server, that's your problem. You can stop it running this command from hybris/bin/platform:
```
ant stopSolrServer
```
To avoid this happening, whenever you stop your hybris instance you should wait for Solr to finish gracefully instead of trying to kill the process multiple times. | Found the solution: Using the pre-installed by Azure Administrator user the initialize process built fine. Don't know why it wouldn't work with my other account, which is set to admin. |
37,499,567 | I'm trying to interface to a classic HD44780 LCD.
I have implemented local ram to which I write the data I wish to show up on the display.
I have defined the ram in this way:
```
type ram_type is array (0 to (16*2)-1) of std_logic_vector(7 downto 0);
signal lcd_mem : ram_type;
```
I've tried initializing the ram in this way:
```
lcd_mem(0 to 6) <= x"45_72_72_6F_72_73_3A";
...
```
But I receive an error on synthesis:
>
> Error (10515): VHDL type mismatch error at display\_ber.vhd(74): ram\_type type does not match string literal
>
>
>
Is there a way to ellegantly initialize the ram block in a similar way ?
Perhaps I should use a string type instead ? | 2016/05/28 | [
"https://Stackoverflow.com/questions/37499567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4340598/"
]
| Yes there is. Note that your definition of `ram_type` is an array of `std_logic_vector`. And `x"45_72_72_6F_72_73_3A"` is a hex string literal. These are not the same type, hence your error.
So, you have to put the value into an array of vectors. Such as:
```
lcd_mem(0 to 6) <= (0 => x"45", 1 => x"72", 2 => x"72", 3 => x"6F", 4 => x"72", 5 => x"73", 6 => x"3A");
``` | Above answer is good. May also code as follows:
type init\_type is array (0 to 6) of std\_logic\_vector(7 downto 0);
constant c\_lcd\_int : init\_type:= (45,72,72,6F,72,73,3A);
lcd\_mem(0 to 6) <= c\_lcd\_int; |
2,862,370 | I'm building a Route Planner Webapp using Spring/Hibernate/Tomcat and a mysql database,
I have a database containing read only data, such as Bus Stop Coordinates, Bus times which is never updated. I'm trying to make the app run faster, each time the application is run it will preform approx 1000 reads to the database to calculate a route.
I have setup a Ehcache which greatly improves the read from database times.
I'm now setting terracotta + Ehcache distributed caching to share the cache with multiple Tomcat JVMs. This seems a bit complicated. I've tried memcached but it was not performing as fast as ehcache.
I'm wondering if a MongoDb or Redis would be better suited. I have no experience with nosql but I would appreciate if anyone has any ideas. What i need is quick access to the read only database. | 2010/05/19 | [
"https://Stackoverflow.com/questions/2862370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/310783/"
]
| >
> I have setup a Ehcache which greatly improves the read from database times. I'm now setting terracotta + Ehcache distributed caching to share the cache with multiple Tomcat JVMs. This seems a bit complicated.
>
>
>
Since your data are read-only, I'm tempted to say that you could live without [distributed and replicated caching](http://ehcache.org/documentation/distributed_caching.html), unless the overhead of the initial load of caches is **that critical** (and in that case, it is not that hard to configure Ehcache, you just need to know where you go). So, if you think you really need this, maybe ask for more specific guidance.
>
> I'm wondering if a MongoDb or Redis would be better suited. I have no experience with nosql but I would appreciate if anyone has any ideas. What i need is quick access to the read only database.
>
>
>
First of all, if you go the NoSQL way, forget Hibernate (might not be an issue though). Secondly, I really wonder what is more complicated: (not) configuring Ehcache to be distributed (I'm still not convinced you need it) or changing your approach for something radically different (that the VAST majority of enterprise business don't need). Thirdly, **nothing will be faster than reading data from memory** in the same JVM.
To summarize: I would 1. consider not using distributed caching (and say goodbye to the configuration problem) or 2. configure Ehcache for distributed caching (I think this is less complicated than changing your whole approach). | First of all mongodb is not a cache per se. its a persistent data store just like mysql is a persistent data store.
so now your question boils down to "should i use ehcache or redis". having used ehcache i can tell you that is a pretty good solution for a distributed cache that does replication/clustering, cache invalidation, monitoring and instrumentation capability.
since your data is read only, a simple distributed map like hazelcast would work as well. its pretty simple to use. |
2,862,370 | I'm building a Route Planner Webapp using Spring/Hibernate/Tomcat and a mysql database,
I have a database containing read only data, such as Bus Stop Coordinates, Bus times which is never updated. I'm trying to make the app run faster, each time the application is run it will preform approx 1000 reads to the database to calculate a route.
I have setup a Ehcache which greatly improves the read from database times.
I'm now setting terracotta + Ehcache distributed caching to share the cache with multiple Tomcat JVMs. This seems a bit complicated. I've tried memcached but it was not performing as fast as ehcache.
I'm wondering if a MongoDb or Redis would be better suited. I have no experience with nosql but I would appreciate if anyone has any ideas. What i need is quick access to the read only database. | 2010/05/19 | [
"https://Stackoverflow.com/questions/2862370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/310783/"
]
| if you want to try routing, you even might look at Neo4j, see [the blog on using an A\* algo for](http://blogs.neotechnology.com/peter/2010/04/cool-spatial-algos-with-neo4j-part1-routing-with-a.html) | First of all mongodb is not a cache per se. its a persistent data store just like mysql is a persistent data store.
so now your question boils down to "should i use ehcache or redis". having used ehcache i can tell you that is a pretty good solution for a distributed cache that does replication/clustering, cache invalidation, monitoring and instrumentation capability.
since your data is read only, a simple distributed map like hazelcast would work as well. its pretty simple to use. |
16,930,121 | I am trying to build a simple application using MapKit that will automatically search for a specific place when the app launches and drop pin(s) on the map at the locations(s). I am seeing all sorts of ways to load locations (lat/lon, etc), but nothing that lets me search for a specific business name, restaurant name, etc.
I am expecting to work with Apple Maps. However, if Google Maps would be a better solve than so be it.
Any help would be appreciated. Thanks | 2013/06/05 | [
"https://Stackoverflow.com/questions/16930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2453899/"
]
| iOS >= 6.1 provides [MKLocalSearch](http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKLocalSearch/Reference/Reference.html), [MKLocalSearchRequest](http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKLocalSearchRequest_class/Reference/Reference.html) to search for natural language points of interest. Sample
```
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.region = regionToSearchIn;
request.naturalLanguageQuery = @"restaurants"; // or business name
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
// do something with the results / error
}];
``` | Make the following steps to display nearest places.
Using google API find the Nearest Places [Google Places API](https://developers.google.com/places/documentation/search)
The google API provide LAt and Long and address Informations.
Then Store the LAt and Long Values to Array then USing this lat and long values you can display Annotations in Apple map (iOS 6+) and Google Map (iOS 5). |
16,930,121 | I am trying to build a simple application using MapKit that will automatically search for a specific place when the app launches and drop pin(s) on the map at the locations(s). I am seeing all sorts of ways to load locations (lat/lon, etc), but nothing that lets me search for a specific business name, restaurant name, etc.
I am expecting to work with Apple Maps. However, if Google Maps would be a better solve than so be it.
Any help would be appreciated. Thanks | 2013/06/05 | [
"https://Stackoverflow.com/questions/16930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2453899/"
]
| iOS >= 6.1 provides [MKLocalSearch](http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKLocalSearch/Reference/Reference.html), [MKLocalSearchRequest](http://developer.apple.com/library/ios/#documentation/MapKit/Reference/MKLocalSearchRequest_class/Reference/Reference.html) to search for natural language points of interest. Sample
```
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.region = regionToSearchIn;
request.naturalLanguageQuery = @"restaurants"; // or business name
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
// do something with the results / error
}];
``` | i know its late but hope this helps!
```
[super viewDidLoad];
[self.searchDisplayController setDelegate:self];
[self.ibSearchBar setDelegate:self];
self.ibMapView.delegate=self;
// Zoom the map to current location.
[self.ibMapView setShowsUserLocation:YES];
[self.ibMapView setUserInteractionEnabled:YES];
[self.ibMapView setUserTrackingMode:MKUserTrackingModeFollow];
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
[locationManager startUpdatingLocation];
[self.ibMapView setRegion:MKCoordinateRegionMake(locationManager.location.coordinate, MKCoordinateSpanMake(0.2, 0.2))];
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.region = self.ibMapView.region;
request.naturalLanguageQuery = @"restaurant";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
results = response;
if (response.mapItems.count == 0)
NSLog(@"No Matches");
else
for (MKMapItem *item in response.mapItems)
{
NSLog(@"name = %@", item.name);
NSLog(@"Phone = %@", item.phoneNumber);
[_matchingItems addObject:item];
MKPointAnnotation *annotation =
[[MKPointAnnotation alloc]init];
annotation.coordinate = item.placemark.coordinate;
annotation.title = item.name;
[self.ibMapView addAnnotation:annotation];
}
}];
```
} |
16,930,121 | I am trying to build a simple application using MapKit that will automatically search for a specific place when the app launches and drop pin(s) on the map at the locations(s). I am seeing all sorts of ways to load locations (lat/lon, etc), but nothing that lets me search for a specific business name, restaurant name, etc.
I am expecting to work with Apple Maps. However, if Google Maps would be a better solve than so be it.
Any help would be appreciated. Thanks | 2013/06/05 | [
"https://Stackoverflow.com/questions/16930121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2453899/"
]
| i know its late but hope this helps!
```
[super viewDidLoad];
[self.searchDisplayController setDelegate:self];
[self.ibSearchBar setDelegate:self];
self.ibMapView.delegate=self;
// Zoom the map to current location.
[self.ibMapView setShowsUserLocation:YES];
[self.ibMapView setUserInteractionEnabled:YES];
[self.ibMapView setUserTrackingMode:MKUserTrackingModeFollow];
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
[locationManager startUpdatingLocation];
[self.ibMapView setRegion:MKCoordinateRegionMake(locationManager.location.coordinate, MKCoordinateSpanMake(0.2, 0.2))];
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.region = self.ibMapView.region;
request.naturalLanguageQuery = @"restaurant";
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
results = response;
if (response.mapItems.count == 0)
NSLog(@"No Matches");
else
for (MKMapItem *item in response.mapItems)
{
NSLog(@"name = %@", item.name);
NSLog(@"Phone = %@", item.phoneNumber);
[_matchingItems addObject:item];
MKPointAnnotation *annotation =
[[MKPointAnnotation alloc]init];
annotation.coordinate = item.placemark.coordinate;
annotation.title = item.name;
[self.ibMapView addAnnotation:annotation];
}
}];
```
} | Make the following steps to display nearest places.
Using google API find the Nearest Places [Google Places API](https://developers.google.com/places/documentation/search)
The google API provide LAt and Long and address Informations.
Then Store the LAt and Long Values to Array then USing this lat and long values you can display Annotations in Apple map (iOS 6+) and Google Map (iOS 5). |
39,183,275 | So this question is sort of one of translation. I am new to C++, and was looking through the class documentation. However, it looks like finding the answer to my question is a bit hard via the documentation.
I have code for generating a random number between 0 and 1 in C++: (obtained from [here](http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution), since the rand() function solution for floats is integer based)
```
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1); //corrected from 1,2
for (int n = 0; n < 10; ++n) {
std::cout << dis(gen) << ' ';
}
std::cout << '\n';
}
```
Next, I would like to create a class or struct or something (not really an OOP guy) that has an API like:
```
float x = my_RandomNumberGenerator.next();
```
In python, I might write something like:
```
class my_RNG():
def __init__(self):
self.rd = (the random device object I initialize in c code)
self.gen = (the mersenne_twister engine object)(rd)
self.distribution = (the uniform real distribution object)
def next():
return self.distribution(self.gen)
my_randomNumberGenerator = my_RNG()
print(my_randomNumberGenerator.next())
```
How would I implement this in C++?
**update** Here is what I have so far (it does not work... or compile...but there seems to be some strangeness in the way things are initialized in my template code that I got from the reference site that I don't understand):
```
#include <iostream>
#include <random>
class MyRNG
{
public:
float next(void);
private:
std::random_device randomDevice;
std::mt19937_64 randomGenerator;
std::uniform_real_distribution distribution;
MyRNG(float range_lower,float range_upper);
};
MyRNG::MyRNG(float range_lower, float range_upper)
{
randomGenerator = std::mersenne_twister_engine(randomDevice);
distribution = std::uniform_real_distribution<> distribution(range_lower,range_upper);
}
MyRNG::next(void)
{
return distribution(randomGenerator);
}
int main() {
MyRNG my_rng = MyRNG(0,1);
std::cout << my_rng.next() << std::endl;
return 0;
}
``` | 2016/08/27 | [
"https://Stackoverflow.com/questions/39183275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834415/"
]
| Seems like you just need some form of probability generation class, see below for a basic implementation which meets your question requirements:
```
template<class Ty = double,
class = std::enable_if_t<std::is_floating_point<Ty>::value>
> class random_probability_generator {
public:
// default constructor uses single random_device for seeding
random_probability_generator()
: mt_eng{std::random_device{}()}, prob_dist(0.0, 1.0) {}
// ... other constructors with custom seeds if necessary
Ty next() { return prob_dist(mt_eng); }
// ... other methods if necessary
private:
std::mt19937 mt_eng;
std::uniform_real_distribution<Ty> prob_dist;
};
```
Then you can use this simply via:
```
random_probability_generator<> pgen;
double p = pgen.next(); // double in range [0.0, 1.0]
```
Or if you want random `float`s instead (as part of your question seems to imply):
```
random_probability_generator<float> pgen;
float p = pgen.next(); // float in range [0.0f, 1.0f]
```
---
Also, to address why the class you posted isn't compiling, the error in your class is that you try to initialise a `std::mt19937_64` type object (`randomGenerator`) with a `std::mersenne_twister_engine` instance but they are fundamentally different types. Instead you would need to do
```
randomGenerator = std::mt19937_64(randomDevice());
```
in `MyRNG` constructor, or construct via initialisation list as I have done in the example above.
---
As pointed out in the comments, a more suitable *c++-esque* implementation of this is to overload `operator()` instead of creating a `next()` method. See below for a better implementation of the above class,
```
template<class FloatType = double,
class Generator = std::mt19937,
class = std::enable_if_t<std::is_floating_point<FloatType>::value>
> class uniform_random_probability_generator {
public:
typedef FloatType result_type;
typedef Generator generator_type;
typedef std::uniform_real_distribution<FloatType> distribution_type;
// default constructor
explicit uniform_random_probability_generator(Generator&& _eng
= Generator{std::random_device{}()}) : eng(std::move(_eng)), dist() {}
// construct from existing pre-defined engine
explicit uniform_random_probability_generator(const Generator& _eng)
: eng(_eng), dist() {}
// generate next random value in distribution (equivalent to next() in above code)
result_type operator()() { return dist(eng); }
// will always yield 0.0 for this class type
constexpr result_type min() const { return dist.min(); }
// will always yield 1.0 for this class type
constexpr result_type max() const { return dist.max(); }
// resets internal state such that next call to operator()
// does not rely on previous call
void reset_distribution_state() { dist.reset(); }
private:
generator_type eng;
distribution_type dist;
};
```
Then you can use this similarly to the first class in this answer,
```
uniform_random_probability_generator<> urpg;
double next_prob = urpg();
```
Additionally, `uniform_random_probability_generator` can use a different `Generator` type as a template parameter so long as this type meets the requirements of [`UniformRandomBitGenerator`](http://en.cppreference.com/w/cpp/concept/UniformRandomBitGenerator). For example, if for any reason you needed to use `std::knuth_b` instead of `std::mt19937` then you can do so as follows:
```
uniform_random_probability_generator<double, std::knuth_b> urpg_kb;
double next_prob = urpg_kb();
``` | You can create a class that holds a random number generator as a private member variable (like `std::mt19937`) and seeds it in the constructor. Your `next` function could just invoke the stored generator to get the next value (applying whatever distribution you want (if any) of course).
This is not very complicated, so I'm afraid I'm missing the *real* point of your question.. |
10,556,425 | I am using the following regular expression.
(?=.+[a-z])(?=.+[A-Z])(?=.+[^a-zA-Z]).{8,}
my goal is to have a password that has 3 of the 4 properties below
upper case character, lower case character, number, special character
I am using <http://rubular.com/r/i26nwsTcaU> and <http://regexlib.com/RETester.aspx> to test the expression with the following inputs
```
P@55w0rd
password1P
Password1
paSSw0rd
```
all of these should pass but only the second and fourth are passing at <http://rubular.com/r/i26nwsTcaU> and all of them pass at <http://regexlib.com/RETester.aspx>.
I also have the following code that I am using to validate
```
private void doValidate(String inputStr,String regex) {
Pattern pattern = Pattern.compile(regex);
if(!pattern.matcher(inputStr).matches()){
String errMessage = "";
throw new UniquenessConstraintViolatedException(errMessage);
}
}
```
this code fails to validate "Password1" which should pass.
as far as the expression goes I understand it like this
```
must have lower (?=.+[a-z])
must have upper (?=.+[A-Z])
must have non alpha (?=.+[^a-zA-Z])
must be eight characters long .{8,}
```
can anyone tell me what it is I'm doing wrong.
Thanks in advance. | 2012/05/11 | [
"https://Stackoverflow.com/questions/10556425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993802/"
]
| Essentially, the `.+` subexpressions are to blame, they should be `.*`. Otherwise, the lookahead part looks for lower case, upper case or non-alpha but a character of each corresponding type does not count if it is the first one in string. So, you are validating not the password, but the password with first char truncated. While @Cfreak is not right, he is close - what you are doing would not be possible with normal regex and you would have to use what he suggests. With the [lookahead](http://www.regular-expressions.info/lookaround.html) groups - `(?=)` - it is possible to do what you need. Still, personally I would rather code it like @Cfreak suggests - it is more readable and your intentions are clearer from the code. Complex regular expressions tend to be hard to write but close to impossible to read, debug, or improve after some time. | Your regex right now says you must have 1 or more lowercase characters, followed by 1 or more upper case characters followed by 1 or more upper or lowercase characters, followed by 8 characters or more.
Regex can't do AND unless you specify where a particular character appears. You basically need to split each part of your regex into it's own regex and check each one. You can check the length with whatever string length method Java has (sorry i'm not a java dev so I don't know what it is off my head).
Pseudo code:
```
if( regexForLower && regexForUpper && regexForSpecial && string.length == 8 ) {
// pass
}
``` |
10,556,425 | I am using the following regular expression.
(?=.+[a-z])(?=.+[A-Z])(?=.+[^a-zA-Z]).{8,}
my goal is to have a password that has 3 of the 4 properties below
upper case character, lower case character, number, special character
I am using <http://rubular.com/r/i26nwsTcaU> and <http://regexlib.com/RETester.aspx> to test the expression with the following inputs
```
P@55w0rd
password1P
Password1
paSSw0rd
```
all of these should pass but only the second and fourth are passing at <http://rubular.com/r/i26nwsTcaU> and all of them pass at <http://regexlib.com/RETester.aspx>.
I also have the following code that I am using to validate
```
private void doValidate(String inputStr,String regex) {
Pattern pattern = Pattern.compile(regex);
if(!pattern.matcher(inputStr).matches()){
String errMessage = "";
throw new UniquenessConstraintViolatedException(errMessage);
}
}
```
this code fails to validate "Password1" which should pass.
as far as the expression goes I understand it like this
```
must have lower (?=.+[a-z])
must have upper (?=.+[A-Z])
must have non alpha (?=.+[^a-zA-Z])
must be eight characters long .{8,}
```
can anyone tell me what it is I'm doing wrong.
Thanks in advance. | 2012/05/11 | [
"https://Stackoverflow.com/questions/10556425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993802/"
]
| Essentially, the `.+` subexpressions are to blame, they should be `.*`. Otherwise, the lookahead part looks for lower case, upper case or non-alpha but a character of each corresponding type does not count if it is the first one in string. So, you are validating not the password, but the password with first char truncated. While @Cfreak is not right, he is close - what you are doing would not be possible with normal regex and you would have to use what he suggests. With the [lookahead](http://www.regular-expressions.info/lookaround.html) groups - `(?=)` - it is possible to do what you need. Still, personally I would rather code it like @Cfreak suggests - it is more readable and your intentions are clearer from the code. Complex regular expressions tend to be hard to write but close to impossible to read, debug, or improve after some time. | As I said in a comment, position-0 capital letters are being ignored.
Here's a regex to which all four passwords match.
```
(?=.+\\d)(?=.+[a-z])(?=\\w*[A-Z]).{8,}
``` |
10,556,425 | I am using the following regular expression.
(?=.+[a-z])(?=.+[A-Z])(?=.+[^a-zA-Z]).{8,}
my goal is to have a password that has 3 of the 4 properties below
upper case character, lower case character, number, special character
I am using <http://rubular.com/r/i26nwsTcaU> and <http://regexlib.com/RETester.aspx> to test the expression with the following inputs
```
P@55w0rd
password1P
Password1
paSSw0rd
```
all of these should pass but only the second and fourth are passing at <http://rubular.com/r/i26nwsTcaU> and all of them pass at <http://regexlib.com/RETester.aspx>.
I also have the following code that I am using to validate
```
private void doValidate(String inputStr,String regex) {
Pattern pattern = Pattern.compile(regex);
if(!pattern.matcher(inputStr).matches()){
String errMessage = "";
throw new UniquenessConstraintViolatedException(errMessage);
}
}
```
this code fails to validate "Password1" which should pass.
as far as the expression goes I understand it like this
```
must have lower (?=.+[a-z])
must have upper (?=.+[A-Z])
must have non alpha (?=.+[^a-zA-Z])
must be eight characters long .{8,}
```
can anyone tell me what it is I'm doing wrong.
Thanks in advance. | 2012/05/11 | [
"https://Stackoverflow.com/questions/10556425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/993802/"
]
| Essentially, the `.+` subexpressions are to blame, they should be `.*`. Otherwise, the lookahead part looks for lower case, upper case or non-alpha but a character of each corresponding type does not count if it is the first one in string. So, you are validating not the password, but the password with first char truncated. While @Cfreak is not right, he is close - what you are doing would not be possible with normal regex and you would have to use what he suggests. With the [lookahead](http://www.regular-expressions.info/lookaround.html) groups - `(?=)` - it is possible to do what you need. Still, personally I would rather code it like @Cfreak suggests - it is more readable and your intentions are clearer from the code. Complex regular expressions tend to be hard to write but close to impossible to read, debug, or improve after some time. | I wouldn't use such a regex.
* it is hard to understand
* hard to debug
* hard to extend
* you can't do much with its result
If you like to tell the client what is wrong with his password, you have investigate the password again. In real world environments you might want to support characters from foreign locales.
```
import java.util.*;
/**
Pwtest
@author Stefan Wagner
@date Fr 11. Mai 20:55:38 CEST 2012
*/
public class Pwtest
{
public int boolcount (boolean [] arr) {
int sum = 0;
for (boolean b : arr)
if (b)
++sum;
return sum;
}
public boolean [] rulesMatch (String [] groups, String password) {
int idx = 0;
boolean [] matches = new boolean [groups.length];
for (String g: groups) {
matches[idx] = (password.matches (".*" + g + ".*"));
++idx;
}
return matches;
}
public Pwtest ()
{
String [] groups = new String [] {"[a-z]", "[A-Z]", "[0-9]", "[^a-zA-Z0-9]"};
String [] pwl = new String [] {"P@55w0rd", "password1P", "Password1", "paSSw0rd", "onlylower", "ONLYUPPER", "1234", ",:?!"};
List <boolean[]> lii = new ArrayList <boolean[]> ();
for (String password: pwl) {
lii.add (rulesMatch (groups, password));
}
for (int i = 0 ; i < lii.size (); ++i) {
boolean [] matches = lii.get (i);
String pw = pwl[i];
if (boolcount (matches) < 3) {
System.out.print ("Password:\t" + pw + " violates rule (s): ");
int idx = 0;
for (boolean b: matches) {
if (! b)
System.out.print (groups[idx] + " ");
++idx;
}
System.out.println ();
}
else System.out.println ("Password:\t" + pw + " fine ");
}
}
public static void main (String args[])
{
new Pwtest ();
}
}
```
Output:
```
Password: P@55w0rd fine
Password: password1P fine
Password: Password1 fine
Password: paSSw0rd fine
Password: onlylower violates rule (s): [A-Z] [0-9] [^a-zA-Z0-9]
Password: ONLYUPPER violates rule (s): [a-z] [0-9] [^a-zA-Z0-9]
Password: 1234 violates rule (s): [a-z] [A-Z] [^a-zA-Z0-9]
Password: ,:?! violates rule (s): [a-z] [A-Z] [0-9]
Password: Übergrößen345 fine
Password: 345ÄÜö violates rule (s): [a-z] [A-Z]
``` |
43,299,737 | I don't know what's going on with the `FileWriter`, because it only writes out the HTML part, but nothing from the `String` array `content`. `content` stores a lot of long `String`s. Is it because of Java's garbage collector?
I print out the `content` and everything is there, but `FileWrter` did not write anything from `content` to that file except the HTML part. I added `System.out.println(k);` inside the enhanced for-loop. `content` array is not null though.
```
public void writeHtml(String[] content) {
File file = new File("final.html");
try {
try (FileWriter Fw = new FileWriter(file)) {
Fw.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
+ "<html>\n"
+ "<head>\n"
+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=us-ascii\">\n"
+ "<title>" + fileName +" for The Delinquent</title>\n"
+ "<style type = \"text/css\">\n"
+ "body {font-family: \"Times New Roman, serif\"; font-size: 14 or 18; text-align: justify;};\n"
+ "p { margin-left: 1%; margin-right: 1%; }\n"
+ "</style>\n"
+ "</head><body>");
for (String k : content) {
Fw.write(k+"\n");
}
Fw.write("</body></html>");
}
} catch (Exception e) {
e.printStackTrack();
}
}
```
How the final.html looks like after running the program:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<title>the_delinquent.txt for The Delinquent</title>
<style type = "text/css">
body {font-family: "Times New Roman, serif"; font-size: 14 or 18; text-
align: justify;};
p { margin-left: 1%; margin-right: 1%; }
</style>
</head><body>
</body></html>
```
I know content is not empty because I did this:
```
for (String k: content) {
System.out.println(k + "\n");
bw.write(k + "\n");
}
```
Everything printed out. so weird : ( | 2017/04/08 | [
"https://Stackoverflow.com/questions/43299737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7838345/"
]
| You code is working. The only thing that prevents `content` to be written - empty `content`. It has no elements. | Your code iis basically correct, maybe the content array is empty.
The following is in modernized java style.
```
public void writeHtml(String[] content) {
Path file = Paths.get("final.html");
try (BufferedWriter fw = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
fw.write("<!DOCTYPE html>\n"
+ "<html>\n"
+ "<head>\n"
+ "<meta charset=UTF-8\">\n"
+ "<title>" + fileName + " for The Delinquent</title>\n"
+ "<style type = \"text/css\">\n"
+ "body {font-family: \"Times New Roman, serif\";"
+ " font-size: 14 or 18; text-align: justify;};\n"
+ "p { margin-left: 1%; margin-right: 1%; }\n"
+ "</style>\n"
+ "</head><body>");
fw.write("Content has: " + content.length + " strings.<br>\n");
for (String k : content) {
fw.write("* " + k + "<br>\n");
}
fw.write("</body></html>\n");
} catch (IOException e) {
System.out.println("Error " + e.getMessage());
}
}
```
* FileWriter is an old utility class that uses the default charset, so not portable. Better specify the charset to correspond to the charset in HTML.
* The encoding UTF-8 allows full Unicode range of characters, like comma like quotes (typical to MS Word). Java internally also uses Unicode, so it is a fine match.
* HTML 5 is the latest HTML version, now generally disposable.
* At one spot a typo `/n` entered.
* Multiple spaces and line breaks are converted to a single space. So I added `<br>` for a line break.
Normally one would add to the method header `throws IOException` to let the caller handle any irregularities. |
2,388 | This question has been closed as general reference: [Who is the cat in chapter 17 of Prisoner of Azkaban?](https://scifi.stackexchange.com/questions/26481/who-was-the-cat-in-the-chapter-17-of-3rd-book)
I think the question deserves downvotes but not close votes. If you see comments there, CVers have chosen Wikia and Google as a ground of general reference which is wrong as per community standards.
Why was the question closed? Should it have been? | 2012/11/03 | [
"https://scifi.meta.stackexchange.com/questions/2388",
"https://scifi.meta.stackexchange.com",
"https://scifi.meta.stackexchange.com/users/931/"
]
| The Wikipedia entry for [Prisoner of Azkaban](http://en.wikipedia.org/wiki/Prisoner_of_azkaban) describes clearly the relevant plot from chapter 17.
>
> While at his cabin, **Hermione discovers *Scabbers* in Hagrid's milk jug**.
> They leave, and Buckbeak is executed. As Ron, Harry, and Hermione are
> leaving Hagrid's house and reeling from the sound of the axe, **the
> *large black dog* approaches them**, pounces on Ron, and drags him under
> the Whomping Willow. **Harry and Hermione and *Crookshanks* dash down
> after them**; oddly, Crookshanks knows the secret knob to press to still
> the flailing tree. They move through an underground tunnel and arrive
> at the Shrieking Shack. They find that the black dog has turned into
> Sirius Black and is in a room with Ron. Harry, Ron, and Hermione
> manage to disarm Black, and before Harry can kill Black, avenging his
> parents' deaths, Professor Lupin enters the room and disarms him.
> Harry, Ron, and Hermione are aghast as Lupin and Black exchange a
> series of nods and embrace. Once the three students calm down enough
> to listen, Lupin and Black explain everything. Lupin is a werewolf who
> remains tame through a special steaming potion made for him by Snape.
> While Lupin was a student at Hogwarts, his best friends, James Potter,
> Sirius Black, and Peter Pettigrew, became Animagi (humans able to take
> on animal forms) so that they could romp in the grounds with Lupin at
> the full moon. They explain how Snape once followed Lupin toward his
> transformation site in a practical joke set up by Sirius, and was
> rescued narrowly by James Potter. At this moment, Snape reveals
> himself from underneath Harry's dropped invisibility cloak, but Harry,
> Ron, and Hermione disarm him, rendering him unconscious. Lupin and
> Black then explain that the real murderer of Harry's parents is not
> Black, but Peter Pettigrew, who has been presumed dead but really
> hidden all these years disguised as Scabbers. Lupin transforms
> Scabbers into Pettigrew, who squeals and hedges but ultimately
> confesses, revealing himself to be Voldemort's servant, and Black to
> be innocent. They all travel back to Hogwarts, but at the sight of the
> full moon, Lupin, who has forgotten to take his controlling potion
> (the steaming liquid), turns into a werewolf. Sirius Black responds by
> turning into the large black dog in order to protect Harry, Ron, and
> Hermione from Lupin. As Black returns from driving the werewolf into
> the woods, a swarm of Dementors approaches, and Black is paralyzed
> with fear. One of the Dementors prepares to suck the soul out of
> Harry, whose patronus charm is simply not strong enough. Out of
> somewhere comes a patronus that drives the Dementors away. Harry
> faints.
>
>
>
The Cat, Rat, and Dog clearly listed in the Wikipedia article are Crookshanks, Scabbers, and Black. Unless we are to make the logical leap to assume that Crookshanks transubstantiated himself into McGonagall or some other Cat within the Shrieking Shack, it clearly answers this question. | >
> [We should only consider as general reference questions that can be easily answered by typing all or part of the question into Google](https://scifi.meta.stackexchange.com/q/689/3267)
>
>
>
[Who is the cat in Prisoner of Azkaban](https://www.google.com/#hl=en&sugexp=les;&gs_nf=3&tok=gtK427mJW24YjdkLF-IbcA&cp=37&gs_id=1j&xhr=t&q=Who+is+the+cat+in+Prisoner+of+Azkaban&pf=p&safe=off&tbo=d&output=search&sclient=psy-ab&oq=Who+is+the+cat+in+Prisoner+of+Azkaban&gs_l=&pbx=1&bav=on.2,or.r_gc.r_pw.r_qf.&fp=6b5bfdee152656d4&bpcl=37189454&biw=1360&bih=606)
What is the *very first word* of the results?
>
> Crookshanks
>
>
> |
29,642 | I noticed in the book "A Beautiful Mind", by Sylvia Nasar, that a recommendation letter, for PhD applications, written for John F. Nash runs as follows: *This man is a genius.*
Then, out of curiosity, I wonder that if such reference letters for PhD applications work in the present days?
Image taken from the [Graduate Alumni Records](http://findingaids.princeton.edu/collections/AC105/c3) of Princeton University:
[](https://i.stack.imgur.com/p7gtk.jpg) | 2014/10/09 | [
"https://academia.stackexchange.com/questions/29642",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/18107/"
]
| Even though the event that inspired this questions may or may not have actually happened, the question is still a valid one.
I suspect it greatly depends on who wrote the recommendation. If the person writing that recommendation is a great authority in this field and is known for not giving praise easily, then such a recommendation letter might help. On the other hand, if I were to write such a letter... | A letter that simply states "This man is a genius" is not helpful for judging the likelihood of a PhD applicant being successful since it takes a lot more than genius to succeed at a PhD and genius is not a requirement for success. Further, the skills required to become "academically famous" do not necessarily make you better at judging the abilities of others. Academically famous people many see more good students than others, but that is not enough for me to take their word at face value, I want to see evidence of why the recommender thinks the person is a genius. Finally, if the student is so good that nothing more needs to be said about, I would be worried about why an academically famous person would be unable to convince his department to accept the genius and convince the genius to attend. |
29,642 | I noticed in the book "A Beautiful Mind", by Sylvia Nasar, that a recommendation letter, for PhD applications, written for John F. Nash runs as follows: *This man is a genius.*
Then, out of curiosity, I wonder that if such reference letters for PhD applications work in the present days?
Image taken from the [Graduate Alumni Records](http://findingaids.princeton.edu/collections/AC105/c3) of Princeton University:
[](https://i.stack.imgur.com/p7gtk.jpg) | 2014/10/09 | [
"https://academia.stackexchange.com/questions/29642",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/18107/"
]
| Even though the event that inspired this questions may or may not have actually happened, the question is still a valid one.
I suspect it greatly depends on who wrote the recommendation. If the person writing that recommendation is a great authority in this field and is known for not giving praise easily, then such a recommendation letter might help. On the other hand, if I were to write such a letter... | In my experience, most communities of high achieving people don't openly value intelligence. Generally they dismiss it and say that hard work and luck is what's really important. And they would laugh at you if you wrote your IQ score on your resume.
If someone said "Person X is very smart" and didn't write anything else, I would see it as a backhanded compliment. Like "X is smart, but he doesn't have the traits that are *actually* valuable in academia."
In fact, if I don't like a professor, and someone asks me what it's like to work with them, I usually say something like "this guy is brilliant." Which is true for pretty much every professor at a good university. |
29,642 | I noticed in the book "A Beautiful Mind", by Sylvia Nasar, that a recommendation letter, for PhD applications, written for John F. Nash runs as follows: *This man is a genius.*
Then, out of curiosity, I wonder that if such reference letters for PhD applications work in the present days?
Image taken from the [Graduate Alumni Records](http://findingaids.princeton.edu/collections/AC105/c3) of Princeton University:
[](https://i.stack.imgur.com/p7gtk.jpg) | 2014/10/09 | [
"https://academia.stackexchange.com/questions/29642",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/18107/"
]
| A letter that simply states "This man is a genius" is not helpful for judging the likelihood of a PhD applicant being successful since it takes a lot more than genius to succeed at a PhD and genius is not a requirement for success. Further, the skills required to become "academically famous" do not necessarily make you better at judging the abilities of others. Academically famous people many see more good students than others, but that is not enough for me to take their word at face value, I want to see evidence of why the recommender thinks the person is a genius. Finally, if the student is so good that nothing more needs to be said about, I would be worried about why an academically famous person would be unable to convince his department to accept the genius and convince the genius to attend. | In my experience, most communities of high achieving people don't openly value intelligence. Generally they dismiss it and say that hard work and luck is what's really important. And they would laugh at you if you wrote your IQ score on your resume.
If someone said "Person X is very smart" and didn't write anything else, I would see it as a backhanded compliment. Like "X is smart, but he doesn't have the traits that are *actually* valuable in academia."
In fact, if I don't like a professor, and someone asks me what it's like to work with them, I usually say something like "this guy is brilliant." Which is true for pretty much every professor at a good university. |
582,190 | The compiler says "Package amsmath Error: \begin{aligned} allowed only in math mode." which I don't understand because "aligned" is inside an "equation" which per se is math mode.
```
\documentclass{article}
\usepackage{amsmath}
\usepackage{adjustbox}
\usepackage[utf8]{inputenc}
\begin{document}
\begin{adjustbox}{max totalsize={.4\textwidth},center}
\begin{equation*}
\textnormal{ Min} \qquad
\begin{aligned}
&36x_{11}+32x_{12}+33x_{13}+19x_{14}+\\
&10x_{21}+\; \: 8x_{22}+\; \: 7x_{23}+20x_{24}+\\
&12x_{31}+17x_{32}+16x_{33}+29x_{34}+\\
&23x_{41}+15x_{42}+16x_{43}+28x_{44}
\end{aligned}
\end{equation*}
\end{adjustbox}
\vskip 5mm
\begin{adjustbox}{max totalsize={.4\textwidth},center}
\begin{equation*}
\textnormal{ s.a.} \qquad
\begin{aligned}
&\sum_{i=1}^{4}x_{ij}=b_i \qquad \forall 1=1,2,3,4\\
&\sum_{i=1}^{4}x_{ij}=b_j \qquad \forall j=1,2,3,4\\
&x_{ij}\ge 0\\
&b_1=3\quad b_2=2 \quad b_3=1 \quad b_4=1
\end{aligned}
\end{equation*}
\end{adjustbox}
\end{document}
``` | 2021/02/06 | [
"https://tex.stackexchange.com/questions/582190",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/216807/"
]
| An easy way to do it could be using tikz matrix library. That an a couple of lines and you have it.
```
\documentclass {standalone}
\usepackage {amssymb}
\usepackage {tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[line cap=round,line join=round]
\def\sep{0.3cm}
\matrix(D)[matrix of nodes,minimum size=1.2cm]
{
$|\alpha|+|\beta|=0$ & $\cdots$ & $\lambda_{1,0}$ & $\lambda_{2,0}$
& $\lambda_{3,0}$ & $\cdots$ & $\lambda_{n-1,0}$
& $\lambda_{n,0}$\\
$|\alpha|+|\beta|\leqslant1$ & $\cdots$ & $\lambda_{1,1}$ & $\lambda_{2,1}$
& $\lambda_{3,1}$ & $\cdots$ & $\lambda_{n-1,1}$
& $\lambda_{n,1}$\\
$|\alpha|+|\beta|\leqslant2$ & $\cdots$ & $\lambda_{1,2}$ & $\lambda_{2,2}$
& $\lambda_{3,2}$ & $\cdots$ & $\lambda_{n-1,2}$
& $\lambda_{n,2}$\\
$\vdots$ & & $\vdots$ & $\vdots$
& $\vdots$ & $\ddots$ & $\vdots$
& $\vdots$\\
$|\alpha|+|\beta|\leqslant n$ & $\cdots$ & $\lambda_{1,n}$ & $\lambda_{2,n}$
& $\lambda_{3,n}$ & $\cdots$ & $\lambda_{n-1,n}$
& $\lambda_{n,n}$\\
};
\draw[thick,red] (D-5-7.south) -- (D-1-3.west) -- (D-1-3.north) -- (D-5-7.east);
\end{tikzpicture}
\end{document}
```
The result is:
[](https://i.stack.imgur.com/obpaI.png) | With `nicematrix` and Tikz.
```
\documentclass{article}
\usepackage{amssymb}
\usepackage{nicematrix}
\usepackage{tikz}
\begin{document}
\begingroup
\setlength{\arraycolsep}{8pt}
\setlength{\extrarowheight}{4mm}
$\begin{NiceMatrix}[xdots/shorten=6pt]
|\alpha|+|\beta|=0 & \Cdots & \lambda_{1,0} & \lambda_{2,0}
& \lambda_{3,0} & \Cdots & \lambda_{n-1,0}
& \lambda_{n,0}\\
|\alpha|+|\beta|\leqslant1 & \Cdots & \lambda_{1,1} & \lambda_{2,1}
& \lambda_{3,1} & \Cdots & \lambda_{n-1,1}
& \lambda_{n,1}\\
|\alpha|+|\beta|\leqslant2 & \Cdots & \lambda_{1,2} & \lambda_{2,2}
& \lambda_{3,2} & \Cdots & \lambda_{n-1,2}
& \lambda_{n,2}\\
\Vdots & & \Vdots & \Vdots
& \Vdots & & \Vdots
& \Vdots\\
|\alpha|+|\beta|\leqslant n & \Cdots & \lambda_{1,n} & \lambda_{2,n}
& \lambda_{3,n} & \Cdots & \lambda_{n-1,n}
& \lambda_{n,n}\\
\CodeAfter
\tikz \draw [thick,red]
([yshift=-3mm]5-7.south) -- ([xshift=-2mm]1-3.west)
-- ([xshift=-0.5mm,yshift=4mm]1-3.north) -- (5-7.east) ;
\line{3-5}{5-7}
\end{NiceMatrix}$
\endgroup
\end{document}
```
You need several compilations (because `nicematrix` uses PGF/Tikz nodes).
[](https://i.stack.imgur.com/vkduU.png) |
56,961,159 | I am a python beginner going over a tutorial on neural networks and the PY torch module. I don't quite understand the behavior of this line.
```
import torch.nn as nn
loss = nn.MSELoss()
print(loss)
>>MSELoss()
```
Since nn.MSELoss is a class, why does calling it to the variable loss not instantiate it as a class object? What type of code is in the class MSELoss that allows it to achieve this behavior? | 2019/07/09 | [
"https://Stackoverflow.com/questions/56961159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11761984/"
]
| Lots of questions.
For a reference, the source code is in `src/backend/access/transam/commit_ts.c`.
1. I am not sure if it can be guaranteed that a later commit log sequence number implies a later timestamp. I would certainly not rely totally on it if the system clock can jump backwards due to time adjustments.
2. The timestamp is not stored in the row at all, but in the `pg_commit_ts` subdirectory of the data directory. Each record takes 10 bytes:
```c
/*
* We need 8+2 bytes per xact. Note that enlarging this struct might mean
* the largest possible file name is more than 5 chars long; see
* SlruScanDirectory.
*/
typedef struct CommitTimestampEntry
{
TimestampTz time;
RepOriginId nodeid;
} CommitTimestampEntry;
```
There is also information about commit timestamps in the transaction log so it can be recovered.
3. No index is needed, because the location of the timestamp is determined by the transaction number (each transaction has a fixed location for the commit timestamp). See `TransactionIdToCTsPage`.
4. Timestamps are kept as long as transaction numbers, if I understand the code correctly.
5. I can't tell what the overhead is, but it probably isn't huge.
6. Why should `VACUUM` or `VACUUM (FULL)` change the commit timestamp? That would be a bug.
Now that I understand what you want to achieve with commit timestamps, a word to that (I wish people would state the *real* question right away):
Commit timestamps are *not* the right tool for you. You could not index the expression, because `pg_xact_commit_timestamp` is not immutable.
Choose the simple and obvious solution and add an extra `timestamp with time zone` column with a `BEFORE` trigger that sets it to `current_timestamp` on `INSERT` and `UPDATE`. That can be indexed.
A famous man has said that premature optimization is the root of all evil. | Laurenz, first off, you're a champion for digging in and helping me out. **Thank you.** For background, I've asked this question in more detail on a few of the PG mailing lists, and got zero responses. I think it was because my complete question was too long.
I tried to be shorter here and, sadly, have not explained the important part clearly. Physical optimization is *not* the driving concern. In fact, the commit\_timestamp system will cost me space as it's a global setting for all tables. My real tables will have full timestamptz (set to UTC) fields that I'll index and aggregate against. What I'm trying to sort out now (design phase) is the *accuracy* of the approach. Namely, am I capturing all events once and only once?
What I'm need is a *reliable sequential number or time line* to mark the highest/latest row I processed and the current highest/latest row. This lets me grab any rows that have not been processed without re-selecting already handled rows, or blocking the table as it adds new rows. This idea is called a "concurrency ID" in some contexts. Here's a sketch adapted from another part of our project where it made sense to use numbers instead of timestamps (but timelines are a type of number line):
D'oh! I can't post images. It's here:
<https://imgur.com/iD9bn5Q>
It shows a number line for tracking records that are in three portions
[Done][Capture these][Tailing]
"Done" is everything from the highest/latest counter processed.
"Capture these" is everything later than "Done" and less than the current max counter in the table.
"Tailing" is any new, higher counters added by other inputs while the "capture these" rows are being processed.
It's easier to see in a picture.
So, I've got a small utility table such as this:
```
CREATE TABLE "rollup_status" (
"id" uuid NOT NULL DEFAULT extensions.gen_random_uuid(), -- We use UUIDs, not necessary here, but it's what we use.
"rollup_name" text NOT NULL DEFAULT false,
"last_processed_dts" timestamptz NOT NULL DEFAULT NULL); -- Marks the last timestamp processed.
```
And now imagine one entry:
```
rollup_name last_processed_dts
error_name_counts 2018-09-26 02:23:00
```
So, my number line (timeline, in the case of the commit timestamps) is processed from whatever the 0 date is through 2018-09-26 02:23:00. The next time through, I get the current max from the table I'm interested in, 'scan':
```
select max(pg_xact_commit_timestamp(xmin)) from scan; -- Pretend that it's 2019-07-07 25:00:00.0000000+10
```
This value becomes the upper bound of my search, and the new value of rollup\_status.last\_processed\_dts.
```
-- Find the changed row(s):
select *
from scan
where pg_xact_commit_timestamp(xmin) > '2019-07-07 20:46:14.694288+10' and
pg_xact_commit_timestamp(xmin) <= '2019-07-07 25:00:00.0000000+10
```
That's the "capture these" segment of my number line. This is also the only use I've got planned for the commit timestamp data. We're pushing data in from various sources, and want their timestamps (adjusted to UTC), not a server timestamp. (Server timestamps can make sense, they just don't happen to in the case of our data.) So, the *sole purpose* of the commit timestamp is to create a reliable number line.
If you look at the chart, it shows three different number lines for the same base table. The table itself only has one number or timeline, there are three different *uses* of that number/time series. So, three rollup\_status rows, going with my sketch table from earlier. The "scan" table needs to know *nothing* about how it is used. This is a *huge* benefit of this strategy. You can add, remove, and redo operations without having to alter the master table or its rows at all.
I'm also considering an ON AFTER INSERT/UPDATE selection trigger with a transition table for populating a timestamptz (set to UTC), like row\_commmitted\_dts. That might be my plan B, but it requires adding the triggers and it seems like it could only be a bit less accurate than the actual transaction commit time. Probably a small difference, but with concurrency stuff, little problems can blow up into big bugs in a hurry.
So, the question is if I can count on the commit timestamp system to produce accurate results that won't appear "in the past." That's why I can't use transaction IDs. They're assigned at the start of the transaction, but can be committed in any order. (As I understand it.) Therefore, my range boundaries of "last processed" and "current maximum in file" can't work. I could get that range and a pending transaction could commit with thousands of records with a timestamp *earlier* than my previously recorded "max value." That's why I'm after commit stamps.
Again, thanks for any help or suggestions. I'm very grateful.
P.S The only discussion I've run into in the Postgres world with something like this is here:
Scalable incremental data aggregation on Postgres and Citus
<https://www.citusdata.com/blog/2018/06/14/scalable-incremental-data-aggregation/>
They're using bigserial counters in this way but, as far as I understand it, that only works for INSERT, not UPDATE. And, honestly, I don't know enough about Postgres transactions and serials to think through the concurrency behavior. |
56,961,159 | I am a python beginner going over a tutorial on neural networks and the PY torch module. I don't quite understand the behavior of this line.
```
import torch.nn as nn
loss = nn.MSELoss()
print(loss)
>>MSELoss()
```
Since nn.MSELoss is a class, why does calling it to the variable loss not instantiate it as a class object? What type of code is in the class MSELoss that allows it to achieve this behavior? | 2019/07/09 | [
"https://Stackoverflow.com/questions/56961159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11761984/"
]
| As this subject doesn't seem to show up in the archives very much, I want to add a bit of detail before moving on. I asked related questions on several lists, forums, and by direct communication. Several people were kind enough to review the source code, provide historical background, and clear this up for me. Hopefully, leaving some detail here will help someone else down the track. Errors are all mine, obviously, corrections and enhancements more than welcome.
* Commit timestamps are assigned when the transaction's work is *completed*, but that's not the same was when it is *committed*. The WAL writer doesn't update the stamps to keep them in chronological sequence.
* Therefore, commit timestamps are **definitely** not a reliable mechanism for finding changes rows in order.
* Multiple clocks. Self-adjusting clocks. Oh the humanity!
* If you do want an in order-change sequence, logical decoding or replication are options. (I tried out logical replication a couple of weeks ago experimentally. Coolest. Thing. Ever.)
* The cost of timestamp tracking is 12 bytes per **transaction**, not per row. So, not so bad. (Timestamps are 8 bytes, transaction IDs are 4 bytes.)
* This is all part of the existing transaction system, so the realities of transaction ID rollaround apply here too. (Not scary in my case.) See:
<https://www.postgresql.org/docs/current/routine-vacuuming.html>
* For the record, you can enable this option on RDS via a parameter group setting. Just set track\_commit\_timestamp to 1 and restart. (The setting is 'on' in an postgres.conf.) | Lots of questions.
For a reference, the source code is in `src/backend/access/transam/commit_ts.c`.
1. I am not sure if it can be guaranteed that a later commit log sequence number implies a later timestamp. I would certainly not rely totally on it if the system clock can jump backwards due to time adjustments.
2. The timestamp is not stored in the row at all, but in the `pg_commit_ts` subdirectory of the data directory. Each record takes 10 bytes:
```c
/*
* We need 8+2 bytes per xact. Note that enlarging this struct might mean
* the largest possible file name is more than 5 chars long; see
* SlruScanDirectory.
*/
typedef struct CommitTimestampEntry
{
TimestampTz time;
RepOriginId nodeid;
} CommitTimestampEntry;
```
There is also information about commit timestamps in the transaction log so it can be recovered.
3. No index is needed, because the location of the timestamp is determined by the transaction number (each transaction has a fixed location for the commit timestamp). See `TransactionIdToCTsPage`.
4. Timestamps are kept as long as transaction numbers, if I understand the code correctly.
5. I can't tell what the overhead is, but it probably isn't huge.
6. Why should `VACUUM` or `VACUUM (FULL)` change the commit timestamp? That would be a bug.
Now that I understand what you want to achieve with commit timestamps, a word to that (I wish people would state the *real* question right away):
Commit timestamps are *not* the right tool for you. You could not index the expression, because `pg_xact_commit_timestamp` is not immutable.
Choose the simple and obvious solution and add an extra `timestamp with time zone` column with a `BEFORE` trigger that sets it to `current_timestamp` on `INSERT` and `UPDATE`. That can be indexed.
A famous man has said that premature optimization is the root of all evil. |
56,961,159 | I am a python beginner going over a tutorial on neural networks and the PY torch module. I don't quite understand the behavior of this line.
```
import torch.nn as nn
loss = nn.MSELoss()
print(loss)
>>MSELoss()
```
Since nn.MSELoss is a class, why does calling it to the variable loss not instantiate it as a class object? What type of code is in the class MSELoss that allows it to achieve this behavior? | 2019/07/09 | [
"https://Stackoverflow.com/questions/56961159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11761984/"
]
| As this subject doesn't seem to show up in the archives very much, I want to add a bit of detail before moving on. I asked related questions on several lists, forums, and by direct communication. Several people were kind enough to review the source code, provide historical background, and clear this up for me. Hopefully, leaving some detail here will help someone else down the track. Errors are all mine, obviously, corrections and enhancements more than welcome.
* Commit timestamps are assigned when the transaction's work is *completed*, but that's not the same was when it is *committed*. The WAL writer doesn't update the stamps to keep them in chronological sequence.
* Therefore, commit timestamps are **definitely** not a reliable mechanism for finding changes rows in order.
* Multiple clocks. Self-adjusting clocks. Oh the humanity!
* If you do want an in order-change sequence, logical decoding or replication are options. (I tried out logical replication a couple of weeks ago experimentally. Coolest. Thing. Ever.)
* The cost of timestamp tracking is 12 bytes per **transaction**, not per row. So, not so bad. (Timestamps are 8 bytes, transaction IDs are 4 bytes.)
* This is all part of the existing transaction system, so the realities of transaction ID rollaround apply here too. (Not scary in my case.) See:
<https://www.postgresql.org/docs/current/routine-vacuuming.html>
* For the record, you can enable this option on RDS via a parameter group setting. Just set track\_commit\_timestamp to 1 and restart. (The setting is 'on' in an postgres.conf.) | Laurenz, first off, you're a champion for digging in and helping me out. **Thank you.** For background, I've asked this question in more detail on a few of the PG mailing lists, and got zero responses. I think it was because my complete question was too long.
I tried to be shorter here and, sadly, have not explained the important part clearly. Physical optimization is *not* the driving concern. In fact, the commit\_timestamp system will cost me space as it's a global setting for all tables. My real tables will have full timestamptz (set to UTC) fields that I'll index and aggregate against. What I'm trying to sort out now (design phase) is the *accuracy* of the approach. Namely, am I capturing all events once and only once?
What I'm need is a *reliable sequential number or time line* to mark the highest/latest row I processed and the current highest/latest row. This lets me grab any rows that have not been processed without re-selecting already handled rows, or blocking the table as it adds new rows. This idea is called a "concurrency ID" in some contexts. Here's a sketch adapted from another part of our project where it made sense to use numbers instead of timestamps (but timelines are a type of number line):
D'oh! I can't post images. It's here:
<https://imgur.com/iD9bn5Q>
It shows a number line for tracking records that are in three portions
[Done][Capture these][Tailing]
"Done" is everything from the highest/latest counter processed.
"Capture these" is everything later than "Done" and less than the current max counter in the table.
"Tailing" is any new, higher counters added by other inputs while the "capture these" rows are being processed.
It's easier to see in a picture.
So, I've got a small utility table such as this:
```
CREATE TABLE "rollup_status" (
"id" uuid NOT NULL DEFAULT extensions.gen_random_uuid(), -- We use UUIDs, not necessary here, but it's what we use.
"rollup_name" text NOT NULL DEFAULT false,
"last_processed_dts" timestamptz NOT NULL DEFAULT NULL); -- Marks the last timestamp processed.
```
And now imagine one entry:
```
rollup_name last_processed_dts
error_name_counts 2018-09-26 02:23:00
```
So, my number line (timeline, in the case of the commit timestamps) is processed from whatever the 0 date is through 2018-09-26 02:23:00. The next time through, I get the current max from the table I'm interested in, 'scan':
```
select max(pg_xact_commit_timestamp(xmin)) from scan; -- Pretend that it's 2019-07-07 25:00:00.0000000+10
```
This value becomes the upper bound of my search, and the new value of rollup\_status.last\_processed\_dts.
```
-- Find the changed row(s):
select *
from scan
where pg_xact_commit_timestamp(xmin) > '2019-07-07 20:46:14.694288+10' and
pg_xact_commit_timestamp(xmin) <= '2019-07-07 25:00:00.0000000+10
```
That's the "capture these" segment of my number line. This is also the only use I've got planned for the commit timestamp data. We're pushing data in from various sources, and want their timestamps (adjusted to UTC), not a server timestamp. (Server timestamps can make sense, they just don't happen to in the case of our data.) So, the *sole purpose* of the commit timestamp is to create a reliable number line.
If you look at the chart, it shows three different number lines for the same base table. The table itself only has one number or timeline, there are three different *uses* of that number/time series. So, three rollup\_status rows, going with my sketch table from earlier. The "scan" table needs to know *nothing* about how it is used. This is a *huge* benefit of this strategy. You can add, remove, and redo operations without having to alter the master table or its rows at all.
I'm also considering an ON AFTER INSERT/UPDATE selection trigger with a transition table for populating a timestamptz (set to UTC), like row\_commmitted\_dts. That might be my plan B, but it requires adding the triggers and it seems like it could only be a bit less accurate than the actual transaction commit time. Probably a small difference, but with concurrency stuff, little problems can blow up into big bugs in a hurry.
So, the question is if I can count on the commit timestamp system to produce accurate results that won't appear "in the past." That's why I can't use transaction IDs. They're assigned at the start of the transaction, but can be committed in any order. (As I understand it.) Therefore, my range boundaries of "last processed" and "current maximum in file" can't work. I could get that range and a pending transaction could commit with thousands of records with a timestamp *earlier* than my previously recorded "max value." That's why I'm after commit stamps.
Again, thanks for any help or suggestions. I'm very grateful.
P.S The only discussion I've run into in the Postgres world with something like this is here:
Scalable incremental data aggregation on Postgres and Citus
<https://www.citusdata.com/blog/2018/06/14/scalable-incremental-data-aggregation/>
They're using bigserial counters in this way but, as far as I understand it, that only works for INSERT, not UPDATE. And, honestly, I don't know enough about Postgres transactions and serials to think through the concurrency behavior. |
120,940 | I am creating a resumé. I want to know whether mentioning stackoverflow profile counts for much in terms of interview factors, e.g. showing my knowledgeability and performance. | 2012/02/01 | [
"https://meta.stackexchange.com/questions/120940",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/177840/"
]
| It entirely depends on the person who is going to interview you, I guess. And of course, what your profile looks like. In general, Stack Overflow has become a very well-known resource over the past years - especially in the US, there is a good chance your interviewer knows the site.
If you are referring to your [current Stack Overflow profile](https://stackoverflow.com/users/1053416/yellow-page), I'd say it won't impress a recruiter much in it current state - it contains 4 questions, one of them downvoted, and only one answer that, while probably helpful, doesn't help prove that you are a knowledgeable person. | Currently the answer is No, as Pekka [already said](https://meta.stackexchange.com/a/120941/152859).
However, if and when you will gain enough reputation you will be invited to create a professional profile [here](http://careers.stackoverflow.com/). ( Stack Overflow Careers site)
This can be introduced in job interviews and will even help you find jobs, pretty similar to LinkedIn. |
230,222 | I am wondering if anyone could clarify my confusion on how to use JavaScript to read/filter SharePoint List items, please? As a code example from MSDN: <https://msdn.microsoft.com/en-us/library/office/hh185007(v=office.14).aspx>
In the CAML query XML, what is the FieldRef field in SharePoint List? Is it defined column names/list properties?
When ClientContext object load collListItem, it has a (Include) parameter which includes a bunch of field/property names, what are they? Are they defined column names/list properties as well?
Is there anyway I can know what field names are, so I can use/filter the List?
Thank you. | 2017/11/15 | [
"https://sharepoint.stackexchange.com/questions/230222",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/70870/"
]
| Actually, you can add a dummy field not present on the list by adding to the `ctx.ListSchema.Field` collection in `OnPreRender`. Then, when the actual rendering starts, SharePoint will just add another column on the view automatically. Then you can add something into that cell in `OnPostRender`.
Here's an example of the code to add the field definition into the schema to make the dummy column:
```
function addTemporaryField(ctx) {
// make sure we haven't added the field already,
// in case OnPreRender fires twice, which it does sometimes
if (ctx.ListSchema.Field.filter(function (fld) {
return fld.Name == 'FakeField';
}).length == 0) {
// create the field schema object to insert
var FakeFieldObj = {
AllowGridEditing: 'FALSE',
DisplayName: 'Fake Field',
RealFieldName: 'FakeField',
Name: 'FakeField',
FieldType: 'Text',
Type: 'Text',
Filterable: 'FALSE',
Sortable: 'FALSE',
ReadOnly: 'TRUE',
};
// find the index of the field to insert next to,
// based on that field's DISPLAY name.
var insertIdx = ctx.ListSchema.Field.map(function (fld) {
return fld.DisplayName;
}).indexOf('Some Field Name');
// if you want to insert *before* the field do not add anything
// but, if you want to insert *after* the field, add 1
insertIdx++;
// insert your fake field schema object into the list schema
ctx.ListSchema.Field.splice(insertIdx, 0, FakeFieldObj);
}
}
```
I wrote [a blog post about it](https://morefunthanapokeintheeye.blogspot.com/2016/06/how-to-add-temporary-columns-to-list-views.html) where I also go into inserting data into the dummy column, and you could certainly render a button in there. | Here is some sample code I wrote for your situation. I was initially thinking about adding an actual `<td>` element to the `<table>`, however, manipulating an existing field is much easier than the DOM.
You need to first add a new placeholder field in your list. That is where the button will be rendered. You basically override the item render and return the proper html with the button.
```
(function () {
var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.OnPostRender = [];
overrideCtx.Templates.Fields =
{
'Button': { 'View': renderButton }
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();
function renderButton(ctx){
var btnTxt = ctx.CurrentItem["Button"];
var id = ctx.CurrentItem.ID;
return "<input type='button' onclick='btnClick(" + id + ")' value='" +
btnTxt + "'></input>";
}
function btnClick(id) {
alert("button " + id + " clicked");
}
```
[](https://i.stack.imgur.com/d8Cxs.png) |
10,789 | I was riding late in the night and weather was colder than what we normally have.
(May not be cold for others, but it was cold for us, people used to with typical subcontinental weather. Temperature had dropped to 5 oC, which is wayyy cold for us)
While riding my way back home which takes hours, I kept on getting tempted to stand nearby a bonfire set up in villages on the way.
I wasn't having enough clothing to keep me warm, which I agree is a stupid thing to go with. Though, despite of being tempted to stand by a bonfire, I refrained from doing so, because I thought I would have felt a bit warm and better, but would have to start riding again which would make me cold and may be I'd end up feeling colder than before.
Was it the right thing to do? | 2016/02/04 | [
"https://outdoors.stackexchange.com/questions/10789",
"https://outdoors.stackexchange.com",
"https://outdoors.stackexchange.com/users/2303/"
]
| **EDIT:** Please also read the other answer, which tells you why wrong (well perhaps not for 100% of the cases=)
This is just *my* experience: I would warm up if I felt cold and had the opportunity to do so. Sure, slowly getting cold again is not comfortable, but staying cold for an even longer time is worse.
Another effect that I noticed is that warming up really brightens the mood (especially if you are with other people), which obviously again helps bearing the cold. E.g. in outdoor camps we used to say that the *moodkillers* were
* being cold/soaken
* being hungry (or only having bad food)
* being tired
And any combination of those makes the others worse. And sums it up pretty well in my experience. | I think part of what is missing in your question and the answer by flawr is core body temperature.
When you first get cold your body automatically shunts blood away from the surface of your skin to decrease heat loss. As you get colder your core body temperature falls (you could think of it like the cold sinking in, but that is not literally true).
When you stand next to the fire, your outer skin starts to warm, but your core temperature does not respond as quickly. Most of your nerves for temperature are in your skin, not in your muscles and insides. When your skin gets to a certain temperature, your body responds by pushing more blood to the surface, trying to keep you from overheating.
You step away from the fire and your skin is still warm and flushed with blood, you will likely have increased heat loss until your blood vessels in your skin shunt the blood back to your core.
In much the same way that a fire in a fireplace (as opposed to an airtight stove) can result in a net heat loss to the house, a short heating next to a hot fire on a cold day can result in a net heat loss to your body. There are of course many variables, but if you are feeling colder, you probably are.
**Edit**
Per request in comments I looked for research specific to the scenario I described. I have included several references to the basic principals of heat exchange related to blood at the skin level. I did not find anything specific to net heat loss **OR** gain from a short warming near the fire. I have experienced this perceived colder after a brief warming, and while I believe my hypothesis above is realistic, it seems to be untested under scientific conditions.
References
* [NEUROPHYSIOLOGY OF THERMOREGULATION](http://dwb.unl.edu/teacher/nsf/c01/c01links/www.science.mcmaster.ca/biology/4s03/thermoregulation.html)
* [PHYSIOLOGICAL RESPONSES TO THE THERMAL ENVIRONMENT](http://www.ilocis.org/documents/chpt42e.htm)
* [Outdoor Action Guide to
Hypothermia And Cold Weather Injuries](https://www.princeton.edu/~oa/safety/hypocold.shtml) |
12,780,524 | I have an array with 40 elements. I just need to show from array the first set of 10 elements and then show some static row in table. After displaying that static row, I just want to show another set of 10 rows. Like wise I need to show all 40 elements. | 2012/10/08 | [
"https://Stackoverflow.com/questions/12780524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1627627/"
]
| You can try
```
$array = range(1,40);
foreach (array_chunk($array, 10) as $current)
{
foreach($current as $data)
{
// Display your Information
}
}
``` | You can try `array_slice` <http://php.net/manual/en/function.array-slice.php> |
12,780,524 | I have an array with 40 elements. I just need to show from array the first set of 10 elements and then show some static row in table. After displaying that static row, I just want to show another set of 10 rows. Like wise I need to show all 40 elements. | 2012/10/08 | [
"https://Stackoverflow.com/questions/12780524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1627627/"
]
| You can try `array_slice` <http://php.net/manual/en/function.array-slice.php> | ### Use [`array_slice()`](http://php.net/manual/en/function.array-slice.php)
>
> It returns the sequence of elements from the array array as specified by the offset and length parameters.
>
>
>
### Example:
```
<?php
$myArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40);
print_r(array_slice($myArray, 0, 10));
print_r(array_slice($myArray, 10, 10));
print_r(array_slice($myArray, 20, 10));
print_r(array_slice($myArray, 30, 10));
?>
```
### Output:
```
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
Array
(
[0] => 11
[1] => 12
[2] => 13
[3] => 14
[4] => 15
[5] => 16
[6] => 17
[7] => 18
[8] => 19
[9] => 20
)
Array
(
[0] => 21
[1] => 22
[2] => 23
[3] => 24
[4] => 25
[5] => 26
[6] => 27
[7] => 28
[8] => 29
[9] => 30
)
Array
(
[0] => 31
[1] => 32
[2] => 33
[3] => 34
[4] => 35
[5] => 36
[6] => 37
[7] => 38
[8] => 39
[9] => 40
)
```
### Fiddle: <http://codepad.viper-7.com/mfzof6> |
12,780,524 | I have an array with 40 elements. I just need to show from array the first set of 10 elements and then show some static row in table. After displaying that static row, I just want to show another set of 10 rows. Like wise I need to show all 40 elements. | 2012/10/08 | [
"https://Stackoverflow.com/questions/12780524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1627627/"
]
| You can try `array_slice` <http://php.net/manual/en/function.array-slice.php> | The most efficient way is using the [**modulus**](http://php.net/manual/en/language.operators.arithmetic.php) operator, like so:
```
$tot = count($array);
for($i=0;$i<$tot;$i++) {
echo $array[$i] . '<br>';
if(($i+1) % 10 == 0) {
echo '--- TEN GROUP --- <br>';
}
}
```
Example output:
```
text_1
text_2
...
text_9
text_10
--- TEN GROUP ---
text_11
text_12
...
text_19
text_20
--- TEN GROUP ---
text_21
text_22
...
``` |
12,780,524 | I have an array with 40 elements. I just need to show from array the first set of 10 elements and then show some static row in table. After displaying that static row, I just want to show another set of 10 rows. Like wise I need to show all 40 elements. | 2012/10/08 | [
"https://Stackoverflow.com/questions/12780524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1627627/"
]
| You can try
```
$array = range(1,40);
foreach (array_chunk($array, 10) as $current)
{
foreach($current as $data)
{
// Display your Information
}
}
``` | ### Use [`array_slice()`](http://php.net/manual/en/function.array-slice.php)
>
> It returns the sequence of elements from the array array as specified by the offset and length parameters.
>
>
>
### Example:
```
<?php
$myArray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40);
print_r(array_slice($myArray, 0, 10));
print_r(array_slice($myArray, 10, 10));
print_r(array_slice($myArray, 20, 10));
print_r(array_slice($myArray, 30, 10));
?>
```
### Output:
```
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
Array
(
[0] => 11
[1] => 12
[2] => 13
[3] => 14
[4] => 15
[5] => 16
[6] => 17
[7] => 18
[8] => 19
[9] => 20
)
Array
(
[0] => 21
[1] => 22
[2] => 23
[3] => 24
[4] => 25
[5] => 26
[6] => 27
[7] => 28
[8] => 29
[9] => 30
)
Array
(
[0] => 31
[1] => 32
[2] => 33
[3] => 34
[4] => 35
[5] => 36
[6] => 37
[7] => 38
[8] => 39
[9] => 40
)
```
### Fiddle: <http://codepad.viper-7.com/mfzof6> |
12,780,524 | I have an array with 40 elements. I just need to show from array the first set of 10 elements and then show some static row in table. After displaying that static row, I just want to show another set of 10 rows. Like wise I need to show all 40 elements. | 2012/10/08 | [
"https://Stackoverflow.com/questions/12780524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1627627/"
]
| You can try
```
$array = range(1,40);
foreach (array_chunk($array, 10) as $current)
{
foreach($current as $data)
{
// Display your Information
}
}
``` | The most efficient way is using the [**modulus**](http://php.net/manual/en/language.operators.arithmetic.php) operator, like so:
```
$tot = count($array);
for($i=0;$i<$tot;$i++) {
echo $array[$i] . '<br>';
if(($i+1) % 10 == 0) {
echo '--- TEN GROUP --- <br>';
}
}
```
Example output:
```
text_1
text_2
...
text_9
text_10
--- TEN GROUP ---
text_11
text_12
...
text_19
text_20
--- TEN GROUP ---
text_21
text_22
...
``` |
29,698,240 | I have a bunch of `EditTexts` and I want to pass data gotten from the `EditTexts` to another `Activity` using `Intents`. Whenever I run the app, it gets a runtime error or something like that and crashes. The Logcat says my application is doing too much work on the thread. Is there any way around this?
Here's my code:
```
@Override
public void onClick(View v) {
final Intent a = new Intent (getApplicationContext(), Cooling.class);
a.putExtra("value15", 15f * Double.valueOf(edit15watt.getText().toString()));
a.putExtra("value20", 20f * Double.valueOf(edit20watt.getText().toString()));
a.putExtra("value40", 40f * Double.valueOf(edit40watt.getText().toString()));
a.putExtra("value60", 60f * Double.valueOf(edit60watt.getText().toString()));
a.putExtra("value75", 75f * Double.valueOf(edit75watt.getText().toString()));
a.putExtra("value100", 100f * Double.valueOf(edit100watt.getText().toString()));
a.putExtra("value11", 11f * Double.valueOf(edit11watt.getText().toString()));
a.putExtra("value18", 18f * Double.valueOf(edit18watt.getText().toString()));
a.putExtra("value23", 23f * Double.valueOf(edit23watt.getText().toString()));
a.putExtra("value50", 50f * Double.valueOf(edit50watt.getText().toString()));
a.putExtra("value90", 90f * Double.valueOf(edit90watt.getText().toString()));
a.putExtra("value200", 200f * Double.valueOf(edit200watt.getText().toString()));
a.putExtra("value250", 250f * Double.valueOf(edit250watt.getText().toString()));
startActivity(a);
}
```
this is what the logcat says
```
04-17 08:20:57.197: E/AndroidRuntime(1102): FATAL EXCEPTION: main
04-17 08:20:57.197: E/AndroidRuntime(1102): Process: com.emma.finalyearproject, PID: 1102
04-17 08:20:57.197: E/AndroidRuntime(1102): java.lang.NumberFormatException: Invalid double: ""
04-17 08:20:57.197: E/AndroidRuntime(1102): at java.lang.StringToReal.invalidReal(StringToReal.java:63)
04-17 08:20:57.197: E/AndroidRuntime(1102): at java.lang.StringToReal.parseDouble(StringToReal.java:248)
04-17 08:20:57.197: E/AndroidRuntime(1102): at java.lang.Double.parseDouble(Double.java:295)
04-17 08:20:57.197: E/AndroidRuntime(1102): at java.lang.Double.valueOf(Double.java:332)
04-17 08:20:57.197: E/AndroidRuntime(1102): at com.emma.finalyearproject.Lighting$1.onClick(Lighting.java:43)
04-17 08:20:57.197: E/AndroidRuntime(1102): at android.view.View.performClick(View.java:4424)
04-17 08:20:57.197: E/AndroidRuntime(1102): at android.view.View$PerformClick.run(View.java:18383)
04-17 08:20:57.197: E/AndroidRuntime(1102): at android.os.Handler.handleCallback(Handler.java:733)
04-17 08:20:57.197: E/AndroidRuntime(1102): at android.os.Handler.dispatchMessage(Handler.java:95)
04-17 08:20:57.197: E/AndroidRuntime(1102): at android.os.Looper.loop(Looper.java:137)
04-17 08:20:57.197: E/AndroidRuntime(1102): at android.app.ActivityThread.main(ActivityThread.java:4998)
04-17 08:20:57.197: E/AndroidRuntime(1102): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 08:20:57.197: E/AndroidRuntime(1102): at java.lang.reflect.Method.invoke(Method.java:515)
04-17 08:20:57.197: E/AndroidRuntime(1102): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
04-17 08:20:57.197: E/AndroidRuntime(1102): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
04-17 08:20:57.197: E/AndroidRuntime(1102): at dalvik.system.NativeStart.main(Native Method)
``` | 2015/04/17 | [
"https://Stackoverflow.com/questions/29698240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4758643/"
]
| you can pass data upto 1mb but log says its due to NumberFormatException | As such there is no limit on the number of extras defined.
You can use the number of extras you are currently using.
But the issue is related to NumberFormatException.
This is not related to Android at all.
Check the line of your program on which exception is happening.
Line number 43 of your program is causing issue.
As "" is not a valid double so this exception is happening. |
11,423,725 | Here is the code I have. I'm getting a red line under `new MainFragment();` with the error `Type mismatch: cannot convert from WishlistFragment to Fragment`:
```
Fragment newfragment = new MainFragment();
```
Here is what my MainFragment.java file looks like:
```
public class MainFragment extends Fragment {
public MainFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
```
Any ides on why this is happening? I have a feeling it's something stupid I am looking over and I am just code-blind right now from a long day. | 2012/07/11 | [
"https://Stackoverflow.com/questions/11423725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/546509/"
]
| Make sure that both places are importing the same `Fragment` class. It feels a bit like in one place you are importing `android.app.Fragment` (the native API Level 11 version of fragments) and in the other places you are importing `android.support.v4.app.Fragment` (the fragments from the Android Support package). | Figured out the issue.... my MainActivity.java file was using:
```
import android.support.v4.app.Fragment;
```
and my MainFragment.java file was using:
```
import android.app.Fragment;
```
So there was a mismatch. I am using ICS 4.0 and higher as my lowest API version. Changing everything to import to the v4 API solved my issue. |
40,579,894 | I am making a custom grid-view in android studio, every cell consist of an image-view and a text-view, but it gives an extra space between the the top and the image, and between the image and the text, see the [Image](https://i.stack.imgur.com/zRZWV.png). i want to get rid of that extra space, but i can't figure out the solution !
Here is the code of the Item (Cell) Layout:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:weightSum="5">
<ImageView
android:id="@+id/picture"
style="@style/Pic" />
<TextView
android:id="@+id/label"
style="@style/Text" />
```
And here is the XML for my main layout:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary">
<TextView
style="@style/Main_Text"
android:text="@string/Main_Menu"/>
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/gridView"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"/>
``` | 2016/11/13 | [
"https://Stackoverflow.com/questions/40579894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770022/"
]
| remove weightsum and in your imageview just add
```
android:adjustViewBounds="true"
android:scaleType="fitXY"
```
and if you want to use weightsum then try to add layoutweight for imageview and textview | try implemets
```
android:adjustViewBounds="true"
``` |
40,579,894 | I am making a custom grid-view in android studio, every cell consist of an image-view and a text-view, but it gives an extra space between the the top and the image, and between the image and the text, see the [Image](https://i.stack.imgur.com/zRZWV.png). i want to get rid of that extra space, but i can't figure out the solution !
Here is the code of the Item (Cell) Layout:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:weightSum="5">
<ImageView
android:id="@+id/picture"
style="@style/Pic" />
<TextView
android:id="@+id/label"
style="@style/Text" />
```
And here is the XML for my main layout:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary">
<TextView
style="@style/Main_Text"
android:text="@string/Main_Menu"/>
<GridView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/gridView"
android:numColumns="3"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"/>
``` | 2016/11/13 | [
"https://Stackoverflow.com/questions/40579894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770022/"
]
| remove weightsum and in your imageview just add
```
android:adjustViewBounds="true"
android:scaleType="fitXY"
```
and if you want to use weightsum then try to add layoutweight for imageview and textview | Remove "android:verticalSpacing="0dip" from your code or You can try this ,
```
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:cacheColorHint="@android:color/transparent"
android:columnWidth="40dip"
android:horizontalSpacing="0dip"
android:numColumns="auto_fit"
android:scrollbars="none"
android:verticalSpacing="0dip" />
``` |
33,236,469 | I have the following switch:
My groupPosition is 0 and childPosition is 1:
```
switch (groupPosition) {
case 0:
switch (childPosition) {
case 0:
if (NetworkManager.isNetworkAvailable(this)) {
new UserAwayTask().execute();
} else
Toast.makeText(this, "Network not available", Toast.LENGTH_LONG).show();
break;
case 1:
selection = null;
selectionArgs = null;
break;
case 2:
selection = Employee.COL_COUNTRY + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
}
case 1:
selection = Employee.COL_DEPARTMENT + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
case 2:
empIDList = GetAllTeamLeaders.teamLeaders(this, TeamLeader.COL_TEAMMEMBERID, TeamLeader.COL_TEAMLEADERNAME + " IS ? ", new String[]{valueReceived});
selection = Employee.COL_EMPID + " IN (" + TextUtils.join(",", Collections.nCopies(empIDList.size(), "?")) + ")";
selectionArgs = empIDList.toArray(new String[empIDList.size()]);
break;
}
```
But each time my selection is: department IS ? COLLATE NOCASE
and selection args is from case 1 from the outer switch.
So this:
```
case 1:
selection = Employee.COL_DEPARTMENT + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
```
is getting executed instead of :
```
case 2:
selection = Employee.COL_COUNTRY + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
```
However if I comment the outer switch's case 1 and case 2. I get the desired result.
What am I missing here? | 2015/10/20 | [
"https://Stackoverflow.com/questions/33236469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2822178/"
]
| You forgot to add a `break` for the top-level `case 0`:
```
case 0:
switch (childPosition) {
case 0:
if (NetworkManager.isNetworkAvailable(this)) {
new UserAwayTask().execute();
} else
Toast.makeText(this, "Network not available", Toast.LENGTH_LONG).show();
break;
case 1:
selection = null;
selectionArgs = null;
break;
case 2:
selection = Employee.COL_COUNTRY + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
}
break; //¯\_(ツ)_/¯
```
Without the `break;`, the flow just proceeds and enters the next `case` block until it reaches a `break` statement (or until it goes out of the `switch`).
Also, it's not bad idea to add a `break` for the nested `case 2` (just in case you add more `case`s in the future and you might end up with the same problem as this one, which by the way is called *fall-through*). | You do not break from your outer switch case 0. Add a `break` at the closing bracket of your inner switch.
```
case 0:
switch (childPosition) {
//
} break;
``` |
33,236,469 | I have the following switch:
My groupPosition is 0 and childPosition is 1:
```
switch (groupPosition) {
case 0:
switch (childPosition) {
case 0:
if (NetworkManager.isNetworkAvailable(this)) {
new UserAwayTask().execute();
} else
Toast.makeText(this, "Network not available", Toast.LENGTH_LONG).show();
break;
case 1:
selection = null;
selectionArgs = null;
break;
case 2:
selection = Employee.COL_COUNTRY + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
}
case 1:
selection = Employee.COL_DEPARTMENT + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
case 2:
empIDList = GetAllTeamLeaders.teamLeaders(this, TeamLeader.COL_TEAMMEMBERID, TeamLeader.COL_TEAMLEADERNAME + " IS ? ", new String[]{valueReceived});
selection = Employee.COL_EMPID + " IN (" + TextUtils.join(",", Collections.nCopies(empIDList.size(), "?")) + ")";
selectionArgs = empIDList.toArray(new String[empIDList.size()]);
break;
}
```
But each time my selection is: department IS ? COLLATE NOCASE
and selection args is from case 1 from the outer switch.
So this:
```
case 1:
selection = Employee.COL_DEPARTMENT + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
```
is getting executed instead of :
```
case 2:
selection = Employee.COL_COUNTRY + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
```
However if I comment the outer switch's case 1 and case 2. I get the desired result.
What am I missing here? | 2015/10/20 | [
"https://Stackoverflow.com/questions/33236469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2822178/"
]
| You forgot to add a `break` for the top-level `case 0`:
```
case 0:
switch (childPosition) {
case 0:
if (NetworkManager.isNetworkAvailable(this)) {
new UserAwayTask().execute();
} else
Toast.makeText(this, "Network not available", Toast.LENGTH_LONG).show();
break;
case 1:
selection = null;
selectionArgs = null;
break;
case 2:
selection = Employee.COL_COUNTRY + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
}
break; //¯\_(ツ)_/¯
```
Without the `break;`, the flow just proceeds and enters the next `case` block until it reaches a `break` statement (or until it goes out of the `switch`).
Also, it's not bad idea to add a `break` for the nested `case 2` (just in case you add more `case`s in the future and you might end up with the same problem as this one, which by the way is called *fall-through*). | Your are missing a break:
```
switch (groupPosition) {
case 0:
switch (childPosition) {
...
}
break; // <-- here
case 1:
selection = Employee.COL_DEPARTMENT + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
case 2:
empIDList = GetAllTeamLeaders.teamLeaders(this, TeamLeader.COL_TEAMMEMBERID, TeamLeader.COL_TEAMLEADERNAME + " IS ? ", new String[]{valueReceived});
selection = Employee.COL_EMPID + " IN (" + TextUtils.join(",", Collections.nCopies(empIDList.size(), "?")) + ")";
selectionArgs = empIDList.toArray(new String[empIDList.size()]);
break;
}
``` |
33,236,469 | I have the following switch:
My groupPosition is 0 and childPosition is 1:
```
switch (groupPosition) {
case 0:
switch (childPosition) {
case 0:
if (NetworkManager.isNetworkAvailable(this)) {
new UserAwayTask().execute();
} else
Toast.makeText(this, "Network not available", Toast.LENGTH_LONG).show();
break;
case 1:
selection = null;
selectionArgs = null;
break;
case 2:
selection = Employee.COL_COUNTRY + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
}
case 1:
selection = Employee.COL_DEPARTMENT + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
case 2:
empIDList = GetAllTeamLeaders.teamLeaders(this, TeamLeader.COL_TEAMMEMBERID, TeamLeader.COL_TEAMLEADERNAME + " IS ? ", new String[]{valueReceived});
selection = Employee.COL_EMPID + " IN (" + TextUtils.join(",", Collections.nCopies(empIDList.size(), "?")) + ")";
selectionArgs = empIDList.toArray(new String[empIDList.size()]);
break;
}
```
But each time my selection is: department IS ? COLLATE NOCASE
and selection args is from case 1 from the outer switch.
So this:
```
case 1:
selection = Employee.COL_DEPARTMENT + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
```
is getting executed instead of :
```
case 2:
selection = Employee.COL_COUNTRY + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
```
However if I comment the outer switch's case 1 and case 2. I get the desired result.
What am I missing here? | 2015/10/20 | [
"https://Stackoverflow.com/questions/33236469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2822178/"
]
| Your are missing a break:
```
switch (groupPosition) {
case 0:
switch (childPosition) {
...
}
break; // <-- here
case 1:
selection = Employee.COL_DEPARTMENT + " IS ? COLLATE NOCASE";
selectionArgs = new String[]{valueReceived};
break;
case 2:
empIDList = GetAllTeamLeaders.teamLeaders(this, TeamLeader.COL_TEAMMEMBERID, TeamLeader.COL_TEAMLEADERNAME + " IS ? ", new String[]{valueReceived});
selection = Employee.COL_EMPID + " IN (" + TextUtils.join(",", Collections.nCopies(empIDList.size(), "?")) + ")";
selectionArgs = empIDList.toArray(new String[empIDList.size()]);
break;
}
``` | You do not break from your outer switch case 0. Add a `break` at the closing bracket of your inner switch.
```
case 0:
switch (childPosition) {
//
} break;
``` |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| You can use [$\_SESSION](http://php.net/manual/en/book.session.php), i.e.:
**script1.php**
```
<?php
session_start();
$_SESSION['myVar'] = "something";
?>
```
**script2.php**
```
<?php
session_start();
echo $_SESSION['myVar'];
//something
?>
``` | I made a tiny library (~2 KB; <100 lines) that allows you to do just this: [varDx](https://github.com/rahuldottech/varDx)
It has functions to write, read, modify, check and delete data.
It implements serialization, and therefore supports all data types.
Here's how you can use it:
```
<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
``` |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| No, by design PHP is a "share nothing" architecture, which means nothing is shared between processes running at the same time or between requests running one after another. There are ways to share data, but you have to do it explicitly.
If you just want to share between 2 requests from the same user, sessions or cookies might be the way to go.
If you want to share between multiple users, you probably want some sort of shared persistence, either short term in a cache (eg. memcached) or more robust like a database.
Either way, the data is actually being retrieved and reconstructed on each request. It's just handled automatically for you in the case of sessions. | Not as such, but you can use cookies or sessions to maintain data for duration of a user's browsing experience, or you can write to a database or file on-disk if the information needs to persist beyond that. |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| No, by design PHP is a "share nothing" architecture, which means nothing is shared between processes running at the same time or between requests running one after another. There are ways to share data, but you have to do it explicitly.
If you just want to share between 2 requests from the same user, sessions or cookies might be the way to go.
If you want to share between multiple users, you probably want some sort of shared persistence, either short term in a cache (eg. memcached) or more robust like a database.
Either way, the data is actually being retrieved and reconstructed on each request. It's just handled automatically for you in the case of sessions. | You can use [$\_SESSION](http://php.net/manual/en/book.session.php), i.e.:
**script1.php**
```
<?php
session_start();
$_SESSION['myVar'] = "something";
?>
```
**script2.php**
```
<?php
session_start();
echo $_SESSION['myVar'];
//something
?>
``` |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| You can use [$\_SESSION](http://php.net/manual/en/book.session.php), i.e.:
**script1.php**
```
<?php
session_start();
$_SESSION['myVar'] = "something";
?>
```
**script2.php**
```
<?php
session_start();
echo $_SESSION['myVar'];
//something
?>
``` | Each request is handled by a php instance of its own. Global variables in php are only accessible from within the same php instance. However you can use something like the [memchached module](http://docs.php.net/memcached) to share data between different instances (which should usually be faster than writing the data to the filesystem). |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| Not as such, but you can use cookies or sessions to maintain data for duration of a user's browsing experience, or you can write to a database or file on-disk if the information needs to persist beyond that. | I made a tiny library (~2 KB; <100 lines) that allows you to do just this: [varDx](https://github.com/rahuldottech/varDx)
It has functions to write, read, modify, check and delete data.
It implements serialization, and therefore supports all data types.
Here's how you can use it:
```
<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file
``` |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| You can use [$\_SESSION](http://php.net/manual/en/book.session.php), i.e.:
**script1.php**
```
<?php
session_start();
$_SESSION['myVar'] = "something";
?>
```
**script2.php**
```
<?php
session_start();
echo $_SESSION['myVar'];
//something
?>
``` | Global variables are bad in most programming. They're especially bad in multithreaded/multiuser systems like webapps. Avoid. If you must use global variables (rather than global constants) put them in a database with transactions guarding updates.
Since you talk about different scripts though, it sounds like what you really want is a web application framework in a more application oriented language --- something like Django (python) or Rails (ruby). These let you think of your code much more like a cohesive PROGRAM, rather than a lot of loosely connected scripts that process web requests. |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| Each request is handled by a php instance of its own. Global variables in php are only accessible from within the same php instance. However you can use something like the [memchached module](http://docs.php.net/memcached) to share data between different instances (which should usually be faster than writing the data to the filesystem). | Global variables are bad in most programming. They're especially bad in multithreaded/multiuser systems like webapps. Avoid. If you must use global variables (rather than global constants) put them in a database with transactions guarding updates.
Since you talk about different scripts though, it sounds like what you really want is a web application framework in a more application oriented language --- something like Django (python) or Rails (ruby). These let you think of your code much more like a cohesive PROGRAM, rather than a lot of loosely connected scripts that process web requests. |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| Not as such, but you can use cookies or sessions to maintain data for duration of a user's browsing experience, or you can write to a database or file on-disk if the information needs to persist beyond that. | Global variables are bad in most programming. They're especially bad in multithreaded/multiuser systems like webapps. Avoid. If you must use global variables (rather than global constants) put them in a database with transactions guarding updates.
Since you talk about different scripts though, it sounds like what you really want is a web application framework in a more application oriented language --- something like Django (python) or Rails (ruby). These let you think of your code much more like a cohesive PROGRAM, rather than a lot of loosely connected scripts that process web requests. |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| Each request is handled by a php instance of its own. Global variables in php are only accessible from within the same php instance. However you can use something like the [memchached module](http://docs.php.net/memcached) to share data between different instances (which should usually be faster than writing the data to the filesystem). | Not as such, but you can use cookies or sessions to maintain data for duration of a user's browsing experience, or you can write to a database or file on-disk if the information needs to persist beyond that. |
1,435,959 | Does PHP have global variables that can be modified by one running script and read by another? | 2009/09/16 | [
"https://Stackoverflow.com/questions/1435959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41021/"
]
| You can actually do this using [shared memory](http://us.php.net/sem), or [APC](http://php.net/apc) (which is using shared memory itself). | Not as such, but you can use cookies or sessions to maintain data for duration of a user's browsing experience, or you can write to a database or file on-disk if the information needs to persist beyond that. |
22,990,945 | If you see the google maps app(the out of box app) and say you search for something like 'food', you will wither see a couple of markers as parker pins or as dots. When you tap on a dot, the dot animates and becomes a full marker pin(you can see the marker scaling up.
I was wondering if we can do the same using goole maps for android v2.
Any tips would be helpful.
ps: my current idea is to use an interpolator and replace the marker icon using setIcon couple of time, but seriously, if Google has already done it then we should be able to do it.
thanks | 2014/04/10 | [
"https://Stackoverflow.com/questions/22990945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1070021/"
]
| Your regex is wrong for what you're trying to do. You will need negative lookahead.
Try this code:
```
$re = '/\b(?!(?:true|false|TRUE|FALSE))\w+\b/';
$str = 'I need true to allow only false specific FALSE words in a TRUE string';
$repl = preg_replace($re, "", $str);
//=> true false FALSE TRUE
```
### [Online Demo](http://regex101.com/r/hN3wX9) | Is this what you want?
(?=.)(true|false|TRUE|FALSE|\s\*)(?!.)

[Debuggex Demo](https://www.debuggex.com/r/8oX3ibPh6h4SQjKq)
```
$regex = '/(?=.)(true|false|TRUE|FALSE|\\s{0,})(?!.)/';
$testString = ''; // Fill this in
preg_match($regex, $testString, $matches);
// the $matches variable contains the list of matches
``` |
22,990,945 | If you see the google maps app(the out of box app) and say you search for something like 'food', you will wither see a couple of markers as parker pins or as dots. When you tap on a dot, the dot animates and becomes a full marker pin(you can see the marker scaling up.
I was wondering if we can do the same using goole maps for android v2.
Any tips would be helpful.
ps: my current idea is to use an interpolator and replace the marker icon using setIcon couple of time, but seriously, if Google has already done it then we should be able to do it.
thanks | 2014/04/10 | [
"https://Stackoverflow.com/questions/22990945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1070021/"
]
| In this case you don't need a regex, you can use `in_array`:
```
$arr = array('true', 'false', 'TRUE', 'FALSE');
$result = (in_array($str, $arr, true)) ? $str : '';
``` | Is this what you want?
(?=.)(true|false|TRUE|FALSE|\s\*)(?!.)

[Debuggex Demo](https://www.debuggex.com/r/8oX3ibPh6h4SQjKq)
```
$regex = '/(?=.)(true|false|TRUE|FALSE|\\s{0,})(?!.)/';
$testString = ''; // Fill this in
preg_match($regex, $testString, $matches);
// the $matches variable contains the list of matches
``` |
22,990,945 | If you see the google maps app(the out of box app) and say you search for something like 'food', you will wither see a couple of markers as parker pins or as dots. When you tap on a dot, the dot animates and becomes a full marker pin(you can see the marker scaling up.
I was wondering if we can do the same using goole maps for android v2.
Any tips would be helpful.
ps: my current idea is to use an interpolator and replace the marker icon using setIcon couple of time, but seriously, if Google has already done it then we should be able to do it.
thanks | 2014/04/10 | [
"https://Stackoverflow.com/questions/22990945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1070021/"
]
| Not sure I well understand your needs, but is that OK for you:
```
if (preg_match('/^(true|false|TRUE|FALSE)$/', $string, $match)) {
echo "Found : ",$m[1],"\n";
} else {
echo "Not found\n";
}
``` | Is this what you want?
(?=.)(true|false|TRUE|FALSE|\s\*)(?!.)

[Debuggex Demo](https://www.debuggex.com/r/8oX3ibPh6h4SQjKq)
```
$regex = '/(?=.)(true|false|TRUE|FALSE|\\s{0,})(?!.)/';
$testString = ''; // Fill this in
preg_match($regex, $testString, $matches);
// the $matches variable contains the list of matches
``` |
50,963,258 | I'm using Elasticsearch [Phrase Suggester](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters-phrase.html) for correcting user's misspellings. everything is working as I expected unless user enters a query which it's first letter is misspelled. At this situation phrase suggester returns nothing or returns unexpected results.
My query for suggestion:
```
{
"suggest": {
"text": "user_query",
"simple_phrase": {
"phrase": {
"field": "title.phrase",,
"collate": {
"query": {
"inlile" : {
"bool": {
"should": [
{ "match": {"title": "{{suggestion}}"}},
{ "match": {"participants": "{{suggestion}}"}}
]
}
}
}
}
}
}
```
}
}
Example when first letter is misspelled:
```
"simple_phrase" : [
{
"text" : "گاشانچی",
"offset" : 0,
"length" : 11,
"options" : [ {
"text" : "گارانتی",
"score" : 0.00253151
}]
}
]
```
Example when fifth letter is misspelled:
```
"simple_phrase" : [
{
"text" : "کاشاوچی",
"offset" : 0,
"length" : 11,
"options" : [ {
"text" : "کاشانچی",
"score" : 0.1121
},
{
"text" : "کاشانجی",
"score" : 0.0021
},
{
"text" : "کاشنچی",
"score" : 0.0020
}]
}
]
```
I expect that these two misspelled queries have same suggestions(my expected suggestions are second one). what is wrong?
P.S: I'm using this feature for Persian language. | 2018/06/21 | [
"https://Stackoverflow.com/questions/50963258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4720169/"
]
| In the codepen you have a width of 150px set. You need to remove this to allow for a full width container.
All columns need to be contained in a row.
I have removed the width from the style, and added a row class to the card-container div. See here:
<https://codepen.io/anon/pen/MXVGVE>
```
<div class="card-container row"> // Columns must be contained within a row class
<div class="card col-lg-4 col-sm-6 col-xs-12">
<div class="side">Jimmy Eat World</div>
<div class="side back"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/29841/jimmy.jpg" alt="Jimmy Eat World"></div>
</div>
<div class="card col-lg-4 col-sm-6 col-xs-12">
Card 2...
</div>
<div class="card col-lg-4 col-sm-6 col-xs-12">
Card 3...
</div>
</div>
``` | **YOU CAN NOT SET `col-..` without wrap it `row` div**
Set `width: 100%;` instead `width: 150px;` to `.card-container`
and add `row` to `card-container`
```css
.card-container {
cursor: pointer;
height: 150px;
perspective: 600;
position: relative;
width: 100%;
}
.card {
height: 100%;
position: absolute;
transform-style: preserve-3d;
transition: all 1s ease-in-out;
width: 100%;
}
.card:hover {
transform: rotateY(180deg);
}
.card .side {
backface-visibility: hidden;
border-radius: 6px;
height: 100%;
position: absolute;
overflow: hidden;
width: 100%;
}
.card .back {
background: #eaeaed;
color: #0087cc;
line-height: 150px;
text-align: center;
transform: rotateY(180deg);
}
```
```html
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<section class="section-heroes container" >
<div class="u-center-text u-margin-bottom-big">
<h2 class="heading-secondary">
Choose your hero membership
</h2>
</div>
<div class="row card-container">
<div class="card col-lg-4 col-sm-6 col-xs-12">
<div class="side">Jimmy Eat World</div>
<div class="side back"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/29841/jimmy.jpg" alt="Jimmy Eat World"></div>
</div>
<div class="card col-lg-4 col-sm-6 col-xs-12">
<div class="side">Jimmy Eat World</div>
<div class="side back"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/29841/jimmy.jpg" alt="Jimmy Eat World"></div>
</div>
<div class="card col-lg-4 col-sm-6 col-xs-12">
<div class="side">Jimmy Eat World</div>
<div class="side back"><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/29841/jimmy.jpg" alt="Jimmy Eat World"></div>
</div>
</div>
``` |
38,668,710 | I wrote several functions to check if the two passwords are equal. I first type two passwords. When I click out of the "verify password" box, it should either display "The passwords match" or "A second try is needed. Please enter your password in the first password box again because the two passwords don't match" depending on whether or not the passwords are equal to each other. If the two passwords are not equal, the message "A second try is needed. Please enter your password in the first password box again because the two passwords don't match" is displayed. I also want the first password box (password1) to turn blank (I want it reset) as well when the two passwords do not match. However, that won't work in my code. What I am doing wrong here?
I used a password.js file and a setpassword.html file.
My password.js file is this:
```
var verifypasswordclick = document.getElementById("txtPWVerified");
function verifypassword1() {
var password1 = document.getElementById("txtPassword").value;
var verifypassword = document.getElementById("txtPWVerified").value;
if(password1 == '' || verifypassword == '') {
return null;
}
if(password1 == verifypassword) {
alert('The passwords match');
}
if(password1 !== verifypassword || password1 == "" || verifypasword == "") {
alert("A second try is needed. Please enter your password in the first password box again because the two passwords don't match");
}
if(password1 !== verifypassword || password1 == "" || verifypasword == "") {
password1 = "";
}
}
verifypasswordclick.addEventListener("blur",verifypassword1);
```
My setpassword.html file is this:
```
<!DOCTYPE html>
<!-- H5FormValidation.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Register Here</title>
</head>
<body>
<h2>Register Here</h2>
<form id="formTest" method="get" action="processData">
<table>
<tr>
<td><label for="txtEmail">Email<span class="required">*</span></label></td>
<td><input type="email" id="txtEmail" name="email" required></td>
</tr>
<tr>
<td><label for="txtPassword">Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPassword" name="password" required></td>
</tr>
<tr>
<td><label for="txtPWVerified">Verify Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPWVerified" name="pwVerified" required></td>
</tr>
<tr>
<td> </td>
<td>
<input type="reset" value="CLEAR" id="btnReset"></td>
</tr>
</table>
</form>
<script src = "password.js"></script>
</body>
</html>
``` | 2016/07/29 | [
"https://Stackoverflow.com/questions/38668710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6642730/"
]
| Solved! :D
```
function getXML() {
fetch('https://privateapi.com/xml')
.then(response => response.text()) // the promise
.then(data => console.log('Data', data)) // data
.catch(error => console.log('Error', error))
}
```
1.Figured out that I had to enable some settings in the server since I was receiving the error "Fetch API cannot load No 'Access-Control-Allow-Origin' header"...
2.Need two .then since first one handles the promise and then second one can be used to convert the response to text. | You are calling `response.json()` which is failing to parse the XML into an object, change that to `response.text()`
```
function getGithubGists() {
fetch('https://privateapi.com/xml')
.then(function(response) {
response.text().then(function(data) {
console.log('data', data)
})
})
.catch(function(error) {
console.log('Error', error)
})
}
``` |
3,816,718 | I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:
```
public enum Enumnum { TypeA, TypeB, TypeC, TypeD }
```
how would I be able to get a `List<Enumnum>` that contains `{ TypeA, TypeB, TypeC, TypeD }`? | 2010/09/28 | [
"https://Stackoverflow.com/questions/3816718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388739/"
]
| Try this code:
```
Enum.GetNames(typeof(Enumnum));
```
This return a `string[]` with all the enum names of the chosen enum. | The OP asked for How to get an array of all `enum` values in C# ?
**What if you want to get an array of selected `enum` values in C# ?**
**Your Enum**
```
enum WeekDays
{
Sunday,
Monday,
Tuesday
}
```
If you want to just select `Sunday` from your `Enum`.
```
WeekDays[] weekDaysArray1 = new WeekDays[] { WeekDays.Sunday };
WeekDays[] weekDaysArray2 = Enum.GetValues(typeof(WeekDays)).Cast<WeekDays>().Where
(x => x == WeekDays.Sunday).ToArray();
```
Credits goes to knowledgeable tl.
References:
[1.](https://stackoverflow.com/questions/3160267/how-to-create-an-array-of-enums)
[2.](https://stackoverflow.com/questions/17123548/convert-enum-to-list)
Hope helps someone. |
3,816,718 | I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:
```
public enum Enumnum { TypeA, TypeB, TypeC, TypeD }
```
how would I be able to get a `List<Enumnum>` that contains `{ TypeA, TypeB, TypeC, TypeD }`? | 2010/09/28 | [
"https://Stackoverflow.com/questions/3816718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388739/"
]
| You may want to do like this:
```
public enum Enumnum {
TypeA = 11,
TypeB = 22,
TypeC = 33,
TypeD = 44
}
```
All int values of this `enum` is `11,22,33,44`.
You can get these values by this:
```
var enumsValues = Enum.GetValues(typeof(Enumnum)).Cast<Enumnum>().ToList().Select(e => (int)e);
```
`string.Join(",", enumsValues)` is `11,22,33,44`. | If you prefer a more generic way, here it is. You can add up more converters as per your need.
```
public static class EnumConverter
{
public static string[] ToNameArray<T>()
{
return Enum.GetNames(typeof(T)).ToArray();
}
public static Array ToValueArray<T>()
{
return Enum.GetValues(typeof(T));
}
public static List<T> ToListOfValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
public static IEnumerable<T> ToEnumerable<T>()
{
return (T[])Enum.GetValues(typeof(T));
}
}
```
Sample Implementations :
```
string[] roles = EnumConverter.ToStringArray<ePermittedRoles>();
List<ePermittedRoles> roles2 = EnumConverter.ToListOfValues<ePermittedRoles>();
Array data = EnumConverter.ToValueArray<ePermittedRoles>();
``` |
3,816,718 | I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:
```
public enum Enumnum { TypeA, TypeB, TypeC, TypeD }
```
how would I be able to get a `List<Enumnum>` that contains `{ TypeA, TypeB, TypeC, TypeD }`? | 2010/09/28 | [
"https://Stackoverflow.com/questions/3816718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388739/"
]
| This is way easier now with the generic method in .NET 5.0.
```
ColorEnum[] colors = Enum.GetValues<ColorEnum>();
```
[MS Doc: Enum.GetValues](https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-5.0#System_Enum_GetValues__1) | The OP asked for How to get an array of all `enum` values in C# ?
**What if you want to get an array of selected `enum` values in C# ?**
**Your Enum**
```
enum WeekDays
{
Sunday,
Monday,
Tuesday
}
```
If you want to just select `Sunday` from your `Enum`.
```
WeekDays[] weekDaysArray1 = new WeekDays[] { WeekDays.Sunday };
WeekDays[] weekDaysArray2 = Enum.GetValues(typeof(WeekDays)).Cast<WeekDays>().Where
(x => x == WeekDays.Sunday).ToArray();
```
Credits goes to knowledgeable tl.
References:
[1.](https://stackoverflow.com/questions/3160267/how-to-create-an-array-of-enums)
[2.](https://stackoverflow.com/questions/17123548/convert-enum-to-list)
Hope helps someone. |
3,816,718 | I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:
```
public enum Enumnum { TypeA, TypeB, TypeC, TypeD }
```
how would I be able to get a `List<Enumnum>` that contains `{ TypeA, TypeB, TypeC, TypeD }`? | 2010/09/28 | [
"https://Stackoverflow.com/questions/3816718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388739/"
]
| Try this code:
```
Enum.GetNames(typeof(Enumnum));
```
This return a `string[]` with all the enum names of the chosen enum. | Something little different:
```
typeof(SomeEnum).GetEnumValues();
``` |
3,816,718 | I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:
```
public enum Enumnum { TypeA, TypeB, TypeC, TypeD }
```
how would I be able to get a `List<Enumnum>` that contains `{ TypeA, TypeB, TypeC, TypeD }`? | 2010/09/28 | [
"https://Stackoverflow.com/questions/3816718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388739/"
]
| You may want to do like this:
```
public enum Enumnum {
TypeA = 11,
TypeB = 22,
TypeC = 33,
TypeD = 44
}
```
All int values of this `enum` is `11,22,33,44`.
You can get these values by this:
```
var enumsValues = Enum.GetValues(typeof(Enumnum)).Cast<Enumnum>().ToList().Select(e => (int)e);
```
`string.Join(",", enumsValues)` is `11,22,33,44`. | also you can use
```
var enumAsJson=typeof(SomeEnum).Name + ":[" + string.Join(",", Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().Select(e => e.ToString())) + "]";
```
for get all elements in enum as json format. |
3,816,718 | I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:
```
public enum Enumnum { TypeA, TypeB, TypeC, TypeD }
```
how would I be able to get a `List<Enumnum>` that contains `{ TypeA, TypeB, TypeC, TypeD }`? | 2010/09/28 | [
"https://Stackoverflow.com/questions/3816718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388739/"
]
| ```
Enum.GetValues(typeof(Enumnum));
```
returns an array of the values in the Enum. | with this:
```
string[] myArray = Enum.GetNames(typeof(Enumnum));
```
and you can access values array like so:
```
Array myArray = Enum.GetValues(typeof(Enumnum));
``` |
3,816,718 | I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:
```
public enum Enumnum { TypeA, TypeB, TypeC, TypeD }
```
how would I be able to get a `List<Enumnum>` that contains `{ TypeA, TypeB, TypeC, TypeD }`? | 2010/09/28 | [
"https://Stackoverflow.com/questions/3816718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388739/"
]
| Try this code:
```
Enum.GetNames(typeof(Enumnum));
```
This return a `string[]` with all the enum names of the chosen enum. | If you prefer a more generic way, here it is. You can add up more converters as per your need.
```
public static class EnumConverter
{
public static string[] ToNameArray<T>()
{
return Enum.GetNames(typeof(T)).ToArray();
}
public static Array ToValueArray<T>()
{
return Enum.GetValues(typeof(T));
}
public static List<T> ToListOfValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}
public static IEnumerable<T> ToEnumerable<T>()
{
return (T[])Enum.GetValues(typeof(T));
}
}
```
Sample Implementations :
```
string[] roles = EnumConverter.ToStringArray<ePermittedRoles>();
List<ePermittedRoles> roles2 = EnumConverter.ToListOfValues<ePermittedRoles>();
Array data = EnumConverter.ToValueArray<ePermittedRoles>();
``` |
3,816,718 | I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:
```
public enum Enumnum { TypeA, TypeB, TypeC, TypeD }
```
how would I be able to get a `List<Enumnum>` that contains `{ TypeA, TypeB, TypeC, TypeD }`? | 2010/09/28 | [
"https://Stackoverflow.com/questions/3816718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388739/"
]
| Something little different:
```
typeof(SomeEnum).GetEnumValues();
``` | The OP asked for How to get an array of all `enum` values in C# ?
**What if you want to get an array of selected `enum` values in C# ?**
**Your Enum**
```
enum WeekDays
{
Sunday,
Monday,
Tuesday
}
```
If you want to just select `Sunday` from your `Enum`.
```
WeekDays[] weekDaysArray1 = new WeekDays[] { WeekDays.Sunday };
WeekDays[] weekDaysArray2 = Enum.GetValues(typeof(WeekDays)).Cast<WeekDays>().Where
(x => x == WeekDays.Sunday).ToArray();
```
Credits goes to knowledgeable tl.
References:
[1.](https://stackoverflow.com/questions/3160267/how-to-create-an-array-of-enums)
[2.](https://stackoverflow.com/questions/17123548/convert-enum-to-list)
Hope helps someone. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.