qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
255,697 | Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Happy Hanukkah!
A beloved Hanukkah tradition for many, the game of [Dreidel](https://en.wikipedia.org/wiki/Dreidel) (*s'vivon* in Hebrew) is a betting game (for money or for chocolate *gelt* (coins)) centered on the titular spinning tops called dreidels. Dreidels have four sides:
נ (nun), ג (gimel), ה (hei), and ש (shin), an acronym for the phrase "neis gadol haya sham": a great miracle happened there, referring to the famous Hanukkah miracle.
The game starts with an ante of one coin put forth by all players. Then, players take turns spinning the dreidel and lose or gain money according to the following rules:
* נ (nun): Do nothing
* ג (gimel): Win all the money in the pot
* ה (hei): Win half the money in the pot, rounding up
* ש (shin): Add one coin to the pot
If at any point the pot becomes empty, all players put forth one coin. If a player must put forth a coin and they have none, they are out of the game. The game ends when players agree to stop or when only one player is remaining.
---
Task
----
Your task is to implement the game of Dreidel.
Input:
* (mapping: str -> int) A number of players, guaranteed to be ≥2, each represented by a string. Each player maps to the starting number of coins for that player, guaranteed to be ≥1.
* (int) The number of rounds, guaranteed to be ≥1. (In each round, every player who's still in the game will spin the dreidel once).
Output:
* (mapping: str -> int) Each player and their corresponding final number of coins at the end of the game.
Rules:
* Standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply. Shortest answer in bytes wins!
* Dreidel outcomes must be random, and must appear with the same probability (25% for each outcome).
* Any reasonable form of input or output is allowed. For instance, to represent the mapping of players to coins, one can use a Python-style dictionary, an array of pairs, etc. The mapping need not have a consistent ordering.
+ All players must be represented in the output, even if they have no money left.
* You can use whatever order for the players within each round is easiest, as long as each player who's still in the game spins once per round.
Notes:
* It is not guaranteed that the total number of coins at the end of the game is equal to the total number of coins at the beginning of the game (there may be some left over in the pot.)
Examples: (bear in mind that results are random)
```python
>>> dreidel({"Abraham": 5, "Batya": 5, "Claire": 5}, 3)
{"Abraham": 3, "Batya": 8, "Claire": 4}
>>> dreidel({"David": 3, "Eliana": 9, "Fievel": 2, "Gabriella": 2}, 15)
{"David": 0, "Eliana": 16, "Fievel": 0, "Gabriella": 0}
``` | 2022/12/19 | [
"https://codegolf.stackexchange.com/questions/255697",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/47670/"
] | [Python](https://www.python.org), ~~197~~ 195 bytes
===================================================
-2 bytes thanks to @Arnauld using `-~p//2` instead of `p//2+p%2`
```python
from random import*
def f(n,c,m,i=0,p=0,s=0):
l=len(c);v=-~c[x:=i%l]and[-1,0,p,~-p//2][i//l&(s<0)and randrange(4)];c[x]+=v
if~-l-c.count(-1)and-~i<m*l:f(n,c,m,i+1,w:=p-v*(c[x]>=0),[s-1,l][w<1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVBLTsMwEN3nFFYkkN2OSYL4KY1BwDEsL1o3Bkv-KUlT2OQibLqBi3AKbsM0KixmRqN5b96b-fhK78NrDIfD524w_O7n23TRk24dtlisT7EbFtm2NcTQABo8WFFCwuhFyeqMOOHaQDVbjYJPWr7Vwp45hXTJK0AkTDwVxaWStijcOe2bkuFwFsB4aekVUyvkqaUYM2LNxB3XFzruwkB5dcTyyTZ-4ep_A8sK9rVIfFzQI_EejYDsUc4puW8qxU6nPOhoQ08EkddwA7cqM1Tmj5s2h_wpbjA_r723ba5gBkJVsix1FoXn_rTm7zO_)
Takes in the mapping as a list of names `n` and a list of coin counts `c` which are the same length, along with a number of rounds `r`.
Modifies the list of coins in place; the values indicate the number of coins, except for if `c[i]` is `-1`, which indicates that person `n[i]` is out of the game.
It works recursively, storing the following between calls (in addition to the current number of coins):
* `i`: How many players have played so far
* `p`: the size of the pot
* `s`: If positive, how many players need to contribute to the pot (set to `len(c)` when the pot is empty, otherwise decreased by one every call) | [Python 3](https://docs.python.org/3/), ~~317 303 311 318 294~~ 270 bytes
=========================================================================
```python
def f(p,r):
m=len(p)
for k in p:p[k]-=1
for _ in range(r):
for i in p:
if p[i]<0:continue
x=randrange(4)
if x<1:p[i]+=m;m=0
if x<2:p[i]-=~m//2;m+=~m//2
if x>2:m+=p[i]>0;p[i]-=1
if m<1:
for j in p:m+=p[j]>0;p[j]-=1
return p
from random import*
```
[Try it online!](https://tio.run/##RY/NbsIwEITveQqLU1yCyE851MFI/X8IhCrT2GWD7VhWQKCqffV0HaftyTsz36zW7tofOlsNQyMVUanLPGUJMVxLmzqaENV5ciRgiWNue9wteBG9t@B5YT9kOjZGEyKIioAibgu7dc7eO9uDPcngXjhWmli7pRN3WRcssHNuasPzP7cc3QX/NstlWZt5HH7jTcnQCsQmryNYTJnBhWEcb2rjTSPbRraNrJf9yWOWKN@Z8JcGHzCu8/3N4DzYPlXp5@x@78VBmBkjq4zMHkR/FdP8qAV4GcRXRipKk//SkzhDg0mF2LMGYUPnDsULyLPUKEoUr2LvQWodwhJ3FCtKhx8 "Python 3 – Try It Online")
* Thanks to Neil for spotting a bug (303 -> 311)
* Thanks to AAM111 for cutting out the `import math` and spotting a bug (311 -> 318)
* Thanks to c-- for some golfing suggestions (318 -> 294 and 294 -> 270)
Players that are out are shown as having negative coins.
### Explanation
```python
def f(p,r): # Create a function, f, which takes in the player dictionary, p, and the number of rounds, r
m=len(p) # Assign the money pot, m, to the number of players
for k in p:p[k]-=1 # And subtract one from each of the players (each player gives one coin to the pot)
for _ in range(r): # Loop r times (r rounds)
for i in p: # Go through each of the players
if p[i]<0:continue # If they are out of the game (money = -1), skip their turn
x=randrange(4) # Spin the dreidel (0 to 3)
if x<1:0 # If it's 0, do nothing
elif x<2:p[i]+=m;m=0 # If it's 1, add all the money from m to that player and set m to 0
elif x<3:a=(int(m)+m%2)//2;p[i]+=a;m-=a # If it's 2, add half the money to that player and reduce m
else:m+=1;p[i]-=1 # If it's 3, add 1 to m and remove 1 from the player
if m<1: # If m is 0
for j in p: # Go through each player
if p[j]>0:p[j]-=1;m+=1 # If they're not out of money, reduce by one and add that to m
else:p[j]=-1 # Otherwise, set their money to -1 (they are now out)
return p # At the end of all the rounds, return the final dictionary
from random import* # Import the random library for the dreidel
``` |
255,697 | Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Happy Hanukkah!
A beloved Hanukkah tradition for many, the game of [Dreidel](https://en.wikipedia.org/wiki/Dreidel) (*s'vivon* in Hebrew) is a betting game (for money or for chocolate *gelt* (coins)) centered on the titular spinning tops called dreidels. Dreidels have four sides:
נ (nun), ג (gimel), ה (hei), and ש (shin), an acronym for the phrase "neis gadol haya sham": a great miracle happened there, referring to the famous Hanukkah miracle.
The game starts with an ante of one coin put forth by all players. Then, players take turns spinning the dreidel and lose or gain money according to the following rules:
* נ (nun): Do nothing
* ג (gimel): Win all the money in the pot
* ה (hei): Win half the money in the pot, rounding up
* ש (shin): Add one coin to the pot
If at any point the pot becomes empty, all players put forth one coin. If a player must put forth a coin and they have none, they are out of the game. The game ends when players agree to stop or when only one player is remaining.
---
Task
----
Your task is to implement the game of Dreidel.
Input:
* (mapping: str -> int) A number of players, guaranteed to be ≥2, each represented by a string. Each player maps to the starting number of coins for that player, guaranteed to be ≥1.
* (int) The number of rounds, guaranteed to be ≥1. (In each round, every player who's still in the game will spin the dreidel once).
Output:
* (mapping: str -> int) Each player and their corresponding final number of coins at the end of the game.
Rules:
* Standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply. Shortest answer in bytes wins!
* Dreidel outcomes must be random, and must appear with the same probability (25% for each outcome).
* Any reasonable form of input or output is allowed. For instance, to represent the mapping of players to coins, one can use a Python-style dictionary, an array of pairs, etc. The mapping need not have a consistent ordering.
+ All players must be represented in the output, even if they have no money left.
* You can use whatever order for the players within each round is easiest, as long as each player who's still in the game spins once per round.
Notes:
* It is not guaranteed that the total number of coins at the end of the game is equal to the total number of coins at the beginning of the game (there may be some left over in the pot.)
Examples: (bear in mind that results are random)
```python
>>> dreidel({"Abraham": 5, "Batya": 5, "Claire": 5}, 3)
{"Abraham": 3, "Batya": 8, "Claire": 4}
>>> dreidel({"David": 3, "Eliana": 9, "Fievel": 2, "Gabriella": 2}, 15)
{"David": 0, "Eliana": 16, "Fievel": 0, "Gabriella": 0}
``` | 2022/12/19 | [
"https://codegolf.stackexchange.com/questions/255697",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/47670/"
] | [Python 3](https://docs.python.org/3/), ~~317 303 311 318 294~~ 270 bytes
=========================================================================
```python
def f(p,r):
m=len(p)
for k in p:p[k]-=1
for _ in range(r):
for i in p:
if p[i]<0:continue
x=randrange(4)
if x<1:p[i]+=m;m=0
if x<2:p[i]-=~m//2;m+=~m//2
if x>2:m+=p[i]>0;p[i]-=1
if m<1:
for j in p:m+=p[j]>0;p[j]-=1
return p
from random import*
```
[Try it online!](https://tio.run/##RY/NbsIwEITveQqLU1yCyE851MFI/X8IhCrT2GWD7VhWQKCqffV0HaftyTsz36zW7tofOlsNQyMVUanLPGUJMVxLmzqaENV5ciRgiWNue9wteBG9t@B5YT9kOjZGEyKIioAibgu7dc7eO9uDPcngXjhWmli7pRN3WRcssHNuasPzP7cc3QX/NstlWZt5HH7jTcnQCsQmryNYTJnBhWEcb2rjTSPbRraNrJf9yWOWKN@Z8JcGHzCu8/3N4DzYPlXp5@x@78VBmBkjq4zMHkR/FdP8qAV4GcRXRipKk//SkzhDg0mF2LMGYUPnDsULyLPUKEoUr2LvQWodwhJ3FCtKhx8 "Python 3 – Try It Online")
* Thanks to Neil for spotting a bug (303 -> 311)
* Thanks to AAM111 for cutting out the `import math` and spotting a bug (311 -> 318)
* Thanks to c-- for some golfing suggestions (318 -> 294 and 294 -> 270)
Players that are out are shown as having negative coins.
### Explanation
```python
def f(p,r): # Create a function, f, which takes in the player dictionary, p, and the number of rounds, r
m=len(p) # Assign the money pot, m, to the number of players
for k in p:p[k]-=1 # And subtract one from each of the players (each player gives one coin to the pot)
for _ in range(r): # Loop r times (r rounds)
for i in p: # Go through each of the players
if p[i]<0:continue # If they are out of the game (money = -1), skip their turn
x=randrange(4) # Spin the dreidel (0 to 3)
if x<1:0 # If it's 0, do nothing
elif x<2:p[i]+=m;m=0 # If it's 1, add all the money from m to that player and set m to 0
elif x<3:a=(int(m)+m%2)//2;p[i]+=a;m-=a # If it's 2, add half the money to that player and reduce m
else:m+=1;p[i]-=1 # If it's 3, add 1 to m and remove 1 from the player
if m<1: # If m is 0
for j in p: # Go through each player
if p[j]>0:p[j]-=1;m+=1 # If they're not out of money, reduce by one and add that to m
else:p[j]=-1 # Otherwise, set their money to -1 (they are now out)
return p # At the end of all the rounds, return the final dictionary
from random import* # Import the random library for the dreidel
``` | C `-m32`, ~~233~~ 220 bytes + 4 bytes = 224 bytes
=================================================
-9 bytes thanks to ceilingcat
(linebreaks for "readability")
```c
m;k;i;j;l;f(p,r)int*p;{
for(l=wcslen(p);k<l;k+=2)p[k]--;
for(srand(p);r--;m=l/2)
for(i=0;i<l;k=rand(i+=2)%4)
if(~p[i])if(k?k<2?p[i]+=m,m=0:k<3?p[i]+=j=m-m/2,m-=j:++m,p[i]--:0,!m)
for(j=0;j<l;j+=2)p[j]>0?p[j]--,m++:(p[j]=-1);}
```
[Try it online!](https://tio.run/##bVDbTsMgGL73KbDJEhgQa6dejOGiPoKXW7Mga5W2sAZqPCz10a0/3aY39oL@h@8Emj9rPQxW1MKISjSixC3zxLhu2op9ufO4kW86NIXDLRH1ohE1lRlpV3XOuYj74JXbxqWHgZXNRUbi2MhUGIAbgLNajiAyuSKmxF/tyuRkXy/rRbaMNZWWWZnO68VsWUl7kVE7ydhhUzHLZTWn1I4DzuegW@JzO7pU4FKBS3UIVeW36TL@OGeW0jmOteSXLCWi7we4FbLKOEzQ/gzBt3nsVGf0RoVQ@A4H81nsSgwwgqREx1a/KI@mhKEkIWKkRR3l/SpHEu2vYXH35NWLsglDsbtX3Yc61g@NMr6AJu0P3BIDk6HZUWp8KpAz23cQS8VYLNCNOEU8@emdcQEg0RcwlObid693LgACck6RU7YAGP6bQfZ/Wa0H3RInk7Du1t1ku3YQM9LZweyYsB9PX3Sv3kHAs3741mWjnsPA7Sz7AQ "C (gcc) – Try It Online")
This is basically a port of [The Thonnu's python answer](https://codegolf.stackexchange.com/a/255706/).
The input is an `int[]` of the form `{5, "Abraham", 5, "Batya", 5, "Claire", 0};`, which is why the loops count by 2. This array will be modified by the function. We can get the length of that with `wcslen`.
Ungolfed old version:
```c
f(int *ptr, int rounds) {
int length = wcslen(ptr);
int money = length / 2; // one for each player
srand(ptr);
for (int i = 0; i < length; i += 2) ptr[i]--; // Decrement each by one
for (; rounds--; ) {
for (int i = 0; i < length; i += 2) {
int k = rand() % 4;
int half_pot = money / 2 + money % 2;
if (ptr[i] >= 0) {
k ?
k < 2 ? ptr[i] += money, money = 0 :
k < 3 ? ptr[i] += half_pot, money -= half_pot
: ++money, ptr[i]--
: 0;
if (!money) {
for (int j = 0; j < length; j += 2) {
if (ptr[j] > 0) {
ptr[j]--;
money++;
} else {
ptr[j] = -1;
}
}
}
}
}
}
}
``` |
255,697 | Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Happy Hanukkah!
A beloved Hanukkah tradition for many, the game of [Dreidel](https://en.wikipedia.org/wiki/Dreidel) (*s'vivon* in Hebrew) is a betting game (for money or for chocolate *gelt* (coins)) centered on the titular spinning tops called dreidels. Dreidels have four sides:
נ (nun), ג (gimel), ה (hei), and ש (shin), an acronym for the phrase "neis gadol haya sham": a great miracle happened there, referring to the famous Hanukkah miracle.
The game starts with an ante of one coin put forth by all players. Then, players take turns spinning the dreidel and lose or gain money according to the following rules:
* נ (nun): Do nothing
* ג (gimel): Win all the money in the pot
* ה (hei): Win half the money in the pot, rounding up
* ש (shin): Add one coin to the pot
If at any point the pot becomes empty, all players put forth one coin. If a player must put forth a coin and they have none, they are out of the game. The game ends when players agree to stop or when only one player is remaining.
---
Task
----
Your task is to implement the game of Dreidel.
Input:
* (mapping: str -> int) A number of players, guaranteed to be ≥2, each represented by a string. Each player maps to the starting number of coins for that player, guaranteed to be ≥1.
* (int) The number of rounds, guaranteed to be ≥1. (In each round, every player who's still in the game will spin the dreidel once).
Output:
* (mapping: str -> int) Each player and their corresponding final number of coins at the end of the game.
Rules:
* Standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply. Shortest answer in bytes wins!
* Dreidel outcomes must be random, and must appear with the same probability (25% for each outcome).
* Any reasonable form of input or output is allowed. For instance, to represent the mapping of players to coins, one can use a Python-style dictionary, an array of pairs, etc. The mapping need not have a consistent ordering.
+ All players must be represented in the output, even if they have no money left.
* You can use whatever order for the players within each round is easiest, as long as each player who's still in the game spins once per round.
Notes:
* It is not guaranteed that the total number of coins at the end of the game is equal to the total number of coins at the beginning of the game (there may be some left over in the pot.)
Examples: (bear in mind that results are random)
```python
>>> dreidel({"Abraham": 5, "Batya": 5, "Claire": 5}, 3)
{"Abraham": 3, "Batya": 8, "Claire": 4}
>>> dreidel({"David": 3, "Eliana": 9, "Fievel": 2, "Gabriella": 2}, 15)
{"David": 0, "Eliana": 16, "Fievel": 0, "Gabriella": 0}
``` | 2022/12/19 | [
"https://codegolf.stackexchange.com/questions/255697",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/47670/"
] | [Python](https://www.python.org), ~~197~~ 195 bytes
===================================================
-2 bytes thanks to @Arnauld using `-~p//2` instead of `p//2+p%2`
```python
from random import*
def f(n,c,m,i=0,p=0,s=0):
l=len(c);v=-~c[x:=i%l]and[-1,0,p,~-p//2][i//l&(s<0)and randrange(4)];c[x]+=v
if~-l-c.count(-1)and-~i<m*l:f(n,c,m,i+1,w:=p-v*(c[x]>=0),[s-1,l][w<1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVBLTsMwEN3nFFYkkN2OSYL4KY1BwDEsL1o3Bkv-KUlT2OQibLqBi3AKbsM0KixmRqN5b96b-fhK78NrDIfD524w_O7n23TRk24dtlisT7EbFtm2NcTQABo8WFFCwuhFyeqMOOHaQDVbjYJPWr7Vwp45hXTJK0AkTDwVxaWStijcOe2bkuFwFsB4aekVUyvkqaUYM2LNxB3XFzruwkB5dcTyyTZ-4ep_A8sK9rVIfFzQI_EejYDsUc4puW8qxU6nPOhoQ08EkddwA7cqM1Tmj5s2h_wpbjA_r723ba5gBkJVsix1FoXn_rTm7zO_)
Takes in the mapping as a list of names `n` and a list of coin counts `c` which are the same length, along with a number of rounds `r`.
Modifies the list of coins in place; the values indicate the number of coins, except for if `c[i]` is `-1`, which indicates that person `n[i]` is out of the game.
It works recursively, storing the following between calls (in addition to the current number of coins):
* `i`: How many players have played so far
* `p`: the size of the pot
* `s`: If positive, how many players need to contribute to the pot (set to `len(c)` when the pot is empty, otherwise decreased by one every call) | [Charcoal](https://github.com/somebody1234/Charcoal), 112 bytes
===============================================================
```
≔Lθζ≧×LθηUMθ⊖ιW∧η⊖LΦ謋κ⁰«≔§Eθλ±ηεF¬‹§θε⁰«≔‽⁴κ≔⎇‹κ²κ÷ζ~κκ§≔θε⁻§θεκF¬‹§θε⁰≧⁺κζ»F¬ζ«≔LΦθ›λ⁰ζUMθ⊖λ»≦⊖η»UMθ⎇›⁰ι⁰ι⭆¹θ`
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVLLTsMwEJS4ha-wcrIlI5UCEq9LobRCAoRKb1UPpl0Sq45DbLdAUb6ECwcQ_BJ8DesmqdIiRC727uzOzHrz8jmKhRmlQr2-vk_d3db-90beslZGml6AjlxMM8bJnB1tXor7AujJKHa0LxOwnNSK4qLoNE0Socc046QNIwMJaAdjKhnCD7FUQGgL4XgVLnk6UjkwvvcqdZi0lk44abDiI8-bQWmu5c71GB4pCvpqhfpXEAkHNGZ4BxQL7lJD6JKn6sg8uuD0dBVfDy2nCd1FZOJ7q3wfjBbmaWml6Qs4OdeuLWdyDHTOyYl0D9KCV5owtsZQl-XkUurpLysTtqj_zy4jayu4VlO7cOPXE-S1geerw_163K4B4a-qIC4Zgr-3p1gpsbRAa3Cx-3xt-9XTVWINTqSfxB9Yfm2kdvTG4RH5LW5zkmH-zd6ObPkvfgzCrZkKh1_Hg-ewLfC9w0Oyw0l4pqTQAoMDDDoSZqAwaGLQFbdGglIebOacbO8NC64f) Link is to verbose version of code. Explanation:
```
≔Lθζ
```
Each player puts one coin into the pot.
```
≧×Lθη
```
The total potential number of plays is the number of players multiplied by the number of rounds.
```
UMθ⊖ι
```
Subtract one coin from each player (which they put into the pot above).
```
W∧η⊖LΦ謋κ⁰«
```
Repeat while there are still plays left and multiple players playing.
```
≔§Eθλ±ηε
```
Get the current player.
```
F¬‹§θε⁰«
```
If they are not out of the game:
```
≔‽⁴κ
```
Spin the dreidel, producing a random number from `0` to `3`.
```
≔⎇‹κ²κ÷ζ~κκ
```
If it is less than `2` then the player loses this amount, otherwise they lose the pot divided by the bitwise not of the random number. Since the latter is negative, they win either the pot or half of the pot rounded up.
```
§≔θε⁻§θεκ
```
Subtract the loss from the player.
```
F¬‹§θε⁰≧⁺κζ
```
If the player is still in the game then add the player's loss to the pot.
```
»F¬ζ«
```
If the pot is now zero:
```
≔LΦθ›λ⁰ζ
```
Put a coin into the pot for each player that is still in the game.
```
UMθ⊖λ
```
Subtract one coin from each player.
```
»≦⊖η
```
Move on to the next player.
```
»UMθ⎇›⁰ι⁰ι
```
Set the coins of players that are out of the game to `0`.
```
⭆¹θ
```
Output the final number of coins for each player.
I wrote this version before all of the rules had been clarified, so it appears that I might be able to save 16 bytes by considering the players in reverse order, not refreshing the pot if the first player scoops it on their very last spin, and outputting arbitrary negative values for players who are out of the game:
```
≔⁰ζ≧×LθηW∧η⊖LΦ謋κ⁰«F¬ζ«≔LΦθ›λ⁰ζUMθ⊖λ»≦⊖η≔§EθληεF¬‹§θε⁰«≔‽⁴κ≔⎇‹κ²κ÷ζ~κκ§≔θε⁻§θεκF¬‹§θε⁰≧⁺κζ»»⭆¹θ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZLPTsJAEMYTb-Upxp62yZIAauK_C4oQEjEEuREOCwx0w3ZrdxdQCE_ihYNGX0mfxt22EJSDvbQz83Xm983u6-cwZGoYM7HZvM_MuHj-fXRc1ZpPJClRWAZXhRZ7yhIdPgkN6fIINYV7lBMTkiSgEFrRIuQCgVTliIQUajhUGKE0OCK5sM6FQUUSCg-xsUmtyZRCKcgeWBW8cayAuOIyi70c46BBQyFznyL7P6P0PMt5G0cRswjJbwQROMG64O2skL1yZmA7rWqacoTPxEpdG5H6o4BOsiNM8bfKxFVTlH3qjuWII3JqK9MUL893UUmmXnYbqDgBhaY0NT7nIyRLCjfcLLhGN2maGtzvsD-WQovL2QHKNPX7L24Af462LWY6pVlm-1oX2opLQx6NfU3cRsoUEtv8TQ-GOr8vHz2_OBd-_-u6t_JrzHrwL-GEgn8nOJPMBhc2qHOco7BBxQYNNlAchXDFyppC-ayf9foB) Link is to verbose version of code. |
255,697 | Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Happy Hanukkah!
A beloved Hanukkah tradition for many, the game of [Dreidel](https://en.wikipedia.org/wiki/Dreidel) (*s'vivon* in Hebrew) is a betting game (for money or for chocolate *gelt* (coins)) centered on the titular spinning tops called dreidels. Dreidels have four sides:
נ (nun), ג (gimel), ה (hei), and ש (shin), an acronym for the phrase "neis gadol haya sham": a great miracle happened there, referring to the famous Hanukkah miracle.
The game starts with an ante of one coin put forth by all players. Then, players take turns spinning the dreidel and lose or gain money according to the following rules:
* נ (nun): Do nothing
* ג (gimel): Win all the money in the pot
* ה (hei): Win half the money in the pot, rounding up
* ש (shin): Add one coin to the pot
If at any point the pot becomes empty, all players put forth one coin. If a player must put forth a coin and they have none, they are out of the game. The game ends when players agree to stop or when only one player is remaining.
---
Task
----
Your task is to implement the game of Dreidel.
Input:
* (mapping: str -> int) A number of players, guaranteed to be ≥2, each represented by a string. Each player maps to the starting number of coins for that player, guaranteed to be ≥1.
* (int) The number of rounds, guaranteed to be ≥1. (In each round, every player who's still in the game will spin the dreidel once).
Output:
* (mapping: str -> int) Each player and their corresponding final number of coins at the end of the game.
Rules:
* Standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply. Shortest answer in bytes wins!
* Dreidel outcomes must be random, and must appear with the same probability (25% for each outcome).
* Any reasonable form of input or output is allowed. For instance, to represent the mapping of players to coins, one can use a Python-style dictionary, an array of pairs, etc. The mapping need not have a consistent ordering.
+ All players must be represented in the output, even if they have no money left.
* You can use whatever order for the players within each round is easiest, as long as each player who's still in the game spins once per round.
Notes:
* It is not guaranteed that the total number of coins at the end of the game is equal to the total number of coins at the beginning of the game (there may be some left over in the pot.)
Examples: (bear in mind that results are random)
```python
>>> dreidel({"Abraham": 5, "Batya": 5, "Claire": 5}, 3)
{"Abraham": 3, "Batya": 8, "Claire": 4}
>>> dreidel({"David": 3, "Eliana": 9, "Fievel": 2, "Gabriella": 2}, 15)
{"David": 0, "Eliana": 16, "Fievel": 0, "Gabriella": 0}
``` | 2022/12/19 | [
"https://codegolf.stackexchange.com/questions/255697",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/47670/"
] | [Charcoal](https://github.com/somebody1234/Charcoal), 112 bytes
===============================================================
```
≔Lθζ≧×LθηUMθ⊖ιW∧η⊖LΦ謋κ⁰«≔§Eθλ±ηεF¬‹§θε⁰«≔‽⁴κ≔⎇‹κ²κ÷ζ~κκ§≔θε⁻§θεκF¬‹§θε⁰≧⁺κζ»F¬ζ«≔LΦθ›λ⁰ζUMθ⊖λ»≦⊖η»UMθ⎇›⁰ι⁰ι⭆¹θ`
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVLLTsMwEJS4ha-wcrIlI5UCEq9LobRCAoRKb1UPpl0Sq45DbLdAUb6ECwcQ_BJ8DesmqdIiRC727uzOzHrz8jmKhRmlQr2-vk_d3db-90beslZGml6AjlxMM8bJnB1tXor7AujJKHa0LxOwnNSK4qLoNE0Socc046QNIwMJaAdjKhnCD7FUQGgL4XgVLnk6UjkwvvcqdZi0lk44abDiI8-bQWmu5c71GB4pCvpqhfpXEAkHNGZ4BxQL7lJD6JKn6sg8uuD0dBVfDy2nCd1FZOJ7q3wfjBbmaWml6Qs4OdeuLWdyDHTOyYl0D9KCV5owtsZQl-XkUurpLysTtqj_zy4jayu4VlO7cOPXE-S1geerw_163K4B4a-qIC4Zgr-3p1gpsbRAa3Cx-3xt-9XTVWINTqSfxB9Yfm2kdvTG4RH5LW5zkmH-zd6ObPkvfgzCrZkKh1_Hg-ewLfC9w0Oyw0l4pqTQAoMDDDoSZqAwaGLQFbdGglIebOacbO8NC64f) Link is to verbose version of code. Explanation:
```
≔Lθζ
```
Each player puts one coin into the pot.
```
≧×Lθη
```
The total potential number of plays is the number of players multiplied by the number of rounds.
```
UMθ⊖ι
```
Subtract one coin from each player (which they put into the pot above).
```
W∧η⊖LΦ謋κ⁰«
```
Repeat while there are still plays left and multiple players playing.
```
≔§Eθλ±ηε
```
Get the current player.
```
F¬‹§θε⁰«
```
If they are not out of the game:
```
≔‽⁴κ
```
Spin the dreidel, producing a random number from `0` to `3`.
```
≔⎇‹κ²κ÷ζ~κκ
```
If it is less than `2` then the player loses this amount, otherwise they lose the pot divided by the bitwise not of the random number. Since the latter is negative, they win either the pot or half of the pot rounded up.
```
§≔θε⁻§θεκ
```
Subtract the loss from the player.
```
F¬‹§θε⁰≧⁺κζ
```
If the player is still in the game then add the player's loss to the pot.
```
»F¬ζ«
```
If the pot is now zero:
```
≔LΦθ›λ⁰ζ
```
Put a coin into the pot for each player that is still in the game.
```
UMθ⊖λ
```
Subtract one coin from each player.
```
»≦⊖η
```
Move on to the next player.
```
»UMθ⎇›⁰ι⁰ι
```
Set the coins of players that are out of the game to `0`.
```
⭆¹θ
```
Output the final number of coins for each player.
I wrote this version before all of the rules had been clarified, so it appears that I might be able to save 16 bytes by considering the players in reverse order, not refreshing the pot if the first player scoops it on their very last spin, and outputting arbitrary negative values for players who are out of the game:
```
≔⁰ζ≧×LθηW∧η⊖LΦ謋κ⁰«F¬ζ«≔LΦθ›λ⁰ζUMθ⊖λ»≦⊖η≔§EθληεF¬‹§θε⁰«≔‽⁴κ≔⎇‹κ²κ÷ζ~κκ§≔θε⁻§θεκF¬‹§θε⁰≧⁺κζ»»⭆¹θ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hZLPTsJAEMYTb-Upxp62yZIAauK_C4oQEjEEuREOCwx0w3ZrdxdQCE_ihYNGX0mfxt22EJSDvbQz83Xm983u6-cwZGoYM7HZvM_MuHj-fXRc1ZpPJClRWAZXhRZ7yhIdPgkN6fIINYV7lBMTkiSgEFrRIuQCgVTliIQUajhUGKE0OCK5sM6FQUUSCg-xsUmtyZRCKcgeWBW8cayAuOIyi70c46BBQyFznyL7P6P0PMt5G0cRswjJbwQROMG64O2skL1yZmA7rWqacoTPxEpdG5H6o4BOsiNM8bfKxFVTlH3qjuWII3JqK9MUL893UUmmXnYbqDgBhaY0NT7nIyRLCjfcLLhGN2maGtzvsD-WQovL2QHKNPX7L24Af462LWY6pVlm-1oX2opLQx6NfU3cRsoUEtv8TQ-GOr8vHz2_OBd-_-u6t_JrzHrwL-GEgn8nOJPMBhc2qHOco7BBxQYNNlAchXDFyppC-ayf9foB) Link is to verbose version of code. | C `-m32`, ~~233~~ 220 bytes + 4 bytes = 224 bytes
=================================================
-9 bytes thanks to ceilingcat
(linebreaks for "readability")
```c
m;k;i;j;l;f(p,r)int*p;{
for(l=wcslen(p);k<l;k+=2)p[k]--;
for(srand(p);r--;m=l/2)
for(i=0;i<l;k=rand(i+=2)%4)
if(~p[i])if(k?k<2?p[i]+=m,m=0:k<3?p[i]+=j=m-m/2,m-=j:++m,p[i]--:0,!m)
for(j=0;j<l;j+=2)p[j]>0?p[j]--,m++:(p[j]=-1);}
```
[Try it online!](https://tio.run/##bVDbTsMgGL73KbDJEhgQa6dejOGiPoKXW7Mga5W2sAZqPCz10a0/3aY39oL@h@8Emj9rPQxW1MKISjSixC3zxLhu2op9ufO4kW86NIXDLRH1ohE1lRlpV3XOuYj74JXbxqWHgZXNRUbi2MhUGIAbgLNajiAyuSKmxF/tyuRkXy/rRbaMNZWWWZnO68VsWUl7kVE7ydhhUzHLZTWn1I4DzuegW@JzO7pU4FKBS3UIVeW36TL@OGeW0jmOteSXLCWi7we4FbLKOEzQ/gzBt3nsVGf0RoVQ@A4H81nsSgwwgqREx1a/KI@mhKEkIWKkRR3l/SpHEu2vYXH35NWLsglDsbtX3Yc61g@NMr6AJu0P3BIDk6HZUWp8KpAz23cQS8VYLNCNOEU8@emdcQEg0RcwlObid693LgACck6RU7YAGP6bQfZ/Wa0H3RInk7Du1t1ku3YQM9LZweyYsB9PX3Sv3kHAs3741mWjnsPA7Sz7AQ "C (gcc) – Try It Online")
This is basically a port of [The Thonnu's python answer](https://codegolf.stackexchange.com/a/255706/).
The input is an `int[]` of the form `{5, "Abraham", 5, "Batya", 5, "Claire", 0};`, which is why the loops count by 2. This array will be modified by the function. We can get the length of that with `wcslen`.
Ungolfed old version:
```c
f(int *ptr, int rounds) {
int length = wcslen(ptr);
int money = length / 2; // one for each player
srand(ptr);
for (int i = 0; i < length; i += 2) ptr[i]--; // Decrement each by one
for (; rounds--; ) {
for (int i = 0; i < length; i += 2) {
int k = rand() % 4;
int half_pot = money / 2 + money % 2;
if (ptr[i] >= 0) {
k ?
k < 2 ? ptr[i] += money, money = 0 :
k < 3 ? ptr[i] += half_pot, money -= half_pot
: ++money, ptr[i]--
: 0;
if (!money) {
for (int j = 0; j < length; j += 2) {
if (ptr[j] > 0) {
ptr[j]--;
money++;
} else {
ptr[j] = -1;
}
}
}
}
}
}
}
``` |
255,697 | Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Happy Hanukkah!
A beloved Hanukkah tradition for many, the game of [Dreidel](https://en.wikipedia.org/wiki/Dreidel) (*s'vivon* in Hebrew) is a betting game (for money or for chocolate *gelt* (coins)) centered on the titular spinning tops called dreidels. Dreidels have four sides:
נ (nun), ג (gimel), ה (hei), and ש (shin), an acronym for the phrase "neis gadol haya sham": a great miracle happened there, referring to the famous Hanukkah miracle.
The game starts with an ante of one coin put forth by all players. Then, players take turns spinning the dreidel and lose or gain money according to the following rules:
* נ (nun): Do nothing
* ג (gimel): Win all the money in the pot
* ה (hei): Win half the money in the pot, rounding up
* ש (shin): Add one coin to the pot
If at any point the pot becomes empty, all players put forth one coin. If a player must put forth a coin and they have none, they are out of the game. The game ends when players agree to stop or when only one player is remaining.
---
Task
----
Your task is to implement the game of Dreidel.
Input:
* (mapping: str -> int) A number of players, guaranteed to be ≥2, each represented by a string. Each player maps to the starting number of coins for that player, guaranteed to be ≥1.
* (int) The number of rounds, guaranteed to be ≥1. (In each round, every player who's still in the game will spin the dreidel once).
Output:
* (mapping: str -> int) Each player and their corresponding final number of coins at the end of the game.
Rules:
* Standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply. Shortest answer in bytes wins!
* Dreidel outcomes must be random, and must appear with the same probability (25% for each outcome).
* Any reasonable form of input or output is allowed. For instance, to represent the mapping of players to coins, one can use a Python-style dictionary, an array of pairs, etc. The mapping need not have a consistent ordering.
+ All players must be represented in the output, even if they have no money left.
* You can use whatever order for the players within each round is easiest, as long as each player who's still in the game spins once per round.
Notes:
* It is not guaranteed that the total number of coins at the end of the game is equal to the total number of coins at the beginning of the game (there may be some left over in the pot.)
Examples: (bear in mind that results are random)
```python
>>> dreidel({"Abraham": 5, "Batya": 5, "Claire": 5}, 3)
{"Abraham": 3, "Batya": 8, "Claire": 4}
>>> dreidel({"David": 3, "Eliana": 9, "Fievel": 2, "Gabriella": 2}, 15)
{"David": 0, "Eliana": 16, "Fievel": 0, "Gabriella": 0}
``` | 2022/12/19 | [
"https://codegolf.stackexchange.com/questions/255697",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/47670/"
] | [Python](https://www.python.org), ~~197~~ 195 bytes
===================================================
-2 bytes thanks to @Arnauld using `-~p//2` instead of `p//2+p%2`
```python
from random import*
def f(n,c,m,i=0,p=0,s=0):
l=len(c);v=-~c[x:=i%l]and[-1,0,p,~-p//2][i//l&(s<0)and randrange(4)];c[x]+=v
if~-l-c.count(-1)and-~i<m*l:f(n,c,m,i+1,w:=p-v*(c[x]>=0),[s-1,l][w<1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVBLTsMwEN3nFFYkkN2OSYL4KY1BwDEsL1o3Bkv-KUlT2OQibLqBi3AKbsM0KixmRqN5b96b-fhK78NrDIfD524w_O7n23TRk24dtlisT7EbFtm2NcTQABo8WFFCwuhFyeqMOOHaQDVbjYJPWr7Vwp45hXTJK0AkTDwVxaWStijcOe2bkuFwFsB4aekVUyvkqaUYM2LNxB3XFzruwkB5dcTyyTZ-4ep_A8sK9rVIfFzQI_EejYDsUc4puW8qxU6nPOhoQ08EkddwA7cqM1Tmj5s2h_wpbjA_r723ba5gBkJVsix1FoXn_rTm7zO_)
Takes in the mapping as a list of names `n` and a list of coin counts `c` which are the same length, along with a number of rounds `r`.
Modifies the list of coins in place; the values indicate the number of coins, except for if `c[i]` is `-1`, which indicates that person `n[i]` is out of the game.
It works recursively, storing the following between calls (in addition to the current number of coins):
* `i`: How many players have played so far
* `p`: the size of the pot
* `s`: If positive, how many players need to contribute to the pot (set to `len(c)` when the pot is empty, otherwise decreased by one every call) | JavaScript, ~~167~~ ~~165~~ 164 bytes
=====================================
Been a long, long time since I tried golfing anything this complex in JS. So much so that I made a complete *mess* of things in my initial solution! This version seems to work properly, although it's pretty hideous.
---
Takes the player data as a 2D-array. Call with `f(rounds)(players)`. Mutates the original input array. Remove the `&&--n` to ignore the rounds and allow the game to play through to the last player standing.
```javascript
(n,p=o=0)=>g=a=>a.map(x=>x.o||(p||a.map(x=>x[1]?--x[++p,1]:x.o||=++o),x.o||(r=[0,p,p+1>>1,-1][Math.random()*4|0],r+1||x[1]?x[p-=r,1]+=r:x.o=++o),x))[o+1]&&--n&&g(a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hY_PSgMxEIfvfYqyhyUxydJYCypkxf8gqAePIYep3d0G0iSka9lC3sRLkfoevoZv4zYtevQ0fMNvvpl531o3qzYftfh8a2t2-r1FlnrhxAiLshEgSigW4FEnyq5wMSIf419HcnXBWCcJ8ZSr85QQhDhM9-Eg5Ih66gkvS04ZV_IR2nkRwM7cAuGjkzhSNBAeY1J10jMRehMRYSc7qDCWjnCV54zZPG8Q4MOtXzWyYowRCCmzy2mAOSwyOpwoOpTZFbRr-KVrAzpUCRUevDq7dKYqjGvQw8vzU7Fsg7aNrte9HA8GOy-fHMQ3sNKzfnKcRLdGg915zxLe6WpVmR6PE97DNOjKGEidfzft_9hs9vUH)
Saved 2 bytes thanks to l4m2
Explanation
-----------
```javascript
(n, // Take the number of rounds as n
p=o=0)=> // Initialise p (the pot) and o (players out of the game) as 0
g=a=> // Named function taking the array of players as a
a.map(x=> // Map each x in a
x.o||( // Return property o of x (initially undefined) OR
p||a.map(x=> // If p is 0 then map each x in a
x[1]? // If the 2nd element (coins) of x is not 0
--x[++p,1] // Decrement it and increment p
:x.o||=++o // Else get the OR of x.o and o incremented, eliminating the current player
),x.o||( // Return x.o OR
r= // Assign to r
[0,p,p+1>>1,-1] // Array of all possible results
[Math.random()*4|0], // Get a random element
r+1||x[1]? // If r is not -1 or the player has coins
x[p-=r,1]+=r // Increment their coins by r and decrement p by r
:x.o=++o // Else increment o and assign it to x.o, eliminating the current player
) //
,x) // Return x
)[o+1] // If there are at least 2 players left in the game
&&--n // And we have rounds left to play
&&g(a) // Then call g again
``` |
255,697 | Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Happy Hanukkah!
A beloved Hanukkah tradition for many, the game of [Dreidel](https://en.wikipedia.org/wiki/Dreidel) (*s'vivon* in Hebrew) is a betting game (for money or for chocolate *gelt* (coins)) centered on the titular spinning tops called dreidels. Dreidels have four sides:
נ (nun), ג (gimel), ה (hei), and ש (shin), an acronym for the phrase "neis gadol haya sham": a great miracle happened there, referring to the famous Hanukkah miracle.
The game starts with an ante of one coin put forth by all players. Then, players take turns spinning the dreidel and lose or gain money according to the following rules:
* נ (nun): Do nothing
* ג (gimel): Win all the money in the pot
* ה (hei): Win half the money in the pot, rounding up
* ש (shin): Add one coin to the pot
If at any point the pot becomes empty, all players put forth one coin. If a player must put forth a coin and they have none, they are out of the game. The game ends when players agree to stop or when only one player is remaining.
---
Task
----
Your task is to implement the game of Dreidel.
Input:
* (mapping: str -> int) A number of players, guaranteed to be ≥2, each represented by a string. Each player maps to the starting number of coins for that player, guaranteed to be ≥1.
* (int) The number of rounds, guaranteed to be ≥1. (In each round, every player who's still in the game will spin the dreidel once).
Output:
* (mapping: str -> int) Each player and their corresponding final number of coins at the end of the game.
Rules:
* Standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply. Shortest answer in bytes wins!
* Dreidel outcomes must be random, and must appear with the same probability (25% for each outcome).
* Any reasonable form of input or output is allowed. For instance, to represent the mapping of players to coins, one can use a Python-style dictionary, an array of pairs, etc. The mapping need not have a consistent ordering.
+ All players must be represented in the output, even if they have no money left.
* You can use whatever order for the players within each round is easiest, as long as each player who's still in the game spins once per round.
Notes:
* It is not guaranteed that the total number of coins at the end of the game is equal to the total number of coins at the beginning of the game (there may be some left over in the pot.)
Examples: (bear in mind that results are random)
```python
>>> dreidel({"Abraham": 5, "Batya": 5, "Claire": 5}, 3)
{"Abraham": 3, "Batya": 8, "Claire": 4}
>>> dreidel({"David": 3, "Eliana": 9, "Fievel": 2, "Gabriella": 2}, 15)
{"David": 0, "Eliana": 16, "Fievel": 0, "Gabriella": 0}
``` | 2022/12/19 | [
"https://codegolf.stackexchange.com/questions/255697",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/47670/"
] | JavaScript, ~~167~~ ~~165~~ 164 bytes
=====================================
Been a long, long time since I tried golfing anything this complex in JS. So much so that I made a complete *mess* of things in my initial solution! This version seems to work properly, although it's pretty hideous.
---
Takes the player data as a 2D-array. Call with `f(rounds)(players)`. Mutates the original input array. Remove the `&&--n` to ignore the rounds and allow the game to play through to the last player standing.
```javascript
(n,p=o=0)=>g=a=>a.map(x=>x.o||(p||a.map(x=>x[1]?--x[++p,1]:x.o||=++o),x.o||(r=[0,p,p+1>>1,-1][Math.random()*4|0],r+1||x[1]?x[p-=r,1]+=r:x.o=++o),x))[o+1]&&--n&&g(a)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hY_PSgMxEIfvfYqyhyUxydJYCypkxf8gqAePIYep3d0G0iSka9lC3sRLkfoevoZv4zYtevQ0fMNvvpl531o3qzYftfh8a2t2-r1FlnrhxAiLshEgSigW4FEnyq5wMSIf419HcnXBWCcJ8ZSr85QQhDhM9-Eg5Ih66gkvS04ZV_IR2nkRwM7cAuGjkzhSNBAeY1J10jMRehMRYSc7qDCWjnCV54zZPG8Q4MOtXzWyYowRCCmzy2mAOSwyOpwoOpTZFbRr-KVrAzpUCRUevDq7dKYqjGvQw8vzU7Fsg7aNrte9HA8GOy-fHMQ3sNKzfnKcRLdGg915zxLe6WpVmR6PE97DNOjKGEidfzft_9hs9vUH)
Saved 2 bytes thanks to l4m2
Explanation
-----------
```javascript
(n, // Take the number of rounds as n
p=o=0)=> // Initialise p (the pot) and o (players out of the game) as 0
g=a=> // Named function taking the array of players as a
a.map(x=> // Map each x in a
x.o||( // Return property o of x (initially undefined) OR
p||a.map(x=> // If p is 0 then map each x in a
x[1]? // If the 2nd element (coins) of x is not 0
--x[++p,1] // Decrement it and increment p
:x.o||=++o // Else get the OR of x.o and o incremented, eliminating the current player
),x.o||( // Return x.o OR
r= // Assign to r
[0,p,p+1>>1,-1] // Array of all possible results
[Math.random()*4|0], // Get a random element
r+1||x[1]? // If r is not -1 or the player has coins
x[p-=r,1]+=r // Increment their coins by r and decrement p by r
:x.o=++o // Else increment o and assign it to x.o, eliminating the current player
) //
,x) // Return x
)[o+1] // If there are at least 2 players left in the game
&&--n // And we have rounds left to play
&&g(a) // Then call g again
``` | C `-m32`, ~~233~~ 220 bytes + 4 bytes = 224 bytes
=================================================
-9 bytes thanks to ceilingcat
(linebreaks for "readability")
```c
m;k;i;j;l;f(p,r)int*p;{
for(l=wcslen(p);k<l;k+=2)p[k]--;
for(srand(p);r--;m=l/2)
for(i=0;i<l;k=rand(i+=2)%4)
if(~p[i])if(k?k<2?p[i]+=m,m=0:k<3?p[i]+=j=m-m/2,m-=j:++m,p[i]--:0,!m)
for(j=0;j<l;j+=2)p[j]>0?p[j]--,m++:(p[j]=-1);}
```
[Try it online!](https://tio.run/##bVDbTsMgGL73KbDJEhgQa6dejOGiPoKXW7Mga5W2sAZqPCz10a0/3aY39oL@h@8Emj9rPQxW1MKISjSixC3zxLhu2op9ufO4kW86NIXDLRH1ohE1lRlpV3XOuYj74JXbxqWHgZXNRUbi2MhUGIAbgLNajiAyuSKmxF/tyuRkXy/rRbaMNZWWWZnO68VsWUl7kVE7ydhhUzHLZTWn1I4DzuegW@JzO7pU4FKBS3UIVeW36TL@OGeW0jmOteSXLCWi7we4FbLKOEzQ/gzBt3nsVGf0RoVQ@A4H81nsSgwwgqREx1a/KI@mhKEkIWKkRR3l/SpHEu2vYXH35NWLsglDsbtX3Yc61g@NMr6AJu0P3BIDk6HZUWp8KpAz23cQS8VYLNCNOEU8@emdcQEg0RcwlObid693LgACck6RU7YAGP6bQfZ/Wa0H3RInk7Du1t1ku3YQM9LZweyYsB9PX3Sv3kHAs3741mWjnsPA7Sz7AQ "C (gcc) – Try It Online")
This is basically a port of [The Thonnu's python answer](https://codegolf.stackexchange.com/a/255706/).
The input is an `int[]` of the form `{5, "Abraham", 5, "Batya", 5, "Claire", 0};`, which is why the loops count by 2. This array will be modified by the function. We can get the length of that with `wcslen`.
Ungolfed old version:
```c
f(int *ptr, int rounds) {
int length = wcslen(ptr);
int money = length / 2; // one for each player
srand(ptr);
for (int i = 0; i < length; i += 2) ptr[i]--; // Decrement each by one
for (; rounds--; ) {
for (int i = 0; i < length; i += 2) {
int k = rand() % 4;
int half_pot = money / 2 + money % 2;
if (ptr[i] >= 0) {
k ?
k < 2 ? ptr[i] += money, money = 0 :
k < 3 ? ptr[i] += half_pot, money -= half_pot
: ++money, ptr[i]--
: 0;
if (!money) {
for (int j = 0; j < length; j += 2) {
if (ptr[j] > 0) {
ptr[j]--;
money++;
} else {
ptr[j] = -1;
}
}
}
}
}
}
}
``` |
255,697 | Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
Happy Hanukkah!
A beloved Hanukkah tradition for many, the game of [Dreidel](https://en.wikipedia.org/wiki/Dreidel) (*s'vivon* in Hebrew) is a betting game (for money or for chocolate *gelt* (coins)) centered on the titular spinning tops called dreidels. Dreidels have four sides:
נ (nun), ג (gimel), ה (hei), and ש (shin), an acronym for the phrase "neis gadol haya sham": a great miracle happened there, referring to the famous Hanukkah miracle.
The game starts with an ante of one coin put forth by all players. Then, players take turns spinning the dreidel and lose or gain money according to the following rules:
* נ (nun): Do nothing
* ג (gimel): Win all the money in the pot
* ה (hei): Win half the money in the pot, rounding up
* ש (shin): Add one coin to the pot
If at any point the pot becomes empty, all players put forth one coin. If a player must put forth a coin and they have none, they are out of the game. The game ends when players agree to stop or when only one player is remaining.
---
Task
----
Your task is to implement the game of Dreidel.
Input:
* (mapping: str -> int) A number of players, guaranteed to be ≥2, each represented by a string. Each player maps to the starting number of coins for that player, guaranteed to be ≥1.
* (int) The number of rounds, guaranteed to be ≥1. (In each round, every player who's still in the game will spin the dreidel once).
Output:
* (mapping: str -> int) Each player and their corresponding final number of coins at the end of the game.
Rules:
* Standard rules of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") apply. Shortest answer in bytes wins!
* Dreidel outcomes must be random, and must appear with the same probability (25% for each outcome).
* Any reasonable form of input or output is allowed. For instance, to represent the mapping of players to coins, one can use a Python-style dictionary, an array of pairs, etc. The mapping need not have a consistent ordering.
+ All players must be represented in the output, even if they have no money left.
* You can use whatever order for the players within each round is easiest, as long as each player who's still in the game spins once per round.
Notes:
* It is not guaranteed that the total number of coins at the end of the game is equal to the total number of coins at the beginning of the game (there may be some left over in the pot.)
Examples: (bear in mind that results are random)
```python
>>> dreidel({"Abraham": 5, "Batya": 5, "Claire": 5}, 3)
{"Abraham": 3, "Batya": 8, "Claire": 4}
>>> dreidel({"David": 3, "Eliana": 9, "Fievel": 2, "Gabriella": 2}, 15)
{"David": 0, "Eliana": 16, "Fievel": 0, "Gabriella": 0}
``` | 2022/12/19 | [
"https://codegolf.stackexchange.com/questions/255697",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/47670/"
] | [Python](https://www.python.org), ~~197~~ 195 bytes
===================================================
-2 bytes thanks to @Arnauld using `-~p//2` instead of `p//2+p%2`
```python
from random import*
def f(n,c,m,i=0,p=0,s=0):
l=len(c);v=-~c[x:=i%l]and[-1,0,p,~-p//2][i//l&(s<0)and randrange(4)];c[x]+=v
if~-l-c.count(-1)and-~i<m*l:f(n,c,m,i+1,w:=p-v*(c[x]>=0),[s-1,l][w<1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVBLTsMwEN3nFFYkkN2OSYL4KY1BwDEsL1o3Bkv-KUlT2OQibLqBi3AKbsM0KixmRqN5b96b-fhK78NrDIfD524w_O7n23TRk24dtlisT7EbFtm2NcTQABo8WFFCwuhFyeqMOOHaQDVbjYJPWr7Vwp45hXTJK0AkTDwVxaWStijcOe2bkuFwFsB4aekVUyvkqaUYM2LNxB3XFzruwkB5dcTyyTZ-4ep_A8sK9rVIfFzQI_EejYDsUc4puW8qxU6nPOhoQ08EkddwA7cqM1Tmj5s2h_wpbjA_r723ba5gBkJVsix1FoXn_rTm7zO_)
Takes in the mapping as a list of names `n` and a list of coin counts `c` which are the same length, along with a number of rounds `r`.
Modifies the list of coins in place; the values indicate the number of coins, except for if `c[i]` is `-1`, which indicates that person `n[i]` is out of the game.
It works recursively, storing the following between calls (in addition to the current number of coins):
* `i`: How many players have played so far
* `p`: the size of the pot
* `s`: If positive, how many players need to contribute to the pot (set to `len(c)` when the pot is empty, otherwise decreased by one every call) | C `-m32`, ~~233~~ 220 bytes + 4 bytes = 224 bytes
=================================================
-9 bytes thanks to ceilingcat
(linebreaks for "readability")
```c
m;k;i;j;l;f(p,r)int*p;{
for(l=wcslen(p);k<l;k+=2)p[k]--;
for(srand(p);r--;m=l/2)
for(i=0;i<l;k=rand(i+=2)%4)
if(~p[i])if(k?k<2?p[i]+=m,m=0:k<3?p[i]+=j=m-m/2,m-=j:++m,p[i]--:0,!m)
for(j=0;j<l;j+=2)p[j]>0?p[j]--,m++:(p[j]=-1);}
```
[Try it online!](https://tio.run/##bVDbTsMgGL73KbDJEhgQa6dejOGiPoKXW7Mga5W2sAZqPCz10a0/3aY39oL@h@8Emj9rPQxW1MKISjSixC3zxLhu2op9ufO4kW86NIXDLRH1ohE1lRlpV3XOuYj74JXbxqWHgZXNRUbi2MhUGIAbgLNajiAyuSKmxF/tyuRkXy/rRbaMNZWWWZnO68VsWUl7kVE7ydhhUzHLZTWn1I4DzuegW@JzO7pU4FKBS3UIVeW36TL@OGeW0jmOteSXLCWi7we4FbLKOEzQ/gzBt3nsVGf0RoVQ@A4H81nsSgwwgqREx1a/KI@mhKEkIWKkRR3l/SpHEu2vYXH35NWLsglDsbtX3Yc61g@NMr6AJu0P3BIDk6HZUWp8KpAz23cQS8VYLNCNOEU8@emdcQEg0RcwlObid693LgACck6RU7YAGP6bQfZ/Wa0H3RInk7Du1t1ku3YQM9LZweyYsB9PX3Sv3kHAs3741mWjnsPA7Sz7AQ "C (gcc) – Try It Online")
This is basically a port of [The Thonnu's python answer](https://codegolf.stackexchange.com/a/255706/).
The input is an `int[]` of the form `{5, "Abraham", 5, "Batya", 5, "Claire", 0};`, which is why the loops count by 2. This array will be modified by the function. We can get the length of that with `wcslen`.
Ungolfed old version:
```c
f(int *ptr, int rounds) {
int length = wcslen(ptr);
int money = length / 2; // one for each player
srand(ptr);
for (int i = 0; i < length; i += 2) ptr[i]--; // Decrement each by one
for (; rounds--; ) {
for (int i = 0; i < length; i += 2) {
int k = rand() % 4;
int half_pot = money / 2 + money % 2;
if (ptr[i] >= 0) {
k ?
k < 2 ? ptr[i] += money, money = 0 :
k < 3 ? ptr[i] += half_pot, money -= half_pot
: ++money, ptr[i]--
: 0;
if (!money) {
for (int j = 0; j < length; j += 2) {
if (ptr[j] > 0) {
ptr[j]--;
money++;
} else {
ptr[j] = -1;
}
}
}
}
}
}
}
``` |
47,243,447 | I have an interval of integers and I need to find all unique cuboids which have a volume that falls within said interval.
I came up with a loop that goes over all uniqe combinations of 3 numbers (size of the cuboid) (1x1x1, 1x1x2, ...; also 2x1x1 is considered the same as 1x1x2) from 1 to the upper range of the interval, and then checks if the calculated volume falls within the interval. This solution works perfectly if the upper range isn't is too large. But if the interval ends in thousands the solution becomes very slow.
I am not really interested in code as I am in an algorithm on how to solve this differently. How would you go about solving this? | 2017/11/11 | [
"https://Stackoverflow.com/questions/47243447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8925893/"
] | If your code is slow it's probably trying ranges of values that could be discarded immediately, or it's overly complicated and calculates square or cubic roots in loop conditions and such. Try something simple like the code example below, where I make sure a ≤ b ≤ c to avoid duplicates:
```js
if (Math.cbrt == undefined) // cubic root fix for older browsers
Math.cbrt = function(x) {var n = 1; while (n * n * n <= x) ++n; return n - 1;}
function cuboids(min_volume, max_volume) {
var results = [];
var cr = Math.cbrt(max_volume);
for (var a = 1; a <= cr; a++) {
var sr = Math.sqrt(max_volume / a);
for (var b = a; b <= sr; b++) {
var lower = Math.ceil(min_volume / (a * b));
var upper = Math.floor(max_volume / (a * b));
for (var c = Math.max(b, lower); c <= upper; c++) {
results.push([a, b, c]);
}
}
}
return results;
}
var results = cuboids(99900, 100000);
for (var i in results) document.write(results[i].join("*") + "<br>");
``` | Define your target interval I = [A … B], giving you M=B-A+1 different integer volumes.
You'll have to consider each of these in isolation.
For any of these target volumes v, a naive algorithm (that's probably still better than yours) would be:
1. find the prime number factorization of that; let that yield Ω(n) factors; store them as a list A.
2. {v,1,1} is possible tuple.
3. for i in 1…Ω(n):
3.1. r = prod(A\_l for l = 1 to i)
3.2 {r, v/r, 1} is possible tuple
3.3 for k in i+1…Ω(n):
3.3.1 s = prod(A\_m for m = i+1 to k)
3.3.2 {r, s, v/r/s} is possible tuple
This algorithm is naive because it assumes that finding A is easy. In fact, you'd ideally already note down all the tuples while creating A. |
47,243,447 | I have an interval of integers and I need to find all unique cuboids which have a volume that falls within said interval.
I came up with a loop that goes over all uniqe combinations of 3 numbers (size of the cuboid) (1x1x1, 1x1x2, ...; also 2x1x1 is considered the same as 1x1x2) from 1 to the upper range of the interval, and then checks if the calculated volume falls within the interval. This solution works perfectly if the upper range isn't is too large. But if the interval ends in thousands the solution becomes very slow.
I am not really interested in code as I am in an algorithm on how to solve this differently. How would you go about solving this? | 2017/11/11 | [
"https://Stackoverflow.com/questions/47243447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8925893/"
] | If your code is slow it's probably trying ranges of values that could be discarded immediately, or it's overly complicated and calculates square or cubic roots in loop conditions and such. Try something simple like the code example below, where I make sure a ≤ b ≤ c to avoid duplicates:
```js
if (Math.cbrt == undefined) // cubic root fix for older browsers
Math.cbrt = function(x) {var n = 1; while (n * n * n <= x) ++n; return n - 1;}
function cuboids(min_volume, max_volume) {
var results = [];
var cr = Math.cbrt(max_volume);
for (var a = 1; a <= cr; a++) {
var sr = Math.sqrt(max_volume / a);
for (var b = a; b <= sr; b++) {
var lower = Math.ceil(min_volume / (a * b));
var upper = Math.floor(max_volume / (a * b));
for (var c = Math.max(b, lower); c <= upper; c++) {
results.push([a, b, c]);
}
}
}
return results;
}
var results = cuboids(99900, 100000);
for (var i in results) document.write(results[i].join("*") + "<br>");
``` | I would probably loop over pairs for the first two dimensions, then directly calculate the min and max values of the third dimension to get in the interval, and save earlier solutions based on the product of the first two dimensions. Something like:
```
volume_interval = (Vmin, Vmax)
solution_intervals = {}
for w = 1 to n do
for d = w to n do
// see whether we've already encountered this case before
if solution_intervals[w*d] is not defined then
// compute min and max height to get in volume interval
min = ceiling(volume_interval.Vmin / (w*d))
max = floor(volume_interval.Vmax / (w*d))
solution_intervals[w*d] = (min, max)
// look up precomputed solution
soln = solution_intervals[w*d]
// print out every possible set of dimensions
for i = soln.min to soln.max do
print w, d, h
``` |
66,119 | So I found this gem, it's cool and all, but it just doesn't have that oomph I'm looking for.
How can I upgrade it? Or failing that, what can I do with it that will help me to get a more powerful gem? | 2012/05/14 | [
"https://gaming.stackexchange.com/questions/66119",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/12087/"
] | You can combine 3 gems at the Jeweler to get 1 gem of the next higher quality level. Once you get to higher level gems, additional ingredients will also be required, such as Pages of Jewelcrafting or Tomes of Secrets. There are 14 tiers of gems in total.
See the [list of Jeweler recipes](http://us.battle.net/d3/en/artisan/jeweler/recipe/) for more information on the specifics. | While the above answers about combining are true, the prices on the AH make low level gems cheaper to purchase outright via gold than by combining them. Aka, if it cost 500g to make a gem out of cheaper gems, that gem usually sells for far less than 500g. |
582,850 | The thin lens equation shows that when there is an object further than the focal point, there is a real image formed on the other side of the lens, and this principle is used for cameras, eyes, etc.
However, when I take a converging lens(that I got from some mobile VR headset), and hold it between me and an object, both of whom are more than the focal length away from the lens, I see an upside-down virtual image of the object.
So my question is, why do I see a virtual image instead of a blur that I would see at the point where the real image forms? What would the ray diagram look like for this?
Here is a picture of this phenomenon:
 | 2020/09/30 | [
"https://physics.stackexchange.com/questions/582850",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/211721/"
] | A converging lens (convex lens) will always create a *real inverted image* if the object is located at a point beyond the focal point (at a place on the opposite side of the lens). The only exception to this, is if the object is closer (to the lens) than the focal point is to the lens, in which case the image will *appear* to be on the same side of the lens as the object and the image will be a right side up and it will be a virtual image.
Just because you are not seeing the image at the exact point where the rays converge, does not mean it is a virtual image. This just means that image is out of focus. | You are seeing the real image, not a virtual image. If you placed a screen at the location where you believe the image to be it would be projected on the screen. Your eyes are focusing for the distance from you to that image. A screen is not necessary.
This is similar to the optical illusion of a small object like a coin or statue in a toy concave mirror setup. Your eyes see a real image, so real looking that you want to touch it, yet your fingers pass through the image. [Here's an example.](https://rads.stackoverflow.com/amzn/click/com/B089RKCHX3)
The image is real, by definition, because rays from points on the object actually converge at points in space where you are looking. For virtual images, the rays do not actually converge at the image location.
EDIT: If you put your eye at the location of the image, you are adding another optical element. Your eye is not capable of focusing at distances less than about 3 cm, so you must move beyond the image location in order for your eye to have focus on the image. |
4,692,030 | I'm storing some html-encoded data in a sql server database and I've written a script to output the data in a csv format minus the html tags and I'm getting a weird issue when html-decoding the remaining data. For example the data contains a quote character (which is html-encoded as `’`), but when I try to html-decode it the data comes out as a series of weird characters (’). Does anyone know how to solve this issue? The output encoding of the page is UTF-8 if that helps.
Any advice would be much appreciated!
Cheers
Tim | 2011/01/14 | [
"https://Stackoverflow.com/questions/4692030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Those 3 weird characters are [how UTF-8 encodes the HTML entity `’`](http://www.fileformat.info/info/unicode/char/2019/index.htm). (They're actually the octets `0xE2 0x80 0x99`, and those bytes render as "’" in your computer's default charset `windows-1252`.) So I don't think you've got an issue with your encoding.
It's evidently a known problem that Excel 2000 has problems with .csv files in UTF-8 encoding. The solution, bizarrely enough, is to [switch the filename extension to .txt](http://unicode.org/mail-arch/unicode-ml/Archives-Old/UML024/0705.html), at which point Excel 2000 will evidently import the file correctly. | If the data is read from the CSV files, open the csv file in notepad press Save As in the fiile menu, save the file as Encoding-UTF8. |
69,746,639 | So Im hitting an api and in the array of objects is an array of grades. Im mapping over the data but not sure how to go about getting the average grade and returning it in jsx. I tried the reduce method it didnt work and I just tried diving it by the length that didnt work either. I appreciate any help
```
data.map( ( element, index ) => {
return (
<div key={index} className="person-card" >
<div><img src={element.pic} alt="pic" />
</div>
<div>
<h2>
<strong>{element.firstName} {element.lastName}</strong>
</h2>
</div>
<div className="email">
Email: {element.email}
</div>
<p> Company: {element.company}</p>
<p>Skill: {element.skill}</p>
</div>
)
} )}
``` | 2021/10/27 | [
"https://Stackoverflow.com/questions/69746639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14714235/"
] | There could be many ways to compute average, but this is one way using `reduce`.
```
const grades = [50, 40, 70];
const average = grades.reduce((acc, grades) => {
return acc + grades
}, 0) / grades.length;
console.log(average);
```
Answer:
```
53.333333333333336
``` | Piggy Backing off Jagrut, reduce is the most viable option for finding the average of a sum of numbers. I believe your execution of his solution might be why reduce wasn't working for you. Here is an example using an array of sample data to find the average grade. You provided us with no example of how the data looks in the array you are mapping through so I had to guess.
```
const apiData = [
{ grades: [50, 60, 90], name: "billy" },
{ grades: [40, 80, 100], name: "jimmy" },
{ grades: [30, 50, 90], name: "Sam" }
];
export default function App() {
const [data] = useState(apiData);
return (
<div className="App">
{data.map((item, index) => {
const average =
item.grades.reduce((a, b) => {
return a + b;
}, 0) / item.grades.length;
const roundedAverage = Math.floor(average);
return (
<>
<div>Name: {item.name}</div>
<div>average grade: {roundedAverage}</div>
</>
);
})}
</div>
);
}
```
To see it in action here is a code sandbox as well: <https://codesandbox.io/s/misty-paper-g2nfr?file=/src/App.js> |
42,168 | I need to test an sftp host for its cutoff of file size upload limitation. I wanted to make a series of files that were of increasingly larger sizes, to try to upload them all and see where they failed.
I was doing `for i in {10000..100000} ; do dd if=/dev/zero of=testfile$i bs=$i count=1 ; done ;`
but that was taking too long, and the files I was getting were starting at 10K, going to 11K, 12K, etc. I want the size to jump in larger increments.
How can a make a series of files that won't have such a fine-grained size difference? I'm thinking the limit is between 0 and 1 MB. | 2012/07/02 | [
"https://unix.stackexchange.com/questions/42168",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/394/"
] | From `dd(1)`:
>
> bs=BYTES
>
>
> /.../
>
>
> BLOCKS and BYTES may be followed by the following multiplicative
> suffixes: c =1, w =2, b =512, kB =1000, K =1024, MB =1000\*1000, M =1024\*1024
>
>
>
Alternatively, if you have a recent version of bash, the `{}` construct also takes a step parameter:
```
for i in {10000..100000..1000}; do dd if=/dev/zero of=testfile$i bs=$i count=1 ; done
``` | For academic purposes, this would give a command 1k input files in increments of 1024 bytes by appending to the same file.
```
while ((++n<=1024)); do
printf '\0%.s' {1..1024} >&3
xxd -g 1 /dev/stdin; echo # sftp command here
done <<<'' 3>/dev/stdin
```
But... trial and error? I'd find a better way. |
32,501,747 | I have a doubt regarding how `equals()` method works for `ArrayList`. The below code snippet prints `true`.
```
ArrayList<String> s = new ArrayList<String>();
ArrayList<Integer> s1 = new ArrayList<Integer>();
System.out.println(s1.equals(s));
```
Why does it print `true`? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32501747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/642551/"
] | Look the [doc](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractList.java#AbstractList.equals%28java.lang.Object%29) for the [equals()](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractList.java#AbstractList.equals%28java.lang.Object%29) method of `ArrayList`
>
> Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.
>
>
>
Since there are no elements, all the conditions satisfied and hence `true`.
If you add elements to the both list (*atleast one in each*), to see the desired output. | The contract of the [`List.equals`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#equals-java.lang.Object-) is that two lists are equal if all their elements are equal (in terms of `equals()`). Here, both are empty lists, so they are equal. The generic type is irrelevant, as there are anyway no list elements to compare.
However, they are not equal in terms of `==` as these are two different objects.
See [this question](https://stackoverflow.com/questions/7520432/java-vs-equals-confusion) for details between `equals()` and `==` |
32,501,747 | I have a doubt regarding how `equals()` method works for `ArrayList`. The below code snippet prints `true`.
```
ArrayList<String> s = new ArrayList<String>();
ArrayList<Integer> s1 = new ArrayList<Integer>();
System.out.println(s1.equals(s));
```
Why does it print `true`? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32501747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/642551/"
] | Look the [doc](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractList.java#AbstractList.equals%28java.lang.Object%29) for the [equals()](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractList.java#AbstractList.equals%28java.lang.Object%29) method of `ArrayList`
>
> Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.
>
>
>
Since there are no elements, all the conditions satisfied and hence `true`.
If you add elements to the both list (*atleast one in each*), to see the desired output. | Here is the ArrayList implementation of the equals method from the AbstractList
with a few commments what it actually does:
```
public boolean equals(Object o) {
if (o == this) // Not the same list so no return
return true;
if (!(o instanceof List)) // is an instance of List, so no return
return false;
ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) { // Both have no next, so no loop here
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext()); // Both validate to false, so negating false return true in the end.
}
``` |
32,501,747 | I have a doubt regarding how `equals()` method works for `ArrayList`. The below code snippet prints `true`.
```
ArrayList<String> s = new ArrayList<String>();
ArrayList<Integer> s1 = new ArrayList<Integer>();
System.out.println(s1.equals(s));
```
Why does it print `true`? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32501747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/642551/"
] | Look the [doc](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractList.java#AbstractList.equals%28java.lang.Object%29) for the [equals()](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractList.java#AbstractList.equals%28java.lang.Object%29) method of `ArrayList`
>
> Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.
>
>
>
Since there are no elements, all the conditions satisfied and hence `true`.
If you add elements to the both list (*atleast one in each*), to see the desired output. | As previous answers pointed, equals returns true because both objects are instances of `List` and have the same size (0).
It's also worth mentioning that the fact that one `List` contains `Integer` and the other `String` does not affect the behaviour because of [type erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html) in Java. |
32,501,747 | I have a doubt regarding how `equals()` method works for `ArrayList`. The below code snippet prints `true`.
```
ArrayList<String> s = new ArrayList<String>();
ArrayList<Integer> s1 = new ArrayList<Integer>();
System.out.println(s1.equals(s));
```
Why does it print `true`? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32501747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/642551/"
] | The contract of the [`List.equals`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#equals-java.lang.Object-) is that two lists are equal if all their elements are equal (in terms of `equals()`). Here, both are empty lists, so they are equal. The generic type is irrelevant, as there are anyway no list elements to compare.
However, they are not equal in terms of `==` as these are two different objects.
See [this question](https://stackoverflow.com/questions/7520432/java-vs-equals-confusion) for details between `equals()` and `==` | Here is the ArrayList implementation of the equals method from the AbstractList
with a few commments what it actually does:
```
public boolean equals(Object o) {
if (o == this) // Not the same list so no return
return true;
if (!(o instanceof List)) // is an instance of List, so no return
return false;
ListIterator<E> e1 = listIterator();
ListIterator<?> e2 = ((List<?>) o).listIterator();
while (e1.hasNext() && e2.hasNext()) { // Both have no next, so no loop here
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext()); // Both validate to false, so negating false return true in the end.
}
``` |
32,501,747 | I have a doubt regarding how `equals()` method works for `ArrayList`. The below code snippet prints `true`.
```
ArrayList<String> s = new ArrayList<String>();
ArrayList<Integer> s1 = new ArrayList<Integer>();
System.out.println(s1.equals(s));
```
Why does it print `true`? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32501747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/642551/"
] | The contract of the [`List.equals`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#equals-java.lang.Object-) is that two lists are equal if all their elements are equal (in terms of `equals()`). Here, both are empty lists, so they are equal. The generic type is irrelevant, as there are anyway no list elements to compare.
However, they are not equal in terms of `==` as these are two different objects.
See [this question](https://stackoverflow.com/questions/7520432/java-vs-equals-confusion) for details between `equals()` and `==` | As previous answers pointed, equals returns true because both objects are instances of `List` and have the same size (0).
It's also worth mentioning that the fact that one `List` contains `Integer` and the other `String` does not affect the behaviour because of [type erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html) in Java. |
124,865 | I am learning solidity. I want to ask how does the value of the token is calculated. Like how does the value of a coin increase and decrease in a programmatical way? which technology or method is used to calculate the value of a cryptocurrency. | 2022/03/28 | [
"https://ethereum.stackexchange.com/questions/124865",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/92051/"
] | Of course you can.
A better question is : should you ?
Probably not, because to do so you will have to write low level assembly code that's error-prone, difficult to debug / read and possibly make assumptions about the solidity compiler that might not hold over time.
Your input data will be :
* function identifier : 4 bytes
* address[] : N \* 20 bytes
* uint256 : 32 bytes
The assumption about the compiler will be the following :
>
> A function can receive more calldata that its signature suggest.
>
>
>
The following function :
```
function do_sth() public view {}
```
Should only receive 4 bytes of calldata : the function identifier. It **cannot** receive less, but it **can** receive more. There is no saying if this assumption will hold on every subsequent versions of solidity...
Your parameters will therefore be embedded in the calldata, and not accessible from solidity, only from assembly reading directly from calldata.
This can be achieved with the following implementation that just reads from calldata, decodes the embedded input and returns them following the standard ABI specifications :
```
function do_sth() public view returns (address[] memory, uint256) {
address[] memory ads;
uint256 input;
assembly {
let tmp := 0
// Skip : function selector : 0x4 bytes
let offset := 0x4
// Compute the number of addresses :
// ((array length - 0x04) - 0x20) / 0x14
// ((array length - sizeof(function Selector)) - sizeof(uint256)) / sizeof(address)
let adsCount := div(sub(sub(calldatasize(), 0x04), 0x20), 0x14)
// Allocate memory for the address array
ads := mload(0x40)
mstore(0x40, add(ads, add(0x20, mul(adsCount, 0x20))))
// Set the size of the array
mstore(ads, adsCount)
// Get an address from calldata on each iteration :
// loads 0x20 bytes from calldata starting at offset : calldata[offset: offset + 0x20)
// shift value by 96 bits (12 bytes) to the right to keep only the relevant portion (first 20 bytes)
// store that value at ads[i]
// increments calldata offset by 0x14 (20 bytes)
for {let i := 0} lt(i, adsCount) {i := add(i, 1)} {
tmp := calldataload(offset)
tmp := shr(96, tmp)
mstore(add(add(ads, 0x20), mul(i, 0x20)), tmp)
offset := add(offset, 0x14)
}
// Get the remaining parameter : uint256 (32 bytes)
input := calldataload(offset)
}
return (ads, input);
}
```
If you were to call this function with the following calldata (you can add as many addresses as you want before the uint256 value / function identifier was omitted):
>
> 0xe9e7cea3dedca5984780bafc599bd69add087d56b387c824cafe52b25fbbe793d7b6800b1ddbfe7d00000000000000000000000000000000000000000000000783c5395de63b678d
>
>
>
With this web3 code for example :
```
const Web3 = require("Web3");
const ENDPOINT = "http://localhost:8545";
const CONTRACT_ADDRESS = "CONTRACT-ADDRESS_HERE";
const YOUR_DATA =
"0xe9e7cea3dedca5984780bafc599bd69add087d56b387c824cafe52b25fbbe793d7b6800b1ddbfe7d00000000000000000000000000000000000000000000000783c5395de63b678d";
let web3 = new Web3(ENDPOINT);
async function main() {
let encodedData =
web3.eth.abi.encodeFunctionSignature({
name: "do_sth",
type: "function",
inputs: [],
}) + YOUR_DATA.replace("0x", "");
let callObject = {
from: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
to: CONTRACT_ADDRESS,
data: encodedData,
};
console.log(
"This call will consume : " +
((await web3.eth.estimateGas(callObject)) + " gas")
);
let output = await web3.eth.call(callObject);
console.log(output);
let decodedData = web3.eth.abi.decodeParameters(
["address[]", "uint256"],
output
);
console.log(decodedData);
}
main();
```
You get your addresses and your uint value extracted from the calldata :
```sh
Result {
'0': [
'0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56',
'0xb387C824CAfE52B25FBbE793d7b6800b1DdBfE7D'
],
'1': '138622266980804814733',
__length__: 2
}
```
Which cost 23593 gas on default settings, a slight improvement over the 24331 gas cost of this solidity version on the same settings :
```
function do_sth2(address[] calldata ads, uint256 input) public view returns (address[] memory, uint256) {
return (ads, input);
}
```
Now you shouldn't do that, and probably don't even need to. You should stick to solidity.
So, it's possible but clearly not recommended.
I hope that answers your question. | The simple answer is no. This is how solidity encode the input. For details you can refer to the ABI encoding here - <https://docs.soliditylang.org/en/v0.8.12/abi-spec.html#formal-specification-of-the-encoding>
`0x65432121 ==> this is function selector`
`0x0000000000000000000000000000000000000000000000000000000000000040 => this the bytes offset indicate where to look for the content of address[]`
`0x00000000000000000000000000000000000000000000000783c5395de63b678d => this is your second argument`
`0x0000000000000000000000000000000000000000000000000000000000000002 => this is the length of address[]`
`0x000000000000000000000000e9e7cea3dedca5984780bafc599bd69add087d56 ==> first element of address[]`
`0x000000000000000000000000b387c824cafe52b25fbbe793d7b6800b1ddbfe7d => second element of address[]` |
21,381,099 | I have created Google query job with my own job id successfully. And able to use the job id again and got successful results yesterday.
But the same Job id not working fine.
I have tried the job id with project Id in the google bigquery UI got the same error as '404' below
```
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Not Found: Table<projectId:some random generated String.some random generated String>"
}
],
"code": 404,
"message": "Not Found: Table <projectId:some random generated String.some random generated String>
}
}
```
Please help me, is there any life time for Job? Or any specific Configuration required while creating Job Id to work permanently?
I am using Java API of Google Bigquery to do the above implementation. Find the logic used below:
**Query Job Creation logic:**
```
String query = "SELECT count(*) AS TOTAL_RECORDS FROM :dataset.:tablename;"
String expectedJobId = "someuniqueString";
JobConfigurationQuery queryConfig = new JobConfigurationQuery()
.setQuery(query);
queryConfig.setUseQueryCache(true);
JobConfiguration config = new JobConfiguration()
.setQuery(queryConfig);
JobReference jobReference = new JobReference();
jobReference.setJobId(expectedJobId);
jobReference.setProjectId(PROJECT_ID);
Job job = new Job().setId(expectedJobId).setConfiguration(
config);
job.setJobReference(jobReference);
job = bigqueryService.jobs()
.insert(PROJECT_ID, job).execute();
```
**Results Retrieved using above JobId :**
```
GetQueryResults queryRequest = bigqueryService.jobs()
.getQueryResults(PROJECT_ID, expectedJobId);
GetQueryResultsResponse queryResponse = queryRequest.execute();
``` | 2014/01/27 | [
"https://Stackoverflow.com/questions/21381099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057658/"
] | The error you're seeing is not a problem looking up the job but looking up the result table. As you noticed, `getQueryResults()` for a particular job will only work for up to 24 hours; after that the table that is created to store the results will expire and get cleaned up.
If you find that this happens within the 24 hour window, you might want to check to make sure the job actually completed successfully. You can use `bigqueryService.jobs.get()` to look up the job status.
If that doesn't help, if you send the job id we (the BigQuery team) can look up in the server logs what is going on with that job. | Sometimes the problem is incorrect dataset location. In my code I have a config based on which I set the dataset location while executing a query. I messed up the location and started getting this error. After 2 hours of debugging finally found the issue.
Corrected the dataset location and it worked fine. |
47,741,273 | I am trying to achieve an effect where I can diagonally crop an image in a way that is displayed below. I am aware of clip path as a solution but it would not be suitable in this scenario since it is not supported by certain browsers which are essential for this particular task. (IE and Edge)
Additionally, the cropped edge would need a black border which adds on to the complexity of what I am trying to do. Having searched for answers and coming up with anything, any suggestions would be appreciated.
[](https://i.stack.imgur.com/qDBHS.jpg) | 2017/12/10 | [
"https://Stackoverflow.com/questions/47741273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7770789/"
] | Maybe you could overlay the image with a rotated element (div or something) that you give a border and white background. This solution would work if you're okay with a solid background color.
Another solution, depending on your requirements, could be to simpy use a .png image with transparency. | Yes you can, it's a bit tricky to get the sizes of the divs correct. But here's generally how to do it:
HTML:
```
<div id="outerwrapper">
<div id="innerwrapper">
<div id="content">
<span>asdf</span>
</div>
</div>
</div>
```
CSS:
```
#content {
width: 100px;
height: 100px;
background-color: red;
transform: rotate(-60deg);
transform-origin: 50% 50%;
position: relative;
}
#content span {
position: relative;
top: 30px;
left: 30px;
}
#innerwrapper {
border-right: solid 3px black;
overflow: hidden;
width: 100px;
height: 100px;
}
#outerwrapper {
transform: rotate(60deg);
transform-origin: 50% 50%;
width: 120px;
height: 120px;
overflow: hidden;
}
```
Fiddle:
<https://jsfiddle.net/ywfpeve8/>
To explain this:
You have a div that contains the content itself. In this example it's just a span, but it can be anything. (I put it in to see that in the end everything is horizontal again)
You rotate that content div to some degree that suits you.
You place that div in a wrapper with a different size where you can position your content in. That div has an `overflow: hidden`, to crop all that content that is outside of the inner wrapper box. That wrapper then also has the border where you want the crop to be highlighted.
That inner wrapper is placed in an outside wrapper that rotates the same amount at the content div, but *backwards*, leaving you with the original 0 degree alignment of the content. This div again has `overflow: hidden` to crop that inner wrapper *again* so that you can hide the other "crop edges" that you want to be invisible. In my example code I didn't to the correct dimensions and positionings as it takes a bit to get right. But if you have an image with a white background, that shouldn't be very hard anymore to get things right.
Bonus: the background of the top-level element (that element that holds the `outerwrapper` can have any background at all and you won't see a rectangular box at the bottom right corner (for this example) as everything just happens with `overflow: hidden` and without bars that go over the content to hide it :) |
162,082 | I'm about to submit a paper where one of the authors is a past student who got a master's degree at my university a few months ago (I was his advisor). He plans to apply for PhD positions at the next deadline, but is presently unemployed. What should we write on the manuscript for his institution? "Master's graduate, previously at XXX University"? "Former student at XXX University" (this doesn't specify that he actually got a degree, though)? The dreaded "Independent researcher"? | 2021/02/01 | [
"https://academia.stackexchange.com/questions/162082",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/958/"
] | Whenever I co-write a paper with former students of mine, based on their MSc thesis, we typically put XXX University as affiliation of both the student and me. The bulk of the work has been done when both of us were affiliated with this university, so this seems appropriate. The fact that the student is no longer affiliated with the university seems of minor importance to me.
Does the venue to which you submit demand that you specify the role of each author? If not, I'd just let it be. If so, consider "MSc alumnus", substituting the appropriate title for "MSc". | He performed the research activity while affiliated with your group. You do **not** need to be PhD/Professor/Dean/whatever-self-important-academic-title to submit a research for peer review. If you really need a *title*, it can be "scientific assistant", or "pre-graduate student" or any linear combination/contraption of the terms.
Along this note, it is clear to me that even Master thesis work is still work (you are even thinking about publishing it), even if the student is learning, so I strongly feel he/she should be compensated, however, let's not derange from the question.
Judging "independent researcher" as dreaded is absolutely unintelligent. No offense intended, it is just a sign of the time, since some independent researcher are known to be independent from their brain, then all independent researcher are to be considered so. This is the most antiscientific way of thinking I can think of. |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | In the noble spirit of one immortal oratorm when he so colorfully advised our hero . . .
>
> This business is well ended.
>
> My liege, and madam, to expostulate
>
> What majesty should be, what duty is,
>
> Why day is day, night night, and time is time,
>
> Were nothing but to waste night, day and time.
>
> Therefore, since brevity is the soul of wit,
>
> And tediousness the limbs and outward flourishes,
>
> I will be brief: your noble son is mad:
>
> Mad call I it; for, to define true madness,
>
> What is’t but to be nothing else but mad?
>
> But let that go.
>
>
>
. . . I can myself do little less than recommend vigorously not timorously, for *timor* no more profits a man than it does a mouse or a moth, any of the following fine and splendid formulations of art:
* *chatty*
* *circuitous*
* *circumlocutory*
* *desultory*
* *diffuse*
* *digressive*
* *discursive*
* *evasive*
* *gabby*
* *garrulous*
* *long-winded*
* *loquacious*
* *maundering*
* *meandering*
* *palaverous*
* *prolix*
* *rambling*
* *talkative*
* *turgid*
* *vague*
* *verbose*
* *waffling*
* *windy*
* *wordy*
and of course, my personal favorite word for vexing prattlers wont to sacrifice wit’s soul on the altar of florid flourish:
• *Polonian*
============= | Last year the question [Word for a person who talks without content](https://english.stackexchange.com/q/242760/26083 "Word for a person who talks without content")
was closed as a duplicate of this one.
While I believe that my answer works for *this* question,
I believe that it works even better for [that one](https://english.stackexchange.com/q/242760/26083 "Word for a person who talks without content").
The answer is ***double-talk***.
>
> [Merriam-Webster](http://www.merriam-webster.com/dictionary/double-talk):
>
>
> * language that appears to be earnest and meaningful
> but in fact is a mixture of sense and nonsense
> * inflated, involved, and often deliberately ambiguous language
> * language that uses many words but has very little meaning
>
>
>
> [English Oxford Dictionaries](https://en.oxforddictionaries.com/definition/us/double-talk):
>
>
>
> another term for *[doublespeak](https://en.oxforddictionaries.com/definition/us/doublespeak)*
>
>
> ***[doublespeak](https://en.oxforddictionaries.com/definition/us/doublespeak)***:
>
>
> Deliberately euphemistic, ambiguous, or obscure language.
>
> *‘the art of political doublespeak’*
>
>
>
>
> [Collins Dictionary](http://www.collinsdictionary.com/dictionary/english/double-talk):
>
>
> empty, deceptive, or ambiguous talk, esp by politicians
>
> [Macmillan Dictionary](http://www.macmillandictionary.com/dictionary/american/double-talk):
> a way of saying things that makes it impossible for people to understand,
> used by people in official positions when they want to hide the truth
>
>
> [grammar.about.com](http://grammar.about.com/od/d/g/doublespeakterm.htm) discusses *doublespeak*:
>
>
> Doublespeak is language that's intended to deceive or confuse people. …
>
>
> Doublespeak may take the form of euphemisms,
> unsupported generalizations, or deliberate ambiguity.
> Contrast with *[plain English](http://grammar.about.com/od/pq/g/Plain-English-term.htm)*.
>
>
> William Lutz has defined doublespeak as
> “language which pretends to communicate but doesn’t.”
>
>
>
>
>
>
>
The [grammar.about.com page referenced above](http://grammar.about.com/od/d/g/doublespeakterm.htm)
lists many other terms, phrases, and references
that relate to these questions, such as
* [bureaucratese](http://grammar.about.com/od/ab/g/bureaucrateseterm.htm)
* [drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm)
* [weasel words](http://grammar.about.com/od/words/a/What-Are-Weasel-Words.htm)
---
### Amusing Contemporary Notes:
* The reference for [drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm) is a link to an article
on [George Carlin’s Essential Drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm),
which, amidst a long string of
“superfluous redundant pleonastic tautologies,”
mentions “over-exaggerating,”
which was recently popularized by an Olympic athlete.
* [Why You’ll Never Be Told, “You’re Fired”](http://grammar.about.com/od/words/fl/51-Euphemisms-for-Youre-Fired.htm) links to a page
that leads with a photograph of Donald Trump. |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | If you are actually talking about someone who waffles on long-windedly before getting to the point (rather than someone who doesn’t say things straight out and honestly, which is how I too would understand ‘straight talk’), the first idiom that comes to mind is ***beating around the bush***. | The opposite of *straight* is *crooked* (the adjective /'krʊkəd/, not the past participle /krʊkt/).
The opposite of *talking* is *thinking*, in the sense that what one says may not represent what one thinks. Particularly when the topic is lying.
So I'd say the opposite of ***straight talk*** would be ***crooked thinking***. |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | The opposite of a familiar and straightforward idiom would be a strange and impenetrable circumlocution. I suggest "obfuscatory tergiversation." | Last year the question [Word for a person who talks without content](https://english.stackexchange.com/q/242760/26083 "Word for a person who talks without content")
was closed as a duplicate of this one.
While I believe that my answer works for *this* question,
I believe that it works even better for [that one](https://english.stackexchange.com/q/242760/26083 "Word for a person who talks without content").
The answer is ***double-talk***.
>
> [Merriam-Webster](http://www.merriam-webster.com/dictionary/double-talk):
>
>
> * language that appears to be earnest and meaningful
> but in fact is a mixture of sense and nonsense
> * inflated, involved, and often deliberately ambiguous language
> * language that uses many words but has very little meaning
>
>
>
> [English Oxford Dictionaries](https://en.oxforddictionaries.com/definition/us/double-talk):
>
>
>
> another term for *[doublespeak](https://en.oxforddictionaries.com/definition/us/doublespeak)*
>
>
> ***[doublespeak](https://en.oxforddictionaries.com/definition/us/doublespeak)***:
>
>
> Deliberately euphemistic, ambiguous, or obscure language.
>
> *‘the art of political doublespeak’*
>
>
>
>
> [Collins Dictionary](http://www.collinsdictionary.com/dictionary/english/double-talk):
>
>
> empty, deceptive, or ambiguous talk, esp by politicians
>
> [Macmillan Dictionary](http://www.macmillandictionary.com/dictionary/american/double-talk):
> a way of saying things that makes it impossible for people to understand,
> used by people in official positions when they want to hide the truth
>
>
> [grammar.about.com](http://grammar.about.com/od/d/g/doublespeakterm.htm) discusses *doublespeak*:
>
>
> Doublespeak is language that's intended to deceive or confuse people. …
>
>
> Doublespeak may take the form of euphemisms,
> unsupported generalizations, or deliberate ambiguity.
> Contrast with *[plain English](http://grammar.about.com/od/pq/g/Plain-English-term.htm)*.
>
>
> William Lutz has defined doublespeak as
> “language which pretends to communicate but doesn’t.”
>
>
>
>
>
>
>
The [grammar.about.com page referenced above](http://grammar.about.com/od/d/g/doublespeakterm.htm)
lists many other terms, phrases, and references
that relate to these questions, such as
* [bureaucratese](http://grammar.about.com/od/ab/g/bureaucrateseterm.htm)
* [drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm)
* [weasel words](http://grammar.about.com/od/words/a/What-Are-Weasel-Words.htm)
---
### Amusing Contemporary Notes:
* The reference for [drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm) is a link to an article
on [George Carlin’s Essential Drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm),
which, amidst a long string of
“superfluous redundant pleonastic tautologies,”
mentions “over-exaggerating,”
which was recently popularized by an Olympic athlete.
* [Why You’ll Never Be Told, “You’re Fired”](http://grammar.about.com/od/words/fl/51-Euphemisms-for-Youre-Fired.htm) links to a page
that leads with a photograph of Donald Trump. |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | I'd suggest *pussyfoot* for the specific use you mentioned. In other uses, I might say an antonym for *straight talk* would be *euphemism* or the vulgar *B.S.* even. | Last year the question [Word for a person who talks without content](https://english.stackexchange.com/q/242760/26083 "Word for a person who talks without content")
was closed as a duplicate of this one.
While I believe that my answer works for *this* question,
I believe that it works even better for [that one](https://english.stackexchange.com/q/242760/26083 "Word for a person who talks without content").
The answer is ***double-talk***.
>
> [Merriam-Webster](http://www.merriam-webster.com/dictionary/double-talk):
>
>
> * language that appears to be earnest and meaningful
> but in fact is a mixture of sense and nonsense
> * inflated, involved, and often deliberately ambiguous language
> * language that uses many words but has very little meaning
>
>
>
> [English Oxford Dictionaries](https://en.oxforddictionaries.com/definition/us/double-talk):
>
>
>
> another term for *[doublespeak](https://en.oxforddictionaries.com/definition/us/doublespeak)*
>
>
> ***[doublespeak](https://en.oxforddictionaries.com/definition/us/doublespeak)***:
>
>
> Deliberately euphemistic, ambiguous, or obscure language.
>
> *‘the art of political doublespeak’*
>
>
>
>
> [Collins Dictionary](http://www.collinsdictionary.com/dictionary/english/double-talk):
>
>
> empty, deceptive, or ambiguous talk, esp by politicians
>
> [Macmillan Dictionary](http://www.macmillandictionary.com/dictionary/american/double-talk):
> a way of saying things that makes it impossible for people to understand,
> used by people in official positions when they want to hide the truth
>
>
> [grammar.about.com](http://grammar.about.com/od/d/g/doublespeakterm.htm) discusses *doublespeak*:
>
>
> Doublespeak is language that's intended to deceive or confuse people. …
>
>
> Doublespeak may take the form of euphemisms,
> unsupported generalizations, or deliberate ambiguity.
> Contrast with *[plain English](http://grammar.about.com/od/pq/g/Plain-English-term.htm)*.
>
>
> William Lutz has defined doublespeak as
> “language which pretends to communicate but doesn’t.”
>
>
>
>
>
>
>
The [grammar.about.com page referenced above](http://grammar.about.com/od/d/g/doublespeakterm.htm)
lists many other terms, phrases, and references
that relate to these questions, such as
* [bureaucratese](http://grammar.about.com/od/ab/g/bureaucrateseterm.htm)
* [drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm)
* [weasel words](http://grammar.about.com/od/words/a/What-Are-Weasel-Words.htm)
---
### Amusing Contemporary Notes:
* The reference for [drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm) is a link to an article
on [George Carlin’s Essential Drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm),
which, amidst a long string of
“superfluous redundant pleonastic tautologies,”
mentions “over-exaggerating,”
which was recently popularized by an Olympic athlete.
* [Why You’ll Never Be Told, “You’re Fired”](http://grammar.about.com/od/words/fl/51-Euphemisms-for-Youre-Fired.htm) links to a page
that leads with a photograph of Donald Trump. |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | If you are actually talking about someone who waffles on long-windedly before getting to the point (rather than someone who doesn’t say things straight out and honestly, which is how I too would understand ‘straight talk’), the first idiom that comes to mind is ***beating around the bush***. | Last year the question [Word for a person who talks without content](https://english.stackexchange.com/q/242760/26083 "Word for a person who talks without content")
was closed as a duplicate of this one.
While I believe that my answer works for *this* question,
I believe that it works even better for [that one](https://english.stackexchange.com/q/242760/26083 "Word for a person who talks without content").
The answer is ***double-talk***.
>
> [Merriam-Webster](http://www.merriam-webster.com/dictionary/double-talk):
>
>
> * language that appears to be earnest and meaningful
> but in fact is a mixture of sense and nonsense
> * inflated, involved, and often deliberately ambiguous language
> * language that uses many words but has very little meaning
>
>
>
> [English Oxford Dictionaries](https://en.oxforddictionaries.com/definition/us/double-talk):
>
>
>
> another term for *[doublespeak](https://en.oxforddictionaries.com/definition/us/doublespeak)*
>
>
> ***[doublespeak](https://en.oxforddictionaries.com/definition/us/doublespeak)***:
>
>
> Deliberately euphemistic, ambiguous, or obscure language.
>
> *‘the art of political doublespeak’*
>
>
>
>
> [Collins Dictionary](http://www.collinsdictionary.com/dictionary/english/double-talk):
>
>
> empty, deceptive, or ambiguous talk, esp by politicians
>
> [Macmillan Dictionary](http://www.macmillandictionary.com/dictionary/american/double-talk):
> a way of saying things that makes it impossible for people to understand,
> used by people in official positions when they want to hide the truth
>
>
> [grammar.about.com](http://grammar.about.com/od/d/g/doublespeakterm.htm) discusses *doublespeak*:
>
>
> Doublespeak is language that's intended to deceive or confuse people. …
>
>
> Doublespeak may take the form of euphemisms,
> unsupported generalizations, or deliberate ambiguity.
> Contrast with *[plain English](http://grammar.about.com/od/pq/g/Plain-English-term.htm)*.
>
>
> William Lutz has defined doublespeak as
> “language which pretends to communicate but doesn’t.”
>
>
>
>
>
>
>
The [grammar.about.com page referenced above](http://grammar.about.com/od/d/g/doublespeakterm.htm)
lists many other terms, phrases, and references
that relate to these questions, such as
* [bureaucratese](http://grammar.about.com/od/ab/g/bureaucrateseterm.htm)
* [drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm)
* [weasel words](http://grammar.about.com/od/words/a/What-Are-Weasel-Words.htm)
---
### Amusing Contemporary Notes:
* The reference for [drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm) is a link to an article
on [George Carlin’s Essential Drivel](http://grammar.about.com/od/words/a/George-Carlins-Essential-Drivel.htm),
which, amidst a long string of
“superfluous redundant pleonastic tautologies,”
mentions “over-exaggerating,”
which was recently popularized by an Olympic athlete.
* [Why You’ll Never Be Told, “You’re Fired”](http://grammar.about.com/od/words/fl/51-Euphemisms-for-Youre-Fired.htm) links to a page
that leads with a photograph of Donald Trump. |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | In the noble spirit of one immortal oratorm when he so colorfully advised our hero . . .
>
> This business is well ended.
>
> My liege, and madam, to expostulate
>
> What majesty should be, what duty is,
>
> Why day is day, night night, and time is time,
>
> Were nothing but to waste night, day and time.
>
> Therefore, since brevity is the soul of wit,
>
> And tediousness the limbs and outward flourishes,
>
> I will be brief: your noble son is mad:
>
> Mad call I it; for, to define true madness,
>
> What is’t but to be nothing else but mad?
>
> But let that go.
>
>
>
. . . I can myself do little less than recommend vigorously not timorously, for *timor* no more profits a man than it does a mouse or a moth, any of the following fine and splendid formulations of art:
* *chatty*
* *circuitous*
* *circumlocutory*
* *desultory*
* *diffuse*
* *digressive*
* *discursive*
* *evasive*
* *gabby*
* *garrulous*
* *long-winded*
* *loquacious*
* *maundering*
* *meandering*
* *palaverous*
* *prolix*
* *rambling*
* *talkative*
* *turgid*
* *vague*
* *verbose*
* *waffling*
* *windy*
* *wordy*
and of course, my personal favorite word for vexing prattlers wont to sacrifice wit’s soul on the altar of florid flourish:
• *Polonian*
============= | The opposite of a familiar and straightforward idiom would be a strange and impenetrable circumlocution. I suggest "obfuscatory tergiversation." |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | In the noble spirit of one immortal oratorm when he so colorfully advised our hero . . .
>
> This business is well ended.
>
> My liege, and madam, to expostulate
>
> What majesty should be, what duty is,
>
> Why day is day, night night, and time is time,
>
> Were nothing but to waste night, day and time.
>
> Therefore, since brevity is the soul of wit,
>
> And tediousness the limbs and outward flourishes,
>
> I will be brief: your noble son is mad:
>
> Mad call I it; for, to define true madness,
>
> What is’t but to be nothing else but mad?
>
> But let that go.
>
>
>
. . . I can myself do little less than recommend vigorously not timorously, for *timor* no more profits a man than it does a mouse or a moth, any of the following fine and splendid formulations of art:
* *chatty*
* *circuitous*
* *circumlocutory*
* *desultory*
* *diffuse*
* *digressive*
* *discursive*
* *evasive*
* *gabby*
* *garrulous*
* *long-winded*
* *loquacious*
* *maundering*
* *meandering*
* *palaverous*
* *prolix*
* *rambling*
* *talkative*
* *turgid*
* *vague*
* *verbose*
* *waffling*
* *windy*
* *wordy*
and of course, my personal favorite word for vexing prattlers wont to sacrifice wit’s soul on the altar of florid flourish:
• *Polonian*
============= | I'd suggest *pussyfoot* for the specific use you mentioned. In other uses, I might say an antonym for *straight talk* would be *euphemism* or the vulgar *B.S.* even. |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | I'd suggest *pussyfoot* for the specific use you mentioned. In other uses, I might say an antonym for *straight talk* would be *euphemism* or the vulgar *B.S.* even. | The opposite of *straight* is *crooked* (the adjective /'krʊkəd/, not the past participle /krʊkt/).
The opposite of *talking* is *thinking*, in the sense that what one says may not represent what one thinks. Particularly when the topic is lying.
So I'd say the opposite of ***straight talk*** would be ***crooked thinking***. |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | If you are actually talking about someone who waffles on long-windedly before getting to the point (rather than someone who doesn’t say things straight out and honestly, which is how I too would understand ‘straight talk’), the first idiom that comes to mind is ***beating around the bush***. | I'd suggest *pussyfoot* for the specific use you mentioned. In other uses, I might say an antonym for *straight talk* would be *euphemism* or the vulgar *B.S.* even. |
96,684 | What is the opposite for the *straight talk* idiom? How do I best call the activity when someone makes a very long preamble before he says what he wants? | 2013/01/04 | [
"https://english.stackexchange.com/questions/96684",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/26017/"
] | In the noble spirit of one immortal oratorm when he so colorfully advised our hero . . .
>
> This business is well ended.
>
> My liege, and madam, to expostulate
>
> What majesty should be, what duty is,
>
> Why day is day, night night, and time is time,
>
> Were nothing but to waste night, day and time.
>
> Therefore, since brevity is the soul of wit,
>
> And tediousness the limbs and outward flourishes,
>
> I will be brief: your noble son is mad:
>
> Mad call I it; for, to define true madness,
>
> What is’t but to be nothing else but mad?
>
> But let that go.
>
>
>
. . . I can myself do little less than recommend vigorously not timorously, for *timor* no more profits a man than it does a mouse or a moth, any of the following fine and splendid formulations of art:
* *chatty*
* *circuitous*
* *circumlocutory*
* *desultory*
* *diffuse*
* *digressive*
* *discursive*
* *evasive*
* *gabby*
* *garrulous*
* *long-winded*
* *loquacious*
* *maundering*
* *meandering*
* *palaverous*
* *prolix*
* *rambling*
* *talkative*
* *turgid*
* *vague*
* *verbose*
* *waffling*
* *windy*
* *wordy*
and of course, my personal favorite word for vexing prattlers wont to sacrifice wit’s soul on the altar of florid flourish:
• *Polonian*
============= | If you are actually talking about someone who waffles on long-windedly before getting to the point (rather than someone who doesn’t say things straight out and honestly, which is how I too would understand ‘straight talk’), the first idiom that comes to mind is ***beating around the bush***. |
73,813,195 | How to create a new variable in the dataframe with a sequence increasing by 0.002, starting at 0 and running until the end of the dataset. I was attempting with:
```
dataset$seq = seq(0, length(dataset), by = 0.002)
dataset$seq = seq(0, nrow(dataset), by = 0.002)
```
But both throw an error about wrong lengths. Thanks for your help. | 2022/09/22 | [
"https://Stackoverflow.com/questions/73813195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19974538/"
] | Another option:
```
dataset$seq <- seq(0, by = 0.002, length.out = nrow(dataset))
``` | One way:
```
library(dplyr)
df %>% mutate(seq = rep(.002, nrow(df)) * 1:nrow(df))
col1 col2 seq
1 a 1 0.002
2 b 2 0.004
3 c 3 0.006
4 d 4 0.008
5 e 5 0.010
6 f 6 0.012
7 g 7 0.014
8 h 8 0.016
9 i 9 0.018
10 j 10 0.020
```
Sure:
```
df %>% mutate(seq = rep(.002, nrow(df)) * 1:nrow(df) - .002)
col1 col2 seq
1 a 1 0.000
2 b 2 0.002
3 c 3 0.004
4 d 4 0.006
5 e 5 0.008
6 f 6 0.010
7 g 7 0.012
8 h 8 0.014
9 i 9 0.016
10 j 10 0.018
``` |
73,813,195 | How to create a new variable in the dataframe with a sequence increasing by 0.002, starting at 0 and running until the end of the dataset. I was attempting with:
```
dataset$seq = seq(0, length(dataset), by = 0.002)
dataset$seq = seq(0, nrow(dataset), by = 0.002)
```
But both throw an error about wrong lengths. Thanks for your help. | 2022/09/22 | [
"https://Stackoverflow.com/questions/73813195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19974538/"
] | Another option:
```
dataset$seq <- seq(0, by = 0.002, length.out = nrow(dataset))
``` | Does it work?
```
set.seed(123)
df <- data.frame(x = rnorm(10), y = rnorm(10), z = rnorm(10))
df$seq <- seq(0, 0.002 * (nrow(df) - 1), 0.002)
x y z seq
1 -0.56047565 1.2240818 -1.0678237 0.000
2 -0.23017749 0.3598138 -0.2179749 0.002
3 1.55870831 0.4007715 -1.0260044 0.004
4 0.07050839 0.1106827 -0.7288912 0.006
5 0.12928774 -0.5558411 -0.6250393 0.008
6 1.71506499 1.7869131 -1.6866933 0.010
7 0.46091621 0.4978505 0.8377870 0.012
8 -1.26506123 -1.9666172 0.1533731 0.014
9 -0.68685285 0.7013559 -1.1381369 0.016
10 -0.44566197 -0.4727914 1.2538149 0.018
``` |
634,918 | I want to create a diagram on `tikz-qtree` that look something like this:
[](https://i.stack.imgur.com/WXACwm.png)
Where "alt", "a", and "s" are aligned at the base, and "R", "AF", and "AF" are also aligned at the base (note that I removed the last edge before the leaves; I need it this way).
My first attempt aligned "s" with the higher node (its sister node):
```
\documentclass{standalone}
\usepackage{tikz}
\usepackage{tikz-qtree}
\tikzset{every tree node/.style={align=center,anchor=base},
frontier/.style={distance from root=80pt}
}
\begin{document}
\begin{tikzpicture}
\Tree
[.Adj
[.Adj
[.alt\\R-Adj ]
[.a\\AF-G ] ]
[.s\\AF-N ] ]
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/3WVkam.png)
Then I tried adding another node before "s" to make "s" be a sister of "alt" and "a". However, The line between the top "Adj" and "s" is broken and doesn't look elegant.
```
\documentclass{standalone}
\usepackage{tikz}
\usepackage{tikz-qtree}
\tikzset{every tree node/.style={align=center,anchor=base},
frontier/.style={distance from root=80pt}
}
\begin{document}
\begin{tikzpicture}
\Tree
[.Adj
[.Adj
[.alt\\R ]
[.a\\AF ] ]
[.\node[shape=coordinate] {}; %removes the space (gap) between the edges
[.s\\AF ] ]]
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/6xzelm.png)
Regarding my issue, I have two questions: (1) how can I set my code so that the right-most line goes straight from "Alt" to "s" without the break in between while still keeping "alt", "a", and "s" aligned at the base? And (2), how can I make the edges (ie, the lines) below each "Adj" be the same length without changing to `anchor=north`? Changing the `anchor` to `north` misaligns my nodes because the letter "l" is taller than "a" and "s" in the sister nodes. | 2022/02/23 | [
"https://tex.stackexchange.com/questions/634918",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/175002/"
] | With `forest` package is simple (for me, since I'm a bit more familiar with it than with `tikz-qtree`) :
```
\documentclass[border=3.141592]{standalone}
\usepackage{forest}
\begin{document}
\begin{forest}
for tree = {
% nodes styles
align = center,
font = \linespread{0.84}\selectfont,
inner sep = 1pt,
% tree style
parent anchor = south,
child anchor = north,
if n={1}{l sep=3mm,s sep=1mm}{l sep=6mm, s sep=4mm}
}
%
[Adj
[Adj,
[alt\\R]
[a\\AF, tier=L2]
]
[s\\AF, tier=L2]
]
\end{forest}
\end{document}
```
[](https://i.stack.imgur.com/IWnm0.png)
**Edit (1):**
or would rather have the next tree with edges fixed angles and without nodes on the top of tree.
**Edit (2):**
Original example using `standalone` document class is now adopted to ˙beamer`. By this is show, that image is independent from used document class:
[](https://i.stack.imgur.com/EXfqn.png)
```
\documentclass{beamer}
\usepackage{forest}
\begin{document}
\begin{frame}
\frametitle{Tree drawn by \texttt{forest} package}
\center
\begin{forest}
for tree = {
% nodes styles
align = center,
font = \linespread{0.84}\selectfont,
inner sep = 1pt,
% tree with fixed angles of edges
calign = fixed edge angles,
calign angle = 30,
}
%
[,coordinate
[Adj,
[alt\\R]
[a\\AF, tier=L]
]
[s\\AF, tier=L]
]
\end{forest}
\end{frame}
\end{document}
```
**Addendum:**
If you prefer (for some reason) to use `tikz-qtree` package to drawn your trees and willing to do manual adjustment for nodes positioning, than you may consider the following solution which to some degree simplified defining levels distances at nodes positioning:
```
\documentclass{standalone}
\usepackage{tikz}
\usepackage{tikz-qtree}
\newlength{\LD}
\begin{document}
\begin{tikzpicture}
\pgfmathsetlength\LD{7mm}
\tikzset{
nodes = {inner sep=2pt, align=center,anchor=base},
frontier/.style = {distance from root=3*\LD},
level distance = \LD
}
\Tree [.~
[.Adj
[.alt R ]
[.a AF ]
]
[.\node[yshift=-\LD] {s}; AF ]
]
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/0FJ9P.png) | After fiddling with the code, I discovered that the code I had been using works; I simply had to move the `tikzset{}` portion from the preamble to inside the `tikzpicture` environment. I don't know why having these settings in the environment works but not when they're in the preamble, but it did. Below is my "new" code and the output. I've added this solution in case it's helpful to others.
```
\documentclass{standalone}
\usepackage{tikz}
\usepackage{tikz-qtree}
\begin{document}
\begin{tikzpicture}
\tikzset{every tree node/.style={align=center,anchor=base},
frontier/.style={distance from root=80pt}}
\Tree
[.Adj
[.Adj
{alt\\ R}
{a\\ AF}
]
{s\\ AF}
]
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/I3ay9m.png) |
26,792,337 | If we have a list `s`, is there any difference between calling `list(s)` versus `s[:]`? It seems to me like they both create new list objects with the exact elements of `s`. | 2014/11/07 | [
"https://Stackoverflow.com/questions/26792337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3765966/"
] | In both cases, they *should* create a (shallow) copy of the list.
Note that there is one corner case (which is hardly worth mentioning) where it might be different...
```
list = tuple # Don't ever do this!
list_copy = list(some_list) # Oops, actually it's a tuple ...
actually_list_copy = some_list[:]
```
With that said, **nobody in their right mind should ever shadow the builtin** `list` **like that.**
My advice, use whichever you feel is easier to read and works nicely in the current context.
* `list(...)` makes it explicit that the output is a list and will make a list out of *any* iterable.
* `something[:]` is a common idiom for "give me a shallow copy of this sequence, I don't really care what kind of sequence it is ...", but it doesn't work on arbitrary iterables. | list() is better - it's more readable. Other than that there is no difference. |
26,792,337 | If we have a list `s`, is there any difference between calling `list(s)` versus `s[:]`? It seems to me like they both create new list objects with the exact elements of `s`. | 2014/11/07 | [
"https://Stackoverflow.com/questions/26792337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3765966/"
] | In both cases, they *should* create a (shallow) copy of the list.
Note that there is one corner case (which is hardly worth mentioning) where it might be different...
```
list = tuple # Don't ever do this!
list_copy = list(some_list) # Oops, actually it's a tuple ...
actually_list_copy = some_list[:]
```
With that said, **nobody in their right mind should ever shadow the builtin** `list` **like that.**
My advice, use whichever you feel is easier to read and works nicely in the current context.
* `list(...)` makes it explicit that the output is a list and will make a list out of *any* iterable.
* `something[:]` is a common idiom for "give me a shallow copy of this sequence, I don't really care what kind of sequence it is ...", but it doesn't work on arbitrary iterables. | I didn't realize, but as ventsyv mentioned, `s[:]` and `list(s)` both create a copy of `s`.
Note you can check if an object is the same using `is` and `id()` can be used to get the object's memory address to actually see if they are the same or not.
```
>>> s = [1,2,3]
>>> listed_s = list(s)
>>> id(s)
44056328
>>> id(listed_s) # different
44101840
>>> listed_s is s
False
>>> bracket_s = s[:]
>>> bracket_s is s
False
>>> id(bracket_s)
44123760
>>> z = s # points to the same object in memory
>>> z is s
True
>>> id(z)
44056328
>>>
```
>
> id(...)
> id(object) -> integer
>
>
>
> ```
> Return the identity of an object. This is guaranteed to be unique among
> simultaneously existing objects. (Hint: it's the object's memory address.)
>
> ```
>
> |
26,792,337 | If we have a list `s`, is there any difference between calling `list(s)` versus `s[:]`? It seems to me like they both create new list objects with the exact elements of `s`. | 2014/11/07 | [
"https://Stackoverflow.com/questions/26792337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3765966/"
] | In both cases, they *should* create a (shallow) copy of the list.
Note that there is one corner case (which is hardly worth mentioning) where it might be different...
```
list = tuple # Don't ever do this!
list_copy = list(some_list) # Oops, actually it's a tuple ...
actually_list_copy = some_list[:]
```
With that said, **nobody in their right mind should ever shadow the builtin** `list` **like that.**
My advice, use whichever you feel is easier to read and works nicely in the current context.
* `list(...)` makes it explicit that the output is a list and will make a list out of *any* iterable.
* `something[:]` is a common idiom for "give me a shallow copy of this sequence, I don't really care what kind of sequence it is ...", but it doesn't work on arbitrary iterables. | The short answer is use `list()`. In google type `python [:]` then type `python list`.
If s is a list then there is no difference, but will s always be a list? Or could it be a sequence or a generator?
```
In [1]: nums = 1, 2, 3
In [2]: nums
Out[2]: (1, 2, 3)
In [3]: nums[:]
Out[3]: (1, 2, 3)
In [4]: list(nums)
Out[4]: [1, 2, 3]
In [7]: strings = (str(x) for x in nums)
In [8]: strings
Out[8]: <generator object <genexpr> at 0x7f77be460550>
In [9]: strings[:]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-358af12435ff> in <module>()
----> 1 strings[:]
TypeError: 'generator' object has no attribute '__getitem__'
In [10]: list(strings)
Out[10]: ['1', '2', '3']
``` |
26,792,337 | If we have a list `s`, is there any difference between calling `list(s)` versus `s[:]`? It seems to me like they both create new list objects with the exact elements of `s`. | 2014/11/07 | [
"https://Stackoverflow.com/questions/26792337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3765966/"
] | list() is better - it's more readable. Other than that there is no difference. | I didn't realize, but as ventsyv mentioned, `s[:]` and `list(s)` both create a copy of `s`.
Note you can check if an object is the same using `is` and `id()` can be used to get the object's memory address to actually see if they are the same or not.
```
>>> s = [1,2,3]
>>> listed_s = list(s)
>>> id(s)
44056328
>>> id(listed_s) # different
44101840
>>> listed_s is s
False
>>> bracket_s = s[:]
>>> bracket_s is s
False
>>> id(bracket_s)
44123760
>>> z = s # points to the same object in memory
>>> z is s
True
>>> id(z)
44056328
>>>
```
>
> id(...)
> id(object) -> integer
>
>
>
> ```
> Return the identity of an object. This is guaranteed to be unique among
> simultaneously existing objects. (Hint: it's the object's memory address.)
>
> ```
>
> |
26,792,337 | If we have a list `s`, is there any difference between calling `list(s)` versus `s[:]`? It seems to me like they both create new list objects with the exact elements of `s`. | 2014/11/07 | [
"https://Stackoverflow.com/questions/26792337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3765966/"
] | The short answer is use `list()`. In google type `python [:]` then type `python list`.
If s is a list then there is no difference, but will s always be a list? Or could it be a sequence or a generator?
```
In [1]: nums = 1, 2, 3
In [2]: nums
Out[2]: (1, 2, 3)
In [3]: nums[:]
Out[3]: (1, 2, 3)
In [4]: list(nums)
Out[4]: [1, 2, 3]
In [7]: strings = (str(x) for x in nums)
In [8]: strings
Out[8]: <generator object <genexpr> at 0x7f77be460550>
In [9]: strings[:]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-358af12435ff> in <module>()
----> 1 strings[:]
TypeError: 'generator' object has no attribute '__getitem__'
In [10]: list(strings)
Out[10]: ['1', '2', '3']
``` | I didn't realize, but as ventsyv mentioned, `s[:]` and `list(s)` both create a copy of `s`.
Note you can check if an object is the same using `is` and `id()` can be used to get the object's memory address to actually see if they are the same or not.
```
>>> s = [1,2,3]
>>> listed_s = list(s)
>>> id(s)
44056328
>>> id(listed_s) # different
44101840
>>> listed_s is s
False
>>> bracket_s = s[:]
>>> bracket_s is s
False
>>> id(bracket_s)
44123760
>>> z = s # points to the same object in memory
>>> z is s
True
>>> id(z)
44056328
>>>
```
>
> id(...)
> id(object) -> integer
>
>
>
> ```
> Return the identity of an object. This is guaranteed to be unique among
> simultaneously existing objects. (Hint: it's the object's memory address.)
>
> ```
>
> |
493,386 | I have a circuit that should operate as a voltage-controlled push-pull current driver, able to source or sink at least 2A (into a 1 ohm load). It has unexpected oscillations on the output current.
[](https://i.stack.imgur.com/Zb8Am.png)
Circuit components:
* U1: [LM358P](http://www.ti.com/lit/ds/symlink/lm358.pdf?HQS=TI-null-null-mousermode-df-pf-null-wwe) "rail to rail" opamp
* Q1, Q2: [IRL540NPBF](https://www.mouser.com/datasheet/2/196/irl540npbf-1732926.pdf) power MOSFET, 36A max
* D1: [6A10-B](https://www.mouser.com/datasheet/2/345/6a05-6a10-25734.pdf) rectifier, 6A max avg forward current
Note: Despite the feedback loop being connected to the noninverting input, the opamp has negative feedback because Q1 and R\_D form an inverting amplifier.
**Quick description of circuit operation**
\$V\_{IN}\$ controls the current. \$V\_{IN}=3.3V\$ (roughly) should give \$V\_{L}=5V\$ and therefore zero current through \$R\_L\$. This aspect works properly, and the circuit is stable under this condition (no oscillations). With \$V\_{IN} < 3.3V\$, the circuit should sink current from \$V\_2\$ through \$R\_L\$, D1, and Q1, to GND. This somewhat works, in that the mean value of \$V\_L\$ decreases below 5V (to 4V, etc), but as \$V\_L\$ decreases there are increasingly large oscillations in \$V\_L\$. The oscillations are (distorted) square waves at about 86 kHz. When the mean of \$V\_L\$ is \$\approx 4V\$, the oscillation amplitude is \$\approx 1 Vpp\$.
**Attempts to diagnose the oscillation**
In an earlier version of the circuit I thought the oscillation might be because of delays in the feedback loop, so I followed the instructions [here](https://electronics.stackexchange.com/questions/400522/constant-current-source-with-mosfet-opamp-and-instrument-amp).
I added \$C\_F =\$ 100 nF to make the crossover frequency \$f = 1/(2 \pi R\_{IN} C\_F ) \approx\$ 500 Hz. This made no significant change to the oscillation.
I have also bypassed the power supplies with the largest capacitors (ceramic and electrolytic) that I had on hand.
Can anyone diagnose the source of the oscillation? Thanks much!
p.s. The circuit was inspired by one in Horowitz & Hill 2nd Ed. See Fig 3.75. | 2020/04/15 | [
"https://electronics.stackexchange.com/questions/493386",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/249387/"
] | A significant factor when using power MOSFETS is their very large input capacitance - in this circuit it will add poles at the output of the opamp and the gate of Q2. Together with the very high loop gain in the circuit due to the added gain of Q1 will make it very difficult to stabilize. | With the inductive Zout of opamp in mind(perhaps +j100 at 1MHz), and the Miller-multiplied Cgatedrain of the first FET, why not dampen any opamp peaking by placing 100 ohms in gate of first FET. |
12,714,887 | Checking the LunarLander example it uses that code for resume the drawer thread:
```
public void surfaceCreated(SurfaceHolder holder) {
// start the thread here so that we don't busy-wait in run()
// waiting for the surface to be created
thread.setRunning(true);
thread.start();
}
```
and this for end:
```
public void surfaceDestroyed(SurfaceHolder holder) {
// we have to tell thread to shut down & wait for it to finish, or else
// it might touch the Surface after we return and explode
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
```
But when I execute the project, press the home button and resume the application it crashes with
```
java.lang.IllegalThreadStateException: Thread already started.
at java.lang.Thread.start(Thread.java:1045)
at com.example.android.lunarlander.LunarView.surfaceCreated(LunarView.java:862)
at android.view.SurfaceView.updateWindow(SurfaceView.java:533)
at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:226)
at android.view.View.dispatchWindowVisibilityChanged(View.java:5839)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
```
I've seen this method for handling the background thread in other examples but it crashes. What is the problem with it? | 2012/10/03 | [
"https://Stackoverflow.com/questions/12714887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/853836/"
] | Your thread is still running, you dont stop it correctly i guess.
You have to interrupt your thread or thats how i solved it. So instead of using setRunning and a boolean to make your thread run you use something like this:
to start it:
```
public void surfaceCreated(SurfaceHolder holder) {
thread.start();
}
```
In the thread:
```
public void run() {
try {
while (true) {
// code here
}
}
catch (InterruptedException e) {
//disable stuff here
}
}
```
And to stop it:
```
public void surfaceDestroyed(SurfaceHolder holder) {
thread.interrupt();
}
```
I just typed this quickly but it should give you an idea. | You can do it like this:
```
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!thread.isAlive()) {
thread.start();
}
}
``` |
12,714,887 | Checking the LunarLander example it uses that code for resume the drawer thread:
```
public void surfaceCreated(SurfaceHolder holder) {
// start the thread here so that we don't busy-wait in run()
// waiting for the surface to be created
thread.setRunning(true);
thread.start();
}
```
and this for end:
```
public void surfaceDestroyed(SurfaceHolder holder) {
// we have to tell thread to shut down & wait for it to finish, or else
// it might touch the Surface after we return and explode
boolean retry = true;
thread.setRunning(false);
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
```
But when I execute the project, press the home button and resume the application it crashes with
```
java.lang.IllegalThreadStateException: Thread already started.
at java.lang.Thread.start(Thread.java:1045)
at com.example.android.lunarlander.LunarView.surfaceCreated(LunarView.java:862)
at android.view.SurfaceView.updateWindow(SurfaceView.java:533)
at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:226)
at android.view.View.dispatchWindowVisibilityChanged(View.java:5839)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:945)
```
I've seen this method for handling the background thread in other examples but it crashes. What is the problem with it? | 2012/10/03 | [
"https://Stackoverflow.com/questions/12714887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/853836/"
] | Your thread is still running, you dont stop it correctly i guess.
You have to interrupt your thread or thats how i solved it. So instead of using setRunning and a boolean to make your thread run you use something like this:
to start it:
```
public void surfaceCreated(SurfaceHolder holder) {
thread.start();
}
```
In the thread:
```
public void run() {
try {
while (true) {
// code here
}
}
catch (InterruptedException e) {
//disable stuff here
}
}
```
And to stop it:
```
public void surfaceDestroyed(SurfaceHolder holder) {
thread.interrupt();
}
```
I just typed this quickly but it should give you an idea. | This is how I solved this issue. In the surfaceCreated method, the state of the thread may have changed to TERMINATED. You need to create the thread a new.
```
@Override
public void surfaceCreated(SurfaceHolder holder) {
bgSurfaceThread = bgSurfaceThread.getState().equals(Thread.State.TERMINATED) ? bgSurfaceThread : new BackgroundSurfaceThread(BackgroundSurfaceView.this);
bgSurfaceThread.setRunning(true);
bgSurfaceThread.start();
}
``` |
31,055 | Could you please correct my text ?
虽然我会说一口流利的法语,但是我想说一口流利的汉语。
我的职业 是律师。
律师 的责任很大,因为他必须解决严重得实情。然后压力大。
可是在巴黎 律师逐渐增加。 因此招聘越来越少。 | 2018/08/11 | [
"https://chinese.stackexchange.com/questions/31055",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/20244/"
] | The a versions are acceptable I'm told. 2 needed no changes.
1. 虽然我会说一口流利的法语,但是我想说一口流利的汉语。(illogical 虽然。。。但是。。。)
1a. 我已经会说一口流利的法语,我希望我的汉语能像我的法语一样流利。
2. 我的职业是律师。
3. 律师的责任很大,因为他必须解决严重得实情。然后压力大。
3a. 作为律师,我的压力很大,责任很重,因为律师总得解决严重的事情。
4. 可是在巴黎 律师逐渐增加。 因此招聘越来越少。
4a. 在巴黎律师的数量越来越多,因此工作机会越来越少。 | 虽然我会说一口流利的法语,但是我想说一口流利的汉语。
我的职业是律师。
律师的责任很大,因为他必须解决严重**得实情**。然后压力大。
律师的责任很大,因为他必须**处理**严重**的案件**。然后压力**很**(1)大。
可是在巴黎,律师逐渐增加。因此**招聘**越来越少。
可是在巴黎,律师逐渐增加。因此**工作机会**越来越少。
(1) [很 - Chinese Grammar Wiki](https://resources.allsetlearning.com/chinese/grammar/%E5%BE%88) |
380,400 | Is it a common phrase 'Thanks for your trouble' ?
I read this sentence in some speaking books.
However, I think the phrase 'thanks for your effort' is better to express my
intentions, doesn't it? | 2017/03/27 | [
"https://english.stackexchange.com/questions/380400",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/226924/"
] | Yes, ***"Thanks for your trouble"*** or ***"Thank you for your trouble"*** is a very common phrase (In fact I use it quite often).
>
> It doesn't mean *He is creating the trouble*, it is *you* who is creating a *trouble/burden* for *him*. To elaborate, think of the sentence like
>
>
> * *"Thank you for (handling/taking care of) the trouble (I put you through)."*
>
>
> You are thanking him for *"taking the trouble to help you."*
>
>
>
Another way of saying this might be - *"Sorry for any inconvenience this might have caused, but I sure do appreciate it."*
Your final phrase - ***"Thanks for your effort"*** would in fact sound quite off in most context.
>
> *Thanks for your effort* makes it sound a little bit like --
> *He failed in helping you, but you appreciate the effort anyway.*
>
>
> I wouldn't use it, as it doesn't really make you seem like you are totally satisfied with "*his (the person you're thanking) help*".
>
>
> *"Thanks for your help/favor"* would be more natural than this variation.
>
>
> | Yes, "thanks for your trouble" is certainly common. This [Ngram](https://books.google.com/ngrams/graph?content=thanks%20for%20your%20trouble&year_start=1800&year_end=2019&corpus=26&smoothing=3&direct_url=t1%3B%2Cthanks%20for%20your%20trouble%3B%2Cc0#t1%3B%2Cthanks%20for%20your%20trouble%3B%2Cc0) shows that it was especially common in the 1800s. The following excerpt is from the *Comedy of the School for Wives*, which was first published in 1663, written by the French playwright and dramaturg, Molière.
>
> *Mir*: And I, madam, like a true modern patron, shall hardly **give you thanks for your trouble.**
>
> *Bis*: Come, sir, to let you see what little foundation you have for your dear sufficiency, I'll take you to pieces.
>
> *Mir*: And what piece will you choose?
>
> *Bis*: Your heart to be sure;…
>
>
>
The expression has tailed-off in recent times, but its use still remains widespread.
[](https://i.stack.imgur.com/Rsqfa.png) |
8,421,325 | Okay, Ive searched around and found how this is supposed to be done. For example, finding [this question](https://stackoverflow.com/questions/6709449/run-php-function-once). However it is not working for me, so I must be doing something wrong, but darned if I know what.
Okay... here is my little code block:
```
<?php
session_start();
if(!isset($_SESSION['didit'])) {
$url = "http://www.mysite.com/clients/vatera.asmx/DoSomething";
file_get_contents($url);
$_SESSION['didit'] = true;
}
?>
```
The **url** `file_get_contents` is all working perfectly. The only thing not working is the "run once" check. It is running the **url** code EVERY time through the page. It should only run it the first time you hit the page in a session. This block is located immediately following the `<html>` tag in my page.
Some other things I have tried:
```
if(empty($_SESSION['didit']))
if($_SESSION['didit'] != true)
if($_SESSION['didit'] <> true)
```
I also tried moving the line setting the variable to precede the **$url** assignment.
None of these have worked. It continues to run the code EVERY time the page is loaded.
Thanks in advance! | 2011/12/07 | [
"https://Stackoverflow.com/questions/8421325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/80209/"
] | When you say "**following** the `<html>` tag", you mean **before**, right?
`session_start()` must come before any output. | how do you test your code? It will work OK only in real browsers. So, if you using `wget` or `curl` to test - your conditional code will always run b/c wget & curl do not keep session cookies by default.
Also be sure that you do not block cookies in your browser. |
39,485 | I'm trying to fix the "failed to refresh: TfsOlapReport" error on the TFS project portal dashboards in SharePoint 2010. I've followed the instructions [here](http://blogs.technet.com/b/chrad/archive/2010/07/21/tfs-dashboards-in-moss-2010-return-access-denied-for-tfsolapreport-to-end-users.aspx) to make sure the Secure Store Service and the TFS Reports are configured correctly.
The only error log I can see is the following stack trace in the SharePoint 2010 server ULS logs when Excel Services attempt to connect to the data source.
The Application ID is "TFS", which links to an account in SSS "DOMAIN\TFSReports". You can see that this lookup succeeds. It looks to me like there is some strange error when opening the OLEDBConnection - PF\_CHECK\_ERROR.
(This is paraphrased from another machine without internet access)
```
StoredCredentialProvider.GetCredentials: Credentials added to stored cache for Secure Store Application Id: TFS
ConnectionManager.GetConnection: ConnectionKey=[[3344175, TFSReports], [Oledb, Stored, TFS, False], 1033, ]
ConnectionManager.GetConnection: Didn't find the connection without the workbook version. Updated connection key with the workbook version for another lookup ConnectionKey=[[3344175, TFSReports], [Oledb, Stored, TFS, False], 1033, ConnectionInfo.WorkbookVersion: Uri=http://sharepoint/Reports/Burndown.xlsx, Version=Wednesday 06 June 2012 14:31:00]
Credentials.TryLogonUser: called for connection username: TFSReports, domain: DOMAIN
PF_CHECK_ERROR return 'hresult error' 0x80040154 ; Stack Trace: NA
OLEDBConnection::SetInitProperties: Class not registered
PF_CHECK_ERROR return 'hresult error' 0x80040154 ; Stack Trace: NA
ConnectionManager.GetConnection: Failed to created new connection [...]
ConnectionManager.GetConnection: Caught an exception [...]
Refresh failed for 'TfsOlapReport' in the workbook http://sharepoint/Reports/Burndown.xlsx
ConnectionManager.InitConnInfoFromOdcFile: ODC File Uri is not valid
ExternalSource.ExecuteOperation: We exhausted all available connection information.
```
I've run out of things to search for now. Has anyone seen anything like this before? Does anyone have a stack trace of a successful Excel Services refresh so I can see where things are going wrong? Any help appreciated. | 2012/06/26 | [
"https://sharepoint.stackexchange.com/questions/39485",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/9106/"
] | Since SharePoint 2010 and Analysis Services 2008 were on seperate machines, I could see the logon via Windows Authentication as DOMAIN\TFSReports was succeeding on the Analysis Services machine in Event Viewer\Security logs. So I knew Excel Services was getting that far...
Googling in general about the PF\_CHECK\_ERROR and "class not registered" it looked like some sort of COM error in the OLEDBConnection. What class or DLL could it be trying to load that isn't registered?
Well, the OLE DB connection type is MS OLAP, and the connection string in the sheet's embedded ODC file specifies OLAP.3. Surprise, surprise, OLAP 2 and 4 are present on the Analysis Services machine, *but not MSOLAP.3!!* (Confirmed with regedit - HKEY\_CLASSES\_ROOT\MSOLAP).
So I opened the report, changed the connection string to Provider=MSOLAP.4 in the connection properties for TfsOlapReport, saved and published - that particular report then refreshed correctly. I have now updated all of the Excel Reports in the Team Project to use OLAP 4 and all dashboards are working.
---
Hope this helps anyone else trying to use Excel Services and the Secure Store Service - I was about to go even further down the rabbit hole with Kerberos, especially as client and server are on different (but trusted) domains, but no you don't need any of that. It really is as simple as the instructions [here](http://blogs.technet.com/b/chrad/archive/2010/07/21/tfs-dashboards-in-moss-2010-return-access-denied-for-tfsolapreport-to-end-users.aspx) as long as all the dependencies are installed correctly!
To get the initial logs I post in the question, I had to turn on Verbose logging for Excel Services Application and Secure Store Service in Central Administration > Monitoring > Configure diagnostic logging. Logs will then appear in %Program Files%\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS (obvious, huh?).
(One thing I'm still unclear about is whether installing MSOLAP 3 on the Analysis Services machine would be a way fix the problem without changing connection strings. Is OLAP loaded by Excel Services on the SharePoint server or by Analysis Services on the Analysis Server? I will confirm when I get hold of an x64 installer for it). | Please confirm the following as mentioned below
1. The ODC file specified in the workbook is in an accessible trusted data connection library, or configure the trusted file location where the workbook resides to allow embedded connections.
2. The unattended service account is configured in Excel Services Global Settings, that the designated target application exists in Secure Store, and that the Excel Services application pool account is a Member of the target application.
3. The document library where the workbook resides is configured as a trusted file location in Excel Services.
If embedded connections are allowed and Always use connection file is not selected, Excel Services will attempt to connect using the embedded connection information. If the connection fails, the appropriate error will display. Excel Services will then attempt to use this ODC file.
A detailed data refresh flowchart has been provided by Microsoft for excel services SP 2010 which should assist you further for self troubleshooting :- <http://technet.microsoft.com/en-us/library/hh369968.aspx> |
553,590 | I just got my new Lenovo Flex 2-15 with preinstalled Windows 8 using which I do not want to use.
I would like to install Ubuntu on it but I never had experience with touch screens and I am wondering if it is a good idea at all and if it will have a proper touch screen support or if not, any other Linux distributions that might have it? Are there any other driver problems like WiFi, for example, that may arise? | 2014/11/25 | [
"https://askubuntu.com/questions/553590",
"https://askubuntu.com",
"https://askubuntu.com/users/351964/"
] | I have a Lenovo Flex 14 (series 1), I have installed Ubuntu 14.04 LTS alongside Windows 8. For me, the touch screen works a treat, although I am old school and never have the need to touch it during normal use, I prefer to use the mouse and keyboard.
Hope that helps. | When you asked this question, the answer would have been no. I was running only Ubuntu on this system with no issues. However I did have to reload Windows on here a couple of months ago and it upgraded to Windows 10. After that, I was able to go back to Ubuntu with no need for Windows (happy dance).
Now, here is where the problems are starting to compound. The laptop would no longer just shutdown, it would power back on after 3 to 5 seconds. Also, wifi would stop functioning after roughly 15 to 20 minutes regardless of what the Ubuntu said. Restarting the network would have no effect. The only thing that I can think of is that there was an update to the UEFI.
I have tried many different flavors of Linux since then, Arch, Kali, Red Hat, Slackware, even FreeBSD in legacy mode. Same issue, wifi drops off after 15 minutes and is no longer useful. The only operating system that seems to work perfectly with this laptop is Windows 10. Believe it or not, it was having issues with Windows 8.1 when I did a restore. I had to hardwire it to be able to update to Windows 10 again. So beware if you are planning on dumping Windows off this machine. It would be best to use a virtual machine and run anything other than Windows on top of Windows. *shudder* |
33,154,012 | I'm new to windowed functions. Here is the original table with 4 types of fruit.
```
fruit quantity
orange 100
banana 27
banana 20
orange 5
melon 5
apple 1
banana 10
banana 4
banana 36
banana 86
banana 47
apple 32
banana 7
banana 5
banana 3
```
Is it possible to turn this into the percentage each fruit makes up of the total quantity for EVERYTHING? Here is what I want:
```
fruit total percentage
apple 33 9%
banana 245 63%
orange 105 27%
melon 5 1%
```
Here is the code I'm trying out, but it's giving me an error:
```
SELECT fruit
, SUM(quantity) / SUM(quantity) OVER () * 100
FROM fruit_inventory
GROUP BY fruit
```
If I undo the `GROUP BY` and remove the first `SUM(quantity)` then I get multiple records that look like this:
```
fruit quantity percentage
apple 1 0%
apple 32 8%
banana 27 7%
banana 20 5%
banana 10 3%
banana 4 1%
banana 36 9%
banana 86 22%
banana 47 12%
banana 7 2%
banana 5 1%
banana 3 1%
melon 5 1%
orange 100 26%
orange 5 1%
``` | 2015/10/15 | [
"https://Stackoverflow.com/questions/33154012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191190/"
] | Use a windowed `sum` of the aggregate `sum`.
```
SELECT Fruit ,
SUM(Quantity) AS Quantity ,
SUM(Quantity) / SUM(SUM(Quantity)) OVER () * 100
FROM @fruitbasket
GROUP BY Fruit;
``` | I believe this is what you're looking for:
```
declare @fruitbasket table
(
Fruit nvarchar(50),
Quantity decimal(19, 5)
);
insert into @fruitbasket
(Fruit, Quantity)
values (N'orange', 100),
(N'banana', 27),
(N'banana', 20),
(N'orange', 5),
(N'melon', 5),
(N'apple', 1),
(N'banana', 10),
(N'banana', 4),
(N'banana', 36),
(N'banana', 86),
(N'banana', 47),
(N'apple', 32),
(N'banana', 7),
(N'banana', 5),
(N'banana', 3);
select Fruit,
sum(Quantity) as Quantity,
sum(Quantity) / (
select sum(Quantity) as Total
from @fruitbasket
) * 100 as PercentageOfTotal
from @fruitbasket
group by Fruit;
``` |
33,154,012 | I'm new to windowed functions. Here is the original table with 4 types of fruit.
```
fruit quantity
orange 100
banana 27
banana 20
orange 5
melon 5
apple 1
banana 10
banana 4
banana 36
banana 86
banana 47
apple 32
banana 7
banana 5
banana 3
```
Is it possible to turn this into the percentage each fruit makes up of the total quantity for EVERYTHING? Here is what I want:
```
fruit total percentage
apple 33 9%
banana 245 63%
orange 105 27%
melon 5 1%
```
Here is the code I'm trying out, but it's giving me an error:
```
SELECT fruit
, SUM(quantity) / SUM(quantity) OVER () * 100
FROM fruit_inventory
GROUP BY fruit
```
If I undo the `GROUP BY` and remove the first `SUM(quantity)` then I get multiple records that look like this:
```
fruit quantity percentage
apple 1 0%
apple 32 8%
banana 27 7%
banana 20 5%
banana 10 3%
banana 4 1%
banana 36 9%
banana 86 22%
banana 47 12%
banana 7 2%
banana 5 1%
banana 3 1%
melon 5 1%
orange 100 26%
orange 5 1%
``` | 2015/10/15 | [
"https://Stackoverflow.com/questions/33154012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191190/"
] | I believe this is what you're looking for:
```
declare @fruitbasket table
(
Fruit nvarchar(50),
Quantity decimal(19, 5)
);
insert into @fruitbasket
(Fruit, Quantity)
values (N'orange', 100),
(N'banana', 27),
(N'banana', 20),
(N'orange', 5),
(N'melon', 5),
(N'apple', 1),
(N'banana', 10),
(N'banana', 4),
(N'banana', 36),
(N'banana', 86),
(N'banana', 47),
(N'apple', 32),
(N'banana', 7),
(N'banana', 5),
(N'banana', 3);
select Fruit,
sum(Quantity) as Quantity,
sum(Quantity) / (
select sum(Quantity) as Total
from @fruitbasket
) * 100 as PercentageOfTotal
from @fruitbasket
group by Fruit;
``` | Using CTE (Common Table Expression) you can have the results like you wanted.
Overall CTE's do have better performance and are better readable.
```
WITH cte AS
(
SELECT DISTINCT
Fruit
,SUM(Quantity) OVER (PARTITION BY fruit ORDER BY fruit) AS sumProducts
,SUM(SUM(Quantity)) OVER () AS totalProducts
FROM stackOverflow
GROUP BY
Fruit
,Quantity
)
SELECT Fruit, CAST(sumProducts AS INT) AS sumProducts, CAST(100 * sumProducts / totalProducts AS DECIMAL(5,2)) AS percentage
FROM cte
``` |
33,154,012 | I'm new to windowed functions. Here is the original table with 4 types of fruit.
```
fruit quantity
orange 100
banana 27
banana 20
orange 5
melon 5
apple 1
banana 10
banana 4
banana 36
banana 86
banana 47
apple 32
banana 7
banana 5
banana 3
```
Is it possible to turn this into the percentage each fruit makes up of the total quantity for EVERYTHING? Here is what I want:
```
fruit total percentage
apple 33 9%
banana 245 63%
orange 105 27%
melon 5 1%
```
Here is the code I'm trying out, but it's giving me an error:
```
SELECT fruit
, SUM(quantity) / SUM(quantity) OVER () * 100
FROM fruit_inventory
GROUP BY fruit
```
If I undo the `GROUP BY` and remove the first `SUM(quantity)` then I get multiple records that look like this:
```
fruit quantity percentage
apple 1 0%
apple 32 8%
banana 27 7%
banana 20 5%
banana 10 3%
banana 4 1%
banana 36 9%
banana 86 22%
banana 47 12%
banana 7 2%
banana 5 1%
banana 3 1%
melon 5 1%
orange 100 26%
orange 5 1%
``` | 2015/10/15 | [
"https://Stackoverflow.com/questions/33154012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191190/"
] | Use a windowed `sum` of the aggregate `sum`.
```
SELECT Fruit ,
SUM(Quantity) AS Quantity ,
SUM(Quantity) / SUM(SUM(Quantity)) OVER () * 100
FROM @fruitbasket
GROUP BY Fruit;
``` | Using CTE (Common Table Expression) you can have the results like you wanted.
Overall CTE's do have better performance and are better readable.
```
WITH cte AS
(
SELECT DISTINCT
Fruit
,SUM(Quantity) OVER (PARTITION BY fruit ORDER BY fruit) AS sumProducts
,SUM(SUM(Quantity)) OVER () AS totalProducts
FROM stackOverflow
GROUP BY
Fruit
,Quantity
)
SELECT Fruit, CAST(sumProducts AS INT) AS sumProducts, CAST(100 * sumProducts / totalProducts AS DECIMAL(5,2)) AS percentage
FROM cte
``` |
537,426 | I was hoping to do something like this:
```
echo 'foo' >&3 3| cat
```
Basically, I want to write '`foo`' to `3`, and then only pipe the data in `3` to `cat`. But the above doesn't work, I get:
```
bash: 3: Bad file descriptor
```
Does anyone understand what I am trying to do?
With Node.js, I have working example, here:
<https://gist.github.com/ORESoftware/0ad178f4512bbf956e54dd08f2412883>
In that Node.js gist, which seems reliable, at the command line we do:
```bsh
node foo.js 3> some-file.sh
```
and in the node process we are writing to the `3` file descriptor.
But I am wondering how to do it with pipes instead of redirection.
Something like this:
```bsh
node foo.js 3| cat
``` | 2019/08/26 | [
"https://unix.stackexchange.com/questions/537426",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/113238/"
] | ```sh
{ echo 'hello on fd3' >&3; } 3>&1 | cat
```
Here, `echo` writes to standard output, but we redirect it to file descriptor 3 (this corresponds to the writing to `w` that you do in your Node application). We then output the stream on file descriptor 3 to standard output to be able to send it over the pipe to `cat`.
To also discard the standard output:
```sh
{ echo 'hello on fd1'; echo 'hello on fd3' >&3; } 3>&1 1>/dev/null | cat
```
The first `echo` writes to standard output, and the second writes, via a redirection as in the first example, to file descriptor 3. File descriptor 3 is then sent to standard output (to be able to pipe it) while standard output is discarded.
Note that the `1` in `1>/dev/null` is not actually needed and just added here for clarity.
Both pipelines output `hello on fd3` only.
For your Node application:
```sh
node foo.js 3>&1 | cat
```
or, to also discard standard output,
```sh
node foo.js 3>&1 1>/dev/null | cat
```
or, to send standard output to standard error (the terminal by default),
```sh
node foo.js 3>&1 1>&2 | cat
``` | Not quite a pipe via process-substitution:
```
# cmd 3> >(cat)
```
Or, if you are ok to mix the output of fd3 and stdout,
```
# cmd 3>&1 | cat
``` |
537,426 | I was hoping to do something like this:
```
echo 'foo' >&3 3| cat
```
Basically, I want to write '`foo`' to `3`, and then only pipe the data in `3` to `cat`. But the above doesn't work, I get:
```
bash: 3: Bad file descriptor
```
Does anyone understand what I am trying to do?
With Node.js, I have working example, here:
<https://gist.github.com/ORESoftware/0ad178f4512bbf956e54dd08f2412883>
In that Node.js gist, which seems reliable, at the command line we do:
```bsh
node foo.js 3> some-file.sh
```
and in the node process we are writing to the `3` file descriptor.
But I am wondering how to do it with pipes instead of redirection.
Something like this:
```bsh
node foo.js 3| cat
``` | 2019/08/26 | [
"https://unix.stackexchange.com/questions/537426",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/113238/"
] | You can do it without process substitutions and without mixing fd 1 and 3 or fd 1 and 2:
```
producer(){ echo to_out; echo >&2 to_err; echo >&3 to_fd3; }
consumer(){ sed "s/^/consumer $@: /" >/dev/tty; }
{ producer 3>&1 >&4 | consumer 3; } 4>&1 | consumer 1
to_err
consumer 1: to_out
consumer 3: to_fd3
{ producer 3>&1 >&4 | consumer 3; } 4>&1
to_out
to_err
consumer 3: to_fd3
``` | Not quite a pipe via process-substitution:
```
# cmd 3> >(cat)
```
Or, if you are ok to mix the output of fd3 and stdout,
```
# cmd 3>&1 | cat
``` |
537,426 | I was hoping to do something like this:
```
echo 'foo' >&3 3| cat
```
Basically, I want to write '`foo`' to `3`, and then only pipe the data in `3` to `cat`. But the above doesn't work, I get:
```
bash: 3: Bad file descriptor
```
Does anyone understand what I am trying to do?
With Node.js, I have working example, here:
<https://gist.github.com/ORESoftware/0ad178f4512bbf956e54dd08f2412883>
In that Node.js gist, which seems reliable, at the command line we do:
```bsh
node foo.js 3> some-file.sh
```
and in the node process we are writing to the `3` file descriptor.
But I am wondering how to do it with pipes instead of redirection.
Something like this:
```bsh
node foo.js 3| cat
``` | 2019/08/26 | [
"https://unix.stackexchange.com/questions/537426",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/113238/"
] | ```sh
{ echo 'hello on fd3' >&3; } 3>&1 | cat
```
Here, `echo` writes to standard output, but we redirect it to file descriptor 3 (this corresponds to the writing to `w` that you do in your Node application). We then output the stream on file descriptor 3 to standard output to be able to send it over the pipe to `cat`.
To also discard the standard output:
```sh
{ echo 'hello on fd1'; echo 'hello on fd3' >&3; } 3>&1 1>/dev/null | cat
```
The first `echo` writes to standard output, and the second writes, via a redirection as in the first example, to file descriptor 3. File descriptor 3 is then sent to standard output (to be able to pipe it) while standard output is discarded.
Note that the `1` in `1>/dev/null` is not actually needed and just added here for clarity.
Both pipelines output `hello on fd3` only.
For your Node application:
```sh
node foo.js 3>&1 | cat
```
or, to also discard standard output,
```sh
node foo.js 3>&1 1>/dev/null | cat
```
or, to send standard output to standard error (the terminal by default),
```sh
node foo.js 3>&1 1>&2 | cat
``` | So with bash, this does work:
```
exec 3<> >(cat > temp.sh)
echo a >&3 # write to it
exec 3>&- # close fd 3.
```
but I am wondering if there is a less verbose way to do it. And to do without process substitution, instead of using pipes. |
537,426 | I was hoping to do something like this:
```
echo 'foo' >&3 3| cat
```
Basically, I want to write '`foo`' to `3`, and then only pipe the data in `3` to `cat`. But the above doesn't work, I get:
```
bash: 3: Bad file descriptor
```
Does anyone understand what I am trying to do?
With Node.js, I have working example, here:
<https://gist.github.com/ORESoftware/0ad178f4512bbf956e54dd08f2412883>
In that Node.js gist, which seems reliable, at the command line we do:
```bsh
node foo.js 3> some-file.sh
```
and in the node process we are writing to the `3` file descriptor.
But I am wondering how to do it with pipes instead of redirection.
Something like this:
```bsh
node foo.js 3| cat
``` | 2019/08/26 | [
"https://unix.stackexchange.com/questions/537426",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/113238/"
] | You can do it without process substitutions and without mixing fd 1 and 3 or fd 1 and 2:
```
producer(){ echo to_out; echo >&2 to_err; echo >&3 to_fd3; }
consumer(){ sed "s/^/consumer $@: /" >/dev/tty; }
{ producer 3>&1 >&4 | consumer 3; } 4>&1 | consumer 1
to_err
consumer 1: to_out
consumer 3: to_fd3
{ producer 3>&1 >&4 | consumer 3; } 4>&1
to_out
to_err
consumer 3: to_fd3
``` | So with bash, this does work:
```
exec 3<> >(cat > temp.sh)
echo a >&3 # write to it
exec 3>&- # close fd 3.
```
but I am wondering if there is a less verbose way to do it. And to do without process substitution, instead of using pipes. |
34,626,507 | I am in an environment that contains a `RollingWindow` class where `RollingWindow<T>` can be a collection of any type/object.
I would like to create a C# method to convert a `RollingWindow<T>` into a `List<T>`.
Essentially I'd use it in the following manner:
```
List<int> intList = new List<int>();
List<Record> = recordList = new List<Record>();
RollingWindow<int> intWindow = new RollingWindow<int>(20); //20 elements long
RollingWindow<Record> = recordWindow = new RollingWindow<Record>(10); //10 elements long
ConvertWindowToList(intList, intWindow); // will populate intList with 20 elements in intWindow
ConvertWindowToList(intList, intWindow); // will populate recordList with 10 elements in recordWindow
```
Any thoughts on how I would do this in c#? | 2016/01/06 | [
"https://Stackoverflow.com/questions/34626507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3655973/"
] | Based on the assumption that `RollingWindow<T>` implements `IEnumerable<T>` then;
```
List<int> intList = intWindow.ToList();
List<Record> recordList = recordWindow.ToList();
```
will work | I assume that the `RollingWindow<T>` is derived from `IEnumerable<T>`.
So this could be possible:
```
var enumerableFromWin = (IEnumerable<int>) intWindow;
intList = new List<int>(enumerableFromWin);
var enumRecFromWin = (IEnumerable<Record>) recordWindow;
recordList = new List<Record>(enumRecFromWin);
``` |
13,206,383 | I spend over 8 hours last night to check all the documentations, browsing various post etc and I almost fixed my problem, yet there is stil something missing that I can't understand.
I have a table which stores various user submissions with a unix timestamp (e.g. 1351867293). I am extracting this information and counting it in order to get a total number for submissions "today", "yesterday", "this week" and so on.
The code I was using (for "today submissions") was:
```
WHERE DATE(from_unixtime(comment_date)) = CURRENT_DATE";
```
So far so good, but there was a time offset and the data wasn't displayed correctly. A user here on stackoverflow suggested to use CONVERT\_TZ in order to get the offset fixed.
And here is the point where I am stuck. I am located in the CST timezone and my server seems to be located in the EST timezone. So I used this code
```
WHERE DATE(CONVERT_TZ(from_unixtime(comment_date), 'EST', 'CST')) = CURRENT_DATE";
```
...but it shows me only "0" as a result, though I have submissions for today. I tried different timezones but they all give me "0" as a result. When I replace EST and CST with numbers, for example:
```
WHERE DATE(CONVERT_TZ(from_unixtime(comment_date), '+00:00', '+07:00')) = CURRENT_DATE";
```
... I get a numeric output, but the number is not right. I tried a lot of combinations, including +08:00, -05:00, but nothing seems to work.
Basically what I am asking is what values to I have to place as those two numbers, in order to get correct results? Everything else on my website works and displays correctly in my timezone (CST), I am having only problems with this query.
The IP of my server is 50.116.13.130 if that helps. | 2012/11/03 | [
"https://Stackoverflow.com/questions/13206383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793672/"
] | Because the newly added elements doesn't exist on DOM when you bind that handler. Try using delegated events like below,
```
$(document).ready(function(){
$(document).on('click', '.testing', function(){
$(this).remove();
return false;
});
});
``` | try this ,it doesn't work because you are creating element dynamically, for dynamically created element use on or live of jquery.
```
$("body").on("click", ".testing", function(event){
$(this).remove();
return false;
});
``` |
1,511,029 | I'm tokening with the following, but unsure how to include the delimiters with it.
```
void Tokenize(const string str, vector<string>& tokens, const string& delimiters)
{
int startpos = 0;
int pos = str.find_first_of(delimiters, startpos);
string strTemp;
while (string::npos != pos || string::npos != startpos)
{
strTemp = str.substr(startpos, pos - startpos);
tokens.push_back(strTemp.substr(0, strTemp.length()));
startpos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, startpos);
}
}
``` | 2009/10/02 | [
"https://Stackoverflow.com/questions/1511029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183276/"
] | I can't really follow your code, could you post a working program?
Anyway, this is a simple tokenizer, without testing edge cases:
```
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void tokenize(vector<string>& tokens, const string& text, const string& del)
{
string::size_type startpos = 0,
currentpos = text.find(del, startpos);
do
{
tokens.push_back(text.substr(startpos, currentpos-startpos+del.size()));
startpos = currentpos + del.size();
currentpos = text.find(del, startpos);
} while(currentpos != string::npos);
tokens.push_back(text.substr(startpos, currentpos-startpos+del.size()));
}
```
Example input, delimiter = `$$`:
```
Hello$$Stack$$Over$$$Flow$$$$!
```
Tokens:
```
Hello$$
Stack$$
Over$$
$Flow$$
$$
!
```
Note: I would never use a tokenizer I wrote without testing! please use [boost::tokenizer](http://www.boost.org/doc/libs/1_40_0/libs/tokenizer/index.html)! | It depends on whether you want the preceding delimiters, the following delimiters, or both, and what you want to do with strings at the beginning and end of the string that may not have delimiters before/after them.
I'm going to assume you want each word, with its preceding and following delimiters, but NOT any strings of delimiters by themselves (e.g. if there's a delimiter following the last string).
```
template <class iter>
void tokenize(std::string const &str, std::string const &delims, iter out) {
int pos = 0;
do {
int beg_word = str.find_first_not_of(delims, pos);
if (beg_word == std::string::npos)
break;
int end_word = str.find_first_of(delims, beg_word);
int beg_next_word = str.find_first_not_of(delims, end_word);
*out++ = std::string(str, pos, beg_next_word-pos);
pos = end_word;
} while (pos != std::string::npos);
}
```
For the moment, I've written it more like an STL algorithm, taking an iterator for its output instead of assuming it's always pushing onto a collection. Since it depends (for the moment) in the input being a string, it doesn't use iterators for the input. |
1,511,029 | I'm tokening with the following, but unsure how to include the delimiters with it.
```
void Tokenize(const string str, vector<string>& tokens, const string& delimiters)
{
int startpos = 0;
int pos = str.find_first_of(delimiters, startpos);
string strTemp;
while (string::npos != pos || string::npos != startpos)
{
strTemp = str.substr(startpos, pos - startpos);
tokens.push_back(strTemp.substr(0, strTemp.length()));
startpos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, startpos);
}
}
``` | 2009/10/02 | [
"https://Stackoverflow.com/questions/1511029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183276/"
] | The [C++ String Toolkit Library (StrTk)](http://www.partow.net/programming/strtk/index.html) has the following solution:
```
std::string str = "abc,123 xyz";
std::vector<std::string> token_list;
strtk::split(";., ",
str,
strtk::range_to_type_back_inserter(token_list),
strtk::include_delimiters);
```
It should result with token\_list have the following elements:
```
Token0 = "abc,"
Token1 = "123 "
Token2 = "xyz"
```
More examples can be found [Here](http://www.codeproject.com/KB/recipes/Tokenizer.aspx) | I can't really follow your code, could you post a working program?
Anyway, this is a simple tokenizer, without testing edge cases:
```
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void tokenize(vector<string>& tokens, const string& text, const string& del)
{
string::size_type startpos = 0,
currentpos = text.find(del, startpos);
do
{
tokens.push_back(text.substr(startpos, currentpos-startpos+del.size()));
startpos = currentpos + del.size();
currentpos = text.find(del, startpos);
} while(currentpos != string::npos);
tokens.push_back(text.substr(startpos, currentpos-startpos+del.size()));
}
```
Example input, delimiter = `$$`:
```
Hello$$Stack$$Over$$$Flow$$$$!
```
Tokens:
```
Hello$$
Stack$$
Over$$
$Flow$$
$$
!
```
Note: I would never use a tokenizer I wrote without testing! please use [boost::tokenizer](http://www.boost.org/doc/libs/1_40_0/libs/tokenizer/index.html)! |
1,511,029 | I'm tokening with the following, but unsure how to include the delimiters with it.
```
void Tokenize(const string str, vector<string>& tokens, const string& delimiters)
{
int startpos = 0;
int pos = str.find_first_of(delimiters, startpos);
string strTemp;
while (string::npos != pos || string::npos != startpos)
{
strTemp = str.substr(startpos, pos - startpos);
tokens.push_back(strTemp.substr(0, strTemp.length()));
startpos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, startpos);
}
}
``` | 2009/10/02 | [
"https://Stackoverflow.com/questions/1511029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183276/"
] | if the delimiters are characters and not strings, then you can use [strtok](http://www.cplusplus.com/reference/clibrary/cstring/strtok/). | It depends on whether you want the preceding delimiters, the following delimiters, or both, and what you want to do with strings at the beginning and end of the string that may not have delimiters before/after them.
I'm going to assume you want each word, with its preceding and following delimiters, but NOT any strings of delimiters by themselves (e.g. if there's a delimiter following the last string).
```
template <class iter>
void tokenize(std::string const &str, std::string const &delims, iter out) {
int pos = 0;
do {
int beg_word = str.find_first_not_of(delims, pos);
if (beg_word == std::string::npos)
break;
int end_word = str.find_first_of(delims, beg_word);
int beg_next_word = str.find_first_not_of(delims, end_word);
*out++ = std::string(str, pos, beg_next_word-pos);
pos = end_word;
} while (pos != std::string::npos);
}
```
For the moment, I've written it more like an STL algorithm, taking an iterator for its output instead of assuming it's always pushing onto a collection. Since it depends (for the moment) in the input being a string, it doesn't use iterators for the input. |
1,511,029 | I'm tokening with the following, but unsure how to include the delimiters with it.
```
void Tokenize(const string str, vector<string>& tokens, const string& delimiters)
{
int startpos = 0;
int pos = str.find_first_of(delimiters, startpos);
string strTemp;
while (string::npos != pos || string::npos != startpos)
{
strTemp = str.substr(startpos, pos - startpos);
tokens.push_back(strTemp.substr(0, strTemp.length()));
startpos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, startpos);
}
}
``` | 2009/10/02 | [
"https://Stackoverflow.com/questions/1511029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183276/"
] | I now this a little sloppy, but this is what I ended up with. I did not want to use boost since this is a school assignment and my instructor wanted me to use find\_first\_of to accomplish this.
Thanks for everyone's help.
```
vector<string> Tokenize(const string& strInput, const string& strDelims)
{
vector<string> vS;
string strOne = strInput;
string delimiters = strDelims;
int startpos = 0;
int pos = strOne.find_first_of(delimiters, startpos);
while (string::npos != pos || string::npos != startpos)
{
if(strOne.substr(startpos, pos - startpos) != "")
vS.push_back(strOne.substr(startpos, pos - startpos));
// if delimiter is a new line (\n) then addt new line
if(strOne.substr(pos, 1) == "\n")
vS.push_back("\\n");
// else if the delimiter is not a space
else if (strOne.substr(pos, 1) != " ")
vS.push_back(strOne.substr(pos, 1));
if( string::npos == strOne.find_first_not_of(delimiters, pos) )
startpos = strOne.find_first_not_of(delimiters, pos);
else
startpos = pos + 1;
pos = strOne.find_first_of(delimiters, startpos);
}
return vS;
}
``` | It depends on whether you want the preceding delimiters, the following delimiters, or both, and what you want to do with strings at the beginning and end of the string that may not have delimiters before/after them.
I'm going to assume you want each word, with its preceding and following delimiters, but NOT any strings of delimiters by themselves (e.g. if there's a delimiter following the last string).
```
template <class iter>
void tokenize(std::string const &str, std::string const &delims, iter out) {
int pos = 0;
do {
int beg_word = str.find_first_not_of(delims, pos);
if (beg_word == std::string::npos)
break;
int end_word = str.find_first_of(delims, beg_word);
int beg_next_word = str.find_first_not_of(delims, end_word);
*out++ = std::string(str, pos, beg_next_word-pos);
pos = end_word;
} while (pos != std::string::npos);
}
```
For the moment, I've written it more like an STL algorithm, taking an iterator for its output instead of assuming it's always pushing onto a collection. Since it depends (for the moment) in the input being a string, it doesn't use iterators for the input. |
1,511,029 | I'm tokening with the following, but unsure how to include the delimiters with it.
```
void Tokenize(const string str, vector<string>& tokens, const string& delimiters)
{
int startpos = 0;
int pos = str.find_first_of(delimiters, startpos);
string strTemp;
while (string::npos != pos || string::npos != startpos)
{
strTemp = str.substr(startpos, pos - startpos);
tokens.push_back(strTemp.substr(0, strTemp.length()));
startpos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, startpos);
}
}
``` | 2009/10/02 | [
"https://Stackoverflow.com/questions/1511029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183276/"
] | The [C++ String Toolkit Library (StrTk)](http://www.partow.net/programming/strtk/index.html) has the following solution:
```
std::string str = "abc,123 xyz";
std::vector<std::string> token_list;
strtk::split(";., ",
str,
strtk::range_to_type_back_inserter(token_list),
strtk::include_delimiters);
```
It should result with token\_list have the following elements:
```
Token0 = "abc,"
Token1 = "123 "
Token2 = "xyz"
```
More examples can be found [Here](http://www.codeproject.com/KB/recipes/Tokenizer.aspx) | It depends on whether you want the preceding delimiters, the following delimiters, or both, and what you want to do with strings at the beginning and end of the string that may not have delimiters before/after them.
I'm going to assume you want each word, with its preceding and following delimiters, but NOT any strings of delimiters by themselves (e.g. if there's a delimiter following the last string).
```
template <class iter>
void tokenize(std::string const &str, std::string const &delims, iter out) {
int pos = 0;
do {
int beg_word = str.find_first_not_of(delims, pos);
if (beg_word == std::string::npos)
break;
int end_word = str.find_first_of(delims, beg_word);
int beg_next_word = str.find_first_not_of(delims, end_word);
*out++ = std::string(str, pos, beg_next_word-pos);
pos = end_word;
} while (pos != std::string::npos);
}
```
For the moment, I've written it more like an STL algorithm, taking an iterator for its output instead of assuming it's always pushing onto a collection. Since it depends (for the moment) in the input being a string, it doesn't use iterators for the input. |
1,511,029 | I'm tokening with the following, but unsure how to include the delimiters with it.
```
void Tokenize(const string str, vector<string>& tokens, const string& delimiters)
{
int startpos = 0;
int pos = str.find_first_of(delimiters, startpos);
string strTemp;
while (string::npos != pos || string::npos != startpos)
{
strTemp = str.substr(startpos, pos - startpos);
tokens.push_back(strTemp.substr(0, strTemp.length()));
startpos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, startpos);
}
}
``` | 2009/10/02 | [
"https://Stackoverflow.com/questions/1511029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183276/"
] | The [C++ String Toolkit Library (StrTk)](http://www.partow.net/programming/strtk/index.html) has the following solution:
```
std::string str = "abc,123 xyz";
std::vector<std::string> token_list;
strtk::split(";., ",
str,
strtk::range_to_type_back_inserter(token_list),
strtk::include_delimiters);
```
It should result with token\_list have the following elements:
```
Token0 = "abc,"
Token1 = "123 "
Token2 = "xyz"
```
More examples can be found [Here](http://www.codeproject.com/KB/recipes/Tokenizer.aspx) | if the delimiters are characters and not strings, then you can use [strtok](http://www.cplusplus.com/reference/clibrary/cstring/strtok/). |
1,511,029 | I'm tokening with the following, but unsure how to include the delimiters with it.
```
void Tokenize(const string str, vector<string>& tokens, const string& delimiters)
{
int startpos = 0;
int pos = str.find_first_of(delimiters, startpos);
string strTemp;
while (string::npos != pos || string::npos != startpos)
{
strTemp = str.substr(startpos, pos - startpos);
tokens.push_back(strTemp.substr(0, strTemp.length()));
startpos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, startpos);
}
}
``` | 2009/10/02 | [
"https://Stackoverflow.com/questions/1511029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/183276/"
] | The [C++ String Toolkit Library (StrTk)](http://www.partow.net/programming/strtk/index.html) has the following solution:
```
std::string str = "abc,123 xyz";
std::vector<std::string> token_list;
strtk::split(";., ",
str,
strtk::range_to_type_back_inserter(token_list),
strtk::include_delimiters);
```
It should result with token\_list have the following elements:
```
Token0 = "abc,"
Token1 = "123 "
Token2 = "xyz"
```
More examples can be found [Here](http://www.codeproject.com/KB/recipes/Tokenizer.aspx) | I now this a little sloppy, but this is what I ended up with. I did not want to use boost since this is a school assignment and my instructor wanted me to use find\_first\_of to accomplish this.
Thanks for everyone's help.
```
vector<string> Tokenize(const string& strInput, const string& strDelims)
{
vector<string> vS;
string strOne = strInput;
string delimiters = strDelims;
int startpos = 0;
int pos = strOne.find_first_of(delimiters, startpos);
while (string::npos != pos || string::npos != startpos)
{
if(strOne.substr(startpos, pos - startpos) != "")
vS.push_back(strOne.substr(startpos, pos - startpos));
// if delimiter is a new line (\n) then addt new line
if(strOne.substr(pos, 1) == "\n")
vS.push_back("\\n");
// else if the delimiter is not a space
else if (strOne.substr(pos, 1) != " ")
vS.push_back(strOne.substr(pos, 1));
if( string::npos == strOne.find_first_not_of(delimiters, pos) )
startpos = strOne.find_first_not_of(delimiters, pos);
else
startpos = pos + 1;
pos = strOne.find_first_of(delimiters, startpos);
}
return vS;
}
``` |
6,582,553 | I have these two pieces of code, and I think they are ugly. How can I change them?
1
```
do_withs = Dowith.where(:friend_id => current_user.id)
@doweets = do_withs.collect { |f| f.doweet_id }
@doweets = @doweets.collect { |f| Doweet.find((F)) }
@doweets = @doweets + current_user.doweets
@doweets.flatten!
@doweets.sort! { |a,b| a.date <=> b.date }
```
2
```
@current_user_doweets = current_user.doweets.limit(10)
@friendships = Friendship.where(:friend_id => current_user.id, :status => true)
@friends = @friendships.collect { |f| User.find(f.user_id) }
@friends_doweets = @friends.collect(&:doweets)
@doweets = @current_user_doweets + @friends_doweets
@doweets.flatten!
@doweets.sort! { |a,b| b.created_at <=> a.created_at }
```
models:
```
class Doweet < ActiveRecord::Base
has_many :comments
has_many :likes
has_many :dowiths
belongs_to :user
end
class Dowith < ActiveRecord::Base
belongs_to :doweet
end
class User < ActiveRecord::Base
has_many :doweets
has_many :friendships
end
class Friendship < ActiveRecord::Base
belongs_to :user
end
``` | 2011/07/05 | [
"https://Stackoverflow.com/questions/6582553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827251/"
] | this simplifies things a tad (but my syntax might be off...
```
@doweets = Dowith.where(:friend_id => current_user.id).collect do |d|
[
Doweet.find(d.doweet_id)
]
end
@doweets << current_user.doweets
@doweets.sort! do |a,b| a.date <=> b.date end
``` | ```
@doweets = Dowith.where(:friend_id => current_user.id).collect &:doweet_id
@doweets = Doweet.find_all_by_id(@doweets)
@doweets = (@doweets + current_user.doweets).sort_by &:date
@current_user_doweets = current_user.doweets.limit(10)
@friendships = Friendship.where(:friend_id => current_user.id, :status => true)
@friends = User.includes(:doweets).find_all_by_id(@friendships.collect(&:user_id))
@friends_doweets = @friends.collect(&:doweets).flatten
@doweets = (@current_user_doweets + @friends_doweets).sort_by &:created_at
``` |
6,582,553 | I have these two pieces of code, and I think they are ugly. How can I change them?
1
```
do_withs = Dowith.where(:friend_id => current_user.id)
@doweets = do_withs.collect { |f| f.doweet_id }
@doweets = @doweets.collect { |f| Doweet.find((F)) }
@doweets = @doweets + current_user.doweets
@doweets.flatten!
@doweets.sort! { |a,b| a.date <=> b.date }
```
2
```
@current_user_doweets = current_user.doweets.limit(10)
@friendships = Friendship.where(:friend_id => current_user.id, :status => true)
@friends = @friendships.collect { |f| User.find(f.user_id) }
@friends_doweets = @friends.collect(&:doweets)
@doweets = @current_user_doweets + @friends_doweets
@doweets.flatten!
@doweets.sort! { |a,b| b.created_at <=> a.created_at }
```
models:
```
class Doweet < ActiveRecord::Base
has_many :comments
has_many :likes
has_many :dowiths
belongs_to :user
end
class Dowith < ActiveRecord::Base
belongs_to :doweet
end
class User < ActiveRecord::Base
has_many :doweets
has_many :friendships
end
class Friendship < ActiveRecord::Base
belongs_to :user
end
``` | 2011/07/05 | [
"https://Stackoverflow.com/questions/6582553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827251/"
] | this simplifies things a tad (but my syntax might be off...
```
@doweets = Dowith.where(:friend_id => current_user.id).collect do |d|
[
Doweet.find(d.doweet_id)
]
end
@doweets << current_user.doweets
@doweets.sort! do |a,b| a.date <=> b.date end
``` | 1) Take advantage of your model associations to reduce the number of database queries you generate by eager-loading with the `includes` method:
```
@doweets = Dowith.where(:friend_id => current_user.id).includes(:doweet).collect(&:doweet) + current_user.doweets
@doweets.sort! {|doweet1, doweet2| doweet1.date <=> doweet2.date}
```
2) Very similar to 1:
```
@friends_doweets = Friendship.where(:friend_id => current_user.id, :status => true).includes(:user => :doweets).collect{|friendship| friendship.user.doweets}
@doweets = current_user.doweets.limit(10) + @friends_doweets
@doweets.sort! { |a,b| b.created_at <=> a.created_at }
```
Watch your log file to see the difference in the number of database queries that occur. It's not a huge deal, but I think you can eliminate a lot of instance variables from your code and replace them with local variables. Instance variables in your controller actions should be used to pass data to your views. |
6,582,553 | I have these two pieces of code, and I think they are ugly. How can I change them?
1
```
do_withs = Dowith.where(:friend_id => current_user.id)
@doweets = do_withs.collect { |f| f.doweet_id }
@doweets = @doweets.collect { |f| Doweet.find((F)) }
@doweets = @doweets + current_user.doweets
@doweets.flatten!
@doweets.sort! { |a,b| a.date <=> b.date }
```
2
```
@current_user_doweets = current_user.doweets.limit(10)
@friendships = Friendship.where(:friend_id => current_user.id, :status => true)
@friends = @friendships.collect { |f| User.find(f.user_id) }
@friends_doweets = @friends.collect(&:doweets)
@doweets = @current_user_doweets + @friends_doweets
@doweets.flatten!
@doweets.sort! { |a,b| b.created_at <=> a.created_at }
```
models:
```
class Doweet < ActiveRecord::Base
has_many :comments
has_many :likes
has_many :dowiths
belongs_to :user
end
class Dowith < ActiveRecord::Base
belongs_to :doweet
end
class User < ActiveRecord::Base
has_many :doweets
has_many :friendships
end
class Friendship < ActiveRecord::Base
belongs_to :user
end
``` | 2011/07/05 | [
"https://Stackoverflow.com/questions/6582553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827251/"
] | 1) Take advantage of your model associations to reduce the number of database queries you generate by eager-loading with the `includes` method:
```
@doweets = Dowith.where(:friend_id => current_user.id).includes(:doweet).collect(&:doweet) + current_user.doweets
@doweets.sort! {|doweet1, doweet2| doweet1.date <=> doweet2.date}
```
2) Very similar to 1:
```
@friends_doweets = Friendship.where(:friend_id => current_user.id, :status => true).includes(:user => :doweets).collect{|friendship| friendship.user.doweets}
@doweets = current_user.doweets.limit(10) + @friends_doweets
@doweets.sort! { |a,b| b.created_at <=> a.created_at }
```
Watch your log file to see the difference in the number of database queries that occur. It's not a huge deal, but I think you can eliminate a lot of instance variables from your code and replace them with local variables. Instance variables in your controller actions should be used to pass data to your views. | ```
@doweets = Dowith.where(:friend_id => current_user.id).collect &:doweet_id
@doweets = Doweet.find_all_by_id(@doweets)
@doweets = (@doweets + current_user.doweets).sort_by &:date
@current_user_doweets = current_user.doweets.limit(10)
@friendships = Friendship.where(:friend_id => current_user.id, :status => true)
@friends = User.includes(:doweets).find_all_by_id(@friendships.collect(&:user_id))
@friends_doweets = @friends.collect(&:doweets).flatten
@doweets = (@current_user_doweets + @friends_doweets).sort_by &:created_at
``` |
14,781,659 | I finally got my Django app to deploy on Heroku, using Vagrant and Postgres for both local and production. The localhost is up and running, and I'm in the admin, adding users. But when I run
```
heroku run python manage.py syncdb
```
it barfs up this error:
psycopg2.OperationalError: could not connect to server: No such file or directory
Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
Same thing happens when I try to access the admin online: <http://vast-sierra-7949.herokuapp.com/admin/>
I'm new to Heroku, and I've tried just about every getting started tutorial I could find, including
<http://gettingstartedwithdjango.com/en/lessons/introduction-and-launch/>
<https://devcenter.heroku.com/articles/django>,
<https://github.com/callmephilip/django-heroku-bootstrap>, and
<https://github.com/jpadilla/django-project-template>
This last github link actually allowed me to deploy, before I was just getting an error when I ran
```
git push heroku master
```
and that error was: manage.py: error: no such option: --noreload
I know there are several posts with this error, but I've looked through as many as I could find with no luck on resolving the issue.
Thank you in advance,
Anthony | 2013/02/08 | [
"https://Stackoverflow.com/questions/14781659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319434/"
] | Well, this part of the stack trace is your code:
```
java.lang.NullPointerException
at com.latlon.InitialSearchActivity.e(Unknown Source)
at com.latlon.InitialSearchActivity.a(Unknown Source)
at com.latlon.InitialSearchActivity.g(Unknown Source)
at com.latlon.InitialSearchActivity.a(Unknown Source)
at com.latlon.MyResultReceiver.onReceiveResult(Unknown Source)
```
Your `onReceiveResult()` method in class `MyResultReceiver` was called. That method called a method `a` in the `InitialSearchActivity` class, which called a method `g` in that class which called a method `a` in that class which called a method `e` in that class. In method `e` there was a `NullPointerException` (ie: in that method you tried to use a variable that you thought contained an object reference, but instead that variable contained `null`.
It looks like the method names have been obfuscated, so you may have to look at the code to figure out what the real method names are. | Check the documentation on Proguard (which is the tool that does the code obfusciation).
It is very likely that you "over-obfusciated", which can cause issues with the deployed code. Just like you are seeing.
You can turn off Proguard functionality by editing the "proguard-project.txt" file. To ensure no obfusciation occurs, make sure every line in this file is commented out (by placing a hash - or # mark at the start of each line).
There is a command called `retrace` that allows you to provide unmap your obfusciation. You will need to provide some files created by proguard to get this working.
Check the docs for full explanation: <http://developer.android.com/tools/help/proguard.html>
Quick fix (to eliminate Proguard) is to comment the file, so it doesn't run in the first place. |
14,781,659 | I finally got my Django app to deploy on Heroku, using Vagrant and Postgres for both local and production. The localhost is up and running, and I'm in the admin, adding users. But when I run
```
heroku run python manage.py syncdb
```
it barfs up this error:
psycopg2.OperationalError: could not connect to server: No such file or directory
Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
Same thing happens when I try to access the admin online: <http://vast-sierra-7949.herokuapp.com/admin/>
I'm new to Heroku, and I've tried just about every getting started tutorial I could find, including
<http://gettingstartedwithdjango.com/en/lessons/introduction-and-launch/>
<https://devcenter.heroku.com/articles/django>,
<https://github.com/callmephilip/django-heroku-bootstrap>, and
<https://github.com/jpadilla/django-project-template>
This last github link actually allowed me to deploy, before I was just getting an error when I ran
```
git push heroku master
```
and that error was: manage.py: error: no such option: --noreload
I know there are several posts with this error, but I've looked through as many as I could find with no luck on resolving the issue.
Thank you in advance,
Anthony | 2013/02/08 | [
"https://Stackoverflow.com/questions/14781659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319434/"
] | Well, this part of the stack trace is your code:
```
java.lang.NullPointerException
at com.latlon.InitialSearchActivity.e(Unknown Source)
at com.latlon.InitialSearchActivity.a(Unknown Source)
at com.latlon.InitialSearchActivity.g(Unknown Source)
at com.latlon.InitialSearchActivity.a(Unknown Source)
at com.latlon.MyResultReceiver.onReceiveResult(Unknown Source)
```
Your `onReceiveResult()` method in class `MyResultReceiver` was called. That method called a method `a` in the `InitialSearchActivity` class, which called a method `g` in that class which called a method `a` in that class which called a method `e` in that class. In method `e` there was a `NullPointerException` (ie: in that method you tried to use a variable that you thought contained an object reference, but instead that variable contained `null`.
It looks like the method names have been obfuscated, so you may have to look at the code to figure out what the real method names are. | Looks like you used some toole (like Proguard) to obfuscate your code.
Did you test your APK after obfuscation?
From the logs above a NullPointerException has occured in your code, you'd need to de-obfuscate your code using the key files generated by the obfuscating tool in order to find out the real place (line of code) where null pointer has been accessed.
Please Note,
In the process of obfuscation, sometimes (human error) can cause some of the required methods to be obfuscated. Which in turn causes those methods not to be found, hence an exception (NoSuchMethod) might be raised. |
14,781,659 | I finally got my Django app to deploy on Heroku, using Vagrant and Postgres for both local and production. The localhost is up and running, and I'm in the admin, adding users. But when I run
```
heroku run python manage.py syncdb
```
it barfs up this error:
psycopg2.OperationalError: could not connect to server: No such file or directory
Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
Same thing happens when I try to access the admin online: <http://vast-sierra-7949.herokuapp.com/admin/>
I'm new to Heroku, and I've tried just about every getting started tutorial I could find, including
<http://gettingstartedwithdjango.com/en/lessons/introduction-and-launch/>
<https://devcenter.heroku.com/articles/django>,
<https://github.com/callmephilip/django-heroku-bootstrap>, and
<https://github.com/jpadilla/django-project-template>
This last github link actually allowed me to deploy, before I was just getting an error when I ran
```
git push heroku master
```
and that error was: manage.py: error: no such option: --noreload
I know there are several posts with this error, but I've looked through as many as I could find with no luck on resolving the issue.
Thank you in advance,
Anthony | 2013/02/08 | [
"https://Stackoverflow.com/questions/14781659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1319434/"
] | Looks like you used some toole (like Proguard) to obfuscate your code.
Did you test your APK after obfuscation?
From the logs above a NullPointerException has occured in your code, you'd need to de-obfuscate your code using the key files generated by the obfuscating tool in order to find out the real place (line of code) where null pointer has been accessed.
Please Note,
In the process of obfuscation, sometimes (human error) can cause some of the required methods to be obfuscated. Which in turn causes those methods not to be found, hence an exception (NoSuchMethod) might be raised. | Check the documentation on Proguard (which is the tool that does the code obfusciation).
It is very likely that you "over-obfusciated", which can cause issues with the deployed code. Just like you are seeing.
You can turn off Proguard functionality by editing the "proguard-project.txt" file. To ensure no obfusciation occurs, make sure every line in this file is commented out (by placing a hash - or # mark at the start of each line).
There is a command called `retrace` that allows you to provide unmap your obfusciation. You will need to provide some files created by proguard to get this working.
Check the docs for full explanation: <http://developer.android.com/tools/help/proguard.html>
Quick fix (to eliminate Proguard) is to comment the file, so it doesn't run in the first place. |
55,216 | I have a player of a gnome who tries to get almost everything from campaign setting books.
Should I grant him these thing without including the entire book?
For example: He tried to get the feat "Shadow weave magic", but I'm not going to include a god and a whole lot of zones of magic just because of one feat. He proposed that we only used the mechanics of the feat, but I declined it since he didn't meet the requirement and couldn't worship Shaar as an alternative to pre.
Next up he's trying to get the "Mad/Tinker gnome" from the Dragonlance campaign settings book. (He is playing a beguiler and the illusions get really high will saves from the added int.)
I can't decide whether I should let him have this feature. How should I handle including features from a campaign setting when it could cause problems? What's the general rule with certain features from campaign setting? | 2015/01/11 | [
"https://rpg.stackexchange.com/questions/55216",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/20811/"
] | The DM Can Allow Anything...
----------------------------
That is, if the DM wants to mix in elements from a variety of settings, he can. No RPG police will bust in if, for example, a DM puts dragonmarks and the Shadow Weave into his homebrew setting. In fact, because the typical individual character has limited resources anyway (I mean, really, most characters only ever have 20 class levels, a half-dozen feats, and about 100 skill points when--and if--the campaign ends), combining disparate elements is sometimes extremely useful for realizing a particular concept.
...But It's Wise to Be Wary
---------------------------
The system as a whole is easily exploited. Gamebreakers and loopholes abound. It's *very* easy to wreck campaign worlds with careful selection of powers and spells, and it's sometimes frustrating for beginning DMs when his players have characters that steamroll average foes by carefully picking special abilities from *every* source. Finally, although rare, sometimes when a character combines a relatively tame ability from one setting with *another* seemingly restrained ability from a different setting, the results are explosive without strict DM oversight.
>
> ### Example
>
>
> The Forgotten Realms setting regional feat **Battle Jump** (*Unapproachable East* 42) allows a creature to execute a charge when the creature drops onto a foe. Combined with the system neutral barbarian alternative class feature **spiritual totem (lion)** (*Complete Champion* 46) to get the the special ability pounce, this is deadly but reasonable. Combined with the Eberron campaign setting prestige class **blade of Orien** (*Dragonmarked* 99-101) and that class's special ability swift leap, allowing the character to teleport short distances as a move action , the character can (depending on the DM's rulings--debates have occurred online over this combination) make *several* charges--and, subsequently full attacks--per turn. This might be a power level beyond the beginning DM's ability to manage.
>
>
> However, the feat Battle Jump is, in the Forgotten Realms setting, restricted to taers...
> 
>
>
> ...and while they look kind of neat, they're often a bit too powerful for most starting games, even without the feat Battle Jump. And in the Eberron Campaign Setting, blades of Orien must have a dragonmark--the Mark of Passage--which is exclusive to humans.
>
>
>
Also, while your homebrew setting can incorporate anybody else's setting material, remember that other folks's setting material is usually written so it meshes best with their campaign settings, providing reasons for the existence of specific oddities and background for what would otherwise be nonsense. And while some elements transition easily into any homebrew campaign (e.g. Eberron's magical birthmarks, Forgotten Realms's semiyetis), ignoring setting-specific requirements and prerequisites can lead to strangeness both mechanically and narratively. Prepare yourself for hard questions about your homebrew kitchen-sink setting. ("But why *can't* my semiyeti have the magical *teleport* birthmark?")
What should you do?
===================
It sounds like the player may just be trying to find a way to increase his character's illusion spells' save DCs. That's certainly a cause for concern, especially initially (*color spray* is an outstanding 1st-level spell), but in a long-term campaign that extra +1 to save DCs becomes less and less important (and the mad gnome version of the tinker gnome doesn't even get *that*), so unless he's angling for something *else* because he's a tinker gnome, it's not really a big deal.
But you *should* ask what his plan is, and he should tell you. Collaboration is the key to a good game. | **Answer: Unless there is a clash between your setting and the lore of whatever a player wants from a campaign book, there is no direct reason to disallow. Consider what is most fun for everyone.**
The two most important rules in D&D, its Golden Rule and Rule Zero:
* *"The GM makes the rules; don't argue with the GM"*
* *"Roleplaying games are entertainment; your goal as a group is to make your games as entertaining as possible."*
But as to how one fits: what are the Gnomes like in your campaign? Are they like the Dragonlance Gnomes? Or more like the Gnomes as in regular 3.5e (elaborated on in *Races of Stone*)? Would the Gnome in question be plausible with what your Gnomes are like? If so, then do it! Note that a "Mad" Gnome is not what you'd think in Dragonlance. In a race where everyone is more or less a mad scientist, a "Mad" Gnome... isn't. They're more focussed and technobabble at speeds that would make the Tenth Doctor NOT go "Whoa, slow down there". They are still kind of tinkerish, but their massage chairs tend not to include a battery of self-guided anti-dragon harpoons "because you don't want to be surprised by one".
Unless there is a clear clash with your setting compared to what the players bring to the table (for example, trying to play a Half-Dragon in a setting where there are no dragons whatsoever) then there is no clear reason to disallow it.
Let me put it this way: Why do *you* think you should not allow this character? Aside from the fact that they're from a campaign book?
Then, reverse roles. If your DM were to say "no" to a character you make because you used something from a campaign book that does not clash with their setting, what would your reaction be? Would you think this is reasonable?
On the other hand, you are the DM and what you say goes (Golden Rule). It is not uncommon for DMs to limit the books from which players can use material to write their characters, either for balance reasons, a challenge, a group-wide preference or because they are in another setting. BUT if you cannot produce a good reason for why you limit this then your players might be upset with this.
Another way to approach this is to determine why your player wants a particular option for their character. If they clearly are trying to powergame you are in your good right to say no. But if they want something because of roleplaying reasons or because it fits their character you should consider allowing it, mainly because it is more fun (Rule Zero).
In conclusion, there is no definite answer to this. Consider the situation, the player and their intentions, and above all what will be fun for everyone (and not just the player!) and decide from there. |
55,216 | I have a player of a gnome who tries to get almost everything from campaign setting books.
Should I grant him these thing without including the entire book?
For example: He tried to get the feat "Shadow weave magic", but I'm not going to include a god and a whole lot of zones of magic just because of one feat. He proposed that we only used the mechanics of the feat, but I declined it since he didn't meet the requirement and couldn't worship Shaar as an alternative to pre.
Next up he's trying to get the "Mad/Tinker gnome" from the Dragonlance campaign settings book. (He is playing a beguiler and the illusions get really high will saves from the added int.)
I can't decide whether I should let him have this feature. How should I handle including features from a campaign setting when it could cause problems? What's the general rule with certain features from campaign setting? | 2015/01/11 | [
"https://rpg.stackexchange.com/questions/55216",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/20811/"
] | ### 3.5 as a system has a lot of flaws, and few advantages – enormous selection of material is the biggest one
If you are not taking advantage of the enormous selection of material available in 3.5 (and the flexibility of the system, which allows you to *use* that material, between feats, multiclassing, and so on), I would argue that you are missing out on one of the few things that 3.5 legitimately does *better* than other, similar systems. If you don’t want all that material, you would be better served by using a different system that works better – which could be 4th or 5th edition, Dungeon World, or even something completely different like Fate.
Furthermore, it’s not as if Wizards consistently made one setting more powerful than another – they were supposed to all be workable together. And that more-or-less actually happened, though mostly because even the core books have *wildly* differing power levels depending on the choices that you make. In fact, just about every other book has *less* variability than core does.
So there’s a good, systemic reason to be fairly accommodating, in terms of material allowed, and limited mechanical reason to avoid the material from specific settings. Furthermore, the overwhelming majority of setting-specific options are really rather generic, they just happened to be printed in a setting-specific book. That does *not* mean you should just allow everything – certain, *specific* options may be problematic. For example, Forgotten Realms may not be higher-power in general, but the incantatrix prestige class from *Player’s Guide to Faerûn* certainly is **much** higher-power than typical. Or, as in your example, the Shadow Weave feat depends an *awful* lot on specific features of the Forgotten Realms, which would be awkward or problematic to include in other settings.
Most material from setting-specific books isn’t really a problem. *Some* of it can be, either because it’s poorly-designed (though that happens plenty in non-setting-specific books, too), or because it is *really* specific to the setting it comes from. I strongly recommend *generally* allowing material from other settings, but reserving the right to ban certain things for reasons of either mechanics or fit.
The tinker gnome, though, I don’t see as all that problematic. Fluff-wise, they’re just gnomes that are a little more creative, not that the default gnomes are falling short in that regard. The tinker gnome doesn’t even have to be treated as a separate race, they can just be special or aberrant gnomes. Mechanically, the [default gnome](http://www.d20srd.org/srd/races.htm#gnomes) gets a +1 bonus to the DCs of Illusion spells, which tinker gnomes don’t get: the +2 Intelligence provides a broader bonus, but since your concern was primarily Illusion spell DCs, note that the *core* option would have been just as good in that regard. Furthermore, [gray elves](http://www.d20srd.org/srd/monsters/elf.htm#grayElf) are a core race that gets the same +2 Intelligence. Tinker gnomes are better than gray elves in general, but not *massively* so; generally speaking, humans make better beguilers than do tinker gnomes anyway. Bonus feats are huge.
So yeah, personally: yes in general, but sometimes no to specifics: for example, no to Shadow Weave, but I’d allow the tinker gnome. | **Answer: Unless there is a clash between your setting and the lore of whatever a player wants from a campaign book, there is no direct reason to disallow. Consider what is most fun for everyone.**
The two most important rules in D&D, its Golden Rule and Rule Zero:
* *"The GM makes the rules; don't argue with the GM"*
* *"Roleplaying games are entertainment; your goal as a group is to make your games as entertaining as possible."*
But as to how one fits: what are the Gnomes like in your campaign? Are they like the Dragonlance Gnomes? Or more like the Gnomes as in regular 3.5e (elaborated on in *Races of Stone*)? Would the Gnome in question be plausible with what your Gnomes are like? If so, then do it! Note that a "Mad" Gnome is not what you'd think in Dragonlance. In a race where everyone is more or less a mad scientist, a "Mad" Gnome... isn't. They're more focussed and technobabble at speeds that would make the Tenth Doctor NOT go "Whoa, slow down there". They are still kind of tinkerish, but their massage chairs tend not to include a battery of self-guided anti-dragon harpoons "because you don't want to be surprised by one".
Unless there is a clear clash with your setting compared to what the players bring to the table (for example, trying to play a Half-Dragon in a setting where there are no dragons whatsoever) then there is no clear reason to disallow it.
Let me put it this way: Why do *you* think you should not allow this character? Aside from the fact that they're from a campaign book?
Then, reverse roles. If your DM were to say "no" to a character you make because you used something from a campaign book that does not clash with their setting, what would your reaction be? Would you think this is reasonable?
On the other hand, you are the DM and what you say goes (Golden Rule). It is not uncommon for DMs to limit the books from which players can use material to write their characters, either for balance reasons, a challenge, a group-wide preference or because they are in another setting. BUT if you cannot produce a good reason for why you limit this then your players might be upset with this.
Another way to approach this is to determine why your player wants a particular option for their character. If they clearly are trying to powergame you are in your good right to say no. But if they want something because of roleplaying reasons or because it fits their character you should consider allowing it, mainly because it is more fun (Rule Zero).
In conclusion, there is no definite answer to this. Consider the situation, the player and their intentions, and above all what will be fun for everyone (and not just the player!) and decide from there. |
55,216 | I have a player of a gnome who tries to get almost everything from campaign setting books.
Should I grant him these thing without including the entire book?
For example: He tried to get the feat "Shadow weave magic", but I'm not going to include a god and a whole lot of zones of magic just because of one feat. He proposed that we only used the mechanics of the feat, but I declined it since he didn't meet the requirement and couldn't worship Shaar as an alternative to pre.
Next up he's trying to get the "Mad/Tinker gnome" from the Dragonlance campaign settings book. (He is playing a beguiler and the illusions get really high will saves from the added int.)
I can't decide whether I should let him have this feature. How should I handle including features from a campaign setting when it could cause problems? What's the general rule with certain features from campaign setting? | 2015/01/11 | [
"https://rpg.stackexchange.com/questions/55216",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/20811/"
] | The DM Can Allow Anything...
----------------------------
That is, if the DM wants to mix in elements from a variety of settings, he can. No RPG police will bust in if, for example, a DM puts dragonmarks and the Shadow Weave into his homebrew setting. In fact, because the typical individual character has limited resources anyway (I mean, really, most characters only ever have 20 class levels, a half-dozen feats, and about 100 skill points when--and if--the campaign ends), combining disparate elements is sometimes extremely useful for realizing a particular concept.
...But It's Wise to Be Wary
---------------------------
The system as a whole is easily exploited. Gamebreakers and loopholes abound. It's *very* easy to wreck campaign worlds with careful selection of powers and spells, and it's sometimes frustrating for beginning DMs when his players have characters that steamroll average foes by carefully picking special abilities from *every* source. Finally, although rare, sometimes when a character combines a relatively tame ability from one setting with *another* seemingly restrained ability from a different setting, the results are explosive without strict DM oversight.
>
> ### Example
>
>
> The Forgotten Realms setting regional feat **Battle Jump** (*Unapproachable East* 42) allows a creature to execute a charge when the creature drops onto a foe. Combined with the system neutral barbarian alternative class feature **spiritual totem (lion)** (*Complete Champion* 46) to get the the special ability pounce, this is deadly but reasonable. Combined with the Eberron campaign setting prestige class **blade of Orien** (*Dragonmarked* 99-101) and that class's special ability swift leap, allowing the character to teleport short distances as a move action , the character can (depending on the DM's rulings--debates have occurred online over this combination) make *several* charges--and, subsequently full attacks--per turn. This might be a power level beyond the beginning DM's ability to manage.
>
>
> However, the feat Battle Jump is, in the Forgotten Realms setting, restricted to taers...
> 
>
>
> ...and while they look kind of neat, they're often a bit too powerful for most starting games, even without the feat Battle Jump. And in the Eberron Campaign Setting, blades of Orien must have a dragonmark--the Mark of Passage--which is exclusive to humans.
>
>
>
Also, while your homebrew setting can incorporate anybody else's setting material, remember that other folks's setting material is usually written so it meshes best with their campaign settings, providing reasons for the existence of specific oddities and background for what would otherwise be nonsense. And while some elements transition easily into any homebrew campaign (e.g. Eberron's magical birthmarks, Forgotten Realms's semiyetis), ignoring setting-specific requirements and prerequisites can lead to strangeness both mechanically and narratively. Prepare yourself for hard questions about your homebrew kitchen-sink setting. ("But why *can't* my semiyeti have the magical *teleport* birthmark?")
What should you do?
===================
It sounds like the player may just be trying to find a way to increase his character's illusion spells' save DCs. That's certainly a cause for concern, especially initially (*color spray* is an outstanding 1st-level spell), but in a long-term campaign that extra +1 to save DCs becomes less and less important (and the mad gnome version of the tinker gnome doesn't even get *that*), so unless he's angling for something *else* because he's a tinker gnome, it's not really a big deal.
But you *should* ask what his plan is, and he should tell you. Collaboration is the key to a good game. | ### 3.5 as a system has a lot of flaws, and few advantages – enormous selection of material is the biggest one
If you are not taking advantage of the enormous selection of material available in 3.5 (and the flexibility of the system, which allows you to *use* that material, between feats, multiclassing, and so on), I would argue that you are missing out on one of the few things that 3.5 legitimately does *better* than other, similar systems. If you don’t want all that material, you would be better served by using a different system that works better – which could be 4th or 5th edition, Dungeon World, or even something completely different like Fate.
Furthermore, it’s not as if Wizards consistently made one setting more powerful than another – they were supposed to all be workable together. And that more-or-less actually happened, though mostly because even the core books have *wildly* differing power levels depending on the choices that you make. In fact, just about every other book has *less* variability than core does.
So there’s a good, systemic reason to be fairly accommodating, in terms of material allowed, and limited mechanical reason to avoid the material from specific settings. Furthermore, the overwhelming majority of setting-specific options are really rather generic, they just happened to be printed in a setting-specific book. That does *not* mean you should just allow everything – certain, *specific* options may be problematic. For example, Forgotten Realms may not be higher-power in general, but the incantatrix prestige class from *Player’s Guide to Faerûn* certainly is **much** higher-power than typical. Or, as in your example, the Shadow Weave feat depends an *awful* lot on specific features of the Forgotten Realms, which would be awkward or problematic to include in other settings.
Most material from setting-specific books isn’t really a problem. *Some* of it can be, either because it’s poorly-designed (though that happens plenty in non-setting-specific books, too), or because it is *really* specific to the setting it comes from. I strongly recommend *generally* allowing material from other settings, but reserving the right to ban certain things for reasons of either mechanics or fit.
The tinker gnome, though, I don’t see as all that problematic. Fluff-wise, they’re just gnomes that are a little more creative, not that the default gnomes are falling short in that regard. The tinker gnome doesn’t even have to be treated as a separate race, they can just be special or aberrant gnomes. Mechanically, the [default gnome](http://www.d20srd.org/srd/races.htm#gnomes) gets a +1 bonus to the DCs of Illusion spells, which tinker gnomes don’t get: the +2 Intelligence provides a broader bonus, but since your concern was primarily Illusion spell DCs, note that the *core* option would have been just as good in that regard. Furthermore, [gray elves](http://www.d20srd.org/srd/monsters/elf.htm#grayElf) are a core race that gets the same +2 Intelligence. Tinker gnomes are better than gray elves in general, but not *massively* so; generally speaking, humans make better beguilers than do tinker gnomes anyway. Bonus feats are huge.
So yeah, personally: yes in general, but sometimes no to specifics: for example, no to Shadow Weave, but I’d allow the tinker gnome. |
64,547,654 | I got this error
>
> 'InvokeCommandAction' cannot be added to a collection or dictionary of type 'TriggerActionCollection'
>
>
>
Xaml file as below
```
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:prismI="clr-namespace:Prism.Interactivity;assembly=Prism.Wpf"
```
```
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewKeyDown">
<prismI:InvokeCommandAction Command="{Binding testCmd}"/> ==> this line was error
</i:EventTrigger>
</i:Interaction.Triggers>
```
NuGet installed package:
* Microsoft.Xaml.Behaviors.Wpf 1.1.19
* Prism.Unity 7.2.0.1422
I dont want to use MVVMLight and write behavious myself to use in `i:Interaction.Behavious` | 2020/10/27 | [
"https://Stackoverflow.com/questions/64547654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492730/"
] | The types in *Prism's* interactitvity namespace are based on the `System.Windows.Interactivity` assembly. It is shipped with *Blend for Visual Studio*. If you install it, you can find the assembly in the path below. Prism does **not contain** these assemblies, it only provides types based on it.
```none
C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.5\Libraries\System.Windows.Interactivity.dll
```
You could alternatively install the NuGet package *[System.Windows.Interactivity.WPF](https://www.nuget.org/packages/System.Windows.Interactivity.WPF/)*, but this package is **not official** so I do not recommend it.
To use the older assemblies in XAML, just replace the namespace declaration with this one.
```
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
```
The *[Microsoft.Xaml.Behaviors.Wpf](https://www.nuget.org/packages/Microsoft.Xaml.Behaviors.Wpf)* package is the open source variant that was released in December 2018. Since it ships different assemblies with different namespaces, it is incompatible with types based in the *Blend SDK* assemblies.
The good news is, that *Prism 8* will use the newer package, too. | Prism 7.2.0.1422 brings it's own (old) version of the XAML Behaviors and you are mixing the new nuget package and the old version, that might be the issue. have you tried using
```
<i:InvokeCommandAction Command="{Binding testCmd}"/>
```
thus replaceing `prismI` with `i`? |
72,231,968 | Is there a function in Lua to generate a variable name with a string and a value?
For example, I have the first (string) part `"vari"` and the second (value) part, which can vary. So I want to generate `"vari1"`, `"vari2"`, `"vari3"` and so on. Something like this:
`"vari"..value = 42` should then be `vari1 = 42`.
Thanks | 2022/05/13 | [
"https://Stackoverflow.com/questions/72231968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12076007/"
] | Yes, but it most likely is a bad idea (and this very much seems to be an XY-problem to me). If you need an enumerated "list" of variables, just use a table:
```lua
local var = { 42, 100, 30 }
var[4] = 33 -- add a fourth variable
print(var[1]) -- prints 42
```
if you really need to set a bunch of variables though (perhaps to adhere to some odd API?), I'd recommend using [`("..."):format(...)`](https://www.lua.org/manual/5.4/manual.html#pdf-string.format) to ensure that your variables will be formatted as `var<int>` rather than `var1.0`, `var1e3` or the like.
Th environment in Lua - both the global environment `_G` and the environment of your script `_ENV` (in Lua 5.2), which usually is the global environment, are **just tables** in the end, so you can write to them and read from them the same way you'd write to and read from tables:
```lua
for value = 1, 3 do
_ENV[("vari%d"):format(value)] = value^2
end
print(var3) -- prints 3*3 = 9
-- verbose ways of accessing var3:
print(_ENV.var3) -- still 9
print(_ENV["var"]) -- 9 as well
```
**Note that this is most likely just pollution of your script environment (likely global pollution) which is considered a bad practice (and often bad for performance). Please outline your actual problem and consider using the list approach.** | Yes. Call:
```
rawset(table, key, value)
```
Example:
```
rawset(_G, 'foo', 'bar')
print(foo)
-- Output: bar
-- Lets loop it and rawget() it too
-- rawset() returns table _G here to rawget()
-- rawset() is executed before rawget() in this case
for i = 1, 10 do
print(rawget(rawset(_G, 'var' .. i, i), 'var' .. i))
end
-- Output: 10 lines - First the number 1 and last the number 10
```
See: <https://lua.org/manual/5.1/manual.html#pdf-rawset>
Putting all together and create an own function...
```
function create_vars(var, start, stop)
for i = start, stop do
print(var .. i, '=>', rawget(rawset(_G, var .. i, i), var .. i))
end
end
```
And use it...
```
> create_vars('var', 42, 42)
var42 => 42
> print(var42)
42
``` |
43,998,637 | ```
strings = ("name", "last", "middle")
file = ["name","blabla","middle"]
for line in file:
if any(s in line for s in strings):
print ("found")
```
I want to compare two lists and get check for the common strings, and **if and only if two or more** strings are same.
The above code works well for **one** but I want it to check for **two** keywords.
Eg: It should **only** `print(found)` if **and only if** 'name' and 'middle' is found. Not only if 'name' is found. It should check for **two** strings. | 2017/05/16 | [
"https://Stackoverflow.com/questions/43998637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7625226/"
] | First you can find number of matches using `list comprehension` and then `len > 2` or not
```
>>> num = 2
>>> l = [i for i in strings if i in file]
>>> if len(l) >= num:
print('found')
found
``` | If you like one-liners here's my proposition:
```
# If two or more elemnts from listA are present in listB returns TRUE
def two_or_more(listA, listB):
return sum(map(lambda x : x in listB, listA)) > 1
``` |
43,998,637 | ```
strings = ("name", "last", "middle")
file = ["name","blabla","middle"]
for line in file:
if any(s in line for s in strings):
print ("found")
```
I want to compare two lists and get check for the common strings, and **if and only if two or more** strings are same.
The above code works well for **one** but I want it to check for **two** keywords.
Eg: It should **only** `print(found)` if **and only if** 'name' and 'middle' is found. Not only if 'name' is found. It should check for **two** strings. | 2017/05/16 | [
"https://Stackoverflow.com/questions/43998637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7625226/"
] | You can use `set`s and [`intersection`](https://docs.python.org/3/library/stdtypes.html#set.intersection) if you want to check for the common items (and it's not important which ones).
```
if len(set(strings).intersection(file)) >= 2: # at least 2 common values
print('found')
```
If you want to look for fixed items you could use the [`issubset`](https://docs.python.org/3/library/stdtypes.html#set.issubset) method:
```
strings = ("name", "last", "middle")
file = ["name","blabla","middle"]
check = {'name', 'middle'} # that's a set containing the items to look for.
if check.issubset(strings) and check.issubset(file):
print('found')
``` | First you can find number of matches using `list comprehension` and then `len > 2` or not
```
>>> num = 2
>>> l = [i for i in strings if i in file]
>>> if len(l) >= num:
print('found')
found
``` |
43,998,637 | ```
strings = ("name", "last", "middle")
file = ["name","blabla","middle"]
for line in file:
if any(s in line for s in strings):
print ("found")
```
I want to compare two lists and get check for the common strings, and **if and only if two or more** strings are same.
The above code works well for **one** but I want it to check for **two** keywords.
Eg: It should **only** `print(found)` if **and only if** 'name' and 'middle' is found. Not only if 'name' is found. It should check for **two** strings. | 2017/05/16 | [
"https://Stackoverflow.com/questions/43998637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7625226/"
] | You can use `set`s and [`intersection`](https://docs.python.org/3/library/stdtypes.html#set.intersection) if you want to check for the common items (and it's not important which ones).
```
if len(set(strings).intersection(file)) >= 2: # at least 2 common values
print('found')
```
If you want to look for fixed items you could use the [`issubset`](https://docs.python.org/3/library/stdtypes.html#set.issubset) method:
```
strings = ("name", "last", "middle")
file = ["name","blabla","middle"]
check = {'name', 'middle'} # that's a set containing the items to look for.
if check.issubset(strings) and check.issubset(file):
print('found')
``` | If you like one-liners here's my proposition:
```
# If two or more elemnts from listA are present in listB returns TRUE
def two_or_more(listA, listB):
return sum(map(lambda x : x in listB, listA)) > 1
``` |
926,478 | I'm setting up a small mail server using postfix+dovecot. When running `oppenssl s_client -connect mail.myserver.com:993` (IMAP), the server's certificate is displayed and I'm able to get an email client to connect fine.
However, when I change the port to `25` (SMTP), I get the error
`SSL routines:ssl3_get_record:wrong version number`, and no certificate is returned.
From my research, it seems that the protocols and ciphers allowed in the `10-ssl.conf` file might be the issue, but I've tried so many combinations and I still get the same error. This is what they are at the moment:
```
ssl_protocols = TLSv1.2 TLSv1.1 TLSv1 !SSLv3 !SSLv2
ssl_cipher_list = HIGH:!SSLv2:!SSLv3:!TLSv1.0:!aNULL:!MD5
```
How can I get the server to return the certificate on the SMTP port? | 2018/08/15 | [
"https://serverfault.com/questions/926478",
"https://serverfault.com",
"https://serverfault.com/users/483298/"
] | Your Postfix + Dovecot setup has two different server software performing different roles:
* Dovecot in your configuratoin is a *mail storage server*, responsible for IMAP. Additionally, Dovecot [provides SASL authentication](https://wiki2.dovecot.org/HowTo/PostfixAndDovecotSASL) for Postfix. The configuration file `/etc/dovecot/conf.d/10-ssl.conf` is for Dovecot alone, and therefore it only affects IMAP with `STARTTLS` on port 143 and IMAPS on port 993.
* Postfix is the *mail delivery agent* (MTA) responsible for SMTP, whether it's for other MTAs on TCP port 25, for *message submission* with `STARTTLS` on port 587 or SMTPS on port 465. The main configuration files for Postfix are `main.cf` and `master.cf` under `/etc/postfix/`.
You can only test IMAPS `993` & SMTPS `465` using `oppenssl s_client -connect mail.example.com:465`. For testing `STARTTLS` on SMTP ports `25` & `587` and IMAP port `143` you need to use:
```
openssl s_client -starttls smtp -connect mail.example.com:25
openssl s_client -starttls smtp -connect mail.example.com:587
openssl s_client -starttls imap -connect mail.example.com:143
```
There's also several websites and tools for testing, discussed in a Security Stack Exchange [question](https://security.stackexchange.com/questions/58857/test-starttls-configuration-of-smtp-server). For configuring TLS in Postfix, see [Postfix TLS Support](http://www.postfix.org/TLS_README.html). The [Postfix and Dovecot SASL](https://wiki2.dovecot.org/HowTo/PostfixAndDovecotSASL) documentation also has an example for configuring *submission*. In addition, you need to add TLS parameters to your `main.cf`. | Port 25 do not use SSL by default. Client have to run `STARTTLS` command to begin the negotiations with server about cryptography. In opposite IMAPS on the port 993 begins SSL negotiations immediately on connect. You have to configure and try the SMTPS on the port 465 that acts exactly like IMAPS on 993. |
926,478 | I'm setting up a small mail server using postfix+dovecot. When running `oppenssl s_client -connect mail.myserver.com:993` (IMAP), the server's certificate is displayed and I'm able to get an email client to connect fine.
However, when I change the port to `25` (SMTP), I get the error
`SSL routines:ssl3_get_record:wrong version number`, and no certificate is returned.
From my research, it seems that the protocols and ciphers allowed in the `10-ssl.conf` file might be the issue, but I've tried so many combinations and I still get the same error. This is what they are at the moment:
```
ssl_protocols = TLSv1.2 TLSv1.1 TLSv1 !SSLv3 !SSLv2
ssl_cipher_list = HIGH:!SSLv2:!SSLv3:!TLSv1.0:!aNULL:!MD5
```
How can I get the server to return the certificate on the SMTP port? | 2018/08/15 | [
"https://serverfault.com/questions/926478",
"https://serverfault.com",
"https://serverfault.com/users/483298/"
] | Your Postfix + Dovecot setup has two different server software performing different roles:
* Dovecot in your configuratoin is a *mail storage server*, responsible for IMAP. Additionally, Dovecot [provides SASL authentication](https://wiki2.dovecot.org/HowTo/PostfixAndDovecotSASL) for Postfix. The configuration file `/etc/dovecot/conf.d/10-ssl.conf` is for Dovecot alone, and therefore it only affects IMAP with `STARTTLS` on port 143 and IMAPS on port 993.
* Postfix is the *mail delivery agent* (MTA) responsible for SMTP, whether it's for other MTAs on TCP port 25, for *message submission* with `STARTTLS` on port 587 or SMTPS on port 465. The main configuration files for Postfix are `main.cf` and `master.cf` under `/etc/postfix/`.
You can only test IMAPS `993` & SMTPS `465` using `oppenssl s_client -connect mail.example.com:465`. For testing `STARTTLS` on SMTP ports `25` & `587` and IMAP port `143` you need to use:
```
openssl s_client -starttls smtp -connect mail.example.com:25
openssl s_client -starttls smtp -connect mail.example.com:587
openssl s_client -starttls imap -connect mail.example.com:143
```
There's also several websites and tools for testing, discussed in a Security Stack Exchange [question](https://security.stackexchange.com/questions/58857/test-starttls-configuration-of-smtp-server). For configuring TLS in Postfix, see [Postfix TLS Support](http://www.postfix.org/TLS_README.html). The [Postfix and Dovecot SASL](https://wiki2.dovecot.org/HowTo/PostfixAndDovecotSASL) documentation also has an example for configuring *submission*. In addition, you need to add TLS parameters to your `main.cf`. | To test services, such as SMTP, that run both the clear text protocol as well as an TLS encrypted version of that protocol *on the same TCP port*, you need to instruct openssl to negotiate the TLS protocol upgrade with [STARTTLS](https://en.wikipedia.org/wiki/Opportunistic_TLS) and the [`-starttls protocol`](https://www.openssl.org/docs/man1.1.0/apps/openssl-s_client.html) switch.
Depending on the openssl version, s\_client supports a number of different protocols:
>
> **`-starttls protocol`**
>
> send the protocol-specific message(s) to switch to TLS for communication. **`protocol`** is a keyword for the intended protocol. Currently, the only supported keywords are "smtp", "pop3", "imap",
> "ftp", "xmpp", "xmpp-server", "irc", "postgres", "lmtp", "nntp", "sieve" and "ldap".
>
>
>
So test your Postfix mail server with:
```
oppenssl s_client -starttls smtp -connect mail.example.com:25
``` |
5,430,862 | What is difference between `ContentObserver` and `DatasetObserver`?
When one or another should be used?
I get `Cursor` with single row. I want to be notified about data changes - eg. when row is updated.
Which observer class should I register? | 2011/03/25 | [
"https://Stackoverflow.com/questions/5430862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296427/"
] | If you are using a `ContentProvider` (via `ContentResolver` or `Activity.managedQuery()`) to get your data, simply attach a `ContentObserver` to your `Cursor`. The code in `onChange()` will be called whenever the `ContentResolver` broadcasts a notification for the `Uri` associated with your cursor.
```
Cursor myCursor = managedQuery(myUri, projection, where, whereArgs, sortBy);
myCursor.registerContentObserver(new ContentObserver() {
@Override
public void onChange(boolean selfChange) {
// This cursor's Uri has been notified of a change
// Call cursor.requery() or run managedQuery() again
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
}
```
Make sure your `ContentProvider` is a "good citizen" and registers the `Uri` with the cursor after a query:
```
cursor.setNotificationUri(getContentResolver(), uri);
```
It should also notify the `ContentResolver` of any changes to the underlying data (for instance, during insert, delete, and update operations on your SQLite database):
```
getContentResolver().notifyChange(uri, null);
```
This approach is a good example of the Observer Pattern of object-oriented design. | From my last app developed I can say.
The main difference between ContentObserver and DataSetObserver, is that ContentObserver makes to Observer any change affects on ContentProvider. On the other hand, DataSetObserver Observer any change effect on the database. |
5,430,862 | What is difference between `ContentObserver` and `DatasetObserver`?
When one or another should be used?
I get `Cursor` with single row. I want to be notified about data changes - eg. when row is updated.
Which observer class should I register? | 2011/03/25 | [
"https://Stackoverflow.com/questions/5430862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296427/"
] | If you are using a `ContentProvider` (via `ContentResolver` or `Activity.managedQuery()`) to get your data, simply attach a `ContentObserver` to your `Cursor`. The code in `onChange()` will be called whenever the `ContentResolver` broadcasts a notification for the `Uri` associated with your cursor.
```
Cursor myCursor = managedQuery(myUri, projection, where, whereArgs, sortBy);
myCursor.registerContentObserver(new ContentObserver() {
@Override
public void onChange(boolean selfChange) {
// This cursor's Uri has been notified of a change
// Call cursor.requery() or run managedQuery() again
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
}
```
Make sure your `ContentProvider` is a "good citizen" and registers the `Uri` with the cursor after a query:
```
cursor.setNotificationUri(getContentResolver(), uri);
```
It should also notify the `ContentResolver` of any changes to the underlying data (for instance, during insert, delete, and update operations on your SQLite database):
```
getContentResolver().notifyChange(uri, null);
```
This approach is a good example of the Observer Pattern of object-oriented design. | To provide the supplement to ptc's answer, `DataSetObserver` is used for handling content changes in the [Adapter](http://developer.android.com/intl/zh-cn/reference/android/widget/Adapter.html), for example, it can be used for [updating listview dynamically with Adapter](https://stackoverflow.com/questions/5320358/update-listview-dynamically-with-adapter). You can register a `DataSetObserver` using the `Adapter#registerDataSetObserver()` method.
`DataSetObserver` can also be used to observe the content changes in the [Cursor](http://developer.android.com/intl/zh-cn/reference/android/database/Cursor.html) in a similar fashion. |
5,430,862 | What is difference between `ContentObserver` and `DatasetObserver`?
When one or another should be used?
I get `Cursor` with single row. I want to be notified about data changes - eg. when row is updated.
Which observer class should I register? | 2011/03/25 | [
"https://Stackoverflow.com/questions/5430862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296427/"
] | If you are using a `ContentProvider` (via `ContentResolver` or `Activity.managedQuery()`) to get your data, simply attach a `ContentObserver` to your `Cursor`. The code in `onChange()` will be called whenever the `ContentResolver` broadcasts a notification for the `Uri` associated with your cursor.
```
Cursor myCursor = managedQuery(myUri, projection, where, whereArgs, sortBy);
myCursor.registerContentObserver(new ContentObserver() {
@Override
public void onChange(boolean selfChange) {
// This cursor's Uri has been notified of a change
// Call cursor.requery() or run managedQuery() again
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
}
```
Make sure your `ContentProvider` is a "good citizen" and registers the `Uri` with the cursor after a query:
```
cursor.setNotificationUri(getContentResolver(), uri);
```
It should also notify the `ContentResolver` of any changes to the underlying data (for instance, during insert, delete, and update operations on your SQLite database):
```
getContentResolver().notifyChange(uri, null);
```
This approach is a good example of the Observer Pattern of object-oriented design. | I'm not sure if this question is still on anyone's radar. I have been struggling with the same question for a little while now. What I came up with as my litmus test for deciding whether to use a DataSet Observer or a ContentObserver is pretty straight-forward:
If I need to send a URI in my notification I use a ContentObserver. If I simply need to notify one object that another object has changed -- I use a DataSetObserver.
The delimiting factor, for me at least, is does the object that is sending out the notification expose it's underlying resources (be they objects, records, queries, or cursors) as "Universal Resource Identifiers" to the rest of the application; or does the object hide the source of its data. |
5,430,862 | What is difference between `ContentObserver` and `DatasetObserver`?
When one or another should be used?
I get `Cursor` with single row. I want to be notified about data changes - eg. when row is updated.
Which observer class should I register? | 2011/03/25 | [
"https://Stackoverflow.com/questions/5430862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296427/"
] | To provide the supplement to ptc's answer, `DataSetObserver` is used for handling content changes in the [Adapter](http://developer.android.com/intl/zh-cn/reference/android/widget/Adapter.html), for example, it can be used for [updating listview dynamically with Adapter](https://stackoverflow.com/questions/5320358/update-listview-dynamically-with-adapter). You can register a `DataSetObserver` using the `Adapter#registerDataSetObserver()` method.
`DataSetObserver` can also be used to observe the content changes in the [Cursor](http://developer.android.com/intl/zh-cn/reference/android/database/Cursor.html) in a similar fashion. | From my last app developed I can say.
The main difference between ContentObserver and DataSetObserver, is that ContentObserver makes to Observer any change affects on ContentProvider. On the other hand, DataSetObserver Observer any change effect on the database. |
5,430,862 | What is difference between `ContentObserver` and `DatasetObserver`?
When one or another should be used?
I get `Cursor` with single row. I want to be notified about data changes - eg. when row is updated.
Which observer class should I register? | 2011/03/25 | [
"https://Stackoverflow.com/questions/5430862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296427/"
] | I'm not sure if this question is still on anyone's radar. I have been struggling with the same question for a little while now. What I came up with as my litmus test for deciding whether to use a DataSet Observer or a ContentObserver is pretty straight-forward:
If I need to send a URI in my notification I use a ContentObserver. If I simply need to notify one object that another object has changed -- I use a DataSetObserver.
The delimiting factor, for me at least, is does the object that is sending out the notification expose it's underlying resources (be they objects, records, queries, or cursors) as "Universal Resource Identifiers" to the rest of the application; or does the object hide the source of its data. | From my last app developed I can say.
The main difference between ContentObserver and DataSetObserver, is that ContentObserver makes to Observer any change affects on ContentProvider. On the other hand, DataSetObserver Observer any change effect on the database. |
5,430,862 | What is difference between `ContentObserver` and `DatasetObserver`?
When one or another should be used?
I get `Cursor` with single row. I want to be notified about data changes - eg. when row is updated.
Which observer class should I register? | 2011/03/25 | [
"https://Stackoverflow.com/questions/5430862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296427/"
] | I'm not sure if this question is still on anyone's radar. I have been struggling with the same question for a little while now. What I came up with as my litmus test for deciding whether to use a DataSet Observer or a ContentObserver is pretty straight-forward:
If I need to send a URI in my notification I use a ContentObserver. If I simply need to notify one object that another object has changed -- I use a DataSetObserver.
The delimiting factor, for me at least, is does the object that is sending out the notification expose it's underlying resources (be they objects, records, queries, or cursors) as "Universal Resource Identifiers" to the rest of the application; or does the object hide the source of its data. | To provide the supplement to ptc's answer, `DataSetObserver` is used for handling content changes in the [Adapter](http://developer.android.com/intl/zh-cn/reference/android/widget/Adapter.html), for example, it can be used for [updating listview dynamically with Adapter](https://stackoverflow.com/questions/5320358/update-listview-dynamically-with-adapter). You can register a `DataSetObserver` using the `Adapter#registerDataSetObserver()` method.
`DataSetObserver` can also be used to observe the content changes in the [Cursor](http://developer.android.com/intl/zh-cn/reference/android/database/Cursor.html) in a similar fashion. |
12,315,277 | I've follow the tutorial from this link:
<http://www.adobe.com/devnet/flashplayer/articles/creating-games-away3d.html>
But the code seem like got problems with it that I can't even load the 3D vase.
Here is the code:
```
package
{
import away3d.containers.View3D;
import away3d.events.LoaderEvent;
import away3d.loaders.Loader3D;
import away3d.loaders.parsers.Parsers;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
public class Main extends Sprite
{
private var _view:View3D;
private var _loader:Loader3D;
public function Main()
{
_view = new View3D();
_view.backgroundColor = 0x666666;
_view.antiAlias = 4;
this.addChild(_view);
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
Parsers.enableAllBundled();
_loader = new Loader3D();
_loader.addEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
_loader.addEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
_loader.load( new URLRequest('vase.awd') );
}
private function onResourceComplete(ev:LoaderEvent):void
{
_loader.removeEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
_loader.removeEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
_view.scene.addChild(_loader);
}
private function onLoadError(ev:LoaderEvent):void
{
trace('Could not find', ev.url);
_loader.removeEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
_loader.removeEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
_loader = null;
}
private function onEnterFrame(ev:Event):void
{
_loader.rotationY = stage.mouseX - stage.stageWidth / 2;
_view.camera.y = 3 * (stage.mouseY - stage.stageHeight/2);
_view.camera.lookAt(_loader.position);
_view.render();
}
}
}
```
Any idea where the error is? Or is it got any tutorial that teaching how to load AWD files into flash?
Thanks. | 2012/09/07 | [
"https://Stackoverflow.com/questions/12315277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213089/"
] | I would suggest you to use AssetLibrary to load your Model, its very simple and easy to handle all the things that models contains,
```
AssetLibrary.addEventListener( AssetEvent.ASSET_COMPLETE, onAssetComplete );
AssetLibrary.addEventListener( LoaderEvent.RESOURCE_COMPLETE, onResourceComplete );
AssetLibrary.addEventListener( LoaderEvent.LOAD_ERROR, onLoadError );
```
for detailed example check [This](http://away3d.com/example/3ds_Max_workflow)
I hope it helps you | delete "Parsers.enableAllBundled();"
try this:
AssetLibrary.enableParser(AWD1Parser)
or
AssetLibrary.enableParser(AWD2Parser)
or
var aWD2Parser:AWD2Parser=new AWD2Parser();
\_loader.load(new URLRequest('vase.awd'),null,"vase.awd",aWD2Parser); |
12,315,277 | I've follow the tutorial from this link:
<http://www.adobe.com/devnet/flashplayer/articles/creating-games-away3d.html>
But the code seem like got problems with it that I can't even load the 3D vase.
Here is the code:
```
package
{
import away3d.containers.View3D;
import away3d.events.LoaderEvent;
import away3d.loaders.Loader3D;
import away3d.loaders.parsers.Parsers;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
public class Main extends Sprite
{
private var _view:View3D;
private var _loader:Loader3D;
public function Main()
{
_view = new View3D();
_view.backgroundColor = 0x666666;
_view.antiAlias = 4;
this.addChild(_view);
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
Parsers.enableAllBundled();
_loader = new Loader3D();
_loader.addEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
_loader.addEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
_loader.load( new URLRequest('vase.awd') );
}
private function onResourceComplete(ev:LoaderEvent):void
{
_loader.removeEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
_loader.removeEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
_view.scene.addChild(_loader);
}
private function onLoadError(ev:LoaderEvent):void
{
trace('Could not find', ev.url);
_loader.removeEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
_loader.removeEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
_loader = null;
}
private function onEnterFrame(ev:Event):void
{
_loader.rotationY = stage.mouseX - stage.stageWidth / 2;
_view.camera.y = 3 * (stage.mouseY - stage.stageHeight/2);
_view.camera.lookAt(_loader.position);
_view.render();
}
}
}
```
Any idea where the error is? Or is it got any tutorial that teaching how to load AWD files into flash?
Thanks. | 2012/09/07 | [
"https://Stackoverflow.com/questions/12315277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213089/"
] | I would suggest you to use AssetLibrary to load your Model, its very simple and easy to handle all the things that models contains,
```
AssetLibrary.addEventListener( AssetEvent.ASSET_COMPLETE, onAssetComplete );
AssetLibrary.addEventListener( LoaderEvent.RESOURCE_COMPLETE, onResourceComplete );
AssetLibrary.addEventListener( LoaderEvent.LOAD_ERROR, onLoadError );
```
for detailed example check [This](http://away3d.com/example/3ds_Max_workflow)
I hope it helps you | The vase AWD file adobe has with their tutorial is no longer valid. The AWD spec changed and adobe never updated their tutorial. You will usually get an End Of File error if you try to load it. |
12,315,277 | I've follow the tutorial from this link:
<http://www.adobe.com/devnet/flashplayer/articles/creating-games-away3d.html>
But the code seem like got problems with it that I can't even load the 3D vase.
Here is the code:
```
package
{
import away3d.containers.View3D;
import away3d.events.LoaderEvent;
import away3d.loaders.Loader3D;
import away3d.loaders.parsers.Parsers;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;
public class Main extends Sprite
{
private var _view:View3D;
private var _loader:Loader3D;
public function Main()
{
_view = new View3D();
_view.backgroundColor = 0x666666;
_view.antiAlias = 4;
this.addChild(_view);
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
Parsers.enableAllBundled();
_loader = new Loader3D();
_loader.addEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
_loader.addEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
_loader.load( new URLRequest('vase.awd') );
}
private function onResourceComplete(ev:LoaderEvent):void
{
_loader.removeEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
_loader.removeEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
_view.scene.addChild(_loader);
}
private function onLoadError(ev:LoaderEvent):void
{
trace('Could not find', ev.url);
_loader.removeEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
_loader.removeEventListener(LoaderEvent.LOAD_ERROR, onLoadError);
_loader = null;
}
private function onEnterFrame(ev:Event):void
{
_loader.rotationY = stage.mouseX - stage.stageWidth / 2;
_view.camera.y = 3 * (stage.mouseY - stage.stageHeight/2);
_view.camera.lookAt(_loader.position);
_view.render();
}
}
}
```
Any idea where the error is? Or is it got any tutorial that teaching how to load AWD files into flash?
Thanks. | 2012/09/07 | [
"https://Stackoverflow.com/questions/12315277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1213089/"
] | delete "Parsers.enableAllBundled();"
try this:
AssetLibrary.enableParser(AWD1Parser)
or
AssetLibrary.enableParser(AWD2Parser)
or
var aWD2Parser:AWD2Parser=new AWD2Parser();
\_loader.load(new URLRequest('vase.awd'),null,"vase.awd",aWD2Parser); | The vase AWD file adobe has with their tutorial is no longer valid. The AWD spec changed and adobe never updated their tutorial. You will usually get an End Of File error if you try to load it. |
72,232,908 | I am trying to parse what I originally suspected was a JSON config file from a server.
After some attempts I was able to navigate and collapse the sections within Notepad++ when I selected the formatter as JavaScript.
However I am stuck on how I can convert/parse this data to JSON/another format, no online tools have been able to help with this.
How can I parse this text? Ideally I was trying to use PowerShell, but Python would also be an option if I can figure out how I can even begin the conversion.
**For example, I am trying to parse out each of the servers, ie. test1, test2, test3 and get the data listed within each block.**
Here is a sample of the config file format:
```
servername {
store {
servers {
* {
value<>
port<>
folder<C:\windows>
monitor<yes>
args<-T -H>
xrg<store>
wysargs<-t -g -b>
accept_any<yes>
pdu_length<23622>
}
test1 {
name<test1>
port<123>
root<c:\test>
monitor<yes>
}
test2 {
name<test2>
port<124>
root<c:\test>
monitor<yes>
}
test3 {
name<test3>
port<125>
root<c:\test>
monitor<yes>
}
}
senders
timeout<30>
}
}
``` | 2022/05/13 | [
"https://Stackoverflow.com/questions/72232908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807561/"
] | Here's something that converts the above configfile into dict/json in python. I'm just doing some regex as @zett42 suggested.
```
import re
import json
lines = open('configfile', 'r').read()
# Quotations around the keys (next 3 lines)
lines2 = re.sub(r'([a-zA-Z\d_*]+)\s?{', r'"\1": {', lines)
# Process k<v> as Key, Value pairs
lines3 = re.sub(r'([a-zA-Z\d_*]+)\s?<([^<]*)>', r'"\1": "\2"', lines2)
# Process single key word on the line as Key, value pair with empty value
lines4 = re.sub(r'^\s*([a-zA-Z\d_*]+)\s*$', r'"\1": ""', lines3, flags=re.MULTILINE)
# Insert replace \n with commas in lines ending with "
lines5 = re.sub(r'"\n', '",', lines4)
# Remove the comma before the closing bracket
lines6 = re.sub(r',\s*}', '}', lines5)
# Remove quotes from numerical values
lines7 = re.sub(r'"(\d+)"', r'\1', lines6)
# Add commas after closing brackets when needed
lines8 = re.sub(r'[ \t\r\f]+(?!-)', '', lines7)
lines9 = re.sub(r'(?<=})\n(?=")', r",\n", lines8)
# Enclose in brackets and escape backslash for json parsing
lines10 = '{' + lines9.replace('\\', '\\\\') + '}'
j = json.JSONDecoder().decode(lines10)
```
Edit:
Here's an alternative that may be a little cleaner
```
# Replace line with just key with key<>
lines2 = re.sub(r'^([^{<>}]+)$', r'\1<>', lines, flags=re.MULTILINE)
# Remove spaces not within <>
lines3 = re.sub(r'\s(?!.*?>)|\s(?![^<]+>)', '', lines2, flags=re.MULTILINE)
# Quotations
lines4 = re.sub(r'([^{<>}]+)(?={)', r'"\1":', lines3)
lines5 = re.sub(r'([^:{<>}]+)<([^{<>}]*)>', r'"\1":"\2"', lines4)
# Add commas
lines6 = re.sub(r'(?<=")"(?!")', ',"', lines5)
lines7 = re.sub(r'}(?!}|$)', '},', lines6)
# Remove quotes from numbers
lines8 = re.sub(r'"(\d+)"', r'\1', lines7)
# Escape \
lines9 = '{' + re.sub(r'\\', r'\\\\', lines8) + '}'
``` | **Edit:** I've since come up with a [much simpler, PowerShell-only solution](https://stackoverflow.com/a/72274775/7571258) which I recommend to use.
I'll keep this answer alive as it might still be useful for other scenarios. Also there are propably differences in performance (I haven't measured).
---
[MYousefi](https://stackoverflow.com/users/1991397/myousefi) already posted a [helpful answer](https://stackoverflow.com/posts/72234367/revisions) with a Python implementation.
For **PowerShell**, I've come up with a solution that works without a convert-to-JSON step. Instead, I've adopted and generalized the [RegEx-based tokenizer code](https://github.com/Vanlightly/DslParser) from Jack Vanlightly (also see [related blog post](https://jack-vanlightly.com/blog/2016/2/24/a-more-efficient-regex-tokenizer)). A *tokenizer* (aka *lexer*) splits and categorizes the elements of the input text and outputs a flat stream of *tokens* (categories) and related data. A *parser* can use these as input to create a structured representation of the input text.
The tokenizer is written in generic C# and can be used for any input that can be split using RegEx. The C# code is included in PowerShell using the `Add-Type` command, so no C# compiler is required.
The parser function `ConvertFrom-ServerData` is written in PowerShell for simplicity. You only use the parser directly, so you don't have to know anything about the tokenizer C# code. If you want to adopt the code to different input, you should only have to modify the PowerShell parser code.
Save the following file in the same directory as the PowerShell script:
**"RegExTokenizer.cs":**
```cs
// Generic, precedence-based RegEx tokenizer.
// This code is based on https://github.com/Vanlightly/DslParser
// from Jack Vanlightly (https://jack-vanlightly.com).
// Modifications:
// - Interface improved for ease-of-use from PowerShell.
// - Return all groups from the RegEx match instead of just the value. This simplifies parsing of key/value pairs by requiring only a single token definition.
// - Some code simplifications, e. g. replacing "for" loops by "foreach".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace DslTokenizer {
public class DslToken<TokenType> {
public TokenType Token { get; set; }
public GroupCollection Groups { get; set; }
}
public class TokenMatch<TokenType> {
public TokenType Token { get; set; }
public GroupCollection Groups { get; set; }
public int StartIndex { get; set; }
public int EndIndex { get; set; }
public int Precedence { get; set; }
}
public class TokenDefinition<TokenType> {
private Regex _regex;
private readonly TokenType _returnsToken;
private readonly int _precedence;
public TokenDefinition( TokenType returnsToken, string regexPattern, int precedence ) {
_regex = new Regex( regexPattern, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled );
_returnsToken = returnsToken;
_precedence = precedence;
}
public IEnumerable<TokenMatch<TokenType>> FindMatches( string inputString ) {
foreach( Match match in _regex.Matches( inputString ) ) {
yield return new TokenMatch<TokenType>() {
StartIndex = match.Index,
EndIndex = match.Index + match.Length,
Token = _returnsToken,
Groups = match.Groups,
Precedence = _precedence
};
}
}
}
public class PrecedenceBasedRegexTokenizer<TokenType> {
private List<TokenDefinition<TokenType>> _tokenDefinitions = new List<TokenDefinition<TokenType>>();
public PrecedenceBasedRegexTokenizer() {}
public PrecedenceBasedRegexTokenizer( IEnumerable<TokenDefinition<TokenType>> tokenDefinitions ) {
_tokenDefinitions = tokenDefinitions.ToList();
}
// Easy-to-use interface as alternative to constructor that takes an IEnumerable.
public void AddTokenDef( TokenType returnsToken, string regexPattern, int precedence = 0 ) {
_tokenDefinitions.Add( new TokenDefinition<TokenType>( returnsToken, regexPattern, precedence ) );
}
public IEnumerable<DslToken<TokenType>> Tokenize( string lqlText ) {
var tokenMatches = FindTokenMatches( lqlText );
var groupedByIndex = tokenMatches.GroupBy( x => x.StartIndex )
.OrderBy( x => x.Key )
.ToList();
TokenMatch<TokenType> lastMatch = null;
foreach( var match in groupedByIndex ) {
var bestMatch = match.OrderBy( x => x.Precedence ).First();
if( lastMatch != null && bestMatch.StartIndex < lastMatch.EndIndex ) {
continue;
}
yield return new DslToken<TokenType>(){ Token = bestMatch.Token, Groups = bestMatch.Groups };
lastMatch = bestMatch;
}
}
private List<TokenMatch<TokenType>> FindTokenMatches( string lqlText ) {
var tokenMatches = new List<TokenMatch<TokenType>>();
foreach( var tokenDefinition in _tokenDefinitions ) {
tokenMatches.AddRange( tokenDefinition.FindMatches( lqlText ).ToList() );
}
return tokenMatches;
}
}
}
```
**Parser function written in PowerShell:**
```sh
$ErrorActionPreference = 'Stop'
Add-Type -TypeDefinition (Get-Content $PSScriptRoot\RegExTokenizer.cs -Raw)
Function ConvertFrom-ServerData {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline)] [string] $InputObject
)
begin {
# Define the kind of possible tokens.
enum ServerDataTokens {
ObjectBegin
ObjectEnd
ValueInt
ValueBool
ValueString
KeyOnly
}
# Create an instance of the tokenizer from "RegExTokenizer.cs".
$tokenizer = [DslTokenizer.PrecedenceBasedRegexTokenizer[ServerDataTokens]]::new()
# Define a RegEx for each token where 1st group matches key and 2nd matches value (if any).
# To resolve ambiguities, most specific RegEx must come first
# (e. g. ValueInt line must come before ValueString line).
# Alternatively pass a 3rd integer parameter that defines the precedence.
$tokenizer.AddTokenDef( [ServerDataTokens]::ObjectBegin, '^\s*([\w*]+)\s*{' )
$tokenizer.AddTokenDef( [ServerDataTokens]::ObjectEnd, '^\s*}\s*$' )
$tokenizer.AddTokenDef( [ServerDataTokens]::ValueInt, '^\s*(\w+)\s*<([+-]?\d+)>\s*$' )
$tokenizer.AddTokenDef( [ServerDataTokens]::ValueBool, '^\s*(\w+)\s*<(yes|no)>\s*$' )
$tokenizer.AddTokenDef( [ServerDataTokens]::ValueString, '^\s*(\w+)\s*<(.*)>\s*$' )
$tokenizer.AddTokenDef( [ServerDataTokens]::KeyOnly, '^\s*(\w+)\s*$' )
}
process {
# Output is an ordered hashtable
$outputObject = [ordered] @{}
$curObject = $outputObject
# A stack is used to keep track of nested objects.
$stack = [Collections.Stack]::new()
# For each token produced by the tokenizer
$tokenizer.Tokenize( $InputObject ).ForEach{
# $_.Groups[0] is the full match, which we discard by assigning to $null
$null, $key, $value = $_.Groups.Value
switch( $_.Token ) {
([ServerDataTokens]::ObjectBegin) {
$child = [ordered] @{}
$curObject[ $key ] = $child
$stack.Push( $curObject )
$curObject = $child
break
}
([ServerDataTokens]::ObjectEnd) {
$curObject = $stack.Pop()
break
}
([ServerDataTokens]::ValueInt) {
$intValue = 0
$curObject[ $key ] = if( [int]::TryParse( $value, [ref] $intValue ) ) { $intValue } else { $value }
break
}
([ServerDataTokens]::ValueBool) {
$curObject[ $key ] = $value -eq 'yes'
break
}
([ServerDataTokens]::ValueString) {
$curObject[ $key ] = $value
break
}
([ServerDataTokens]::KeyOnly) {
$curObject[ $key ] = $null
break
}
}
}
$outputObject # Implicit output
}
}
```
**Usage example:**
```sh
$sampleData = @'
servername {
store {
servers {
* {
value<>
port<>
folder<C:\windows>
monitor<yes>
args<-T -H>
xrg<store>
wysargs<-t -g -b>
accept_any<yes>
pdu_length<23622>
}
test1 {
name<test1>
port<123>
root<c:\test>
monitor<yes>
}
test2 {
name<test2>
port<124>
root<c:\test>
monitor<yes>
}
test3 {
name<test3>
port<125>
root<c:\test>
monitor<yes>
}
}
senders
timeout<30>
}
}
'@
# Call the parser
$objects = $sampleData | ConvertFrom-ServerData
# The parser outputs nested hashtables, so we have to use GetEnumerator() to
# iterate over the key/value pairs.
$objects.servername.store.servers.GetEnumerator().ForEach{
"[ SERVER: $($_.Key) ]"
# Convert server values hashtable to PSCustomObject for better output formatting
[PSCustomObject] $_.Value | Format-List
}
```
**Output:**
```text
[ SERVER: * ]
value :
port :
folder : C:\windows
monitor : True
args : -T -H
xrg : store
wysargs : -t -g -b
accept_any : True
pdu_length : 23622
[ SERVER: test1 ]
name : test1
port : 123
root : c:\test
monitor : True
[ SERVER: test2 ]
name : test2
port : 124
root : c:\test
monitor : True
[ SERVER: test3 ]
name : test3
port : 125
root : c:\test
monitor : True
```
**Notes:**
* If you pass input from `Get-Content` to the parser, make sure to use parameter `-Raw`, e. g. `$objects = Get-Content input.cfg -Raw | ConvertFrom-ServerData`. Otherwise the parser would try to parse each input line on its own.
* I've opted to convert "yes"/"no" values to `bool`, so they output as "True"/"False". Remove the line `$tokenizer.AddTokenDef( 'ValueBool', ...` to parse them as `string` instead and output as-is.
* Keys without values `<>` (the "senders" in the example) are stored as keys with value `$null`.
* The RegEx's enforce that values can be single-line only (as the sample data suggests). This allows us to have embedded `>` characters without the need to escape them. |
72,232,908 | I am trying to parse what I originally suspected was a JSON config file from a server.
After some attempts I was able to navigate and collapse the sections within Notepad++ when I selected the formatter as JavaScript.
However I am stuck on how I can convert/parse this data to JSON/another format, no online tools have been able to help with this.
How can I parse this text? Ideally I was trying to use PowerShell, but Python would also be an option if I can figure out how I can even begin the conversion.
**For example, I am trying to parse out each of the servers, ie. test1, test2, test3 and get the data listed within each block.**
Here is a sample of the config file format:
```
servername {
store {
servers {
* {
value<>
port<>
folder<C:\windows>
monitor<yes>
args<-T -H>
xrg<store>
wysargs<-t -g -b>
accept_any<yes>
pdu_length<23622>
}
test1 {
name<test1>
port<123>
root<c:\test>
monitor<yes>
}
test2 {
name<test2>
port<124>
root<c:\test>
monitor<yes>
}
test3 {
name<test3>
port<125>
root<c:\test>
monitor<yes>
}
}
senders
timeout<30>
}
}
``` | 2022/05/13 | [
"https://Stackoverflow.com/questions/72232908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807561/"
] | I've come up with an even simpler solution than my [previous one](https://stackoverflow.com/a/72241688/7571258) which uses **PowerShell** code only.
Using the [RegEx alternation operator](https://learn.microsoft.com/en-us/dotnet/standard/base-types/alternation-constructs-in-regular-expressions) `|` we combine all token patterns into a single pattern and use [named subexpressions](https://learn.microsoft.com/en-us/dotnet/standard/base-types/grouping-constructs-in-regular-expressions#named-matched-subexpressions) to determine which one has actually matched.
The rest of the code is structurally similar to the C#/PS version.
```sh
using namespace System.Text.RegularExpressions
$ErrorActionPreference = 'Stop'
Function ConvertFrom-ServerData {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline)] [string] $InputObject
)
begin {
# Key can consist of anything except whitespace and < > { }
$keyPattern = '[^\s<>{}]+'
# Order of the patterns is important
$pattern = (
"(?<IntKey>$keyPattern)\s*<(?<IntValue>\d+)>",
"(?<TrueKey>$keyPattern)\s*<yes>",
"(?<FalseKey>$keyPattern)\s*<no>",
"(?<StrKey>$keyPattern)\s*<(?<StrValue>.*?)>",
"(?<ObjectBegin>$keyPattern)\s*{",
"(?<ObjectEnd>})",
"(?<KeyOnly>$keyPattern)",
"(?<Invalid>\S+)" # any non-whitespace sequence that didn't match the valid patterns
) -join '|'
}
process {
# Output is an ordered hashtable
$curObject = $outputObject = [ordered] @{}
# A stack is used to keep track of nested objects.
$stack = [Collections.Stack]::new()
# For each pattern match
foreach( $match in [RegEx]::Matches( $InputObject, $pattern, [RegexOptions]::Multiline ) ) {
# Get the RegEx groups that have actually matched.
$matchGroups = $match.Groups.Where{ $_.Success -and $_.Name.Length -gt 1 }
$key = $matchGroups[ 0 ].Value
switch( $matchGroups[ 0 ].Name ) {
'ObjectBegin' {
$child = [ordered] @{}
$curObject[ $key ] = $child
$stack.Push( $curObject )
$curObject = $child
break
}
'ObjectEnd' {
if( $stack.Count -eq 0 ) {
Write-Error -EA Stop "Parse error: Curly braces are unbalanced. There are more '}' than '{' in config data."
}
$curObject = $stack.Pop()
break
}
'IntKey' {
$value = $matchGroups[ 1 ].Value
$intValue = 0
$curObject[ $key ] = if( [int]::TryParse( $value, [ref] $intValue ) ) { $intValue } else { $value }
break
}
'TrueKey' {
$curObject[ $key ] = $true
break
}
'FalseKey' {
$curObject[ $key ] = $false
break
}
'StrKey' {
$value = $matchGroups[ 1 ].Value
$curObject[ $key ] = $value
break
}
'KeyOnly' {
$curObject[ $key ] = $null
break
}
'Invalid' {
Write-Warning "Invalid token at index $($match.Index): $key"
break
}
}
}
if( $stack.Count -gt 0 ) {
Write-Error "Parse error: Curly braces are unbalanced. There are more '{' than '}' in config data."
}
$outputObject # Implicit output
}
}
```
**Usage example:**
```sh
$sampleData = @'
test-server {
store {
servers {
* {
value<>
port<>
folder<C:\windows> monitor<yes>
args<-T -H>
xrg<store>
wysargs<-t -g -b>
accept_any<yes>
pdu_length<23622>
}
test1 {
name<test1>
port<123>
root<c:\test>
monitor<yes>
}
test2 {
name<test2>
port<124>
root<c:\test>
monitor<yes>
}
test3 {
name<test3>
port<125>
root<c:\test>
monitor<yes>
}
}
senders
timeout<30>
}
}
'@
# Call the parser
$objects = $sampleData | ConvertFrom-ServerData
# Uncomment to verify the whole result
#$objects | ConvertTo-Json -Depth 10
# The parser outputs nested hashtables, so we have to use GetEnumerator() to
# iterate over the key/value pairs.
$objects.'test-server'.store.servers.GetEnumerator().ForEach{
"[ SERVER: $($_.Key) ]"
# Convert server values hashtable to PSCustomObject for better output formatting
[PSCustomObject] $_.Value | Format-List
}
```
**Output:**
```text
[ SERVER: * ]
value :
port :
folder : C:\windows
monitor : True
args : -T -H
xrg : store
wysargs : -t -g -b
accept_any : True
pdu_length : 23622
[ SERVER: test1 ]
name : test1
port : 123
root : c:\test
monitor : True
[ SERVER: test2 ]
name : test2
port : 124
root : c:\test
monitor : True
[ SERVER: test3 ]
name : test3
port : 125
root : c:\test
monitor : True
```
**Notes:**
* I have further relaxed the regular expressions. Keys may now consist of any character except whitespace, `<`, `>`, `{` and `}`.
* Line breaks are no longer required. This is more flexible but you can't have strings with embedded `>` characters. Let me know if this is a problem.
* I have added detection of invalid tokens, which are output as warnings. Remove the `"(?<Invalid>\S+)"` line, if you want to ignore invalid tokens instead.
* Unbalanced curly braces are detected and reported as error.
* You can see how the RegEx works and get explanations at [RegEx101](https://regex101.com/r/wbvoot/1).
**C# version:**
* I've since created a faster [C# version of the parser](https://gist.github.com/zett42/6dc8867cec5c2310ccf9aeb87f2ddf16).
* It requires PowerShell 7+. It can be imported using `Add-Type -Path FileName.cs` and called like `[zett42.ServerDataParser]::Parse($text)`.
* It doesn't use RegEx. It is based on `ReadOnlySpan<char>` and uses only simple string operations. In the benchmarks I did it was about 10x faster than a C# version that used RegEx and about 60x faster than the PS-only version. | **Edit:** I've since come up with a [much simpler, PowerShell-only solution](https://stackoverflow.com/a/72274775/7571258) which I recommend to use.
I'll keep this answer alive as it might still be useful for other scenarios. Also there are propably differences in performance (I haven't measured).
---
[MYousefi](https://stackoverflow.com/users/1991397/myousefi) already posted a [helpful answer](https://stackoverflow.com/posts/72234367/revisions) with a Python implementation.
For **PowerShell**, I've come up with a solution that works without a convert-to-JSON step. Instead, I've adopted and generalized the [RegEx-based tokenizer code](https://github.com/Vanlightly/DslParser) from Jack Vanlightly (also see [related blog post](https://jack-vanlightly.com/blog/2016/2/24/a-more-efficient-regex-tokenizer)). A *tokenizer* (aka *lexer*) splits and categorizes the elements of the input text and outputs a flat stream of *tokens* (categories) and related data. A *parser* can use these as input to create a structured representation of the input text.
The tokenizer is written in generic C# and can be used for any input that can be split using RegEx. The C# code is included in PowerShell using the `Add-Type` command, so no C# compiler is required.
The parser function `ConvertFrom-ServerData` is written in PowerShell for simplicity. You only use the parser directly, so you don't have to know anything about the tokenizer C# code. If you want to adopt the code to different input, you should only have to modify the PowerShell parser code.
Save the following file in the same directory as the PowerShell script:
**"RegExTokenizer.cs":**
```cs
// Generic, precedence-based RegEx tokenizer.
// This code is based on https://github.com/Vanlightly/DslParser
// from Jack Vanlightly (https://jack-vanlightly.com).
// Modifications:
// - Interface improved for ease-of-use from PowerShell.
// - Return all groups from the RegEx match instead of just the value. This simplifies parsing of key/value pairs by requiring only a single token definition.
// - Some code simplifications, e. g. replacing "for" loops by "foreach".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace DslTokenizer {
public class DslToken<TokenType> {
public TokenType Token { get; set; }
public GroupCollection Groups { get; set; }
}
public class TokenMatch<TokenType> {
public TokenType Token { get; set; }
public GroupCollection Groups { get; set; }
public int StartIndex { get; set; }
public int EndIndex { get; set; }
public int Precedence { get; set; }
}
public class TokenDefinition<TokenType> {
private Regex _regex;
private readonly TokenType _returnsToken;
private readonly int _precedence;
public TokenDefinition( TokenType returnsToken, string regexPattern, int precedence ) {
_regex = new Regex( regexPattern, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled );
_returnsToken = returnsToken;
_precedence = precedence;
}
public IEnumerable<TokenMatch<TokenType>> FindMatches( string inputString ) {
foreach( Match match in _regex.Matches( inputString ) ) {
yield return new TokenMatch<TokenType>() {
StartIndex = match.Index,
EndIndex = match.Index + match.Length,
Token = _returnsToken,
Groups = match.Groups,
Precedence = _precedence
};
}
}
}
public class PrecedenceBasedRegexTokenizer<TokenType> {
private List<TokenDefinition<TokenType>> _tokenDefinitions = new List<TokenDefinition<TokenType>>();
public PrecedenceBasedRegexTokenizer() {}
public PrecedenceBasedRegexTokenizer( IEnumerable<TokenDefinition<TokenType>> tokenDefinitions ) {
_tokenDefinitions = tokenDefinitions.ToList();
}
// Easy-to-use interface as alternative to constructor that takes an IEnumerable.
public void AddTokenDef( TokenType returnsToken, string regexPattern, int precedence = 0 ) {
_tokenDefinitions.Add( new TokenDefinition<TokenType>( returnsToken, regexPattern, precedence ) );
}
public IEnumerable<DslToken<TokenType>> Tokenize( string lqlText ) {
var tokenMatches = FindTokenMatches( lqlText );
var groupedByIndex = tokenMatches.GroupBy( x => x.StartIndex )
.OrderBy( x => x.Key )
.ToList();
TokenMatch<TokenType> lastMatch = null;
foreach( var match in groupedByIndex ) {
var bestMatch = match.OrderBy( x => x.Precedence ).First();
if( lastMatch != null && bestMatch.StartIndex < lastMatch.EndIndex ) {
continue;
}
yield return new DslToken<TokenType>(){ Token = bestMatch.Token, Groups = bestMatch.Groups };
lastMatch = bestMatch;
}
}
private List<TokenMatch<TokenType>> FindTokenMatches( string lqlText ) {
var tokenMatches = new List<TokenMatch<TokenType>>();
foreach( var tokenDefinition in _tokenDefinitions ) {
tokenMatches.AddRange( tokenDefinition.FindMatches( lqlText ).ToList() );
}
return tokenMatches;
}
}
}
```
**Parser function written in PowerShell:**
```sh
$ErrorActionPreference = 'Stop'
Add-Type -TypeDefinition (Get-Content $PSScriptRoot\RegExTokenizer.cs -Raw)
Function ConvertFrom-ServerData {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline)] [string] $InputObject
)
begin {
# Define the kind of possible tokens.
enum ServerDataTokens {
ObjectBegin
ObjectEnd
ValueInt
ValueBool
ValueString
KeyOnly
}
# Create an instance of the tokenizer from "RegExTokenizer.cs".
$tokenizer = [DslTokenizer.PrecedenceBasedRegexTokenizer[ServerDataTokens]]::new()
# Define a RegEx for each token where 1st group matches key and 2nd matches value (if any).
# To resolve ambiguities, most specific RegEx must come first
# (e. g. ValueInt line must come before ValueString line).
# Alternatively pass a 3rd integer parameter that defines the precedence.
$tokenizer.AddTokenDef( [ServerDataTokens]::ObjectBegin, '^\s*([\w*]+)\s*{' )
$tokenizer.AddTokenDef( [ServerDataTokens]::ObjectEnd, '^\s*}\s*$' )
$tokenizer.AddTokenDef( [ServerDataTokens]::ValueInt, '^\s*(\w+)\s*<([+-]?\d+)>\s*$' )
$tokenizer.AddTokenDef( [ServerDataTokens]::ValueBool, '^\s*(\w+)\s*<(yes|no)>\s*$' )
$tokenizer.AddTokenDef( [ServerDataTokens]::ValueString, '^\s*(\w+)\s*<(.*)>\s*$' )
$tokenizer.AddTokenDef( [ServerDataTokens]::KeyOnly, '^\s*(\w+)\s*$' )
}
process {
# Output is an ordered hashtable
$outputObject = [ordered] @{}
$curObject = $outputObject
# A stack is used to keep track of nested objects.
$stack = [Collections.Stack]::new()
# For each token produced by the tokenizer
$tokenizer.Tokenize( $InputObject ).ForEach{
# $_.Groups[0] is the full match, which we discard by assigning to $null
$null, $key, $value = $_.Groups.Value
switch( $_.Token ) {
([ServerDataTokens]::ObjectBegin) {
$child = [ordered] @{}
$curObject[ $key ] = $child
$stack.Push( $curObject )
$curObject = $child
break
}
([ServerDataTokens]::ObjectEnd) {
$curObject = $stack.Pop()
break
}
([ServerDataTokens]::ValueInt) {
$intValue = 0
$curObject[ $key ] = if( [int]::TryParse( $value, [ref] $intValue ) ) { $intValue } else { $value }
break
}
([ServerDataTokens]::ValueBool) {
$curObject[ $key ] = $value -eq 'yes'
break
}
([ServerDataTokens]::ValueString) {
$curObject[ $key ] = $value
break
}
([ServerDataTokens]::KeyOnly) {
$curObject[ $key ] = $null
break
}
}
}
$outputObject # Implicit output
}
}
```
**Usage example:**
```sh
$sampleData = @'
servername {
store {
servers {
* {
value<>
port<>
folder<C:\windows>
monitor<yes>
args<-T -H>
xrg<store>
wysargs<-t -g -b>
accept_any<yes>
pdu_length<23622>
}
test1 {
name<test1>
port<123>
root<c:\test>
monitor<yes>
}
test2 {
name<test2>
port<124>
root<c:\test>
monitor<yes>
}
test3 {
name<test3>
port<125>
root<c:\test>
monitor<yes>
}
}
senders
timeout<30>
}
}
'@
# Call the parser
$objects = $sampleData | ConvertFrom-ServerData
# The parser outputs nested hashtables, so we have to use GetEnumerator() to
# iterate over the key/value pairs.
$objects.servername.store.servers.GetEnumerator().ForEach{
"[ SERVER: $($_.Key) ]"
# Convert server values hashtable to PSCustomObject for better output formatting
[PSCustomObject] $_.Value | Format-List
}
```
**Output:**
```text
[ SERVER: * ]
value :
port :
folder : C:\windows
monitor : True
args : -T -H
xrg : store
wysargs : -t -g -b
accept_any : True
pdu_length : 23622
[ SERVER: test1 ]
name : test1
port : 123
root : c:\test
monitor : True
[ SERVER: test2 ]
name : test2
port : 124
root : c:\test
monitor : True
[ SERVER: test3 ]
name : test3
port : 125
root : c:\test
monitor : True
```
**Notes:**
* If you pass input from `Get-Content` to the parser, make sure to use parameter `-Raw`, e. g. `$objects = Get-Content input.cfg -Raw | ConvertFrom-ServerData`. Otherwise the parser would try to parse each input line on its own.
* I've opted to convert "yes"/"no" values to `bool`, so they output as "True"/"False". Remove the line `$tokenizer.AddTokenDef( 'ValueBool', ...` to parse them as `string` instead and output as-is.
* Keys without values `<>` (the "senders" in the example) are stored as keys with value `$null`.
* The RegEx's enforce that values can be single-line only (as the sample data suggests). This allows us to have embedded `>` characters without the need to escape them. |
72,955,820 | I have a dataframe with columns as mentioned
```
[-10800,
-9000,
-7200,
-5400,
-3600,
-1800,
0,
180,
300,
1200,
1800,
2400,
3600,
'-10800_R',
'-9000_R',
'-7200_R',
'-5400_R',
'-3600_R',
'-1800_R',
'0_R',
'180_R',
'300_R',
'1200_R',
'1800_R',
'2400_R',
'3600_R']
```
I want to only select the '\_R' columns
I am using list comprehension
```
[i for i in df.columns.to_list() if '_R' in i]
```
but i am getting the error of
```
TypeError: argument of type 'int' is not iterable
```
Is there another way to do it? | 2022/07/12 | [
"https://Stackoverflow.com/questions/72955820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9620357/"
] | When executing an [`EXPLAIN ANALYSE` on the last query](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=bb264a6c22078c879ecaffab12b43136), this is the output:
```none
-> Filter: ((T1.colA / T.col1) > 0) (cost=1.00 rows=0) (actual time=0.047..0.061 rows=3 loops=1)
-> Inner hash join (T.col2 = T1.colA) (cost=1.00 rows=0) (actual time=0.039..0.051 rows=3 loops=1)
-> Filter: (T.col1 <> 0) (cost=0.23 rows=1) (actual time=0.006..0.015 rows=4 loops=1)
-> Table scan on T (cost=0.23 rows=6) (actual time=0.004..0.012 rows=6 loops=1)
-> Hash
-> Table scan on T1 (cost=0.45 rows=2) (actual time=0.015..0.019 rows=2 loops=1)
```
The inner actions are executed first. Here we see that the records from `T` are first filtered by `T.col1 <> 0` and only then they are joined with the records from `T1`. This explains why no division by zero occurs. It also makes sense that this filter is applied *before* the join, as that potentially makes the join operation involve fewer records. | Some general rules in MySQL:
* AND'd clauses in WHERE are *usually* performed left to right.
* MATCH and SPATIAL tests will be performed before other tests.
* The Optimizer has limited smarts.
* The Optimizer may choose to start with any of the JOINed tables first.
* LEFT JOIN may *or may not* force the 'left' table to read first.
* Subqueries and function calls -- who knows.
* AND has precedence over OR. That is, `a OR b AND c` means `a OR (b AND c)` but that does not say which will be *performed* first.
* Some of the above items can be determined by `EXPLAIN`, `EXPLAIN FORMAT=JSON` and the Optimizer Trace.
Write your SQL defensively! |
1,903,783 | The population of graduate students in the northern part of Evanston is given by the formula P(t)=(t^2+100) ln(t+2), where t represents the time in years since 2000. Using Python, find the rate of change of this population in 2006, as well as the year that the population will reach 500 graduate students.
For the final answer, I got 12ln(8) + 17, and at time t is 10 years. Can someone verify as to this? | 2016/08/25 | [
"https://math.stackexchange.com/questions/1903783",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/362936/"
] | **Hint:** Without loss of generality, suppose $c$ is the largest side. Hence, $c<a+b$. Also,
$$\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b}\leq\frac{a}{a+b}+\frac{b}{a+b}+\frac{c}{a+b}\,.$$
Note that the bound is sharp. In the limit $a\to 0$ and $b\to c$, we have the sum goes to $2$. | Since $a,b,c$ are the sides of a triangle, there exist $p,q,r\in\mathbb R^+$ such that $a=p+q$, $b=q+r$, $c=r+p$ ([Ravi substitution](https://mblog1024.wordpress.com/2011/02/14/ravi-substitution-explained/)).
$$\sum\_{\text{cyc}}\frac{a}{b+c}<2\iff \sum\_{\text{cyc}}\frac{p+q}{p+q+2r}<2$$
Now multiply both sides by $(2p+q+r)(p+2q+r)(p+q+2r)$, expand, rearrange.
See [WolframAlpha (link)](http://www.wolframalpha.com/input/?i=(p%2Bq)(2p%2Bq%2Br)(p%2B2q%2Br)%2B(q%2Br)(p%2B2q%2Br)(p%2Bq%2B2r)%2B(r%2Bp)(2p%2Bq%2Br)(p%2Bq%2B2r)-2(2p%2Bq%2Br)(p%2B2q%2Br)(p%2Bq%2B2r)) if you want.
$$\iff 3 p^2 q+3 p^2 r+3 p q^2+14 p q r+3 p r^2+3 q^2 r+3 q r^2
>0,$$
which is trivial, because $p,q,r>0$. |
1,903,783 | The population of graduate students in the northern part of Evanston is given by the formula P(t)=(t^2+100) ln(t+2), where t represents the time in years since 2000. Using Python, find the rate of change of this population in 2006, as well as the year that the population will reach 500 graduate students.
For the final answer, I got 12ln(8) + 17, and at time t is 10 years. Can someone verify as to this? | 2016/08/25 | [
"https://math.stackexchange.com/questions/1903783",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/362936/"
] | Since $a,b,c$ are the sides of a triangle, there exist $p,q,r\in\mathbb R^+$ such that $a=p+q$, $b=q+r$, $c=r+p$ ([Ravi substitution](https://mblog1024.wordpress.com/2011/02/14/ravi-substitution-explained/)).
$$\sum\_{\text{cyc}}\frac{a}{b+c}<2\iff \sum\_{\text{cyc}}\frac{p+q}{p+q+2r}<2$$
Now multiply both sides by $(2p+q+r)(p+2q+r)(p+q+2r)$, expand, rearrange.
See [WolframAlpha (link)](http://www.wolframalpha.com/input/?i=(p%2Bq)(2p%2Bq%2Br)(p%2B2q%2Br)%2B(q%2Br)(p%2B2q%2Br)(p%2Bq%2B2r)%2B(r%2Bp)(2p%2Bq%2Br)(p%2Bq%2B2r)-2(2p%2Bq%2Br)(p%2B2q%2Br)(p%2Bq%2B2r)) if you want.
$$\iff 3 p^2 q+3 p^2 r+3 p q^2+14 p q r+3 p r^2+3 q^2 r+3 q r^2
>0,$$
which is trivial, because $p,q,r>0$. | >
> Let $a,b,c$ be the lengths of the sides of a triangle. Prove that
>
>
> \begin{align}\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b}&<2\tag{1}\label{1}.\end{align}
>
>
>
Let $\rho,\ r,\ R$
be the semiperimeter,
inradius and circumradius
of the triangle $ABC$, then
we can rewrite \eqref{1} as
\begin{align}
\frac a{2\rho-a}
+\frac b{2\rho-b}
+\frac c{2\rho-c}
&=
\frac{
4\,(a+b+c)\rho^2
-4\,(ab+bc+ca)\,\rho
+3\,abc
}{
8\rho^3-4\,(a+b+c)\,\rho^2+2\,(ab+bc+ca)\,\rho
-abc
}
<2
\tag{2}\label{2}
,
\end{align}
then, rearranging,
\begin{align}
16\rho^3
-12(a+b+c)\rho^2
+8(ab+bc+ca)\rho-5abc
&>0
\tag{3}\label{3}
,\\
16\rho^3
-12(2\rho)\rho^2
+8(\rho^2+r^2+4rR)\rho-5\cdot4\rho r R
&>0
\tag{4}\label{4}
,\\
4r\rho(2r+3R)
&>0
\tag{5}\label{5}
,
\end{align}
which always holds. |
1,903,783 | The population of graduate students in the northern part of Evanston is given by the formula P(t)=(t^2+100) ln(t+2), where t represents the time in years since 2000. Using Python, find the rate of change of this population in 2006, as well as the year that the population will reach 500 graduate students.
For the final answer, I got 12ln(8) + 17, and at time t is 10 years. Can someone verify as to this? | 2016/08/25 | [
"https://math.stackexchange.com/questions/1903783",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/362936/"
] | **Hint:** Without loss of generality, suppose $c$ is the largest side. Hence, $c<a+b$. Also,
$$\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b}\leq\frac{a}{a+b}+\frac{b}{a+b}+\frac{c}{a+b}\,.$$
Note that the bound is sharp. In the limit $a\to 0$ and $b\to c$, we have the sum goes to $2$. | As @user236182 pointed out, we can write $a=p+q$, $b=q+r$, and $c=r+p$, with $p,q,r>0$. Letting $s = p+q+r$, we have
$$\frac{a}{b+c} = \frac{s-r}{s+r} = 1 - \frac{2r}{s+r} $$
and hence
$$\sum\limits\_{\text{cyc}}{\frac{a}{b+c}}< 2 \iff \sum\limits\_{\text{cyc}}{\left(1-\frac{2r}{s+r}\right)}< 2 \iff \sum\limits\_{\text{cyc}}{\frac{2r}{s+r}} > 1. $$
By Cauchy-Schwarz we have
$$\left(\sum\limits\_{\text{cyc}}{\frac{r}{s+r}}\right)\left(\sum\limits\_{\text{cyc}}{r(s+r)}\right)\ge\left(\sum\limits\_{\text{cyc}}{r}\right)^2 = s^2. $$
Furthermore,
$$\sum\limits\_{\text{cyc}}{r(s+r)} = s\sum\limits\_{\text{cyc}}{r}+\sum\limits\_{\text{cyc}}{r^2} = s^2 + (p^2+q^2+r^2) < s^2+(p+q+r)^2 = 2s^2. $$
Note that the inequality is strict as $p,q,r>0$. It follows that
$$ 2s^2\sum\limits\_{\text{cyc}}{\frac{r}{s+r}} > \left(\sum\limits\_{\text{cyc}}{\frac{r}{s+r}}\right)\left(\sum\limits\_{\text{cyc}}{r(s+r)}\right) \ge s^2 $$
and hence $\sum\limits\_{\text{cyc}}{\frac{2r}{s+r}} > 1$, as desired. |
1,903,783 | The population of graduate students in the northern part of Evanston is given by the formula P(t)=(t^2+100) ln(t+2), where t represents the time in years since 2000. Using Python, find the rate of change of this population in 2006, as well as the year that the population will reach 500 graduate students.
For the final answer, I got 12ln(8) + 17, and at time t is 10 years. Can someone verify as to this? | 2016/08/25 | [
"https://math.stackexchange.com/questions/1903783",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/362936/"
] | As @user236182 pointed out, we can write $a=p+q$, $b=q+r$, and $c=r+p$, with $p,q,r>0$. Letting $s = p+q+r$, we have
$$\frac{a}{b+c} = \frac{s-r}{s+r} = 1 - \frac{2r}{s+r} $$
and hence
$$\sum\limits\_{\text{cyc}}{\frac{a}{b+c}}< 2 \iff \sum\limits\_{\text{cyc}}{\left(1-\frac{2r}{s+r}\right)}< 2 \iff \sum\limits\_{\text{cyc}}{\frac{2r}{s+r}} > 1. $$
By Cauchy-Schwarz we have
$$\left(\sum\limits\_{\text{cyc}}{\frac{r}{s+r}}\right)\left(\sum\limits\_{\text{cyc}}{r(s+r)}\right)\ge\left(\sum\limits\_{\text{cyc}}{r}\right)^2 = s^2. $$
Furthermore,
$$\sum\limits\_{\text{cyc}}{r(s+r)} = s\sum\limits\_{\text{cyc}}{r}+\sum\limits\_{\text{cyc}}{r^2} = s^2 + (p^2+q^2+r^2) < s^2+(p+q+r)^2 = 2s^2. $$
Note that the inequality is strict as $p,q,r>0$. It follows that
$$ 2s^2\sum\limits\_{\text{cyc}}{\frac{r}{s+r}} > \left(\sum\limits\_{\text{cyc}}{\frac{r}{s+r}}\right)\left(\sum\limits\_{\text{cyc}}{r(s+r)}\right) \ge s^2 $$
and hence $\sum\limits\_{\text{cyc}}{\frac{2r}{s+r}} > 1$, as desired. | >
> Let $a,b,c$ be the lengths of the sides of a triangle. Prove that
>
>
> \begin{align}\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b}&<2\tag{1}\label{1}.\end{align}
>
>
>
Let $\rho,\ r,\ R$
be the semiperimeter,
inradius and circumradius
of the triangle $ABC$, then
we can rewrite \eqref{1} as
\begin{align}
\frac a{2\rho-a}
+\frac b{2\rho-b}
+\frac c{2\rho-c}
&=
\frac{
4\,(a+b+c)\rho^2
-4\,(ab+bc+ca)\,\rho
+3\,abc
}{
8\rho^3-4\,(a+b+c)\,\rho^2+2\,(ab+bc+ca)\,\rho
-abc
}
<2
\tag{2}\label{2}
,
\end{align}
then, rearranging,
\begin{align}
16\rho^3
-12(a+b+c)\rho^2
+8(ab+bc+ca)\rho-5abc
&>0
\tag{3}\label{3}
,\\
16\rho^3
-12(2\rho)\rho^2
+8(\rho^2+r^2+4rR)\rho-5\cdot4\rho r R
&>0
\tag{4}\label{4}
,\\
4r\rho(2r+3R)
&>0
\tag{5}\label{5}
,
\end{align}
which always holds. |
1,903,783 | The population of graduate students in the northern part of Evanston is given by the formula P(t)=(t^2+100) ln(t+2), where t represents the time in years since 2000. Using Python, find the rate of change of this population in 2006, as well as the year that the population will reach 500 graduate students.
For the final answer, I got 12ln(8) + 17, and at time t is 10 years. Can someone verify as to this? | 2016/08/25 | [
"https://math.stackexchange.com/questions/1903783",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/362936/"
] | **Hint:** Without loss of generality, suppose $c$ is the largest side. Hence, $c<a+b$. Also,
$$\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b}\leq\frac{a}{a+b}+\frac{b}{a+b}+\frac{c}{a+b}\,.$$
Note that the bound is sharp. In the limit $a\to 0$ and $b\to c$, we have the sum goes to $2$. | \begin{align\*}
\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b} & = \frac{2a}{2(b+c)}+\frac{2b}{2(c+a)}+\frac{2c}{2(a+b)} \\
&< \frac{2a}{a+b+c} + \frac{2b}{c+a+b} + \frac{2c}{a+b+c} \\
&= 2
\end{align\*} |
1,903,783 | The population of graduate students in the northern part of Evanston is given by the formula P(t)=(t^2+100) ln(t+2), where t represents the time in years since 2000. Using Python, find the rate of change of this population in 2006, as well as the year that the population will reach 500 graduate students.
For the final answer, I got 12ln(8) + 17, and at time t is 10 years. Can someone verify as to this? | 2016/08/25 | [
"https://math.stackexchange.com/questions/1903783",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/362936/"
] | **Hint:** Without loss of generality, suppose $c$ is the largest side. Hence, $c<a+b$. Also,
$$\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b}\leq\frac{a}{a+b}+\frac{b}{a+b}+\frac{c}{a+b}\,.$$
Note that the bound is sharp. In the limit $a\to 0$ and $b\to c$, we have the sum goes to $2$. | >
> Let $a,b,c$ be the lengths of the sides of a triangle. Prove that
>
>
> \begin{align}\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b}&<2\tag{1}\label{1}.\end{align}
>
>
>
Let $\rho,\ r,\ R$
be the semiperimeter,
inradius and circumradius
of the triangle $ABC$, then
we can rewrite \eqref{1} as
\begin{align}
\frac a{2\rho-a}
+\frac b{2\rho-b}
+\frac c{2\rho-c}
&=
\frac{
4\,(a+b+c)\rho^2
-4\,(ab+bc+ca)\,\rho
+3\,abc
}{
8\rho^3-4\,(a+b+c)\,\rho^2+2\,(ab+bc+ca)\,\rho
-abc
}
<2
\tag{2}\label{2}
,
\end{align}
then, rearranging,
\begin{align}
16\rho^3
-12(a+b+c)\rho^2
+8(ab+bc+ca)\rho-5abc
&>0
\tag{3}\label{3}
,\\
16\rho^3
-12(2\rho)\rho^2
+8(\rho^2+r^2+4rR)\rho-5\cdot4\rho r R
&>0
\tag{4}\label{4}
,\\
4r\rho(2r+3R)
&>0
\tag{5}\label{5}
,
\end{align}
which always holds. |
1,903,783 | The population of graduate students in the northern part of Evanston is given by the formula P(t)=(t^2+100) ln(t+2), where t represents the time in years since 2000. Using Python, find the rate of change of this population in 2006, as well as the year that the population will reach 500 graduate students.
For the final answer, I got 12ln(8) + 17, and at time t is 10 years. Can someone verify as to this? | 2016/08/25 | [
"https://math.stackexchange.com/questions/1903783",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/362936/"
] | \begin{align\*}
\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b} & = \frac{2a}{2(b+c)}+\frac{2b}{2(c+a)}+\frac{2c}{2(a+b)} \\
&< \frac{2a}{a+b+c} + \frac{2b}{c+a+b} + \frac{2c}{a+b+c} \\
&= 2
\end{align\*} | >
> Let $a,b,c$ be the lengths of the sides of a triangle. Prove that
>
>
> \begin{align}\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b}&<2\tag{1}\label{1}.\end{align}
>
>
>
Let $\rho,\ r,\ R$
be the semiperimeter,
inradius and circumradius
of the triangle $ABC$, then
we can rewrite \eqref{1} as
\begin{align}
\frac a{2\rho-a}
+\frac b{2\rho-b}
+\frac c{2\rho-c}
&=
\frac{
4\,(a+b+c)\rho^2
-4\,(ab+bc+ca)\,\rho
+3\,abc
}{
8\rho^3-4\,(a+b+c)\,\rho^2+2\,(ab+bc+ca)\,\rho
-abc
}
<2
\tag{2}\label{2}
,
\end{align}
then, rearranging,
\begin{align}
16\rho^3
-12(a+b+c)\rho^2
+8(ab+bc+ca)\rho-5abc
&>0
\tag{3}\label{3}
,\\
16\rho^3
-12(2\rho)\rho^2
+8(\rho^2+r^2+4rR)\rho-5\cdot4\rho r R
&>0
\tag{4}\label{4}
,\\
4r\rho(2r+3R)
&>0
\tag{5}\label{5}
,
\end{align}
which always holds. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.