qid
int64
1
74.7M
question
stringlengths
22
28.7k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
24
26.4k
response_k
stringlengths
25
24.2k
51,274,370
``` import React from "react"; import styles from "../articles.css"; const TeamInfo = props => ( <div className={styles.articleTeamHeader}> <div className={styles.left}> style={{ background: `url('/images/teams/${props.team.logo}')` }} </div> <div className={styles.right}> <div> <span> {props.team.city} {props.team.name} </span> </div> <div> <strong> W{props.team.stats[0].wins}-L{props.team.stats[0].defeats} </strong> </div> </div> </div> ); export default TeamInfo; ``` the code that render this ``` import React from 'react'; import TeamInfo from '../../Elements/TeamInfo'; const header = (props) => { const teaminfofunc = (team) => { return team ? ( <TeamInfo team={team}/> ) : null } return ( <div> {teaminfofunc(props.teamdata)} </div> ) } export default header; ``` and I am getting error TypeError: props is undefined in line 8 why is that ? Line 8 is > > background: `url('/images/teams/${props.team.logo}')` > > > **Update**: I found that in index.js the `componentWillMount` bring the data correctly but in the `render()` those data (article and team) was not passed to render, any idea why ? ``` import React, {Component} from 'react'; import axios from 'axios'; import {URL} from "../../../../config"; import styles from '../../articles.css'; import Header from './header'; import Body from './body'; class NewsArticles extends Component { state = { article:[], team: [] } componentWillMount() { axios.get(`${URL}/articles?id=${this.props.match.params.id}`) .then(response => { let article = response.data[0]; axios.get(`${URL}/teams?id=${article.team}`) .then(response => { this.props.setState({ article, team:response.data }) }) }) } render() { const article = this.state.article; const team = this.state.team; return ( <div className={styles.articleWrapper}> <Header teamdata={team[0]} date={article.date} author={article.author} /> <Body /> </div> ) } } export default NewsArticles; ```
2018/07/10
[ "https://Stackoverflow.com/questions/51274370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/283322/" ]
You render your component immediately, long before your AJAX call finishes, and pass it the first element of an empty array: ``` <Header teamdata={team[0]} ``` `componentWillMount` does not block rendering. In your render function, short circuit if there's no team to render. ``` render() { const { article, team, } = this.state; if(!team || !team.length) { // You can return a loading indicator, or null here to show nothing return (<div>loading</div>); } return ( <div className={styles.articleWrapper}> <Header teamdata={team[0]} date={article.date} author={article.author} /> <Body /> </div> ) } ``` You're also calling `this.props.setState`, which is probably erroring, and you should never call `setState` on a different component in React. You probably want `this.setState`
You should always gate any object traversal in case the component renders without the data. ``` {props && props.team && props.team.logo ? <div className={styles.left}> style={{ background: `url('/images/teams/${props.team.logo}')` }} </div> : null} ``` This may not be you exact issue, but without knowing how the prop is rendered that is all we can do from this side of the code. --- Update based on your edit. You can't be sure that props.teamdata exists, and therefore your component will be rendered without this data. You'll need to gate this side also, and you don't need to seperate it as a function, also. Here is an example of what it could look like: ``` import React from 'react'; import TeamInfo from '../../Elements/TeamInfo'; const header = (props) => ( <div> {props.teamdata ? <TeamInfo team={props.teamdata}/> : null} </div> ) export default header; ```
51,274,370
``` import React from "react"; import styles from "../articles.css"; const TeamInfo = props => ( <div className={styles.articleTeamHeader}> <div className={styles.left}> style={{ background: `url('/images/teams/${props.team.logo}')` }} </div> <div className={styles.right}> <div> <span> {props.team.city} {props.team.name} </span> </div> <div> <strong> W{props.team.stats[0].wins}-L{props.team.stats[0].defeats} </strong> </div> </div> </div> ); export default TeamInfo; ``` the code that render this ``` import React from 'react'; import TeamInfo from '../../Elements/TeamInfo'; const header = (props) => { const teaminfofunc = (team) => { return team ? ( <TeamInfo team={team}/> ) : null } return ( <div> {teaminfofunc(props.teamdata)} </div> ) } export default header; ``` and I am getting error TypeError: props is undefined in line 8 why is that ? Line 8 is > > background: `url('/images/teams/${props.team.logo}')` > > > **Update**: I found that in index.js the `componentWillMount` bring the data correctly but in the `render()` those data (article and team) was not passed to render, any idea why ? ``` import React, {Component} from 'react'; import axios from 'axios'; import {URL} from "../../../../config"; import styles from '../../articles.css'; import Header from './header'; import Body from './body'; class NewsArticles extends Component { state = { article:[], team: [] } componentWillMount() { axios.get(`${URL}/articles?id=${this.props.match.params.id}`) .then(response => { let article = response.data[0]; axios.get(`${URL}/teams?id=${article.team}`) .then(response => { this.props.setState({ article, team:response.data }) }) }) } render() { const article = this.state.article; const team = this.state.team; return ( <div className={styles.articleWrapper}> <Header teamdata={team[0]} date={article.date} author={article.author} /> <Body /> </div> ) } } export default NewsArticles; ```
2018/07/10
[ "https://Stackoverflow.com/questions/51274370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/283322/" ]
You render your component immediately, long before your AJAX call finishes, and pass it the first element of an empty array: ``` <Header teamdata={team[0]} ``` `componentWillMount` does not block rendering. In your render function, short circuit if there's no team to render. ``` render() { const { article, team, } = this.state; if(!team || !team.length) { // You can return a loading indicator, or null here to show nothing return (<div>loading</div>); } return ( <div className={styles.articleWrapper}> <Header teamdata={team[0]} date={article.date} author={article.author} /> <Body /> </div> ) } ``` You're also calling `this.props.setState`, which is probably erroring, and you should never call `setState` on a different component in React. You probably want `this.setState`
First -- while this is stylistic -- it's not good practice to pass `props` directly to your functional component. Do this instead. ``` const TeamInfo = ({team}) => ( <div className={styles.articleTeamHeader}> <div className={styles.left}> style={{ background: `url('/images/teams/${team.logo}')` }} </div> <div className={styles.right}> <div> <span> {team.city} {team.name} </span> </div> <div> <strong> W{team.stats[0].wins}-L{team.stats[0].defeats} </strong> </div> </div> </div> ); ``` Second, you might just want to do some kind of `null` check. If `team` is `undefined` the first time the component tries to render, you might just want to render `null` so you're not wasting cycles. In case this isn't the issue, you'd learn a lot by `console.log`-ing your props so you know what everything is each time your component tries to render. It's okay if data is `undefined` if you're in a state that will soon resolve.
42,507,309
How does MCU now that the string a variable is pointing on is in data memory or in program memory? What does compiler do when I'm casting a `const char *` to `char *` (e.g. when calling `strlen` function)? Can `char *` be used as a `char *` and `const char *` without any performance loss?
2017/02/28
[ "https://Stackoverflow.com/questions/42507309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5542689/" ]
The STM32s use a flat 32-bit address space, so RAM and program memory (flash) are in the same logical space. The Cortex core of course knows which type of memory is where, probably through hardware address decoders that are triggered by the address being accessed. This is of course way outside the scope of what C cares about, though. Dropping `const` is not a run-time operation, so there should be no performance overhead. Of course dropping `const` is *bad*, since somewhere you risk someone actually believing that a `const` pointer means data there won't be written to, and going back on that promise can make badness happen.
With and without const, assuming your string is truly read only, is going to change whether it lands in .data or .rodata or some other read only section (.text, etc). Basically is it going to be in flash or in ram. The flash on these parts if I remember right at best has an extra wait state or is basically half the speed of ram...at best. (Fairly common for mcus in general, there are exceptions though). If you are running in the slower range of clocks, of you boost the clock the the ram performance vs flash will improve. So having it in flash (const) vs sram is going to be slower for any code that parses through that string. This assumes your linker script and bootstrap are such that .data is actually copied to ram on boot...
42,507,309
How does MCU now that the string a variable is pointing on is in data memory or in program memory? What does compiler do when I'm casting a `const char *` to `char *` (e.g. when calling `strlen` function)? Can `char *` be used as a `char *` and `const char *` without any performance loss?
2017/02/28
[ "https://Stackoverflow.com/questions/42507309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5542689/" ]
By taking a STM32F4 example with 1MB flash/ROM memory and 192KB RAM memory (128KB SDRAM + 64KB CCM) - the memory map looks something as follows: * Flash/ROM - 0x08000000 to 0x080FFFFF (1MB) * RAM - 0x20000000 to 0x2001FFFF (128KB) There's more areas with separate address spaces that I won't cover here for the simplicity of the explanation. Such memories include Backup SRAM and CCM RAM, just to name two. In addition, each area may be further divided sections, such as RAM being divided to bss, stack and heap. Now onto your question about strings and their locations - constant strings, such as: ``` const char *str = "This is a string in ROM"; ``` are placed in flash memory. During compilation, the compiler places a temporary symbol that references such string. Later during linking phase, the linker (which knows about concrete values for each memory section) lays down all of your data (program, constant data etc.) in each section one after another and - once it knows concrete values of each such object - replaces those symbols placed by the compiler with concrete values which then appear in your binary. Because of this, later on during runtime when the assignment above is done, your `str` variable is simply assigned a constant value deduced by the linker (such as 0x08001234) which points directly to the first byte of the string. When it comes to dynamically allocated values - whenever you call malloc or new a similar task is done. Assuming sufficient memory is available, you are given the address to the requested chunk of memory in RAM and those calculations are during runtime. As for the question regarding `const` qualifier - there is not meaning to it once the code is executed. For example, during runtime the `strlen` function will simply go over memory byte-by-byte starting at the passed location and ending once binary `0` is encountered. It doesn't matter what "type" of bytes are being analyzed, because this information is lost once your code is converted to byte code. Regarding `const` in your context - `const` qualifier appearing in function parameter denotes that such function will not modify the contents of the string. If it attempted to, a compilation error would be raised, unless it implicitly performs a cast to a non-const type. You may, of course, pass a non-const variable as a const parameter of a function. The other way however - that is passing a const parameter to a non-const function - will raise an error, as this function may potentially modify the contents of the memory you point to, which you implicitly specified to be non-modifiable by making it `const`. So to summarize and answer your question: you can do casts as much as you want and this will not be reflected at runtime. It's simply an instruction to the compiler to treat given variable differently than the original during its type checks. By doing an implicit cast, you should however be aware that such cast may potentially be unsafe.
With and without const, assuming your string is truly read only, is going to change whether it lands in .data or .rodata or some other read only section (.text, etc). Basically is it going to be in flash or in ram. The flash on these parts if I remember right at best has an extra wait state or is basically half the speed of ram...at best. (Fairly common for mcus in general, there are exceptions though). If you are running in the slower range of clocks, of you boost the clock the the ram performance vs flash will improve. So having it in flash (const) vs sram is going to be slower for any code that parses through that string. This assumes your linker script and bootstrap are such that .data is actually copied to ram on boot...
65,933,118
I want to use `<div onInput={onChange} contentEditable>` to save user input like textarea does. I've heard that I need to use onInput listener to trigger fn when input change. The problem is when I update text with React state, It moves the caret to beginning of text constantly this is my code ``` import React from "react"; const App = () => { const [value, setValue] = React.useState("I am edittable"); const onChange = (e) => { const html = e.target.innerHTML; setValue(html); }; return ( <div onInput={onChange} contentEditable> {value} </div> ); }; export default App; ``` codesandbox <https://codesandbox.io/s/react-editable-cell-pwil6?file=/src/App.js:0-310> how could I fix it ?
2021/01/28
[ "https://Stackoverflow.com/questions/65933118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13694078/" ]
This is what you need to have: ``` <div onChange={onChange} contentEditable> ``` instead of `onInput` it should be `onChange` demo:<https://codesandbox.io/s/react-editable-cell-forked-ey7o1?file=/src/App.js>
This is old, but I just solved this for myself, and I thought I'd share it. onChange will never fire, and onInput isn't the best way. You need to simulate onChange with onFocus and onBlur. Copy the value of the innerHTML to a variable when onFocus occurs. When onBlur occurs, test innerHTML against the variable to see if it changed. If so, do your onChange stuff. You need something like this: ``` const onFocus = (e) => { val_start = e.target.innerHTML; }; const onBlur = (e) => { if(val_start !== e.target.innerHTML) { //Whatever you put here will act just like an onChange event const html = e.target.innerHTML; setValue(html); } }; ```
65,933,118
I want to use `<div onInput={onChange} contentEditable>` to save user input like textarea does. I've heard that I need to use onInput listener to trigger fn when input change. The problem is when I update text with React state, It moves the caret to beginning of text constantly this is my code ``` import React from "react"; const App = () => { const [value, setValue] = React.useState("I am edittable"); const onChange = (e) => { const html = e.target.innerHTML; setValue(html); }; return ( <div onInput={onChange} contentEditable> {value} </div> ); }; export default App; ``` codesandbox <https://codesandbox.io/s/react-editable-cell-pwil6?file=/src/App.js:0-310> how could I fix it ?
2021/01/28
[ "https://Stackoverflow.com/questions/65933118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13694078/" ]
this has a solution, but onChange doesn't register the event. It won't change the state. Do not use it! My suggestion is to use onInput, but DO NOT use the state variable as innerHTML for the editable element. Put some default value, the contentEditable will handle the change of the innerHTML, while the onInput will handle the change of the state from the value of the innerHTML. If you want to be sure that innerHTML will not be empty you can add onBlur event, that checks if it is ==="" and will update it with the default value or something else, etc.
This is old, but I just solved this for myself, and I thought I'd share it. onChange will never fire, and onInput isn't the best way. You need to simulate onChange with onFocus and onBlur. Copy the value of the innerHTML to a variable when onFocus occurs. When onBlur occurs, test innerHTML against the variable to see if it changed. If so, do your onChange stuff. You need something like this: ``` const onFocus = (e) => { val_start = e.target.innerHTML; }; const onBlur = (e) => { if(val_start !== e.target.innerHTML) { //Whatever you put here will act just like an onChange event const html = e.target.innerHTML; setValue(html); } }; ```
3,768,086
Show that $(X\_n)\_n$ converges in probability to $X$ if and only if for every continuous function $f$ with compact support, $f(X\_n)$ converges in probability to $f(X).$ $\implies$ is very easy, the problem is with the converse. Any suggestions to begin?
2020/07/24
[ "https://math.stackexchange.com/questions/3768086", "https://math.stackexchange.com", "https://math.stackexchange.com/users/776035/" ]
The problem is not clear as stated. Interpretation $\#1$: If you interpret it as "find the probability that the game end in an evenly numbered round" you can reason recursively. Let $P$ denote the answer. The probability that the game ends in the first round is $\frac 26+\frac 46\times \frac 46=\frac 79$. If you don't end in the first round, the probability is now $1-P$. Thus $$P=\frac 79\times 0 +\frac 29\times (1-P)\implies \boxed{P=\frac 2{11}}$$ as in your solution. Interpretation $\#2$: If the problem meant "find the probability that $B$ wins given that $A$ starts" that too can be solved recursively. Let $\Psi$ denote that answer and let $\Phi$ be the probability that $B$ wins given that $B$ starts. Then $$\Psi=\frac 46\times \Phi$$ and $$\Phi=\frac 46 +\frac 26\times \Psi$$ This system is easily solved and yields $$\boxed {\Psi=\frac 47}$$ as desired.
The answer = 1/2 The game has to end by either A winning or B winning Let's say A wins. He is just as likely to roll a 1 or a 2 on the last roll. Therefore in a game that A wins, probability of an even roll ending the game is 1/2, as 1(odd) and 2(even) are equally likely. Let's say B wins. He is just as likely to roll a 3/4/5/6 on the last roll. Therefore in a game that B wins, probability of an even roll ending the game is 1/2, as 4 and 6 are favourable outcomes. P.S. I have assumed that "ending on an even roll" as written in the title means the die outputs an even number. I agree that while the body of the question seems to suggest an even *turn*, this seems like the correct interpretation to me.
3,768,086
Show that $(X\_n)\_n$ converges in probability to $X$ if and only if for every continuous function $f$ with compact support, $f(X\_n)$ converges in probability to $f(X).$ $\implies$ is very easy, the problem is with the converse. Any suggestions to begin?
2020/07/24
[ "https://math.stackexchange.com/questions/3768086", "https://math.stackexchange.com", "https://math.stackexchange.com/users/776035/" ]
Thanks to the comment of @JMoravitz I realized my mistake. I was interpreting turns as the rolls $A$ AND $B$, as in $\{A\_1,B\_1\}, \{A\_2,B\_2\}, \dots$. In reality the question is merely asking what the probability of $B$ winning if $A$ rolls first. **The work is as follows:** We calculate the probability of $B$ winning. Denote the probability of $B$ winning on their $i$th roll as $S\_i$. Now, the probabilities of $B$ winning on her first roll, second roll, third roll, etc., are as follows: \begin{equation\*} P(S\_1) = \biggr(\frac{2}{3}\biggr)\biggr(\frac{2}{3}\biggr), \quad P(S\_2) = \biggr(\frac{2}{3}\biggr)\biggr(\frac{1}{3}\biggr)\biggr(\frac{2}{3}\biggr)\biggr(\frac{2}{3}\biggr), \quad P(S\_3) = \biggr(\biggr(\frac{2}{3}\biggr)\biggr(\frac{1}{3}\biggr)\biggr)^2\biggr(\frac{2}{3}\biggr)\biggr(\frac{2}{3}\biggr), \dots \end{equation\*} It then follows that in general that $\displaystyle P(S\_i) = \biggr(\frac{2}{9}\biggr)^{i-1} \biggr(\frac{4}{9}\biggr).$ Thus, it follows that the probability of $B$ winning is calculated as \begin{equation\*} P(S) = P\biggr(\bigcup\_{i=1}^\infty S\_i\biggr) = \sum\_{i=1}^\infty P(S\_i) = \sum\_{i=1}^\infty \biggr(\frac{2}{9}\biggr)^{i-1} \biggr(\frac{4}{9}\biggr) = \frac{4}{9} \sum\_{i=1}^\infty \biggr(\frac{2}{9}\biggr)^{i-1} = \frac{4}{9} \cdot \frac{9}{7} = \frac{4}{7}. \end{equation\*}
The answer = 1/2 The game has to end by either A winning or B winning Let's say A wins. He is just as likely to roll a 1 or a 2 on the last roll. Therefore in a game that A wins, probability of an even roll ending the game is 1/2, as 1(odd) and 2(even) are equally likely. Let's say B wins. He is just as likely to roll a 3/4/5/6 on the last roll. Therefore in a game that B wins, probability of an even roll ending the game is 1/2, as 4 and 6 are favourable outcomes. P.S. I have assumed that "ending on an even roll" as written in the title means the die outputs an even number. I agree that while the body of the question seems to suggest an even *turn*, this seems like the correct interpretation to me.
3,768,086
Show that $(X\_n)\_n$ converges in probability to $X$ if and only if for every continuous function $f$ with compact support, $f(X\_n)$ converges in probability to $f(X).$ $\implies$ is very easy, the problem is with the converse. Any suggestions to begin?
2020/07/24
[ "https://math.stackexchange.com/questions/3768086", "https://math.stackexchange.com", "https://math.stackexchange.com/users/776035/" ]
Working under the assumption that the intended interpretation of the question was merely asking the probability that $B$ wins (*i.e. distinguishing between the term "rounds" as iterating whenever A has a turn and "turns" iterating whenever either A or B has a turn*) two other approaches have already been written. Here I will include yet another approach: Consider the final round, that is a roll of $A$ followed by a roll of $B$, where we allow $B$ to roll even in the event that $A$ has already won despite the roll not influencing the final result of the game. Ordinarily there are $6\times 6 = 36$ equally likely results for a round. Here, we condition on the fact that it is the *last* round, implying that it was not the case that both players missed their respective targets. This gives $6\times 6 - 4\times 2 = 28$ equally likely possible final rounds. Of these, $4\times 4 = 16$ of them end with $A$ missing their target and $B$ hitting theirs. The probability of $B$ winning the game is then: $$\dfrac{16}{28} = \dfrac{4}{7}$$
The answer = 1/2 The game has to end by either A winning or B winning Let's say A wins. He is just as likely to roll a 1 or a 2 on the last roll. Therefore in a game that A wins, probability of an even roll ending the game is 1/2, as 1(odd) and 2(even) are equally likely. Let's say B wins. He is just as likely to roll a 3/4/5/6 on the last roll. Therefore in a game that B wins, probability of an even roll ending the game is 1/2, as 4 and 6 are favourable outcomes. P.S. I have assumed that "ending on an even roll" as written in the title means the die outputs an even number. I agree that while the body of the question seems to suggest an even *turn*, this seems like the correct interpretation to me.
3,768,086
Show that $(X\_n)\_n$ converges in probability to $X$ if and only if for every continuous function $f$ with compact support, $f(X\_n)$ converges in probability to $f(X).$ $\implies$ is very easy, the problem is with the converse. Any suggestions to begin?
2020/07/24
[ "https://math.stackexchange.com/questions/3768086", "https://math.stackexchange.com", "https://math.stackexchange.com/users/776035/" ]
Thanks to the comment of @JMoravitz I realized my mistake. I was interpreting turns as the rolls $A$ AND $B$, as in $\{A\_1,B\_1\}, \{A\_2,B\_2\}, \dots$. In reality the question is merely asking what the probability of $B$ winning if $A$ rolls first. **The work is as follows:** We calculate the probability of $B$ winning. Denote the probability of $B$ winning on their $i$th roll as $S\_i$. Now, the probabilities of $B$ winning on her first roll, second roll, third roll, etc., are as follows: \begin{equation\*} P(S\_1) = \biggr(\frac{2}{3}\biggr)\biggr(\frac{2}{3}\biggr), \quad P(S\_2) = \biggr(\frac{2}{3}\biggr)\biggr(\frac{1}{3}\biggr)\biggr(\frac{2}{3}\biggr)\biggr(\frac{2}{3}\biggr), \quad P(S\_3) = \biggr(\biggr(\frac{2}{3}\biggr)\biggr(\frac{1}{3}\biggr)\biggr)^2\biggr(\frac{2}{3}\biggr)\biggr(\frac{2}{3}\biggr), \dots \end{equation\*} It then follows that in general that $\displaystyle P(S\_i) = \biggr(\frac{2}{9}\biggr)^{i-1} \biggr(\frac{4}{9}\biggr).$ Thus, it follows that the probability of $B$ winning is calculated as \begin{equation\*} P(S) = P\biggr(\bigcup\_{i=1}^\infty S\_i\biggr) = \sum\_{i=1}^\infty P(S\_i) = \sum\_{i=1}^\infty \biggr(\frac{2}{9}\biggr)^{i-1} \biggr(\frac{4}{9}\biggr) = \frac{4}{9} \sum\_{i=1}^\infty \biggr(\frac{2}{9}\biggr)^{i-1} = \frac{4}{9} \cdot \frac{9}{7} = \frac{4}{7}. \end{equation\*}
The problem is not clear as stated. Interpretation $\#1$: If you interpret it as "find the probability that the game end in an evenly numbered round" you can reason recursively. Let $P$ denote the answer. The probability that the game ends in the first round is $\frac 26+\frac 46\times \frac 46=\frac 79$. If you don't end in the first round, the probability is now $1-P$. Thus $$P=\frac 79\times 0 +\frac 29\times (1-P)\implies \boxed{P=\frac 2{11}}$$ as in your solution. Interpretation $\#2$: If the problem meant "find the probability that $B$ wins given that $A$ starts" that too can be solved recursively. Let $\Psi$ denote that answer and let $\Phi$ be the probability that $B$ wins given that $B$ starts. Then $$\Psi=\frac 46\times \Phi$$ and $$\Phi=\frac 46 +\frac 26\times \Psi$$ This system is easily solved and yields $$\boxed {\Psi=\frac 47}$$ as desired.
3,768,086
Show that $(X\_n)\_n$ converges in probability to $X$ if and only if for every continuous function $f$ with compact support, $f(X\_n)$ converges in probability to $f(X).$ $\implies$ is very easy, the problem is with the converse. Any suggestions to begin?
2020/07/24
[ "https://math.stackexchange.com/questions/3768086", "https://math.stackexchange.com", "https://math.stackexchange.com/users/776035/" ]
Thanks to the comment of @JMoravitz I realized my mistake. I was interpreting turns as the rolls $A$ AND $B$, as in $\{A\_1,B\_1\}, \{A\_2,B\_2\}, \dots$. In reality the question is merely asking what the probability of $B$ winning if $A$ rolls first. **The work is as follows:** We calculate the probability of $B$ winning. Denote the probability of $B$ winning on their $i$th roll as $S\_i$. Now, the probabilities of $B$ winning on her first roll, second roll, third roll, etc., are as follows: \begin{equation\*} P(S\_1) = \biggr(\frac{2}{3}\biggr)\biggr(\frac{2}{3}\biggr), \quad P(S\_2) = \biggr(\frac{2}{3}\biggr)\biggr(\frac{1}{3}\biggr)\biggr(\frac{2}{3}\biggr)\biggr(\frac{2}{3}\biggr), \quad P(S\_3) = \biggr(\biggr(\frac{2}{3}\biggr)\biggr(\frac{1}{3}\biggr)\biggr)^2\biggr(\frac{2}{3}\biggr)\biggr(\frac{2}{3}\biggr), \dots \end{equation\*} It then follows that in general that $\displaystyle P(S\_i) = \biggr(\frac{2}{9}\biggr)^{i-1} \biggr(\frac{4}{9}\biggr).$ Thus, it follows that the probability of $B$ winning is calculated as \begin{equation\*} P(S) = P\biggr(\bigcup\_{i=1}^\infty S\_i\biggr) = \sum\_{i=1}^\infty P(S\_i) = \sum\_{i=1}^\infty \biggr(\frac{2}{9}\biggr)^{i-1} \biggr(\frac{4}{9}\biggr) = \frac{4}{9} \sum\_{i=1}^\infty \biggr(\frac{2}{9}\biggr)^{i-1} = \frac{4}{9} \cdot \frac{9}{7} = \frac{4}{7}. \end{equation\*}
Working under the assumption that the intended interpretation of the question was merely asking the probability that $B$ wins (*i.e. distinguishing between the term "rounds" as iterating whenever A has a turn and "turns" iterating whenever either A or B has a turn*) two other approaches have already been written. Here I will include yet another approach: Consider the final round, that is a roll of $A$ followed by a roll of $B$, where we allow $B$ to roll even in the event that $A$ has already won despite the roll not influencing the final result of the game. Ordinarily there are $6\times 6 = 36$ equally likely results for a round. Here, we condition on the fact that it is the *last* round, implying that it was not the case that both players missed their respective targets. This gives $6\times 6 - 4\times 2 = 28$ equally likely possible final rounds. Of these, $4\times 4 = 16$ of them end with $A$ missing their target and $B$ hitting theirs. The probability of $B$ winning the game is then: $$\dfrac{16}{28} = \dfrac{4}{7}$$
1,428,377
So I was watching the show Numb3rs, and the math genius was teaching, and something he did just stumped me. He was asking his class (more specifically a student) on which of the three cards is the car. The other two cards have an animal on them. Now, the student picked the middle card to begin with. So the cards looks like this ``` +---+---+---+ | 1 | X | 3 | +---+---+---+ ``` *The `X` Representing The Picked Card* Then he flipped over the third card, and it turned out to be an animal. All that is left now is one more animal, and a car. He asks the student if the chances are higher of getting a car if they switch cards. The student responds no (That's what I thought too). The student was wrong. What the teacher said is "Switching cards actually doubles your chances of getting the car". So my question is, why does switching selected cards double your chances of getting the car when 1 of the 3 cards are already revealed. I thought it would just be a simple 50/50 still, please explain why the chances double!
2015/09/09
[ "https://math.stackexchange.com/questions/1428377", "https://math.stackexchange.com", "https://math.stackexchange.com/users/269300/" ]
This is the classic version of the Monty Hall problem. Note that there is only one car, so the host is always able to reveal a goat behind one of the other two doors that were unselected. So the fact that he does this reveals no new information if the contestant does not switch. So by not switching: $$P\_n = \frac{1}{3}$$ If on the other hand the contestant switches, he has inverted his probability of winning (wins when he would have lost if not switching, and vice-versa), so: $$P\_s = 1 - P\_n = \frac{2}{3}$$
The probability that you've picked the *wrong* card in the first place is 2/3. This happens to be the truth even when one of the cards is removed; it's just that 2/3 of the initial guesses are wrong. So when you have the chance to change your mind, you do it, because in the "second round", 1/2 of the guesses are correct (assuming they are random). Finally, chances when you keep the card are 2/3 times 1/2 that the guess is wrong. On the other hand, chances are 1/3 times 1/2 that the guess is wrong when you switch the cards. Comparing the terms gives the answer, I think.
1,428,377
So I was watching the show Numb3rs, and the math genius was teaching, and something he did just stumped me. He was asking his class (more specifically a student) on which of the three cards is the car. The other two cards have an animal on them. Now, the student picked the middle card to begin with. So the cards looks like this ``` +---+---+---+ | 1 | X | 3 | +---+---+---+ ``` *The `X` Representing The Picked Card* Then he flipped over the third card, and it turned out to be an animal. All that is left now is one more animal, and a car. He asks the student if the chances are higher of getting a car if they switch cards. The student responds no (That's what I thought too). The student was wrong. What the teacher said is "Switching cards actually doubles your chances of getting the car". So my question is, why does switching selected cards double your chances of getting the car when 1 of the 3 cards are already revealed. I thought it would just be a simple 50/50 still, please explain why the chances double!
2015/09/09
[ "https://math.stackexchange.com/questions/1428377", "https://math.stackexchange.com", "https://math.stackexchange.com/users/269300/" ]
This is the classic version of the Monty Hall problem. Note that there is only one car, so the host is always able to reveal a goat behind one of the other two doors that were unselected. So the fact that he does this reveals no new information if the contestant does not switch. So by not switching: $$P\_n = \frac{1}{3}$$ If on the other hand the contestant switches, he has inverted his probability of winning (wins when he would have lost if not switching, and vice-versa), so: $$P\_s = 1 - P\_n = \frac{2}{3}$$
The situation your first intuition tells you happens is that if the host picks a card *entirely at random* then there's an equal chance of either other cards revealing a car. However, the *actual* situation is that the host picks a card *after* you made the first selection. So, you have either selected a car or not.   There's a $1/3$ chance you selected the car using unbiased random selection. Now, if the host were to reveal a car it would be game over (you would be certainly wrong to either keep your choice or pick the remaining card.)   Still, we know this hasn't happened because the host did not reveal a car.   (Typically this never happens because the host is using *foreknowledge* to avoid this branch of the probability tree. However even if that's not the case, we still know a car was not revealed.) * If you selected a car, the host was free to flip either other card.   Then if you change your mind you are certainly wrong. * If you did not select a car, the card the host didn't choose is a car.   Then if you change your mind you are certainly right. Thus there is a $2/3$ chance of you being right if you change your mind.
1,428,377
So I was watching the show Numb3rs, and the math genius was teaching, and something he did just stumped me. He was asking his class (more specifically a student) on which of the three cards is the car. The other two cards have an animal on them. Now, the student picked the middle card to begin with. So the cards looks like this ``` +---+---+---+ | 1 | X | 3 | +---+---+---+ ``` *The `X` Representing The Picked Card* Then he flipped over the third card, and it turned out to be an animal. All that is left now is one more animal, and a car. He asks the student if the chances are higher of getting a car if they switch cards. The student responds no (That's what I thought too). The student was wrong. What the teacher said is "Switching cards actually doubles your chances of getting the car". So my question is, why does switching selected cards double your chances of getting the car when 1 of the 3 cards are already revealed. I thought it would just be a simple 50/50 still, please explain why the chances double!
2015/09/09
[ "https://math.stackexchange.com/questions/1428377", "https://math.stackexchange.com", "https://math.stackexchange.com/users/269300/" ]
The situation your first intuition tells you happens is that if the host picks a card *entirely at random* then there's an equal chance of either other cards revealing a car. However, the *actual* situation is that the host picks a card *after* you made the first selection. So, you have either selected a car or not.   There's a $1/3$ chance you selected the car using unbiased random selection. Now, if the host were to reveal a car it would be game over (you would be certainly wrong to either keep your choice or pick the remaining card.)   Still, we know this hasn't happened because the host did not reveal a car.   (Typically this never happens because the host is using *foreknowledge* to avoid this branch of the probability tree. However even if that's not the case, we still know a car was not revealed.) * If you selected a car, the host was free to flip either other card.   Then if you change your mind you are certainly wrong. * If you did not select a car, the card the host didn't choose is a car.   Then if you change your mind you are certainly right. Thus there is a $2/3$ chance of you being right if you change your mind.
The probability that you've picked the *wrong* card in the first place is 2/3. This happens to be the truth even when one of the cards is removed; it's just that 2/3 of the initial guesses are wrong. So when you have the chance to change your mind, you do it, because in the "second round", 1/2 of the guesses are correct (assuming they are random). Finally, chances when you keep the card are 2/3 times 1/2 that the guess is wrong. On the other hand, chances are 1/3 times 1/2 that the guess is wrong when you switch the cards. Comparing the terms gives the answer, I think.
17,178,030
I have a minor detail question regarding jade templates I'm seeing the following template: ``` p(data-ng-show="submitting") i.icon-cog.icon-spin | Authenticating... ``` being converted to this HTML ``` <p data-ng-show="submitting"><i class="icon-cog icon-spin"></i>Authenticating...</p> ``` Note the single space before "Authenticating..." is not carried over into the compiled HTML. Is the only solution here to use   to force a white space?
2013/06/18
[ "https://Stackoverflow.com/questions/17178030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/480807/" ]
That's how Jade is supposed to work, and I know, it's veeery bad having to deal with such a thing. You can do this: ``` p(data-ng-show="submitting") i.icon-cog.icon-spin | Authenticating... ``` which I think is somewhat tricky. Another option is to print an whitespace HTML entity, as already suggested by @brnrd: ``` p(data-ng-show="submitting") i.icon-cog.icon-spin | &nbsp;Authenticating... ``` *Yet another option*, but very bad in my opinion (or not that much if you use i18n), is: ``` p(data-ng-show="submitting") i.icon-cog.icon-spin = " Authenticating..." ```
Just add a white space character : ``` &nbsp; ``` As : ``` p(data-ng-show="submitting") i.icon-cog.icon-spin | &nbsp;Authenticating... ``` It does the trick.
37,178,602
I've List Tuple with int and string in it, each time I add new position to this list, I check for the same string in already added elements. Once I see the same - the goal is to change int (to do +1). For example if we have (3, box; 1, apple; 2, PC) and we need to add "apple", so I must change existing "1, apple" to "2, apple". But I can't do it because Item1 return error "The property has no setter". Where my mistake? Thanks. ``` string[] elements = s.Split(); // Contains all elements as strings. List<Tuple<int, string>> elementsList = new List<Tuple<int, string>>(); var sortItems = elementsList.OrderBy(x => x.Item1); for (int i = 0; i < elements.Length; i++) { foreach (var item in sortItems) { if (Equals(item.Item1, elements[i])) { item.Item1 += 1; } } elementsList.Add(new Tuple<int, string>(1, elements[i])); } return elementsList; ```
2016/05/12
[ "https://Stackoverflow.com/questions/37178602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6323762/" ]
According to the [documentation](https://msdn.microsoft.com/en-us/library/dd268536%28v=vs.110%29.aspx) of `Tuple<T1,T2>`, the properties cannot be written, which basically means that tuples are immutable. It is impossible to modify its contents in-place; it is necessary to create a new tuple.
`Tuple<T1, T2>` does not allow you to modify the values inside because it is immutable. Instead try using a `Dictionary` ``` string[] elements = s.Split(); // Contains all elements as strings. IDictionary<string, int> elementsMap = new Dictionary<string, int>(); for (int i = 0; i < elements.Length; i++) { string name = elements[i]; if (elementsMap.ContainsKey(name)) { elementsMap[name] += 1; } else { elementsMap.Add(name, 1); } } return elementsMap; ``` Or through Linq(credit to Jeppe Stig Nielsen): ``` var elementsMap = elements.GroupBy(e => e).ToDictionary(g => g.Key, g => g.Count()); ```
37,178,602
I've List Tuple with int and string in it, each time I add new position to this list, I check for the same string in already added elements. Once I see the same - the goal is to change int (to do +1). For example if we have (3, box; 1, apple; 2, PC) and we need to add "apple", so I must change existing "1, apple" to "2, apple". But I can't do it because Item1 return error "The property has no setter". Where my mistake? Thanks. ``` string[] elements = s.Split(); // Contains all elements as strings. List<Tuple<int, string>> elementsList = new List<Tuple<int, string>>(); var sortItems = elementsList.OrderBy(x => x.Item1); for (int i = 0; i < elements.Length; i++) { foreach (var item in sortItems) { if (Equals(item.Item1, elements[i])) { item.Item1 += 1; } } elementsList.Add(new Tuple<int, string>(1, elements[i])); } return elementsList; ```
2016/05/12
[ "https://Stackoverflow.com/questions/37178602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6323762/" ]
According to the [documentation](https://msdn.microsoft.com/en-us/library/dd268536%28v=vs.110%29.aspx) of `Tuple<T1,T2>`, the properties cannot be written, which basically means that tuples are immutable. It is impossible to modify its contents in-place; it is necessary to create a new tuple.
Tuples are immutable types, so basically they are not intented to be changed and have no setter. The reasons got listed up here : [Why Tuple's items are ReadOnly?](https://stackoverflow.com/questions/3131400/why-tuples-items-are-readonly) Either you create a new tuple (as Codor suggested) or you just create your own implementation, like shown here: [Why a Tuple, or a KeyValueItem, don't have a setter?](https://stackoverflow.com/questions/19725158/why-a-tuple-or-a-keyvalueitem-dont-have-a-setter)
37,178,602
I've List Tuple with int and string in it, each time I add new position to this list, I check for the same string in already added elements. Once I see the same - the goal is to change int (to do +1). For example if we have (3, box; 1, apple; 2, PC) and we need to add "apple", so I must change existing "1, apple" to "2, apple". But I can't do it because Item1 return error "The property has no setter". Where my mistake? Thanks. ``` string[] elements = s.Split(); // Contains all elements as strings. List<Tuple<int, string>> elementsList = new List<Tuple<int, string>>(); var sortItems = elementsList.OrderBy(x => x.Item1); for (int i = 0; i < elements.Length; i++) { foreach (var item in sortItems) { if (Equals(item.Item1, elements[i])) { item.Item1 += 1; } } elementsList.Add(new Tuple<int, string>(1, elements[i])); } return elementsList; ```
2016/05/12
[ "https://Stackoverflow.com/questions/37178602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6323762/" ]
According to the [documentation](https://msdn.microsoft.com/en-us/library/dd268536%28v=vs.110%29.aspx) of `Tuple<T1,T2>`, the properties cannot be written, which basically means that tuples are immutable. It is impossible to modify its contents in-place; it is necessary to create a new tuple.
Tuple class is immutable which means its properties do no have public setters to overwrite the underlying value. Tuples are not meant to be used in a key-value manner, which is probably closer to what you are trying to achieve. Tuples are more suitable for pairing *- well they are could be used for more than 2 practically -* two correlated pieces of data, such as coordinates for example, or width and height. More examples in the answers of the link below : [Practical example where Tuple can be used in .Net 4.0?](https://stackoverflow.com/questions/2745426/practical-example-where-tuple-can-be-used-in-net-4-0) **When should you use a Dictionary ?** Simply when you are doing lookups by a certain unique key to read/modify the an object(which could be a collection it self) corresponding to that key. a quick google around would show you tons of uses.
37,178,602
I've List Tuple with int and string in it, each time I add new position to this list, I check for the same string in already added elements. Once I see the same - the goal is to change int (to do +1). For example if we have (3, box; 1, apple; 2, PC) and we need to add "apple", so I must change existing "1, apple" to "2, apple". But I can't do it because Item1 return error "The property has no setter". Where my mistake? Thanks. ``` string[] elements = s.Split(); // Contains all elements as strings. List<Tuple<int, string>> elementsList = new List<Tuple<int, string>>(); var sortItems = elementsList.OrderBy(x => x.Item1); for (int i = 0; i < elements.Length; i++) { foreach (var item in sortItems) { if (Equals(item.Item1, elements[i])) { item.Item1 += 1; } } elementsList.Add(new Tuple<int, string>(1, elements[i])); } return elementsList; ```
2016/05/12
[ "https://Stackoverflow.com/questions/37178602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6323762/" ]
`Tuple<T1, T2>` does not allow you to modify the values inside because it is immutable. Instead try using a `Dictionary` ``` string[] elements = s.Split(); // Contains all elements as strings. IDictionary<string, int> elementsMap = new Dictionary<string, int>(); for (int i = 0; i < elements.Length; i++) { string name = elements[i]; if (elementsMap.ContainsKey(name)) { elementsMap[name] += 1; } else { elementsMap.Add(name, 1); } } return elementsMap; ``` Or through Linq(credit to Jeppe Stig Nielsen): ``` var elementsMap = elements.GroupBy(e => e).ToDictionary(g => g.Key, g => g.Count()); ```
Tuples are immutable types, so basically they are not intented to be changed and have no setter. The reasons got listed up here : [Why Tuple's items are ReadOnly?](https://stackoverflow.com/questions/3131400/why-tuples-items-are-readonly) Either you create a new tuple (as Codor suggested) or you just create your own implementation, like shown here: [Why a Tuple, or a KeyValueItem, don't have a setter?](https://stackoverflow.com/questions/19725158/why-a-tuple-or-a-keyvalueitem-dont-have-a-setter)
37,178,602
I've List Tuple with int and string in it, each time I add new position to this list, I check for the same string in already added elements. Once I see the same - the goal is to change int (to do +1). For example if we have (3, box; 1, apple; 2, PC) and we need to add "apple", so I must change existing "1, apple" to "2, apple". But I can't do it because Item1 return error "The property has no setter". Where my mistake? Thanks. ``` string[] elements = s.Split(); // Contains all elements as strings. List<Tuple<int, string>> elementsList = new List<Tuple<int, string>>(); var sortItems = elementsList.OrderBy(x => x.Item1); for (int i = 0; i < elements.Length; i++) { foreach (var item in sortItems) { if (Equals(item.Item1, elements[i])) { item.Item1 += 1; } } elementsList.Add(new Tuple<int, string>(1, elements[i])); } return elementsList; ```
2016/05/12
[ "https://Stackoverflow.com/questions/37178602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6323762/" ]
`Tuple<T1, T2>` does not allow you to modify the values inside because it is immutable. Instead try using a `Dictionary` ``` string[] elements = s.Split(); // Contains all elements as strings. IDictionary<string, int> elementsMap = new Dictionary<string, int>(); for (int i = 0; i < elements.Length; i++) { string name = elements[i]; if (elementsMap.ContainsKey(name)) { elementsMap[name] += 1; } else { elementsMap.Add(name, 1); } } return elementsMap; ``` Or through Linq(credit to Jeppe Stig Nielsen): ``` var elementsMap = elements.GroupBy(e => e).ToDictionary(g => g.Key, g => g.Count()); ```
Tuple class is immutable which means its properties do no have public setters to overwrite the underlying value. Tuples are not meant to be used in a key-value manner, which is probably closer to what you are trying to achieve. Tuples are more suitable for pairing *- well they are could be used for more than 2 practically -* two correlated pieces of data, such as coordinates for example, or width and height. More examples in the answers of the link below : [Practical example where Tuple can be used in .Net 4.0?](https://stackoverflow.com/questions/2745426/practical-example-where-tuple-can-be-used-in-net-4-0) **When should you use a Dictionary ?** Simply when you are doing lookups by a certain unique key to read/modify the an object(which could be a collection it self) corresponding to that key. a quick google around would show you tons of uses.
37,178,602
I've List Tuple with int and string in it, each time I add new position to this list, I check for the same string in already added elements. Once I see the same - the goal is to change int (to do +1). For example if we have (3, box; 1, apple; 2, PC) and we need to add "apple", so I must change existing "1, apple" to "2, apple". But I can't do it because Item1 return error "The property has no setter". Where my mistake? Thanks. ``` string[] elements = s.Split(); // Contains all elements as strings. List<Tuple<int, string>> elementsList = new List<Tuple<int, string>>(); var sortItems = elementsList.OrderBy(x => x.Item1); for (int i = 0; i < elements.Length; i++) { foreach (var item in sortItems) { if (Equals(item.Item1, elements[i])) { item.Item1 += 1; } } elementsList.Add(new Tuple<int, string>(1, elements[i])); } return elementsList; ```
2016/05/12
[ "https://Stackoverflow.com/questions/37178602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6323762/" ]
Tuples are immutable types, so basically they are not intented to be changed and have no setter. The reasons got listed up here : [Why Tuple's items are ReadOnly?](https://stackoverflow.com/questions/3131400/why-tuples-items-are-readonly) Either you create a new tuple (as Codor suggested) or you just create your own implementation, like shown here: [Why a Tuple, or a KeyValueItem, don't have a setter?](https://stackoverflow.com/questions/19725158/why-a-tuple-or-a-keyvalueitem-dont-have-a-setter)
Tuple class is immutable which means its properties do no have public setters to overwrite the underlying value. Tuples are not meant to be used in a key-value manner, which is probably closer to what you are trying to achieve. Tuples are more suitable for pairing *- well they are could be used for more than 2 practically -* two correlated pieces of data, such as coordinates for example, or width and height. More examples in the answers of the link below : [Practical example where Tuple can be used in .Net 4.0?](https://stackoverflow.com/questions/2745426/practical-example-where-tuple-can-be-used-in-net-4-0) **When should you use a Dictionary ?** Simply when you are doing lookups by a certain unique key to read/modify the an object(which could be a collection it self) corresponding to that key. a quick google around would show you tons of uses.
5,256,122
Here I create one project that will track our current location. But I have a problem coding it... I don't know exactly how to use the OVERLAY class and when it is called. I have posted my code.. Please help me ``` package com.techno.gps; import java.io.IOException; import java.util.List; import java.util.Locale; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import com.google.android.maps.Projection; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.RectF; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; public class gps extends MapActivity{ MapController mapController; Location location; MyPositionOverlay positionOverlay; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get a reference to the MapView MapView myMapView = (MapView)findViewById(R.id.mapView); // Get the Map View’s controller mapController = myMapView.getController(); // Configure the map display options myMapView.setSatellite(true); myMapView.setStreetView(true); myMapView.displayZoomControls(false); // Zoom in mapController.setZoom(17); //add postionoverlay positionOverlay = new MyPositionOverlay(); List<Overlay> overlays = myMapView.getOverlays(); overlays.add(positionOverlay); LocationManager locationManager; String context = Context.LOCATION_SERVICE; locationManager = (LocationManager)getSystemService(context); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_LOW); String provider = locationManager.getBestProvider(criteria, true); location = locationManager.getLastKnownLocation(provider); updateWithNewLocation(location); locationManager.requestLocationUpdates(provider, 2000, 10,locationListener); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } private void updateWithNewLocation(Location location) { String latLongString; TextView myLocationText; myLocationText = (TextView)findViewById(R.id.myLocationText); String addressString = "No address found"; if (location != null) { // Update the map location. positionOverlay.setLocation(location); Double geoLat = location.getLatitude()*1E6; Double geoLng = location.getLongitude()*1E6; GeoPoint point = new GeoPoint(geoLat.intValue(), geoLng.intValue()); mapController.animateTo(point); double lat = location.getLatitude(); double lng = location.getLongitude(); latLongString = "Lat: "+ lat + " Long:" + lng; double latitude = location.getLatitude(); double longitude = location.getLongitude(); Geocoder gc = new Geocoder(this, Locale.getDefault()); try { List<Address> addresses = gc.getFromLocation(latitude, longitude, 1); StringBuilder sb = new StringBuilder(); if (addresses.size() > 0) { Address address = addresses.get(0); for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { sb.append(address.getAddressLine(i)).append("\n"); } sb.append(address.getLocality()).append("\n"); sb.append(address.getPostalCode()).append("\n"); sb.append(address.getCountryName()); } addressString = sb.toString(); } catch (IOException e) { } } else { latLongString = "No location found"; } myLocationText.setText("Your Current Position is:\n" +latLongString + "\n" + addressString); } private final LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { updateWithNewLocation(location); } public void onProviderDisabled(String provider) { updateWithNewLocation(null); } public void onProviderEnabled(String provider) { } public void onStatusChanged(String provider, int status,Bundle extras) { } }; public class MyPositionOverlay extends Overlay { Location location; @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { Projection projection = mapView.getProjection(); if (shadow == false) { // Get the current location Double latitude = location.getLatitude()*1E6; Double longitude = location.getLongitude()*1E6; GeoPoint geoPoint; geoPoint = new GeoPoint(latitude.intValue(),longitude.intValue()); // Convert the location to screen pixels int mRadius=5; Point point = new Point(); projection.toPixels(geoPoint, point); RectF oval = new RectF(point.x - mRadius, point.y - mRadius, point.x + mRadius, point.y + mRadius); // Setup the paint Paint paint = new Paint(); paint.setARGB(250, 255, 0, 0); paint.setAntiAlias(true); paint.setFakeBoldText(true); Paint backPaint = new Paint(); backPaint.setARGB(175, 50, 50, 50); backPaint.setAntiAlias(true); RectF backRect = new RectF(point.x + 2 + mRadius, point.y - 3*mRadius, point.x + 65, point.y + mRadius); // Draw the marker canvas.drawOval(oval, paint); canvas.drawRoundRect(backRect, 5, 5, backPaint); canvas.drawText("Here I Am", point.x + 2*mRadius, point.y, paint); } super.draw(canvas, mapView, shadow); } @Override public boolean onTap(GeoPoint point, MapView mapView) { // Return true if screen tap is handled by this overlay return false; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } } } ``` thanks...
2011/03/10
[ "https://Stackoverflow.com/questions/5256122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1004437/" ]
Strange that you don't know your own code. You should try writing it by yourself. Copy-pasting does not work always. To answer your question. An Overlay is drawable object that can be shown on top of the map on a different layer above the MapView. This is the part of the code where you add that drawing to the MapView. ``` positionOverlay = new MyPositionOverlay(); List<Overlay> overlays = myMapView.getOverlays(); overlays.add(positionOverlay); ``` You are doing this in OnCreate(). Which does not makes sense, because you have no position fix yet. 1. Add the overlay when you get a pos-fix in updateWithNewLocation() 2. To call draw forcefully use MapView.invalidate()
i have the same example code, with 2.2 android, works, but don't drow the overlay, with my position, otherwise, with debuggin you can see code working properltly. Really strange. I think code is correct, because, in onCreate, code is initializated, then in updateWithNewLocation, the overlay is updated with `positionOverlay.setLocation(location);`
6,970
During *some* exercises (push-ups, crunshes) my whole body shakes, I feel a tremor that I cannot control. This happens even during first push-up, when I'm not tired at at all. So, my questions are: 1. What could be a reason for this? 2. Does this tremor affect the efficiency of my workout? 3. Should I be trying to control it, and if yes, how? I'm 37, and started working out recently after a long period without any physical activity.
2012/06/25
[ "https://fitness.stackexchange.com/questions/6970", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/3558/" ]
Here's an article from LiveStrong.com about muscle tremors: <http://www.livestrong.com/article/446452-tremors-while-exercising/> Basically, without a proper medical examination, there is no way to tell if the cause is just lack of fitness or nutrition or something else. SO, step one: get a complete physical, step two find a local personal trainer to make sure you have a good/proper workout routine and associate diet. You can 'work through' or force yourself to continue, but this could lead to further issues - so, take a step back, your body is telling you something and you need a professional medical person to help understand what it's saying. I'm sure its nothing more than your current condition and diet.
The uber physical therapy expert Mike Reinold in his sport coach's seminars tells them they can only rule things *in* - only a doctor with the right equipment can rule something out. so I agree with @Meade while at the same time who can afford a real check-up? I don't like the sound of "my whole body" shaking. When I do weighted push ups with my feet elevated on a bench, my hips will shake just before failure on my heavy sets because the small synergist muscles are giving out. I know these are weak because I can't do hip airplanes very well despite my squatting strength. That doesn't sound like what's happening to you, unless all your synergists are weak. You might try backing off completely and looking for extremely wussy exercises (wall push ups) and see if that helps, but of course now we're playing doctor ruling out god knows what.
6,970
During *some* exercises (push-ups, crunshes) my whole body shakes, I feel a tremor that I cannot control. This happens even during first push-up, when I'm not tired at at all. So, my questions are: 1. What could be a reason for this? 2. Does this tremor affect the efficiency of my workout? 3. Should I be trying to control it, and if yes, how? I'm 37, and started working out recently after a long period without any physical activity.
2012/06/25
[ "https://fitness.stackexchange.com/questions/6970", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/3558/" ]
Here's an article from LiveStrong.com about muscle tremors: <http://www.livestrong.com/article/446452-tremors-while-exercising/> Basically, without a proper medical examination, there is no way to tell if the cause is just lack of fitness or nutrition or something else. SO, step one: get a complete physical, step two find a local personal trainer to make sure you have a good/proper workout routine and associate diet. You can 'work through' or force yourself to continue, but this could lead to further issues - so, take a step back, your body is telling you something and you need a professional medical person to help understand what it's saying. I'm sure its nothing more than your current condition and diet.
There are several reasons for your tremor, ranging from Parkinson's (for which you, according to incidence statistics, are too young) and cerebellar ataxia (unlikely without other neurological deficits or a previous history of trauma) to benign muscular apraxia. The only way to know would be to perform a physical examination. You say that your whole body shakes, and that is, in its literal sense, a neurological symptom. However, seeing that you just started working out after a long period without physical activity, the most likely etiology is that you have poor inter- and intramuscular coordination. Basically, your brain and muscles aren't used to performing those movements smoothly and efficiently. This always happens during the initial phases of training, even for experienced athletes after years of training with a short detraining period, but also when doing a new exercise. In case your tremor does not subside within the next 5-6 training sessions, or at least improve, then it is likely something else. If it does, then you have nothing to worry about, there is no need to control it, and it will go away on its own once you get more used to performing those movements.
6,970
During *some* exercises (push-ups, crunshes) my whole body shakes, I feel a tremor that I cannot control. This happens even during first push-up, when I'm not tired at at all. So, my questions are: 1. What could be a reason for this? 2. Does this tremor affect the efficiency of my workout? 3. Should I be trying to control it, and if yes, how? I'm 37, and started working out recently after a long period without any physical activity.
2012/06/25
[ "https://fitness.stackexchange.com/questions/6970", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/3558/" ]
Here's an article from LiveStrong.com about muscle tremors: <http://www.livestrong.com/article/446452-tremors-while-exercising/> Basically, without a proper medical examination, there is no way to tell if the cause is just lack of fitness or nutrition or something else. SO, step one: get a complete physical, step two find a local personal trainer to make sure you have a good/proper workout routine and associate diet. You can 'work through' or force yourself to continue, but this could lead to further issues - so, take a step back, your body is telling you something and you need a professional medical person to help understand what it's saying. I'm sure its nothing more than your current condition and diet.
While workout your body shakes,it has two reasons.First is that may your body shaking means you are working and strengthening your muscle.Second is the negative point it must be due to the weakness and deficiency of vitamins or water in your body.If your doing some exercise to the first time like stretching and strengthening then it was sure that your body will shake.But if the muscle starts shaking in the beginning of the exercise then it is a warning that the exercise is too difficult for your body to handle.There are things that effect accordingly so you have to prepare yourself for the effects of exercise in your body.
6,970
During *some* exercises (push-ups, crunshes) my whole body shakes, I feel a tremor that I cannot control. This happens even during first push-up, when I'm not tired at at all. So, my questions are: 1. What could be a reason for this? 2. Does this tremor affect the efficiency of my workout? 3. Should I be trying to control it, and if yes, how? I'm 37, and started working out recently after a long period without any physical activity.
2012/06/25
[ "https://fitness.stackexchange.com/questions/6970", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/3558/" ]
The uber physical therapy expert Mike Reinold in his sport coach's seminars tells them they can only rule things *in* - only a doctor with the right equipment can rule something out. so I agree with @Meade while at the same time who can afford a real check-up? I don't like the sound of "my whole body" shaking. When I do weighted push ups with my feet elevated on a bench, my hips will shake just before failure on my heavy sets because the small synergist muscles are giving out. I know these are weak because I can't do hip airplanes very well despite my squatting strength. That doesn't sound like what's happening to you, unless all your synergists are weak. You might try backing off completely and looking for extremely wussy exercises (wall push ups) and see if that helps, but of course now we're playing doctor ruling out god knows what.
There are several reasons for your tremor, ranging from Parkinson's (for which you, according to incidence statistics, are too young) and cerebellar ataxia (unlikely without other neurological deficits or a previous history of trauma) to benign muscular apraxia. The only way to know would be to perform a physical examination. You say that your whole body shakes, and that is, in its literal sense, a neurological symptom. However, seeing that you just started working out after a long period without physical activity, the most likely etiology is that you have poor inter- and intramuscular coordination. Basically, your brain and muscles aren't used to performing those movements smoothly and efficiently. This always happens during the initial phases of training, even for experienced athletes after years of training with a short detraining period, but also when doing a new exercise. In case your tremor does not subside within the next 5-6 training sessions, or at least improve, then it is likely something else. If it does, then you have nothing to worry about, there is no need to control it, and it will go away on its own once you get more used to performing those movements.
6,970
During *some* exercises (push-ups, crunshes) my whole body shakes, I feel a tremor that I cannot control. This happens even during first push-up, when I'm not tired at at all. So, my questions are: 1. What could be a reason for this? 2. Does this tremor affect the efficiency of my workout? 3. Should I be trying to control it, and if yes, how? I'm 37, and started working out recently after a long period without any physical activity.
2012/06/25
[ "https://fitness.stackexchange.com/questions/6970", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/3558/" ]
The uber physical therapy expert Mike Reinold in his sport coach's seminars tells them they can only rule things *in* - only a doctor with the right equipment can rule something out. so I agree with @Meade while at the same time who can afford a real check-up? I don't like the sound of "my whole body" shaking. When I do weighted push ups with my feet elevated on a bench, my hips will shake just before failure on my heavy sets because the small synergist muscles are giving out. I know these are weak because I can't do hip airplanes very well despite my squatting strength. That doesn't sound like what's happening to you, unless all your synergists are weak. You might try backing off completely and looking for extremely wussy exercises (wall push ups) and see if that helps, but of course now we're playing doctor ruling out god knows what.
While workout your body shakes,it has two reasons.First is that may your body shaking means you are working and strengthening your muscle.Second is the negative point it must be due to the weakness and deficiency of vitamins or water in your body.If your doing some exercise to the first time like stretching and strengthening then it was sure that your body will shake.But if the muscle starts shaking in the beginning of the exercise then it is a warning that the exercise is too difficult for your body to handle.There are things that effect accordingly so you have to prepare yourself for the effects of exercise in your body.
6,970
During *some* exercises (push-ups, crunshes) my whole body shakes, I feel a tremor that I cannot control. This happens even during first push-up, when I'm not tired at at all. So, my questions are: 1. What could be a reason for this? 2. Does this tremor affect the efficiency of my workout? 3. Should I be trying to control it, and if yes, how? I'm 37, and started working out recently after a long period without any physical activity.
2012/06/25
[ "https://fitness.stackexchange.com/questions/6970", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/3558/" ]
While workout your body shakes,it has two reasons.First is that may your body shaking means you are working and strengthening your muscle.Second is the negative point it must be due to the weakness and deficiency of vitamins or water in your body.If your doing some exercise to the first time like stretching and strengthening then it was sure that your body will shake.But if the muscle starts shaking in the beginning of the exercise then it is a warning that the exercise is too difficult for your body to handle.There are things that effect accordingly so you have to prepare yourself for the effects of exercise in your body.
There are several reasons for your tremor, ranging from Parkinson's (for which you, according to incidence statistics, are too young) and cerebellar ataxia (unlikely without other neurological deficits or a previous history of trauma) to benign muscular apraxia. The only way to know would be to perform a physical examination. You say that your whole body shakes, and that is, in its literal sense, a neurological symptom. However, seeing that you just started working out after a long period without physical activity, the most likely etiology is that you have poor inter- and intramuscular coordination. Basically, your brain and muscles aren't used to performing those movements smoothly and efficiently. This always happens during the initial phases of training, even for experienced athletes after years of training with a short detraining period, but also when doing a new exercise. In case your tremor does not subside within the next 5-6 training sessions, or at least improve, then it is likely something else. If it does, then you have nothing to worry about, there is no need to control it, and it will go away on its own once you get more used to performing those movements.
55,733,604
I've just built and deployed an app to Google Play. It worked well when I was running it through Android Studio but now it crashes when I download it from Google Play. Because this is my first time, I don't even know how to view the crash report/stacktrace of the app that was downloaded from Google Play. I appreciate any and all help. **UPDATE** So I got the stacktrace for the APK. It tells me that my `TopImageFragment.java` class cannot create my `MemeViewModel.java` class. I have no clue why its giving this error. Everything works fine as it is. It seems that proguard is indeed phasing out an important class: ``` 2019-04-18 00:46:32.062 8099-8099/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.ozbek.onur.memegenerator, PID: 8099 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ozbek.onur.memegenerator/com.ozbek.onur.memegenerator.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2853) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6703) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) Caused by: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:155) at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) at com.ozbek.onur.memegenerator.TopImageFragment.onActivityCreated(TopImageFragment.java:89) ```
2019/04/17
[ "https://Stackoverflow.com/questions/55733604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8095827/" ]
This kind of problem usually happens because your app deployed to Google Play was a release build and proguard minified your app and removed a class it shouldn't have. When you build in Android Studio it is a debug build that does not get minified. That's why you see the crash only from Google Play. Before uploading to Google Play, test out your release APK file on a device and watch logcat for the error. That should tell you what class got removed by mistake and you can correct that by specifying custom proguard rules and trying again until the app stops crashing. Then when you upload to Google Play, you should be good. You can also enable proguard in a debug build as well by changing your build.gradle file. Then when you run through Android Studio, you should see the same error as you see through Google Play. One other alternative, you can disable proguard/minification in your release build. However this is not recommended because your app will be larger than it needs to be.
In my suggestion, keep your phone connected to your your PC/Laptop while you download and attempt to open it. Use Logcat on android studio, it mostly has all answers or at least errors that lead to the answers. try putting error logs here so we can have a proper look at it. 1) Try the same version of your application that you deployed on Google play store by pushing it through the android studio and see if the problem continues! 2) If same thing happens then put breakpoint on the entry point (onCreate method in most cases in MainActivity class) of your application and Go to Run->Debug "YourProject" option and do step by step debug for each command being executed and see which one is causing problem.
55,733,604
I've just built and deployed an app to Google Play. It worked well when I was running it through Android Studio but now it crashes when I download it from Google Play. Because this is my first time, I don't even know how to view the crash report/stacktrace of the app that was downloaded from Google Play. I appreciate any and all help. **UPDATE** So I got the stacktrace for the APK. It tells me that my `TopImageFragment.java` class cannot create my `MemeViewModel.java` class. I have no clue why its giving this error. Everything works fine as it is. It seems that proguard is indeed phasing out an important class: ``` 2019-04-18 00:46:32.062 8099-8099/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.ozbek.onur.memegenerator, PID: 8099 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ozbek.onur.memegenerator/com.ozbek.onur.memegenerator.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2853) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6703) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) Caused by: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:155) at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) at com.ozbek.onur.memegenerator.TopImageFragment.onActivityCreated(TopImageFragment.java:89) ```
2019/04/17
[ "https://Stackoverflow.com/questions/55733604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8095827/" ]
Check if you have any java files that don't have an access modifier. In my experience, just declaring a class without a public or private modifier, causes this problem.
In my suggestion, keep your phone connected to your your PC/Laptop while you download and attempt to open it. Use Logcat on android studio, it mostly has all answers or at least errors that lead to the answers. try putting error logs here so we can have a proper look at it. 1) Try the same version of your application that you deployed on Google play store by pushing it through the android studio and see if the problem continues! 2) If same thing happens then put breakpoint on the entry point (onCreate method in most cases in MainActivity class) of your application and Go to Run->Debug "YourProject" option and do step by step debug for each command being executed and see which one is causing problem.
55,733,604
I've just built and deployed an app to Google Play. It worked well when I was running it through Android Studio but now it crashes when I download it from Google Play. Because this is my first time, I don't even know how to view the crash report/stacktrace of the app that was downloaded from Google Play. I appreciate any and all help. **UPDATE** So I got the stacktrace for the APK. It tells me that my `TopImageFragment.java` class cannot create my `MemeViewModel.java` class. I have no clue why its giving this error. Everything works fine as it is. It seems that proguard is indeed phasing out an important class: ``` 2019-04-18 00:46:32.062 8099-8099/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.ozbek.onur.memegenerator, PID: 8099 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ozbek.onur.memegenerator/com.ozbek.onur.memegenerator.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2853) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6703) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) Caused by: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:155) at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) at com.ozbek.onur.memegenerator.TopImageFragment.onActivityCreated(TopImageFragment.java:89) ```
2019/04/17
[ "https://Stackoverflow.com/questions/55733604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8095827/" ]
My app suffered the same problem and it was a ProGuard kill. Because ProGuard renames all classes unless otherwise instructed. So, in your case, you have to add > > @Keep > > > annotation before your class name **MemeViewModel**. example, ``` @Keep class MemeViewModel{ // // } ```
In my suggestion, keep your phone connected to your your PC/Laptop while you download and attempt to open it. Use Logcat on android studio, it mostly has all answers or at least errors that lead to the answers. try putting error logs here so we can have a proper look at it. 1) Try the same version of your application that you deployed on Google play store by pushing it through the android studio and see if the problem continues! 2) If same thing happens then put breakpoint on the entry point (onCreate method in most cases in MainActivity class) of your application and Go to Run->Debug "YourProject" option and do step by step debug for each command being executed and see which one is causing problem.
55,733,604
I've just built and deployed an app to Google Play. It worked well when I was running it through Android Studio but now it crashes when I download it from Google Play. Because this is my first time, I don't even know how to view the crash report/stacktrace of the app that was downloaded from Google Play. I appreciate any and all help. **UPDATE** So I got the stacktrace for the APK. It tells me that my `TopImageFragment.java` class cannot create my `MemeViewModel.java` class. I have no clue why its giving this error. Everything works fine as it is. It seems that proguard is indeed phasing out an important class: ``` 2019-04-18 00:46:32.062 8099-8099/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.ozbek.onur.memegenerator, PID: 8099 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ozbek.onur.memegenerator/com.ozbek.onur.memegenerator.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2853) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6703) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) Caused by: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:155) at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) at com.ozbek.onur.memegenerator.TopImageFragment.onActivityCreated(TopImageFragment.java:89) ```
2019/04/17
[ "https://Stackoverflow.com/questions/55733604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8095827/" ]
Check if you have any java files that don't have an access modifier. In my experience, just declaring a class without a public or private modifier, causes this problem.
This kind of problem usually happens because your app deployed to Google Play was a release build and proguard minified your app and removed a class it shouldn't have. When you build in Android Studio it is a debug build that does not get minified. That's why you see the crash only from Google Play. Before uploading to Google Play, test out your release APK file on a device and watch logcat for the error. That should tell you what class got removed by mistake and you can correct that by specifying custom proguard rules and trying again until the app stops crashing. Then when you upload to Google Play, you should be good. You can also enable proguard in a debug build as well by changing your build.gradle file. Then when you run through Android Studio, you should see the same error as you see through Google Play. One other alternative, you can disable proguard/minification in your release build. However this is not recommended because your app will be larger than it needs to be.
55,733,604
I've just built and deployed an app to Google Play. It worked well when I was running it through Android Studio but now it crashes when I download it from Google Play. Because this is my first time, I don't even know how to view the crash report/stacktrace of the app that was downloaded from Google Play. I appreciate any and all help. **UPDATE** So I got the stacktrace for the APK. It tells me that my `TopImageFragment.java` class cannot create my `MemeViewModel.java` class. I have no clue why its giving this error. Everything works fine as it is. It seems that proguard is indeed phasing out an important class: ``` 2019-04-18 00:46:32.062 8099-8099/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.ozbek.onur.memegenerator, PID: 8099 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ozbek.onur.memegenerator/com.ozbek.onur.memegenerator.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2853) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6703) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) Caused by: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:155) at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) at com.ozbek.onur.memegenerator.TopImageFragment.onActivityCreated(TopImageFragment.java:89) ```
2019/04/17
[ "https://Stackoverflow.com/questions/55733604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8095827/" ]
This kind of problem usually happens because your app deployed to Google Play was a release build and proguard minified your app and removed a class it shouldn't have. When you build in Android Studio it is a debug build that does not get minified. That's why you see the crash only from Google Play. Before uploading to Google Play, test out your release APK file on a device and watch logcat for the error. That should tell you what class got removed by mistake and you can correct that by specifying custom proguard rules and trying again until the app stops crashing. Then when you upload to Google Play, you should be good. You can also enable proguard in a debug build as well by changing your build.gradle file. Then when you run through Android Studio, you should see the same error as you see through Google Play. One other alternative, you can disable proguard/minification in your release build. However this is not recommended because your app will be larger than it needs to be.
My app suffered the same problem and it was a ProGuard kill. Because ProGuard renames all classes unless otherwise instructed. So, in your case, you have to add > > @Keep > > > annotation before your class name **MemeViewModel**. example, ``` @Keep class MemeViewModel{ // // } ```
55,733,604
I've just built and deployed an app to Google Play. It worked well when I was running it through Android Studio but now it crashes when I download it from Google Play. Because this is my first time, I don't even know how to view the crash report/stacktrace of the app that was downloaded from Google Play. I appreciate any and all help. **UPDATE** So I got the stacktrace for the APK. It tells me that my `TopImageFragment.java` class cannot create my `MemeViewModel.java` class. I have no clue why its giving this error. Everything works fine as it is. It seems that proguard is indeed phasing out an important class: ``` 2019-04-18 00:46:32.062 8099-8099/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.ozbek.onur.memegenerator, PID: 8099 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ozbek.onur.memegenerator/com.ozbek.onur.memegenerator.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2853) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2928) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1609) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6703) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) Caused by: java.lang.RuntimeException: Cannot create an instance of class com.ozbek.onur.memegenerator.MemeViewModel at android.arch.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:155) at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:210) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) at com.ozbek.onur.memegenerator.TopImageFragment.onActivityCreated(TopImageFragment.java:89) ```
2019/04/17
[ "https://Stackoverflow.com/questions/55733604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8095827/" ]
Check if you have any java files that don't have an access modifier. In my experience, just declaring a class without a public or private modifier, causes this problem.
My app suffered the same problem and it was a ProGuard kill. Because ProGuard renames all classes unless otherwise instructed. So, in your case, you have to add > > @Keep > > > annotation before your class name **MemeViewModel**. example, ``` @Keep class MemeViewModel{ // // } ```
28,614,099
I have two vectors ``` vector<int> vint; vector<vector<int>::iterator> viter; ``` What is the best way to remove all elements in `vint` whose iterators are present in `viter`. Currently, I workaround temporarily moving to a `list` Edit: (Some more background) This is my current code. I wish I could avoid moving to list and back to vector ``` void foo(std::vector<Blah>& bvec) { std::list<Blah> blist; std::move(bvec.begin(), bvec.end(), std::back_inserter(blist)); bvec.clear(); std::vector<std::list<Blah>::iterator> selectedElements; { //Critical section which holds a mutex. Should be as fast as possible for(auto it = blist.begin(), it_end= blist.end(); it != it_end; ++it) { if(shouldElementBeRemoved(*it)) selectedElements.push_back(it); } } for(auto& it: selectedElements) { if(shouldElementReallyBeRemoved(*it)) blist.erase(it); } std::move(blist.begin(), blist.end(), std::back_inserter(bvec)); } ``` Could be simplified without list if I can remove directly from vector. ``` void foo(std::vector<Blah>& bvec) { std::vector<std::vector<Blah>::iterator> selectedElements; { //Critical section which holds a mutex. Should be as fast as possible for(auto it = bvec.begin(), it_end= bvec.end(); it != it_end; ++it) { if(shouldElementBeRemoved(*it)) selectedElements.push_back(it); } } for(auto& it: selectedElements) { if(shouldElementReallyBeRemoved(*it)) // bvect.erase(it); //Not safe! } } ```
2015/02/19
[ "https://Stackoverflow.com/questions/28614099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463758/" ]
This seemed to do the right thing for me: ``` #include <algorithm> for (auto current = vint.end(); current >= vint.begin();) { current--; if (any_of( viter.begin(), viter.end(), [current](std::vector<int>::iterator it) { return current == it; })) { vint.erase(current); } } ``` Using `any_of` allows the iterator vector to be unsorted.
Perhaps this would be appropriate for your situation: ``` struct Blah { bool deleted = false; // add a special field // other data }; void foo(std::vector<Blah>& bvec) { { //Critical section which holds a mutex. Should be as fast as possible // mark them quickly for(auto& b: bvec) if(shouldElementBeRemoved(b)) b.deleted = true; } // remove them slowly for(auto i = bvec.begin(); i != bvec.end();) { if(i->deleted && shouldElementReallyBeRemoved(*i)) i = bvec.erase(i); else { i->deleted = false; ++i; } } } ```
28,614,099
I have two vectors ``` vector<int> vint; vector<vector<int>::iterator> viter; ``` What is the best way to remove all elements in `vint` whose iterators are present in `viter`. Currently, I workaround temporarily moving to a `list` Edit: (Some more background) This is my current code. I wish I could avoid moving to list and back to vector ``` void foo(std::vector<Blah>& bvec) { std::list<Blah> blist; std::move(bvec.begin(), bvec.end(), std::back_inserter(blist)); bvec.clear(); std::vector<std::list<Blah>::iterator> selectedElements; { //Critical section which holds a mutex. Should be as fast as possible for(auto it = blist.begin(), it_end= blist.end(); it != it_end; ++it) { if(shouldElementBeRemoved(*it)) selectedElements.push_back(it); } } for(auto& it: selectedElements) { if(shouldElementReallyBeRemoved(*it)) blist.erase(it); } std::move(blist.begin(), blist.end(), std::back_inserter(bvec)); } ``` Could be simplified without list if I can remove directly from vector. ``` void foo(std::vector<Blah>& bvec) { std::vector<std::vector<Blah>::iterator> selectedElements; { //Critical section which holds a mutex. Should be as fast as possible for(auto it = bvec.begin(), it_end= bvec.end(); it != it_end; ++it) { if(shouldElementBeRemoved(*it)) selectedElements.push_back(it); } } for(auto& it: selectedElements) { if(shouldElementReallyBeRemoved(*it)) // bvect.erase(it); //Not safe! } } ```
2015/02/19
[ "https://Stackoverflow.com/questions/28614099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463758/" ]
You should be able to use your second snippet with a small modification - instead of iterating over `selectedElements` in the forward direction, go backwards. Then the call to `bvec.erase` will never invalidate any iterators that remain in `selectedElements`. ``` void foo(std::vector<Blah>& bvec) { std::vector<std::vector<Blah>::iterator> selectedElements; selectedElements.reserve(bvec.size()); // avoid growing the vector while you hold a mutex lock { //Critical section which holds a mutex. Should be as fast as possible for(auto it = bvec.begin(), it_end= bvec.end(); it != it_end; ++it) { if(shouldElementBeRemoved(*it)) selectedElements.push_back(it); } } for(auto first = selectedElements.rbegin(), last = selectedElements.rend(); first != last; ++first) { if(shouldElementReallyBeRemoved(**first)) bvec.erase(*first); } } ``` [Live demo](http://coliru.stacked-crooked.com/a/cfc5307f1ae17eeb)
This seemed to do the right thing for me: ``` #include <algorithm> for (auto current = vint.end(); current >= vint.begin();) { current--; if (any_of( viter.begin(), viter.end(), [current](std::vector<int>::iterator it) { return current == it; })) { vint.erase(current); } } ``` Using `any_of` allows the iterator vector to be unsorted.
28,614,099
I have two vectors ``` vector<int> vint; vector<vector<int>::iterator> viter; ``` What is the best way to remove all elements in `vint` whose iterators are present in `viter`. Currently, I workaround temporarily moving to a `list` Edit: (Some more background) This is my current code. I wish I could avoid moving to list and back to vector ``` void foo(std::vector<Blah>& bvec) { std::list<Blah> blist; std::move(bvec.begin(), bvec.end(), std::back_inserter(blist)); bvec.clear(); std::vector<std::list<Blah>::iterator> selectedElements; { //Critical section which holds a mutex. Should be as fast as possible for(auto it = blist.begin(), it_end= blist.end(); it != it_end; ++it) { if(shouldElementBeRemoved(*it)) selectedElements.push_back(it); } } for(auto& it: selectedElements) { if(shouldElementReallyBeRemoved(*it)) blist.erase(it); } std::move(blist.begin(), blist.end(), std::back_inserter(bvec)); } ``` Could be simplified without list if I can remove directly from vector. ``` void foo(std::vector<Blah>& bvec) { std::vector<std::vector<Blah>::iterator> selectedElements; { //Critical section which holds a mutex. Should be as fast as possible for(auto it = bvec.begin(), it_end= bvec.end(); it != it_end; ++it) { if(shouldElementBeRemoved(*it)) selectedElements.push_back(it); } } for(auto& it: selectedElements) { if(shouldElementReallyBeRemoved(*it)) // bvect.erase(it); //Not safe! } } ```
2015/02/19
[ "https://Stackoverflow.com/questions/28614099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463758/" ]
You should be able to use your second snippet with a small modification - instead of iterating over `selectedElements` in the forward direction, go backwards. Then the call to `bvec.erase` will never invalidate any iterators that remain in `selectedElements`. ``` void foo(std::vector<Blah>& bvec) { std::vector<std::vector<Blah>::iterator> selectedElements; selectedElements.reserve(bvec.size()); // avoid growing the vector while you hold a mutex lock { //Critical section which holds a mutex. Should be as fast as possible for(auto it = bvec.begin(), it_end= bvec.end(); it != it_end; ++it) { if(shouldElementBeRemoved(*it)) selectedElements.push_back(it); } } for(auto first = selectedElements.rbegin(), last = selectedElements.rend(); first != last; ++first) { if(shouldElementReallyBeRemoved(**first)) bvec.erase(*first); } } ``` [Live demo](http://coliru.stacked-crooked.com/a/cfc5307f1ae17eeb)
Perhaps this would be appropriate for your situation: ``` struct Blah { bool deleted = false; // add a special field // other data }; void foo(std::vector<Blah>& bvec) { { //Critical section which holds a mutex. Should be as fast as possible // mark them quickly for(auto& b: bvec) if(shouldElementBeRemoved(b)) b.deleted = true; } // remove them slowly for(auto i = bvec.begin(); i != bvec.end();) { if(i->deleted && shouldElementReallyBeRemoved(*i)) i = bvec.erase(i); else { i->deleted = false; ++i; } } } ```
16,830
I want to cook a soft polenta. I would like the consistency to be like pudding - just firm enough to hold a shape (it doesn't flow out of the spoon if you take a heaped spoonful), but not firm enough to be cut into pieces. My ingredients will be cornmeal (not cornflour; it seems to be ~600 µm grain size), milk and olive oil. I am looking for the correct ratio by weight to achieve this consistency. If you don't have a ratio for this case, but know a ratio for a similar polenta (e.g. cornmeal + stock) which gives this consistency, I'd be glad to know this one too, I think I can get the tweaking right by myself.
2011/08/12
[ "https://cooking.stackexchange.com/questions/16830", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/4638/" ]
Yes, it depends on brand, humidity, etc. My local variety is 1:4 to 1:4.5 (polenta:water) to get to that softness level Add nothing else until you have the polenta at the desired consistency and softness
For better authenticity (I know you are not asking for that, but still...) you might want to replace the olive oil with butter, or some other tasty animal fat. The polenta areas in Italy are mostly (\*) not olive oil areas, and I can imagine that the olive oil, if it is a good one, would add a marked taste of its own. 1:4 sounds good, remember that polenta becomes stiffer as it cools down, so don't be dismayed if it just looks like yellow soup in the pot. (\*) exception: the Garda lake. Polenta and olives.
4,652,190
So I have been doing a lot of reading about the way iOS handles application state notifications, and it looks like they may have created a problem for me in iOS 4. Before 4.x, I was cleaning out my NSUserDefaults in the `- (void)applicationWillTerminate:(UIApplication *)application {}` delegate method. Unfortunately, it does not look like this method is used anymore when the user quits the app from the desktop (pressing the red "-"). Instead the app receives a SIGKIL. Has anyone schemed a way to capture this and do something when the app is terminated (such as clean out the UserDefaults)? I would prefer to not disable the multitasking since that's non-standard behavior. Any help at all would be appreciated. Thanks!
2011/01/10
[ "https://Stackoverflow.com/questions/4652190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410856/" ]
That method will still be sent if iOS ever decides to quit the app. You should probably put the same cleanup code in [applicationWillResignActive:](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html) if you want it to clean up when moving to the background as well. However, if you say you want to support multitasking, why are you wiping the default? Shouldn't the user be able to come back to the app exactly as they left it?
By "clean out" do you mean "synchronize to disk"? (i.e. by calling -synchronize) If so, NSUserDefaults handles this for you automatically, no need to worry about it.
4,652,190
So I have been doing a lot of reading about the way iOS handles application state notifications, and it looks like they may have created a problem for me in iOS 4. Before 4.x, I was cleaning out my NSUserDefaults in the `- (void)applicationWillTerminate:(UIApplication *)application {}` delegate method. Unfortunately, it does not look like this method is used anymore when the user quits the app from the desktop (pressing the red "-"). Instead the app receives a SIGKIL. Has anyone schemed a way to capture this and do something when the app is terminated (such as clean out the UserDefaults)? I would prefer to not disable the multitasking since that's non-standard behavior. Any help at all would be appreciated. Thanks!
2011/01/10
[ "https://Stackoverflow.com/questions/4652190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410856/" ]
That method will still be sent if iOS ever decides to quit the app. You should probably put the same cleanup code in [applicationWillResignActive:](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html) if you want it to clean up when moving to the background as well. However, if you say you want to support multitasking, why are you wiping the default? Shouldn't the user be able to come back to the app exactly as they left it?
You still need the code in applicationWillTerminate: for those iOS 4 devices that don't support multi-tasking. But you'll also need to call the same code when the app goes into the background (applicationDidEnterBackground:). You might also consider applicationWillResignActive:, but this would get called when a call or an SMS arrives rather than only when it goes into the background.
25,384,725
I have written following code to read from a file list of filenames on each line and append some data to it. ``` open my $info,'<',"abc.txt"; while(<$info>){ chomp $_; my $filename = "temp/".$_.".xml"; print"\n"; print $filename; print "\n"; } close $info; ``` Content of abc.txt ``` file1 file2 file3 ``` Now I was expecting my code to give me following output ``` temp/file1.xml temp/file2.xml temp/file3.xml ``` but instead I am getting output ``` .xml/file1 .xml/file2 .xml/file3 ```
2014/08/19
[ "https://Stackoverflow.com/questions/25384725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486527/" ]
Your file has windows line endings `\r\n`. `chomp` removes the `\n` ([Newline](http://en.wikipedia.org/wiki/Newline)) but leaves the `\r` ([Carriage return](http://en.wikipedia.org/wiki/Carriage_return)). Using [`Data::Dumper`](http://perldoc.perl.org/Data/Dumper.html) with `Useqq` you can examine the variable: ``` use Data::Dumper; $Data::Dumper::Useqq = 1; print Dumper($filename); ``` This should output something like: ``` $VAR1 = "temp/file1\r.xml"; ``` When printed normally, it will output `temp/file`, move the cursor to the start of the line and overwrite `temp` with `.xml`. To remove the line endings, replace `chomp` with: ``` s/\r\n$//; ``` or as noted by **@Borodin**: ``` s/\s+\z//; ``` which "has the advantage of working for any line terminator, as well as removing trailing whitespace, which is commonly unwanted"
As has been stated, your file has windows line endings. The following self-contained example demonstrates what you're working with: ``` use strict; use warnings; open my $info, '<', \ "file1\r\nfile2\r\nfile3\r\n"; while(<$info>){ chomp; my $filename = "temp/".$_.".xml"; use Data::Dump; dd $filename; print $filename, "\n"; } ``` Outputs: ``` "temp/file1\r.xml" .xml/file1 "temp/file2\r.xml" .xml/file2 "temp/file3\r.xml" .xml/file3 ``` Now there are two ways to fix this 1. Adjust the [`$INPUT_RECORD_SEPARATOR`](http://perldoc.perl.org/perlvar.html) to that of your file. ``` local $/ = "\r\n"; while(<$info>){ chomp; ``` [`chomp`](http://perldoc.perl.org/functions/chomp.html) automatically works on the value of `$/`. 2. Use a regex instead of [`chomp`](http://perldoc.perl.org/functions/chomp.html) to strip the line endings Since [perl 5.10](http://perldoc.perl.org/perl5100delta.html#Regular-expressions) there is a escape code [`\R`](http://perldoc.perl.org/perlrebackslash.html#Misc) which stands for a *generic newline*. ``` while(<$info>){ s/\R//; ``` Alternatively, you could just strip all trailing spacing to be even more sure of covering your bases: ``` while(<$info>){ s/\s+\z//; ```
74,202,726
[![My assigment](https://i.stack.imgur.com/dmCPJ.png)](https://i.stack.imgur.com/dmCPJ.png) I am pretty new to this so sorry if i am not clear. My code works so far for one year (12 months), however when i want to find the average rainfall for two years (24 months), it finds it for 48 months. Not sure how to fix this, or where the problem is situated. ```java import java.util.Scanner; public class AverageRainfall { public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.println("How many years did it rain? "); int years = kb.nextInt(); for (int i = 1; i <= years; i++){ for(int j = 1; j <= (years * 12); j++){ System.out.println("How many inches of rain this month?"); totalRain += kb.nextInt(); System.out.println("Month: " + j); System.out.println(totalRain + " Inches of rain!" ); } } System.out.println("The average rainfall over the period of: " + years + "years is:" + totalRain/(12*years) + "Inches"); } } ``` I tried changing things inside my for loop conditions but I can't figure it out.
2022/10/26
[ "https://Stackoverflow.com/questions/74202726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17062245/" ]
1. Given you know the extension and its unlikely to appear elsewhere in the string, find it, and truncate to it. Do that in a `CROSS APPLY` so we can use the value multiple times. 2. Then find the nearest slash (using `REVERSE`) and use `SUBSTRING` from there to the end. ``` SELECT SUBSTRING(Y.[VALUE], LEN(Y.[VALUE]) - PATINDEX('%\%', REVERSE(Y.[VALUE])) + 2, LEN(Y.[VALUE])) FROM ( VALUES ('/FILE "\"G:\Enterprise_Data\Packages\SSIS_Packages_Source_to_Target_Data_Snowflake.dtsx\""/CHECKPOINTING OFF /REPORTING E') ) AS X ([Value]) CROSS APPLY ( VALUES (SUBSTRING(X.[Value], 1, PATINDEX('%.dtsx%', X.[Value])-1)) ) AS Y ([Value]); ``` Returns: > > SSIS\_Packages\_Source\_to\_Target\_Data\_Snowflake > > >
Thank you @Dale K for your response and solutions provided. I was able to replicate the same for my query to obtain the result. Below is how I modified the query in my environment to fetch only the new string column1 after applying the string manipulations based on your solution: SELECT SUBSTRING(Y.column1, LEN(Y.column1) - PATINDEX('%%', REVERSE(Y.column1)) +2, LEN(Y.column1)) FROM (SELECT column1 FROM CTE1) AS X ([column2]) CROSS APPLY (SELECT SUBSTRING(X.column2, 1, PATINDEX('%.dtsx%', X.column2)-1) FROM CTE1) AS Y ([column1]) I am actually query a CTE table (CTE1) to get my desired result. The issue is that, I have other columns in the CTE1 that I need to include in the final select query results, which of course should include the string manipulated results from Column1. Currently, I get errors when I try to include other columns in my final result from the CTE1 along with the resultset from the query above. Example of final query: Select Jobname,job\_step,job\_date,job\_duration,Column1 (this will be the resultset from the string manipulation)FROM CTE1; So, what I'm currently doing that is not working is as follows: ``` SELECT C1.Jobname,C1.job_step,C1.job_date,C1.job_duration,Column1 =(SELECT SUBSTRING(Y.column1, LEN(Y.column1) - PATINDEX('%\%', REVERSE(Y.column1)) +2, LEN(Y.column1)) FROM (SELECT column1 FROM CTE1) AS X ([column2]) CROSS APPLY (SELECT SUBSTRING(X.column2, 1, PATINDEX('%.dtsx%', X.column2)-1) FROM CTE1) AS Y ([column1])) FROM CTE1 C1 ``` Please, how can I obtain the final results with all the above columns present in the resultsets? Thank you.
74,202,726
[![My assigment](https://i.stack.imgur.com/dmCPJ.png)](https://i.stack.imgur.com/dmCPJ.png) I am pretty new to this so sorry if i am not clear. My code works so far for one year (12 months), however when i want to find the average rainfall for two years (24 months), it finds it for 48 months. Not sure how to fix this, or where the problem is situated. ```java import java.util.Scanner; public class AverageRainfall { public static void main(String[] args) { Scanner kb = new Scanner(System.in); System.out.println("How many years did it rain? "); int years = kb.nextInt(); for (int i = 1; i <= years; i++){ for(int j = 1; j <= (years * 12); j++){ System.out.println("How many inches of rain this month?"); totalRain += kb.nextInt(); System.out.println("Month: " + j); System.out.println(totalRain + " Inches of rain!" ); } } System.out.println("The average rainfall over the period of: " + years + "years is:" + totalRain/(12*years) + "Inches"); } } ``` I tried changing things inside my for loop conditions but I can't figure it out.
2022/10/26
[ "https://Stackoverflow.com/questions/74202726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17062245/" ]
Another possible way is this. not sure on the performance of it though ``` SELECT vt.[value] FROM ( VALUES ('/FILE "\"G:\Enterprise_Data\Packages\SSIS_Packages_Source_to_Target_Data_Snowflake.dtsx\""/CHECKPOINTING OFF /REPORTING E') ) AS X ([Value]) OUTER APPLY ( SELECT * FROM STRING_SPLIT(x.Value,'\') ) vt WHERE vt.[value] LIKE '%.dtsx' ```
Thank you @Dale K for your response and solutions provided. I was able to replicate the same for my query to obtain the result. Below is how I modified the query in my environment to fetch only the new string column1 after applying the string manipulations based on your solution: SELECT SUBSTRING(Y.column1, LEN(Y.column1) - PATINDEX('%%', REVERSE(Y.column1)) +2, LEN(Y.column1)) FROM (SELECT column1 FROM CTE1) AS X ([column2]) CROSS APPLY (SELECT SUBSTRING(X.column2, 1, PATINDEX('%.dtsx%', X.column2)-1) FROM CTE1) AS Y ([column1]) I am actually query a CTE table (CTE1) to get my desired result. The issue is that, I have other columns in the CTE1 that I need to include in the final select query results, which of course should include the string manipulated results from Column1. Currently, I get errors when I try to include other columns in my final result from the CTE1 along with the resultset from the query above. Example of final query: Select Jobname,job\_step,job\_date,job\_duration,Column1 (this will be the resultset from the string manipulation)FROM CTE1; So, what I'm currently doing that is not working is as follows: ``` SELECT C1.Jobname,C1.job_step,C1.job_date,C1.job_duration,Column1 =(SELECT SUBSTRING(Y.column1, LEN(Y.column1) - PATINDEX('%\%', REVERSE(Y.column1)) +2, LEN(Y.column1)) FROM (SELECT column1 FROM CTE1) AS X ([column2]) CROSS APPLY (SELECT SUBSTRING(X.column2, 1, PATINDEX('%.dtsx%', X.column2)-1) FROM CTE1) AS Y ([column1])) FROM CTE1 C1 ``` Please, how can I obtain the final results with all the above columns present in the resultsets? Thank you.
1,816,451
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
2009/11/29
[ "https://Stackoverflow.com/questions/1816451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206504/" ]
There are **[lots of choices](http://curl.haxx.se/libcurl/competitors.html)**! Try **[libwww](http://www.w3.org/Library/)** -- but be warned, most people strongly prefer `libcurl`. It's much easier to use.
`system("wget -q -O file.htm http://url.com");`
1,816,451
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
2009/11/29
[ "https://Stackoverflow.com/questions/1816451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206504/" ]
There are **[lots of choices](http://curl.haxx.se/libcurl/competitors.html)**! Try **[libwww](http://www.w3.org/Library/)** -- but be warned, most people strongly prefer `libcurl`. It's much easier to use.
There's a very light way and I've done this myself when implementing a high-scale back end service for a large media provider in the UK. This method is extremely operating-system specific. 1. open a TCP socket to the HTTP server 2. send a "`GET /path/to/url HTTP/1.1\r\nHost: www.host.com\r\n\r\n`" (the `Host` header is required for HTTP/1.1 and most virtual servers, don't forget the two blank lines, and a newline requires a carriage return as well for HTTP headers) 3. wait for the response 4. close the socket If you are going to close the socket at the end of the connection you may also want to send a `Connection: close\r\n` as part of your headers to inform the web server that you will terminate the connection after retrieving the web page. You may run into trouble if you're fetching an encoded or generated web page in which case you'll have to add logic to interpret the fetched data.
1,816,451
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
2009/11/29
[ "https://Stackoverflow.com/questions/1816451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206504/" ]
There are **[lots of choices](http://curl.haxx.se/libcurl/competitors.html)**! Try **[libwww](http://www.w3.org/Library/)** -- but be warned, most people strongly prefer `libcurl`. It's much easier to use.
On Windows (Windows XP, Windows 2000 Professional with SP3 and above) you could use [WinHttpReadData](http://msdn.microsoft.com/en-us/library/aa384104(VS.85).aspx) API. There's also an example at the bottom of that page. More info on **Windows HTTP Services** on [MSDN](http://msdn.microsoft.com/en-us/library/aa384273(VS.85).aspx)
1,816,451
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
2009/11/29
[ "https://Stackoverflow.com/questions/1816451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206504/" ]
There are **[lots of choices](http://curl.haxx.se/libcurl/competitors.html)**! Try **[libwww](http://www.w3.org/Library/)** -- but be warned, most people strongly prefer `libcurl`. It's much easier to use.
I have used Winsock when I need as few dependencies as possible and it has worked well. You need to write more code than using a separate library or the Microsoft WinHTTP library. The functions you need are WSAStartup, socket, connect, send, recv, closesocket and WSACleanup. See sample code for the [send](http://msdn.microsoft.com/en-us/library/ms740149%28VS.85%29.aspx) function.
1,816,451
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
2009/11/29
[ "https://Stackoverflow.com/questions/1816451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206504/" ]
There's a very light way and I've done this myself when implementing a high-scale back end service for a large media provider in the UK. This method is extremely operating-system specific. 1. open a TCP socket to the HTTP server 2. send a "`GET /path/to/url HTTP/1.1\r\nHost: www.host.com\r\n\r\n`" (the `Host` header is required for HTTP/1.1 and most virtual servers, don't forget the two blank lines, and a newline requires a carriage return as well for HTTP headers) 3. wait for the response 4. close the socket If you are going to close the socket at the end of the connection you may also want to send a `Connection: close\r\n` as part of your headers to inform the web server that you will terminate the connection after retrieving the web page. You may run into trouble if you're fetching an encoded or generated web page in which case you'll have to add logic to interpret the fetched data.
`system("wget -q -O file.htm http://url.com");`
1,816,451
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
2009/11/29
[ "https://Stackoverflow.com/questions/1816451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206504/" ]
On Windows (Windows XP, Windows 2000 Professional with SP3 and above) you could use [WinHttpReadData](http://msdn.microsoft.com/en-us/library/aa384104(VS.85).aspx) API. There's also an example at the bottom of that page. More info on **Windows HTTP Services** on [MSDN](http://msdn.microsoft.com/en-us/library/aa384273(VS.85).aspx)
`system("wget -q -O file.htm http://url.com");`
1,816,451
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
2009/11/29
[ "https://Stackoverflow.com/questions/1816451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206504/" ]
I have used Winsock when I need as few dependencies as possible and it has worked well. You need to write more code than using a separate library or the Microsoft WinHTTP library. The functions you need are WSAStartup, socket, connect, send, recv, closesocket and WSACleanup. See sample code for the [send](http://msdn.microsoft.com/en-us/library/ms740149%28VS.85%29.aspx) function.
`system("wget -q -O file.htm http://url.com");`
1,816,451
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
2009/11/29
[ "https://Stackoverflow.com/questions/1816451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206504/" ]
There's a very light way and I've done this myself when implementing a high-scale back end service for a large media provider in the UK. This method is extremely operating-system specific. 1. open a TCP socket to the HTTP server 2. send a "`GET /path/to/url HTTP/1.1\r\nHost: www.host.com\r\n\r\n`" (the `Host` header is required for HTTP/1.1 and most virtual servers, don't forget the two blank lines, and a newline requires a carriage return as well for HTTP headers) 3. wait for the response 4. close the socket If you are going to close the socket at the end of the connection you may also want to send a `Connection: close\r\n` as part of your headers to inform the web server that you will terminate the connection after retrieving the web page. You may run into trouble if you're fetching an encoded or generated web page in which case you'll have to add logic to interpret the fetched data.
I have used Winsock when I need as few dependencies as possible and it has worked well. You need to write more code than using a separate library or the Microsoft WinHTTP library. The functions you need are WSAStartup, socket, connect, send, recv, closesocket and WSACleanup. See sample code for the [send](http://msdn.microsoft.com/en-us/library/ms740149%28VS.85%29.aspx) function.
1,816,451
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
2009/11/29
[ "https://Stackoverflow.com/questions/1816451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206504/" ]
On Windows (Windows XP, Windows 2000 Professional with SP3 and above) you could use [WinHttpReadData](http://msdn.microsoft.com/en-us/library/aa384104(VS.85).aspx) API. There's also an example at the bottom of that page. More info on **Windows HTTP Services** on [MSDN](http://msdn.microsoft.com/en-us/library/aa384273(VS.85).aspx)
I have used Winsock when I need as few dependencies as possible and it has worked well. You need to write more code than using a separate library or the Microsoft WinHTTP library. The functions you need are WSAStartup, socket, connect, send, recv, closesocket and WSACleanup. See sample code for the [send](http://msdn.microsoft.com/en-us/library/ms740149%28VS.85%29.aspx) function.
31,400
My front downspout is not long enough and currently all the water just comes back and rests between my sloped sidewalk and the graded edge of my house. ![enter image description here](https://i.stack.imgur.com/dNCRf.png) I'm thinking I can move the downspout so that it goes over my sloped sidewalk and I can walk under it like so. ![enter image description here](https://i.stack.imgur.com/Lw89D.png) I'm thinking I'll get some sort of L shaped bracer for the part coming off the house but I'm not sure how I would add supports for the part that comes down on the yard. How would I brace a freestanding downspout? I'm currently planning on having the house dug up in the spring and having it wrapped to reduce water seepage so I'm not looking at fixing the sidewalk or implementing the underground stuff at the moment as I'll just have to do it again later. My other option is just making my downspout really long but I would like to use the sidewalk. Perhaps there is another option I may be missing. ![enter image description here](https://i.stack.imgur.com/fLrKm.png)
2013/09/03
[ "https://diy.stackexchange.com/questions/31400", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/2210/" ]
This isn't a downspout problem, this is a grading problem. The ground has either eroded over time or was never properly graded in the first place. Probably a combination. Either way, the end result is that water collects in the low places and only dissipates by absorbing into the ground (not good; that can cause foundation problems like liquefaction of the soil underneath a slab or P&B foundation, or weeping and frost heaves against a basement wall) or evaporating. You're not going to fix this by extending the downspout; you may *reduce* the amount of water collecting, but rain will still fall naturally into this valley next to your house, or fall against the side of your house and then run down into it. You're going to have to solve the problem by creating a continuously-downhill path for this water, directing it away from your house. This sidewalk; is it sloped in a V with the lowest point at its center? If so, it was probably built as much to direct runoff as to be a walking path, and you should investigate where the sidewalk should be sending the water (probably around to the front of the house and down the driveway) and make adjustments accordingly. If not, why does it slope? It is really old and sloping due to erosion underneath it, or did the contractor who put it in just not have his level with him that day? Can we get some real pictures of the side of your house and this valley, with indications of where the water currently pools?
The original post is several years old. I noticed the "answer" provide didn't answer the actual question. You could drive LONG metal rod, or stake into the ground, where the overhead portion of the gutter comes down to the ground. The rod would extend maybe 2feet above the ground. Then, the final downspout could be attached to the rod, with a strap piece.
37,029,197
I am new in IOS developing. In `Main.storyoard`, I added a new `viewcontroller`, assigned it to a new class `LoginViewController` and provided a storyboard-ID `loginview`. In the `LoginViewController` class, after successful login I tried the following code to call the default viewcontroller having storyboard-ID `webview`. ``` NSString *storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"webview"]; [self presentViewController:vc animated:YES completion:nil]; ``` During debugging I got the following exception > > 2016-05-04 18:37:11.020 gcmexample[2690:86862] > bool \_WebTryThreadLock(bool), 0x7fa5d3f3d840: Tried to obtain the web > lock from a thread other than the main thread or the web thread. This > may be a result of calling to UIKit from a secondary thread. Crashing > now... 1 0x11328d34b WebThreadLock 2 0x10e5547dd -[UIWebView > \_webViewCommonInitWithWebView:scalesPageToFit:] 3 0x10e555179 -[UIWebView initWithCoder:] 4 0x10e7b5822 UINibDecoderDecodeObjectForValue 5 0x10e7b5558 -[UINibDecoder > decodeObjectForKey:] 6 0x10e5e1483 -[UIRuntimeConnection > initWithCoder:] 7 0x10e7b5822 UINibDecoderDecodeObjectForValue 8 > > 0x10e7b59e3 UINibDecoderDecodeObjectForValue 9 0x10e7b5558 > -[UINibDecoder decodeObjectForKey:] 10 0x10e5e06c3 -[UINib instantiateWithOwner:options:] 11 0x10e3b9eea -[UIViewController > \_loadViewFromNibNamed:bundle:] 12 0x10e3ba816 -[UIViewController loadView] 13 0x10e3bab74 -[UIViewController loadViewIfRequired] 14 > 0x10e3bb2e7 -[UIViewController view] 15 0x10eb65f87 > -[\_UIFullscreenPresentationController \_setPresentedViewController:] 16 0x10e38af62 -[UIPresentationController > initWithPresentedViewController:presentingViewController:] 17 > 0x10e3cdc8c -[UIViewController > \_presentViewController:withAnimationController:completion:] 18 0x10e3d0f2c -[UIViewController > \_performCoordinatedPresentOrDismiss:animated:] 19 0x10e3d0a3b -[UIViewController presentViewController:animated:completion:] 20 0x10d065eed **34-[LoginViewController btnSign\_in:]\_block\_invoke 21 > 0x10fd3f6b5 \_\_75-[\_\_NSURLSessionLocal > taskForClass:request:uploadFile:bodyData:completion:]\_block\_invoke 22 > 0x10fd51a02 \_\_49-[\_\_NSCFLocalSessionTask > \_task\_onqueue\_didFinish]\_block\_invoke 23 0x10d1dc304 \_\_NSBLOCKOPERATION\_IS\_CALLING\_OUT\_TO\_A\_BLOCK** 24 0x10d118035 -[NSBlockOperation main] 25 0x10d0faf8a -[\_\_NSOperationInternal \_start:] 26 0x10d0fab9b \_\_NSOQSchedule\_f 27 0x11057f49b \_dispatch\_client\_callout 28 0x1105658ec \_dispatch\_queue\_drain 29 0x110564e0d \_dispatch\_queue\_invoke 30 0x110567a56 > \_dispatch\_root\_queue\_drain 31 0x1105674c5 \_dispatch\_worker\_thread3 > > > Does anyone know whats the error here? Please help.
2016/05/04
[ "https://Stackoverflow.com/questions/37029197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5747962/" ]
try the below code instead of your's. The problem seems to be you are doing an UI operation from different tread which you have created for login service. But it's recommended that the UI operation should performed on main thread ``` dispatch_async(dispatch_get_main_queue(), ^{ NSString *storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"webview"]; [self presentViewController:vc animated:YES completion:nil]; }); ```
You are performing present action on secondary thread instead `main thread`. All the UI Operations must be performed on Main Thread only, otherwise it will not take effect. To perform some action on Main Thread use following `dispatch_async` block which performs on main thread. ``` dispatch_async(dispatch_get_main_queue(), ^{ NSString *storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"webview"]; [self presentViewController:vc animated:YES completion:nil]; }); ```
37,029,197
I am new in IOS developing. In `Main.storyoard`, I added a new `viewcontroller`, assigned it to a new class `LoginViewController` and provided a storyboard-ID `loginview`. In the `LoginViewController` class, after successful login I tried the following code to call the default viewcontroller having storyboard-ID `webview`. ``` NSString *storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"webview"]; [self presentViewController:vc animated:YES completion:nil]; ``` During debugging I got the following exception > > 2016-05-04 18:37:11.020 gcmexample[2690:86862] > bool \_WebTryThreadLock(bool), 0x7fa5d3f3d840: Tried to obtain the web > lock from a thread other than the main thread or the web thread. This > may be a result of calling to UIKit from a secondary thread. Crashing > now... 1 0x11328d34b WebThreadLock 2 0x10e5547dd -[UIWebView > \_webViewCommonInitWithWebView:scalesPageToFit:] 3 0x10e555179 -[UIWebView initWithCoder:] 4 0x10e7b5822 UINibDecoderDecodeObjectForValue 5 0x10e7b5558 -[UINibDecoder > decodeObjectForKey:] 6 0x10e5e1483 -[UIRuntimeConnection > initWithCoder:] 7 0x10e7b5822 UINibDecoderDecodeObjectForValue 8 > > 0x10e7b59e3 UINibDecoderDecodeObjectForValue 9 0x10e7b5558 > -[UINibDecoder decodeObjectForKey:] 10 0x10e5e06c3 -[UINib instantiateWithOwner:options:] 11 0x10e3b9eea -[UIViewController > \_loadViewFromNibNamed:bundle:] 12 0x10e3ba816 -[UIViewController loadView] 13 0x10e3bab74 -[UIViewController loadViewIfRequired] 14 > 0x10e3bb2e7 -[UIViewController view] 15 0x10eb65f87 > -[\_UIFullscreenPresentationController \_setPresentedViewController:] 16 0x10e38af62 -[UIPresentationController > initWithPresentedViewController:presentingViewController:] 17 > 0x10e3cdc8c -[UIViewController > \_presentViewController:withAnimationController:completion:] 18 0x10e3d0f2c -[UIViewController > \_performCoordinatedPresentOrDismiss:animated:] 19 0x10e3d0a3b -[UIViewController presentViewController:animated:completion:] 20 0x10d065eed **34-[LoginViewController btnSign\_in:]\_block\_invoke 21 > 0x10fd3f6b5 \_\_75-[\_\_NSURLSessionLocal > taskForClass:request:uploadFile:bodyData:completion:]\_block\_invoke 22 > 0x10fd51a02 \_\_49-[\_\_NSCFLocalSessionTask > \_task\_onqueue\_didFinish]\_block\_invoke 23 0x10d1dc304 \_\_NSBLOCKOPERATION\_IS\_CALLING\_OUT\_TO\_A\_BLOCK** 24 0x10d118035 -[NSBlockOperation main] 25 0x10d0faf8a -[\_\_NSOperationInternal \_start:] 26 0x10d0fab9b \_\_NSOQSchedule\_f 27 0x11057f49b \_dispatch\_client\_callout 28 0x1105658ec \_dispatch\_queue\_drain 29 0x110564e0d \_dispatch\_queue\_invoke 30 0x110567a56 > \_dispatch\_root\_queue\_drain 31 0x1105674c5 \_dispatch\_worker\_thread3 > > > Does anyone know whats the error here? Please help.
2016/05/04
[ "https://Stackoverflow.com/questions/37029197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5747962/" ]
try the below code instead of your's. The problem seems to be you are doing an UI operation from different tread which you have created for login service. But it's recommended that the UI operation should performed on main thread ``` dispatch_async(dispatch_get_main_queue(), ^{ NSString *storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"webview"]; [self presentViewController:vc animated:YES completion:nil]; }); ```
Try this ``` UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyNetworkStoryboard" bundle:nil]; MyNetworkTableViewController *myVC = (MyNetworkTableViewController *)[storyboard instantiateViewControllerWithIdentifier:@"networkController"]; UIViewController *frontViewController = myVC; [self.navigationController pushViewController:frontViewController animated:YES]; ```
37,029,197
I am new in IOS developing. In `Main.storyoard`, I added a new `viewcontroller`, assigned it to a new class `LoginViewController` and provided a storyboard-ID `loginview`. In the `LoginViewController` class, after successful login I tried the following code to call the default viewcontroller having storyboard-ID `webview`. ``` NSString *storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"webview"]; [self presentViewController:vc animated:YES completion:nil]; ``` During debugging I got the following exception > > 2016-05-04 18:37:11.020 gcmexample[2690:86862] > bool \_WebTryThreadLock(bool), 0x7fa5d3f3d840: Tried to obtain the web > lock from a thread other than the main thread or the web thread. This > may be a result of calling to UIKit from a secondary thread. Crashing > now... 1 0x11328d34b WebThreadLock 2 0x10e5547dd -[UIWebView > \_webViewCommonInitWithWebView:scalesPageToFit:] 3 0x10e555179 -[UIWebView initWithCoder:] 4 0x10e7b5822 UINibDecoderDecodeObjectForValue 5 0x10e7b5558 -[UINibDecoder > decodeObjectForKey:] 6 0x10e5e1483 -[UIRuntimeConnection > initWithCoder:] 7 0x10e7b5822 UINibDecoderDecodeObjectForValue 8 > > 0x10e7b59e3 UINibDecoderDecodeObjectForValue 9 0x10e7b5558 > -[UINibDecoder decodeObjectForKey:] 10 0x10e5e06c3 -[UINib instantiateWithOwner:options:] 11 0x10e3b9eea -[UIViewController > \_loadViewFromNibNamed:bundle:] 12 0x10e3ba816 -[UIViewController loadView] 13 0x10e3bab74 -[UIViewController loadViewIfRequired] 14 > 0x10e3bb2e7 -[UIViewController view] 15 0x10eb65f87 > -[\_UIFullscreenPresentationController \_setPresentedViewController:] 16 0x10e38af62 -[UIPresentationController > initWithPresentedViewController:presentingViewController:] 17 > 0x10e3cdc8c -[UIViewController > \_presentViewController:withAnimationController:completion:] 18 0x10e3d0f2c -[UIViewController > \_performCoordinatedPresentOrDismiss:animated:] 19 0x10e3d0a3b -[UIViewController presentViewController:animated:completion:] 20 0x10d065eed **34-[LoginViewController btnSign\_in:]\_block\_invoke 21 > 0x10fd3f6b5 \_\_75-[\_\_NSURLSessionLocal > taskForClass:request:uploadFile:bodyData:completion:]\_block\_invoke 22 > 0x10fd51a02 \_\_49-[\_\_NSCFLocalSessionTask > \_task\_onqueue\_didFinish]\_block\_invoke 23 0x10d1dc304 \_\_NSBLOCKOPERATION\_IS\_CALLING\_OUT\_TO\_A\_BLOCK** 24 0x10d118035 -[NSBlockOperation main] 25 0x10d0faf8a -[\_\_NSOperationInternal \_start:] 26 0x10d0fab9b \_\_NSOQSchedule\_f 27 0x11057f49b \_dispatch\_client\_callout 28 0x1105658ec \_dispatch\_queue\_drain 29 0x110564e0d \_dispatch\_queue\_invoke 30 0x110567a56 > \_dispatch\_root\_queue\_drain 31 0x1105674c5 \_dispatch\_worker\_thread3 > > > Does anyone know whats the error here? Please help.
2016/05/04
[ "https://Stackoverflow.com/questions/37029197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5747962/" ]
You are performing present action on secondary thread instead `main thread`. All the UI Operations must be performed on Main Thread only, otherwise it will not take effect. To perform some action on Main Thread use following `dispatch_async` block which performs on main thread. ``` dispatch_async(dispatch_get_main_queue(), ^{ NSString *storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"webview"]; [self presentViewController:vc animated:YES completion:nil]; }); ```
Try this ``` UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyNetworkStoryboard" bundle:nil]; MyNetworkTableViewController *myVC = (MyNetworkTableViewController *)[storyboard instantiateViewControllerWithIdentifier:@"networkController"]; UIViewController *frontViewController = myVC; [self.navigationController pushViewController:frontViewController animated:YES]; ```
2,269,542
A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM. I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly. Is there an alternative, cross-browser *evented* approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).
2010/02/15
[ "https://Stackoverflow.com/questions/2269542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253511/" ]
Have a variable in the parent: ``` var setToLoad = false; ``` Follow it up with a function to set it: ``` function SetToLoad() { setToLoad = true; } ``` Then in the child iframe call this function using the window.opener ``` function CallSetToLoad() { window.opener.SetToLoad(); } window.onload = CallSetToLoad; ``` This won't run until the iframe is finished loading, and if it's in the same domain it'll allow access to the opener. This would require editing a small portion of the 3rd party script. EDIT: Alternative solution Given that you can't edit the script, you might try something like: ``` frames["myiframe"].onload = function() { // do your stuff here } ```
Can you inject arbitrary scripting code into your iframe? If so, you should be able to make it so that some code executes in the iframe upon the the iframe loading that calls code in the parent page.
2,269,542
A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM. I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly. Is there an alternative, cross-browser *evented* approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).
2010/02/15
[ "https://Stackoverflow.com/questions/2269542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253511/" ]
using jquery? ``` function callIframe(url, callback) { $(document.body).append('<IFRAME id="myId" ...>'); $('iframe#myId').attr('src', url); $('iframe#myId').load(function() { callback(this); }); } ``` Question answered in [jQuery .ready in a dynamically inserted iframe](https://stackoverflow.com/questions/205087/jquery-ready-in-a-dynamically-inserted-iframe)
Can you inject arbitrary scripting code into your iframe? If so, you should be able to make it so that some code executes in the iframe upon the the iframe loading that calls code in the parent page.
2,269,542
A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM. I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly. Is there an alternative, cross-browser *evented* approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).
2010/02/15
[ "https://Stackoverflow.com/questions/2269542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253511/" ]
Have a variable in the parent: ``` var setToLoad = false; ``` Follow it up with a function to set it: ``` function SetToLoad() { setToLoad = true; } ``` Then in the child iframe call this function using the window.opener ``` function CallSetToLoad() { window.opener.SetToLoad(); } window.onload = CallSetToLoad; ``` This won't run until the iframe is finished loading, and if it's in the same domain it'll allow access to the opener. This would require editing a small portion of the 3rd party script. EDIT: Alternative solution Given that you can't edit the script, you might try something like: ``` frames["myiframe"].onload = function() { // do your stuff here } ```
First: You probably won't be able to manipulate its dom when it loads html from other domain And You probably are interested in DOMready. Look here: [jQuery .ready in a dynamically inserted iframe](https://stackoverflow.com/questions/205087/jquery-ready-in-a-dynamically-inserted-iframe)
2,269,542
A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM. I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly. Is there an alternative, cross-browser *evented* approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).
2010/02/15
[ "https://Stackoverflow.com/questions/2269542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253511/" ]
using jquery? ``` function callIframe(url, callback) { $(document.body).append('<IFRAME id="myId" ...>'); $('iframe#myId').attr('src', url); $('iframe#myId').load(function() { callback(this); }); } ``` Question answered in [jQuery .ready in a dynamically inserted iframe](https://stackoverflow.com/questions/205087/jquery-ready-in-a-dynamically-inserted-iframe)
Have a variable in the parent: ``` var setToLoad = false; ``` Follow it up with a function to set it: ``` function SetToLoad() { setToLoad = true; } ``` Then in the child iframe call this function using the window.opener ``` function CallSetToLoad() { window.opener.SetToLoad(); } window.onload = CallSetToLoad; ``` This won't run until the iframe is finished loading, and if it's in the same domain it'll allow access to the opener. This would require editing a small portion of the 3rd party script. EDIT: Alternative solution Given that you can't edit the script, you might try something like: ``` frames["myiframe"].onload = function() { // do your stuff here } ```
2,269,542
A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM. I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly. Is there an alternative, cross-browser *evented* approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).
2010/02/15
[ "https://Stackoverflow.com/questions/2269542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253511/" ]
Have a variable in the parent: ``` var setToLoad = false; ``` Follow it up with a function to set it: ``` function SetToLoad() { setToLoad = true; } ``` Then in the child iframe call this function using the window.opener ``` function CallSetToLoad() { window.opener.SetToLoad(); } window.onload = CallSetToLoad; ``` This won't run until the iframe is finished loading, and if it's in the same domain it'll allow access to the opener. This would require editing a small portion of the 3rd party script. EDIT: Alternative solution Given that you can't edit the script, you might try something like: ``` frames["myiframe"].onload = function() { // do your stuff here } ```
Bilal, There's a document.readyState property that you can check (works in IE). ``` foo(){ if([your iframe id].document.readyState != "complete") { setTimeout("foo()", 500); //wait 500 ms then call foo } else { //iframe doc is ready } } ``` Arkady
2,269,542
A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM. I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly. Is there an alternative, cross-browser *evented* approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).
2010/02/15
[ "https://Stackoverflow.com/questions/2269542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253511/" ]
using jquery? ``` function callIframe(url, callback) { $(document.body).append('<IFRAME id="myId" ...>'); $('iframe#myId').attr('src', url); $('iframe#myId').load(function() { callback(this); }); } ``` Question answered in [jQuery .ready in a dynamically inserted iframe](https://stackoverflow.com/questions/205087/jquery-ready-in-a-dynamically-inserted-iframe)
First: You probably won't be able to manipulate its dom when it loads html from other domain And You probably are interested in DOMready. Look here: [jQuery .ready in a dynamically inserted iframe](https://stackoverflow.com/questions/205087/jquery-ready-in-a-dynamically-inserted-iframe)
2,269,542
A 3rd party script on my web page creates an iframe. I need to know when this iframe is ready, so I can manipulate its DOM. I can think of a hacky approach: repeatedly try to modify the iFrame's DOM, and return success when a change we make sticks between two attempts. For this to work, I would prefer a property I can check on the iframe repeatedly. Is there an alternative, cross-browser *evented* approach to knowing that the iframe is ready? E.g. can we redefine the onLoad function to call into our code (but I don't know if I can do this, since I didn't create the iframe).
2010/02/15
[ "https://Stackoverflow.com/questions/2269542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253511/" ]
using jquery? ``` function callIframe(url, callback) { $(document.body).append('<IFRAME id="myId" ...>'); $('iframe#myId').attr('src', url); $('iframe#myId').load(function() { callback(this); }); } ``` Question answered in [jQuery .ready in a dynamically inserted iframe](https://stackoverflow.com/questions/205087/jquery-ready-in-a-dynamically-inserted-iframe)
Bilal, There's a document.readyState property that you can check (works in IE). ``` foo(){ if([your iframe id].document.readyState != "complete") { setTimeout("foo()", 500); //wait 500 ms then call foo } else { //iframe doc is ready } } ``` Arkady
43,852,064
I am using a combination of `django-storages` and `ManifestStaticFilesStorage` to server static files and media from `S3`. ``` class StaticStorage(ManifestFilesMixin, S3BotoStorage): location = settings.STATICFILES_LOCATION ``` When I run `collectstatic` I can see the newest version of my `JS` file on S3 with the correct timestamp. I can also see that file being referenced in the `staticfiles.json` manifest. However looking at the site in the browser I am still seeing the old `JS` being pulled down, not the one in the `manifest` What could be going wrong?
2017/05/08
[ "https://Stackoverflow.com/questions/43852064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1158977/" ]
The `staticfiles.json` seems to be loaded once when the server starts up (from the S3 instance). If you run `collectstatic` while the server is running it has no way of knowing that there were changes made to S3. You need to restart the server after running `collectstatic` if changes have been made.
You can read [this post](https://devblog.kogan.com/blog/a-hidden-gem-in-django-1-7-manifeststaticfilesstorage) for more infomation. In short: > > By default staticfiles.json will reside in STATIC\_ROOT which is the > directory where all static files are collected in. We host all our > static assets on an S3 bucket which means staticfiles.json by default > would end up being synced to S3. > > > So if your `staticfiles.json` being cached, your static files will be the old ones. There are 2 ways to fix this: * Versionize `staticfiles.json` like you're already done with your static files * Keep `staticfiles.json` in local instead of S3
64,226,188
I have a fragment showing a list of items, observing from view model (from a http service, they are not persisted in database). Now, I need to delete one of those items. I have a delete result live data so the view can observe when an item has been deleted. **Fragment** ``` fun onViewCreated(view: View, savedInstanceState: Bundle?) { //... viewModel.deleteItemLiveData.observe(viewLifecycleOwner) { when (it.status) { Result.Status.ERROR -> showDeletingError() Result.Status.SUCCESS -> { itemsAdapter.remove(it.value) commentsAdapter.notifyItemRemoved(it.value) } } } } fun deleteItem(itemId: String, itemIndex: Int) = lifecycleScope.launch { viewModel.deleteItem(itemId, itemIndex) } ``` **ViewModel** ``` val deleteItemLiveData = MutableLiveData<Result<Int>>() suspend fun deleteItem(itemId: String, itemIndex: Int) = withContext(Dispatchers.IO) { val result = service.deleteItem(itemId) withContext(Dispatchers.Main) { if (result.success) { deleteItemLiveData.value = Result.success(itemIndex) } else { deleteItemLiveData.value = Result.error() } } } ``` It is working fine, but the problem comes when I navigate to another fragment and go back again. `deleteItemLIveData` is emitted again with the last `Result`, so fragment tries to remove again the item from the adapter, and it crashes. How con I solve this?
2020/10/06
[ "https://Stackoverflow.com/questions/64226188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3026283/" ]
I think you should follow the official documentation: [Vision Client Libraries](https://cloud.google.com/vision/docs/libraries#client-libraries-install-python) ``` import io import os # Imports the Google Cloud client library from google.cloud import vision # Instantiates a client client = vision.ImageAnnotatorClient() # The name of the image file to annotate file_name = os.path.abspath('resources/wakeupcat.jpg') # Loads the image into memory with io.open(file_name, 'rb') as image_file: content = image_file.read() image = vision.Image(content=content) # Performs label detection on the image file response = client.label_detection(image=image) labels = response.label_annotations print('Labels:') for label in labels: print(label.description) ``` It is used to create the image the **vision** module: ``` image = vision.Image(content=content) not image = types.Image(content=IMAGE_CONTENT) ```
This should be the answer since Google Vision changed Type and Emun methods. I also faced the issue since vision-1 and vision-2 have some differences when you need text data from pdf/img file. ``` import json import re from google.cloud import vision from google.cloud import storage # Supported mime_types are: 'application/pdf' and 'image/tiff' mime_type = 'application/pdf' # How many pages should be grouped into each json output file. batch_size = 2 client = vision.ImageAnnotatorClient() feature = vision.Feature( type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) gcs_source = vision.GcsSource(uri=gcs_source_uri) input_config = vision.InputConfig( gcs_source=gcs_source, mime_type=mime_type) gcs_destination = vision.GcsDestination(uri=gcs_destination_uri) output_config = vision.OutputConfig( gcs_destination=gcs_destination, batch_size=batch_size) async_request = vision.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config) operation = client.async_batch_annotate_files( requests=[async_request]) print('Waiting for the operation to finish.') operation.result(timeout=420) # Once the request has completed and the output has been # written to GCS, we can list all the output files. storage_client = storage.Client() match = re.match(r'gs://([^/]+)/(.+)', gcs_destination_uri) bucket_name = match.group(1) prefix = match.group(2) bucket = storage_client.get_bucket(bucket_name) # List objects with the given prefix. blob_list = list(bucket.list_blobs(prefix=prefix)) print('Output files:') for blob in blob_list: print(blob.name) # Process the first output file from GCS. # Since we specified batch_size=2, the first response contains # the first two pages of the input file. output = blob_list[0] json_string = output.download_as_string() response = json.loads(json_string) # The actual response for the first page of the input file. first_page_response = response['responses'][0] annotation = first_page_response['fullTextAnnotation'] # Here we print the full text from the first page. # The response contains more information: # annotation/pages/blocks/paragraphs/words/symbols # including confidence scores and bounding boxes print('Full text:\n') print(annotation['text']) ```
64,226,188
I have a fragment showing a list of items, observing from view model (from a http service, they are not persisted in database). Now, I need to delete one of those items. I have a delete result live data so the view can observe when an item has been deleted. **Fragment** ``` fun onViewCreated(view: View, savedInstanceState: Bundle?) { //... viewModel.deleteItemLiveData.observe(viewLifecycleOwner) { when (it.status) { Result.Status.ERROR -> showDeletingError() Result.Status.SUCCESS -> { itemsAdapter.remove(it.value) commentsAdapter.notifyItemRemoved(it.value) } } } } fun deleteItem(itemId: String, itemIndex: Int) = lifecycleScope.launch { viewModel.deleteItem(itemId, itemIndex) } ``` **ViewModel** ``` val deleteItemLiveData = MutableLiveData<Result<Int>>() suspend fun deleteItem(itemId: String, itemIndex: Int) = withContext(Dispatchers.IO) { val result = service.deleteItem(itemId) withContext(Dispatchers.Main) { if (result.success) { deleteItemLiveData.value = Result.success(itemIndex) } else { deleteItemLiveData.value = Result.error() } } } ``` It is working fine, but the problem comes when I navigate to another fragment and go back again. `deleteItemLIveData` is emitted again with the last `Result`, so fragment tries to remove again the item from the adapter, and it crashes. How con I solve this?
2020/10/06
[ "https://Stackoverflow.com/questions/64226188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3026283/" ]
I think you should follow the official documentation: [Vision Client Libraries](https://cloud.google.com/vision/docs/libraries#client-libraries-install-python) ``` import io import os # Imports the Google Cloud client library from google.cloud import vision # Instantiates a client client = vision.ImageAnnotatorClient() # The name of the image file to annotate file_name = os.path.abspath('resources/wakeupcat.jpg') # Loads the image into memory with io.open(file_name, 'rb') as image_file: content = image_file.read() image = vision.Image(content=content) # Performs label detection on the image file response = client.label_detection(image=image) labels = response.label_annotations print('Labels:') for label in labels: print(label.description) ``` It is used to create the image the **vision** module: ``` image = vision.Image(content=content) not image = types.Image(content=IMAGE_CONTENT) ```
This worked for me as of 10/24/22 ``` from google.cloud.vision_v1.types import Image ```
64,226,188
I have a fragment showing a list of items, observing from view model (from a http service, they are not persisted in database). Now, I need to delete one of those items. I have a delete result live data so the view can observe when an item has been deleted. **Fragment** ``` fun onViewCreated(view: View, savedInstanceState: Bundle?) { //... viewModel.deleteItemLiveData.observe(viewLifecycleOwner) { when (it.status) { Result.Status.ERROR -> showDeletingError() Result.Status.SUCCESS -> { itemsAdapter.remove(it.value) commentsAdapter.notifyItemRemoved(it.value) } } } } fun deleteItem(itemId: String, itemIndex: Int) = lifecycleScope.launch { viewModel.deleteItem(itemId, itemIndex) } ``` **ViewModel** ``` val deleteItemLiveData = MutableLiveData<Result<Int>>() suspend fun deleteItem(itemId: String, itemIndex: Int) = withContext(Dispatchers.IO) { val result = service.deleteItem(itemId) withContext(Dispatchers.Main) { if (result.success) { deleteItemLiveData.value = Result.success(itemIndex) } else { deleteItemLiveData.value = Result.error() } } } ``` It is working fine, but the problem comes when I navigate to another fragment and go back again. `deleteItemLIveData` is emitted again with the last `Result`, so fragment tries to remove again the item from the adapter, and it crashes. How con I solve this?
2020/10/06
[ "https://Stackoverflow.com/questions/64226188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3026283/" ]
This should be the answer since Google Vision changed Type and Emun methods. I also faced the issue since vision-1 and vision-2 have some differences when you need text data from pdf/img file. ``` import json import re from google.cloud import vision from google.cloud import storage # Supported mime_types are: 'application/pdf' and 'image/tiff' mime_type = 'application/pdf' # How many pages should be grouped into each json output file. batch_size = 2 client = vision.ImageAnnotatorClient() feature = vision.Feature( type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) gcs_source = vision.GcsSource(uri=gcs_source_uri) input_config = vision.InputConfig( gcs_source=gcs_source, mime_type=mime_type) gcs_destination = vision.GcsDestination(uri=gcs_destination_uri) output_config = vision.OutputConfig( gcs_destination=gcs_destination, batch_size=batch_size) async_request = vision.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config) operation = client.async_batch_annotate_files( requests=[async_request]) print('Waiting for the operation to finish.') operation.result(timeout=420) # Once the request has completed and the output has been # written to GCS, we can list all the output files. storage_client = storage.Client() match = re.match(r'gs://([^/]+)/(.+)', gcs_destination_uri) bucket_name = match.group(1) prefix = match.group(2) bucket = storage_client.get_bucket(bucket_name) # List objects with the given prefix. blob_list = list(bucket.list_blobs(prefix=prefix)) print('Output files:') for blob in blob_list: print(blob.name) # Process the first output file from GCS. # Since we specified batch_size=2, the first response contains # the first two pages of the input file. output = blob_list[0] json_string = output.download_as_string() response = json.loads(json_string) # The actual response for the first page of the input file. first_page_response = response['responses'][0] annotation = first_page_response['fullTextAnnotation'] # Here we print the full text from the first page. # The response contains more information: # annotation/pages/blocks/paragraphs/words/symbols # including confidence scores and bounding boxes print('Full text:\n') print(annotation['text']) ```
This worked for me as of 10/24/22 ``` from google.cloud.vision_v1.types import Image ```
17,283,208
I am trying to find all db entries that have a lat lon that fall into a certain mile range from my location. I am basing my answer off of this stackoverflow answer: > > [MySQL Great Circle Distance (Haversine formula)](https://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula) > > > Here is what I have: ``` IQueryable<myTable> busLst = (from b in db.myTable where (3959 * Math.Acos(Math.Cos(radians(latLonRequest.lat)) * Math.Cos(radians(b.lat)) * Math.Cos(radians(b.lon) - radians(latLonRequest.lon)) + Math.Sin(radians(latLonRequest.lat)) * Math.Sin(radians(b.lat)))) < latLonRequest.MaxDistance select b ); ``` I am getting the following error: ``` "errorCode": "NotSupportedException", "message": "LINQ to Entities does not recognize the method 'Double Acos(Double)' method, and this method cannot be translated into a store expression.", "stackTrace": "[GetByLatLonRequest: 6/24/2013 6:57:14 PM]:\n[REQUEST: {lat:3,lon:3,maxDistance:10,measureSystem:N}]\nSystem.NotSupportedException: LINQ to Entities does not recognize the method 'Double Acos(Double)' method, and this method cannot be translated into a store expression.\r\n at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.DefaultTranslator.Translate(ExpressionConverter parent, ```
2013/06/24
[ "https://Stackoverflow.com/questions/17283208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/605669/" ]
Off the top of my head (not extensively tested) ``` typedef unsigned long long BIG; BIG mod_multiply( BIG A, BIG B, BIG C ) { BIG mod_product = 0; A %= C; while (A) { B %= C; if (A & 1) mod_product = (mod_product + B) % C; A >>= 1; B <<= 1; } return mod_product; } ``` This has complexity `O(log A)` iterations. You can probably replace most of the `%` with a conditional subtraction, for a bit more performance. ``` typedef unsigned long long BIG; BIG mod_multiply( BIG A, BIG B, BIG C ) { BIG mod_product = 0; // A %= C; may or may not help performance B %= C; while (A) { if (A & 1) { mod_product += B; if (mod_product > C) mod_product -= C; } A >>= 1; B <<= 1; if (B > C) B -= C; } return mod_product; } ``` This version has only one long integer modulo -- it may even be faster than the large-chunk method, depending on how your processor implements integer modulo. * Live demo: <https://ideone.com/1pTldb> -- same result as Yakk's.
An implementation of [this](http://stackoverflow.com/a/14859713/256138) stack overflow answer prior: ``` #include <stdint.h> #include <tuple> #include <iostream> typedef std::tuple< uint32_t, uint32_t > split_t; split_t split( uint64_t a ) { static const uint32_t mask = -1; auto retval = std::make_tuple( mask&a, ( a >> 32 ) ); // std::cout << "(" << std::get<0>(retval) << "," << std::get<1>(retval) << ")\n"; return retval; } typedef std::tuple< uint64_t, uint64_t, uint64_t, uint64_t > cross_t; template<typename Lambda> cross_t cross( split_t lhs, split_t rhs, Lambda&& op ) { return std::make_tuple( op(std::get<0>(lhs), std::get<0>(rhs)), op(std::get<1>(lhs), std::get<0>(rhs)), op(std::get<0>(lhs), std::get<1>(rhs)), op(std::get<1>(lhs), std::get<1>(rhs)) ); } // c must have high bit unset: uint64_t a_times_2_k_mod_c( uint64_t a, unsigned k, uint64_t c ) { a %= c; for (unsigned i = 0; i < k; ++i) { a <<= 1; a %= c; } return a; } // c must have about 2 high bits unset: uint64_t a_times_b_mod_c( uint64_t a, uint64_t b, uint64_t c ) { // ensure a and b are < c: a %= c; b %= c; auto Z = cross( split(a), split(b), [](uint32_t lhs, uint32_t rhs)->uint64_t { return (uint64_t)lhs * (uint64_t)rhs; } ); uint64_t to_the_0; uint64_t to_the_32_a; uint64_t to_the_32_b; uint64_t to_the_64; std::tie( to_the_0, to_the_32_a, to_the_32_b, to_the_64 ) = Z; // std::cout << to_the_0 << "+ 2^32 *(" << to_the_32_a << "+" << to_the_32_b << ") + 2^64 * " << to_the_64 << "\n"; // this line is the one that requires 2 high bits in c to be clear // if you just add 2 of them then do a %c, then add the third and do // a %c, you can relax the requirement to "one high bit must be unset": return (to_the_0 + a_times_2_k_mod_c(to_the_32_a+to_the_32_b, 32, c) // + will not overflow! + a_times_2_k_mod_c(to_the_64, 64, c) ) %c; } int main() { uint64_t retval = a_times_b_mod_c( 19010000000000000000, 1011000000000000, 1231231231231211 ); std::cout << retval << "\n"; } ``` The idea here is to split your 64-bit integer into a pair of 32-bit integers, which are safe to multiply in 64-bit land. We express `a*b` as `(a_high * 2^32 + a_low) * (b_high * 2^32 + b_low)`, do the 4-fold multiplication (keeping track of the 232 factors without storing them in our bits), then note that doing `a * 2^k % c` can be done via a series of `k` repeats of this pattern: `((a*2 %c) *2%c)...`. So we can take this 3 to 4 element polynomial of 64-bit integers in 232 and reduce it without having to worry about things. The expensive part is the `a_times_2_k_mod_c` function (the only loop). You can make it go many times faster if you know that `c` has more than one high bit clear. You could instead replace the `a %= c` with subtraction `a -= (a>=c)*c;` Doing both isn't all that practical. [Live example](https://ideone.com/0TFtz0)
20,154,196
I'm working on a web service API for one of our customers. I've never touched this code before and the original developer is no longer with the company. ``` XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(xmlReply); XmlElement element = (XmlElement)xDoc.GetElementsByTagName('TagName')[0]; ``` What is the purpose of the `XmlElement` class name inside the parentheses?
2013/11/22
[ "https://Stackoverflow.com/questions/20154196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Make sure to **unset** the FNDELAY flag for descriptor using fcntl, otherwise VMIN/VTIME are ignored. [Serial Programming Guide for POSIX Operating Systems](http://www.cmrr.umn.edu/~strupp/serial.html#config)
I'd recommend using vmin and vtime both 0 if you're using nonblocking reads. That will give you the behavior that if data is available, then it will be returned; the fd will be ready for select, poll, etc whenever data is available. vmin and vtime are useful if you're doing blocking reads. For example if you're expecting a particular packet size then you could set vmin. If you want to make sure you get data every half second you could set vtime. Obviously vmin and vtime are only for non-canonical mode (non-line mode) My suspicion is that in nonblocking mode if you set vmin say to 5, then the fd will not be read-ready and read will return EWOULDBLOCK until 5 characters are ready. I don't know and don't have an easy test case to try, because all the serial work I've done has been either blocking or has set both to 0.
20,154,196
I'm working on a web service API for one of our customers. I've never touched this code before and the original developer is no longer with the company. ``` XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(xmlReply); XmlElement element = (XmlElement)xDoc.GetElementsByTagName('TagName')[0]; ``` What is the purpose of the `XmlElement` class name inside the parentheses?
2013/11/22
[ "https://Stackoverflow.com/questions/20154196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Andrey is right. In non-blocking mode, VMIN/VTIME have no effect (FNDELAY / O\_NDELAY seem to be linux variants of O\_NONBLOCK, the portable, POSIX flag). When using select() with a file in non-blocking mode, you get an event for every byte that arrives. At high serial data rates, this hammers the CPU. It's better to use blocking mode with VMIN, so that select() waits for a block of data before firing an event, and VTIME to limit the delay, for blocks smaller than VMIN. Sam said "If you want to make sure you get data every half second you could set vtime" (VTIME = 5). Intuitively, you may expect that to be true, but it's not. The BSD termios man page explains it better than linux (though they both work the same way). The VTIME timer is an *interbyte* timer. It starts over with each new byte arriving at the serial port. In a worst case scenario, select() can wait up to 20 seconds before firing an event. Suppose you have VMIN = 250, VTIME = 1, and serial port at 115200 bps. Also suppose you have an attached device sending single bytes slowly, at a consistent rate of 9 cps. The time between bytes is 0.11 seconds, long enough for the interbyte timer of 0.10 to expire, and select() to report a readable event for each byte. All is well. Now suppose your device increases its output rate to 11 cps. The time between bytes is 0.09 seconds. It's not long enough for the interbyte timer to expire, and with each new byte, it starts over. To get a readable event, VMIN = 250 must be satisfied. At 11 cps, that takes 22.7 seconds. It may seem that your device has stalled, but the VTIME design is the real cause of delay. I tested this with two Perl scripts, sender and receiver, a two port serial card, and a null modem cable. I proved that it works as the man page says. VTIME is an interbyte timer that's reset with the arrival of each new byte. A better design would have the timer anchored, not rolling. It would continue ticking until it expires, or VMIN is satisfied, whichever comes first. The existing design could be fixed, but there is 30 years of legacy to overcome. In practice, you may rarely encounter such a scenario. But it lurks, so beware.
I'd recommend using vmin and vtime both 0 if you're using nonblocking reads. That will give you the behavior that if data is available, then it will be returned; the fd will be ready for select, poll, etc whenever data is available. vmin and vtime are useful if you're doing blocking reads. For example if you're expecting a particular packet size then you could set vmin. If you want to make sure you get data every half second you could set vtime. Obviously vmin and vtime are only for non-canonical mode (non-line mode) My suspicion is that in nonblocking mode if you set vmin say to 5, then the fd will not be read-ready and read will return EWOULDBLOCK until 5 characters are ready. I don't know and don't have an easy test case to try, because all the serial work I've done has been either blocking or has set both to 0.
20,154,196
I'm working on a web service API for one of our customers. I've never touched this code before and the original developer is no longer with the company. ``` XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(xmlReply); XmlElement element = (XmlElement)xDoc.GetElementsByTagName('TagName')[0]; ``` What is the purpose of the `XmlElement` class name inside the parentheses?
2013/11/22
[ "https://Stackoverflow.com/questions/20154196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Andrey is right. In non-blocking mode, VMIN/VTIME have no effect (FNDELAY / O\_NDELAY seem to be linux variants of O\_NONBLOCK, the portable, POSIX flag). When using select() with a file in non-blocking mode, you get an event for every byte that arrives. At high serial data rates, this hammers the CPU. It's better to use blocking mode with VMIN, so that select() waits for a block of data before firing an event, and VTIME to limit the delay, for blocks smaller than VMIN. Sam said "If you want to make sure you get data every half second you could set vtime" (VTIME = 5). Intuitively, you may expect that to be true, but it's not. The BSD termios man page explains it better than linux (though they both work the same way). The VTIME timer is an *interbyte* timer. It starts over with each new byte arriving at the serial port. In a worst case scenario, select() can wait up to 20 seconds before firing an event. Suppose you have VMIN = 250, VTIME = 1, and serial port at 115200 bps. Also suppose you have an attached device sending single bytes slowly, at a consistent rate of 9 cps. The time between bytes is 0.11 seconds, long enough for the interbyte timer of 0.10 to expire, and select() to report a readable event for each byte. All is well. Now suppose your device increases its output rate to 11 cps. The time between bytes is 0.09 seconds. It's not long enough for the interbyte timer to expire, and with each new byte, it starts over. To get a readable event, VMIN = 250 must be satisfied. At 11 cps, that takes 22.7 seconds. It may seem that your device has stalled, but the VTIME design is the real cause of delay. I tested this with two Perl scripts, sender and receiver, a two port serial card, and a null modem cable. I proved that it works as the man page says. VTIME is an interbyte timer that's reset with the arrival of each new byte. A better design would have the timer anchored, not rolling. It would continue ticking until it expires, or VMIN is satisfied, whichever comes first. The existing design could be fixed, but there is 30 years of legacy to overcome. In practice, you may rarely encounter such a scenario. But it lurks, so beware.
Make sure to **unset** the FNDELAY flag for descriptor using fcntl, otherwise VMIN/VTIME are ignored. [Serial Programming Guide for POSIX Operating Systems](http://www.cmrr.umn.edu/~strupp/serial.html#config)
109,838
When I include absolute URLs in the top link bar (i.e. ones that start with a slash), they are treated as relative when using the bar, inherited, in subsites. Is there a way to make it treat these as *actual* absolute URLs, and not relative?
2014/07/25
[ "https://sharepoint.stackexchange.com/questions/109838", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/31630/" ]
Use "../yoururl/targetlocation", with those two dots. Edit: Or you could also use the complete URL, e.g. `http://sitecollection/subsite/`
Absolute links to subsites that don't exist are treated as relative, but those that point to existing subsites work correctly. The trouble is that this doesn't change once the missing subsite has been created, so the trick is to actually remove the link and create a new one (even though its text and URL are just the same). This seems silly, so I'm not going to mark it as the right answer yet, in case someone can point out the obvious that I'm missing! `:-)`
40,521,324
In my input method service I am trying to select the text before the current cursor position. Following is the code snippet ``` InputConnection inputConnection = getCurrentInputConnection(); ExtractedText extractedText = inputConnection.getExtractedText(new ExtractedTextRequest(), 0); inputConnection.setSelection(extractedText.selectionStart-1,extractedText.selectionEnd); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.updateSelection(null, extractedText.selectionStart-1,extractedText.selectionEnd, 0, 0); ``` This has a very flaky behaviour, sometimes it selects, sometimes it just moves the cursor one step back. Can anybody point out what is it that I am doing wrong? ADDITION: Since this question has remained unanswered for some time, I would like to pose an alternate question. I was looking around for some alternate ways of selecting text and on the hackers-Keyboard, pressing the shift and then a arrow key does the trick, but I am not able to replicate the process. I tried sending the d-pad keys down and up key-events along with meta\_shift\_on flag. But that is not working... Again, what am I doing wrong?
2016/11/10
[ "https://Stackoverflow.com/questions/40521324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2693743/" ]
I solved this problem by using the shift+arrow keys. ``` 1 --> I was requesting the "inputConnection" for each event. I have now started using just one instance of inputConnection which I request for on the hook "onBindInput" and use it for all. 2 --> Sending Meta_shift_on as a flag along with the dpad_left/right/whatever was not enough, Now I send a press down shift event, then dpad up-down, and then up shift event. following is the pseudo-code: private void moveSelection(int dpad_keyCode) { inputMethodService.sendDownKeyEvent(KeyEvent.KEYCODE_SHIFT_LEFT, 0); inputMethodService.sendDownAndUpKeyEvent(dpad_keyCode, 0); inputMethodService.sendUpKeyEvent(KeyEvent.KEYCODE_SHIFT_LEFT, 0); } ``` And that is all it took. Note: This solution is more or less a hack and I am still looking for a better solution that also allows me to switch anchor of a selection. If you know better, please share.
``` inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT)); inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_)); inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFKEYCODE_DPAD_T_LEFT)); inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT)); ```
40,521,324
In my input method service I am trying to select the text before the current cursor position. Following is the code snippet ``` InputConnection inputConnection = getCurrentInputConnection(); ExtractedText extractedText = inputConnection.getExtractedText(new ExtractedTextRequest(), 0); inputConnection.setSelection(extractedText.selectionStart-1,extractedText.selectionEnd); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.updateSelection(null, extractedText.selectionStart-1,extractedText.selectionEnd, 0, 0); ``` This has a very flaky behaviour, sometimes it selects, sometimes it just moves the cursor one step back. Can anybody point out what is it that I am doing wrong? ADDITION: Since this question has remained unanswered for some time, I would like to pose an alternate question. I was looking around for some alternate ways of selecting text and on the hackers-Keyboard, pressing the shift and then a arrow key does the trick, but I am not able to replicate the process. I tried sending the d-pad keys down and up key-events along with meta\_shift\_on flag. But that is not working... Again, what am I doing wrong?
2016/11/10
[ "https://Stackoverflow.com/questions/40521324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2693743/" ]
Best solution for selection in IME ``` private void SelectionLeft() { ExtractedText extractedText = mLatinIme.getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(), 0); if (extractedText == null || extractedText.text == null) return; int selectionStart = extractedText.selectionStart; int selectionEnd = extractedText.selectionEnd; mLatinIme.getCurrentInputConnection().setSelection(selectionStart, selectionEnd - 1); } private void SelectionRight() { ExtractedText extractedText = mLatinIme.getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(), 0); if (extractedText == null || extractedText.text == null) return; int selectionStart = extractedText.selectionStart; int selectionEnd = extractedText.selectionEnd; mLatinIme.getCurrentInputConnection().setSelection(selectionStart, selectionEnd + 1); } ```
I solved this problem by using the shift+arrow keys. ``` 1 --> I was requesting the "inputConnection" for each event. I have now started using just one instance of inputConnection which I request for on the hook "onBindInput" and use it for all. 2 --> Sending Meta_shift_on as a flag along with the dpad_left/right/whatever was not enough, Now I send a press down shift event, then dpad up-down, and then up shift event. following is the pseudo-code: private void moveSelection(int dpad_keyCode) { inputMethodService.sendDownKeyEvent(KeyEvent.KEYCODE_SHIFT_LEFT, 0); inputMethodService.sendDownAndUpKeyEvent(dpad_keyCode, 0); inputMethodService.sendUpKeyEvent(KeyEvent.KEYCODE_SHIFT_LEFT, 0); } ``` And that is all it took. Note: This solution is more or less a hack and I am still looking for a better solution that also allows me to switch anchor of a selection. If you know better, please share.
40,521,324
In my input method service I am trying to select the text before the current cursor position. Following is the code snippet ``` InputConnection inputConnection = getCurrentInputConnection(); ExtractedText extractedText = inputConnection.getExtractedText(new ExtractedTextRequest(), 0); inputConnection.setSelection(extractedText.selectionStart-1,extractedText.selectionEnd); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.updateSelection(null, extractedText.selectionStart-1,extractedText.selectionEnd, 0, 0); ``` This has a very flaky behaviour, sometimes it selects, sometimes it just moves the cursor one step back. Can anybody point out what is it that I am doing wrong? ADDITION: Since this question has remained unanswered for some time, I would like to pose an alternate question. I was looking around for some alternate ways of selecting text and on the hackers-Keyboard, pressing the shift and then a arrow key does the trick, but I am not able to replicate the process. I tried sending the d-pad keys down and up key-events along with meta\_shift\_on flag. But that is not working... Again, what am I doing wrong?
2016/11/10
[ "https://Stackoverflow.com/questions/40521324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2693743/" ]
Best solution for selection in IME ``` private void SelectionLeft() { ExtractedText extractedText = mLatinIme.getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(), 0); if (extractedText == null || extractedText.text == null) return; int selectionStart = extractedText.selectionStart; int selectionEnd = extractedText.selectionEnd; mLatinIme.getCurrentInputConnection().setSelection(selectionStart, selectionEnd - 1); } private void SelectionRight() { ExtractedText extractedText = mLatinIme.getCurrentInputConnection().getExtractedText(new ExtractedTextRequest(), 0); if (extractedText == null || extractedText.text == null) return; int selectionStart = extractedText.selectionStart; int selectionEnd = extractedText.selectionEnd; mLatinIme.getCurrentInputConnection().setSelection(selectionStart, selectionEnd + 1); } ```
``` inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT)); inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_)); inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFKEYCODE_DPAD_T_LEFT)); inputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT)); ```
60,223,840
As part of my system, I need to use Kafka and Zookeeper cluster on top of Kubernetes. I'm using Statefulset for deploying them and use headless service for Kafka's Broker to be able to talk with the Zookeeper servers. Its seems that the clusters are running - (by typing `kubectl get pods`) ``` NAME READY STATUS RESTARTS AGE kafka-statefulset-0 1/1 Running 14 5d10h kafka-statefulset-1 1/1 Running 14 5d10h kafka-statefulset-2 1/1 Running 16 5d10h kafka-statefulset-3 1/1 Running 14 5d10h kafka-statefulset-4 1/1 Running 14 5d10h zookeeper-statefulset-0 1/1 Running 5 5d10h zookeeper-statefulset-1 1/1 Running 5 5d10h zookeeper-statefulset-2 1/1 Running 5 5d10h ``` My problem is that I do not really understand how can I check if they can communicate properly. **What I have already tried -** I tried - ``` kafkacat -L -b kafka-statefulset-0.kafka headless.default.svc.cluster.local:9093 ``` and got - > > % ERROR: Failed to acquire metadata: Local: Broker transport failure > > > I tried - ``` kafkacat -b 172.17.0.10:9093 -t second_topic -P ``` and got - ``` % ERROR: Local: Host resolution failure: kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093/0: Failed to resolve 'kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093': Name or service not known % ERROR: Local: Host resolution failure: kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093/1: Failed to resolve 'kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093': Name or service not known % ERROR: Local: Host resolution failure: kafka-statefulset-3.kafka-headless.default.svc.cluster.local:9093/3: Failed to resolve 'kafka-statefulset-3.kafka-headless.default.svc.cluster.local:9093': Name or service not known % ERROR: Local: Host resolution failure: kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093/4: Failed to resolve 'kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093': Name or service not known % ERROR: Local: Host resolution failure: kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093/2: Failed to resolve 'kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093': Name or service not known ``` but when I ran - ``` kafkacat -L -b 172.17.0.10:9093 ``` I get - ``` Metadata for all topics (from broker -1: 172.17.0.10:9093/bootstrap): 5 brokers: broker 2 at kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093 broker 4 at kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093 broker 1 at kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093 broker 3 at kafka-statefulset-3.kafka-headless.default.svc.cluster.local:9093 broker 0 at kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093 4 topics: topic "second_topic" with 1 partitions: partition 0, leader 4, replicas: 4, isrs: 4 ``` As I understand right now, I have not configured the services correctly for connecting with them from outside the cluster, but I can connect to them from within the cluster. Although I can communicate with them from within the cluster, I keep getting errors I can't understand. For example (installing Kafkacat inside the pod's container and trying to talk with other Kafka's broker) - ``` > kubectl exec -it kafka-statefulset-0 bash > apt-get install kafkacat > kafkacat -b kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093 -t TOPIC -P > kafkacat -L -b kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093 ``` I got the right metadata but with error in the end - ``` etadata for all topics (from broker -1: kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093/bootstrap): 5 brokers: broker 2 at kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093 broker 4 at kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093 broker 1 at kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093 broker 3 at kafka-statefulset-3.kafka-headless.default.svc.cluster.local:9093 broker 0 at kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093 5 topics: topic "TOPIC" with 1 partitions: partition 0, leader 2, replicas: 2, isrs: 2 topic "second_topic" with 1 partitions: partition 0, leader 4, replicas: 4, isrs: 4 topic "first_topic" with 1 partitions: partition 0, leader 2, replicas: 2, isrs: 2 topic "nir_topic" with 1 partitions: partition 0, leader 0, replicas: 0, isrs: 0 topic "first" with 1 partitions: partition 0, leader 3, replicas: 3, isrs: 3 %3|1581685918.022|FAIL|rdkafka#producer-0| kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093/0: Failed to connect to broker at kafka-statefulset-0.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.022|ERROR|rdkafka#producer-0| kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093/0: Failed to connect to broker at kafka-statefulset-0.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.022|FAIL|rdkafka#producer-0| kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093/2: Failed to connect to broker at kafka-statefulset-2.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.022|ERROR|rdkafka#producer-0| kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093/2: Failed to connect to broker at kafka-statefulset-2.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.023|FAIL|rdkafka#producer-0| kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093/4: Failed to connect to broker at kafka-statefulset-4.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.023|ERROR|rdkafka#producer-0| kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093/4: Failed to connect to broker at kafka-statefulset-4.kafka-headless.default.svc.cluster.local:: Interrupted system call ``` What cloud be the problem? How can I check the communication between them and check the functionalities correctness of both of them - Kafka and Zookeeper? **Some more information about the system (I can copy all the YAML configuration if needed, but it is pretty long)**- 1. There is a Statefulset of Kafka and Statefulset of Zookeeper. 2. Kafka's Broker can talk with the zookeeper through port 2181. My configuration is - > > -override zookeeper.connect=zookeeper-statefulset-0.zookeeper-headless.default.svc.cluster.local:2181 ... > > > 3. I also built headless service for talking with each Kafka's Broker through port 9093 4. Zookeeper ports: a. 2181 - client port b. 2888 - server port c. 3888 - port for leader election 5.The services which run - ``` NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kafka-headless ClusterIP None <none> 9093/TCP 5d10h kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 5d11h zookeeper-cs ClusterIP 10.106.99.170 <none> 2181/TCP 5d11h zookeeper-headless ClusterIP None <none> 2888/TCP,3888/TCP 5d11h ``` **UPDATE - Adding Kafka and Zookeeper configuration files** kafka - ``` apiVersion: apps/v1 kind: StatefulSet metadata: spec: selector: matchLabels: app: kafka-app serviceName: kafka-headless replicas: 5 podManagementPolicy: Parallel template: metadata: labels: app: kafka-app kafkaMinReplicas: need-supervision spec: affinity: podAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 1 podAffinityTerm: labelSelector: matchExpressions: - key: "app" operator: In values: - zookeeper-app topologyKey: "kubernetes.io/hostname" terminationGracePeriodSeconds: 300 containers: - name: k8skafka imagePullPolicy: Always image: gcr.io/google_containers/kubernetes-kafka:1.0-10.2.1 resources: requests: memory: "1Gi" cpu: 500m ports: - containerPort: 9093 name: server command: - sh - -c - "exec kafka-server-start.sh /opt/kafka/config/server.properties --override broker.id=${HOSTNAME##*-} \ --override listeners=PLAINTEXT://:9093 \ --override zookeeper.connect=zookeeper-statefulset-0.zookeeper-headless.default.svc.cluster.local:2181,zookeeper-statefulset-1.zookeeper-headless.default.svc.cluster.local:2181,zookeeper-statefulset-2.zookeeper-headless.default.svc.cluster.local:2181 \ --override log.dir=/var/lib/kafka \ --override auto.create.topics.enable=true \ --override auto.leader.rebalance.enable=true \ --override background.threads=10 \ --override compression.type=producer \ --override delete.topic.enable=false \ --override leader.imbalance.check.interval.seconds=300 \ --override leader.imbalance.per.broker.percentage=10 \ --override log.flush.interval.messages=9223372036854775807 \ --override log.flush.offset.checkpoint.interval.ms=60000 \ --override log.flush.scheduler.interval.ms=9223372036854775807 \ --override log.retention.bytes=-1 \ --override log.retention.hours=168 \ --override log.roll.hours=168 \ --override log.roll.jitter.hours=0 \ --override log.segment.bytes=1073741824 \ --override log.segment.delete.delay.ms=60000 \ --override message.max.bytes=1000012 \ --override min.insync.replicas=1 \ --override num.io.threads=8 \ --override num.network.threads=3 \ --override num.recovery.threads.per.data.dir=1 \ --override num.replica.fetchers=1 \ --override offset.metadata.max.bytes=4096 \ --override offsets.commit.required.acks=-1 \ --override offsets.commit.timeout.ms=5000 \ --override offsets.load.buffer.size=5242880 \ --override offsets.retention.check.interval.ms=600000 \ --override offsets.retention.minutes=1440 \ --override offsets.topic.compression.codec=0 \ --override offsets.topic.num.partitions=50 \ --override offsets.topic.replication.factor=3 \ --override offsets.topic.segment.bytes=104857600 \ --override queued.max.requests=500 \ --override quota.consumer.default=9223372036854775807 \ --override quota.producer.default=9223372036854775807 \ --override replica.fetch.min.bytes=1 \ --override replica.fetch.wait.max.ms=500 \ --override replica.high.watermark.checkpoint.interval.ms=5000 \ --override replica.lag.time.max.ms=10000 \ --override replica.socket.receive.buffer.bytes=65536 \ --override replica.socket.timeout.ms=30000 \ --override request.timeout.ms=30000 \ --override socket.receive.buffer.bytes=102400 \ --override socket.request.max.bytes=104857600 \ --override socket.send.buffer.bytes=102400 \ --override unclean.leader.election.enable=true \ --override zookeeper.session.timeout.ms=30000 \ --override zookeeper.set.acl=false \ --override broker.id.generation.enable=true \ --override connections.max.idle.ms=600000 \ --override controlled.shutdown.enable=true \ --override controlled.shutdown.max.retries=3 \ --override controlled.shutdown.retry.backoff.ms=5000 \ --override controller.socket.timeout.ms=30000 \ --override default.replication.factor=1 \ --override fetch.purgatory.purge.interval.requests=1000 \ --override group.max.session.timeout.ms=300000 \ --override group.min.session.timeout.ms=6000 \ --override inter.broker.protocol.version=0.10.2-IV0 \ --override log.cleaner.backoff.ms=15000 \ --override log.cleaner.dedupe.buffer.size=134217728 \ --override log.cleaner.delete.retention.ms=86400000 \ --override log.cleaner.enable=true \ --override log.cleaner.io.buffer.load.factor=0.9 \ --override log.cleaner.io.buffer.size=524288 \ --override log.cleaner.io.max.bytes.per.second=1.7976931348623157E308 \ --override log.cleaner.min.cleanable.ratio=0.5 \ --override log.cleaner.min.compaction.lag.ms=0 \ --override log.cleaner.threads=1 \ --override log.cleanup.policy=delete \ --override log.index.interval.bytes=4096 \ --override log.index.size.max.bytes=10485760 \ --override log.message.timestamp.difference.max.ms=9223372036854775807 \ --override log.message.timestamp.type=CreateTime \ --override log.preallocate=false \ --override log.retention.check.interval.ms=300000 \ --override max.connections.per.ip=2147483647 \ --override num.partitions=1 \ --override producer.purgatory.purge.interval.requests=1000 \ --override replica.fetch.backoff.ms=1000 \ --override replica.fetch.max.bytes=1048576 \ --override replica.fetch.response.max.bytes=10485760 \ --override reserved.broker.max.id=1000 " env: - name: KAFKA_HEAP_OPTS value : "-Xmx512M -Xms512M" - name: KAFKA_OPTS value: "-Dlogging.level=INFO" volumeMounts: - name: datadir mountPath: /var/lib/kafka readinessProbe: exec: command: - sh - -c - "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server=localhost:9093" securityContext: fsGroup: 1000 volumeClaimTemplates: - metadata: name: datadir spec: accessModes: - ReadWriteOnce resources: requests: storage: 1Gi ``` Zookeeper - ``` apiVersion: apps/v1 kind: StatefulSet metadata: name: zookeeper-statefulset spec: selector: matchLabels: app: zookeeper-app serviceName: zookeeper-headless replicas: 5 updateStrategy: type: RollingUpdate podManagementPolicy: OrderedReady template: metadata: labels: app: zookeeper-app spec: containers: - name: kubernetes-zookeeper imagePullPolicy: Always image: "k8s.gcr.io/kubernetes-zookeeper:1.0-3.4.10" resources: requests: memory: "1Gi" cpu: "0.5" ports: # Expose by zookeeper-cs to the client - containerPort: 2181 name: client # Expose by zookeeper-headless to the other replicas of the set - containerPort: 2888 name: server - containerPort: 3888 name: leader-election command: - sh - -c - "start-zookeeper \ --servers=3 \ --data_dir=/var/lib/zookeeper/data \ --data_log_dir=/var/lib/zookeeper/data/log \ --conf_dir=/opt/zookeeper/conf \ --client_port=2181 \ --election_port=3888 \ --server_port=2888 \ --tick_time=2000 \ --init_limit=10 \ --sync_limit=5 \ --heap=512M \ --max_client_cnxns=60 \ --snap_retain_count=3 \ --purge_interval=12 \ --max_session_timeout=40000 \ --min_session_timeout=4000 \ --log_level=INFO" readinessProbe: exec: command: ["sh", "-c", "zookeeper-ready 2181"] initialDelaySeconds: 60 timeoutSeconds: 10 livenessProbe: exec: command: - sh - -c - "zookeeper-ready 2181" initialDelaySeconds: 60 timeoutSeconds: 10 volumeMounts: - name: zookeeper-volume mountPath: /var/lib/zookeeper securityContext: fsGroup: 1000 volumeClaimTemplates: - metadata: name: zookeeper-volume spec: accessModes: [ "ReadWriteOnce" ] resources: requests: storage: 1Gi ```
2020/02/14
[ "https://Stackoverflow.com/questions/60223840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10535123/" ]
`kafkacat -L -b kafka-statefulset-0.kafka headless.default.svc.cluster.local:9093` Doesn't work. There is a space in there after the first `-b` flag --- `kafkacat -b 172.17.0.10:9093 -t second_topic -P` Without the correct `advertised.listeners` that return the resolvable addresses of brokers, this won't work. --- `kafkacat -L -b 172.17.0.10:9093` This is a step in the right direction, but you're using the Docker network IP, and not a Cluster / Node Port of any of the services, still isn't portable to other machines outside your cluster. --- > > installing Kafkacat inside the pod's container and trying to talk with other Kafka's broker > > > That's a good test to make sure that replication will at least work, but doesn't solve the external client issue. --- > > I got the right metadata but with error in the end > > > That could be a sign that your healthcheck on the broker or zookeeper is failing and the pod is restarting. Notice that the error cycles from 0,2,4... > > I also built headless service for talking with each Kafka's Broker through port 9093 > > > Okay, great, but you need to set `advertised.listeners` of each broker to now accept connections on 9093. --- All in all, I think just using existing Kafka Helm charts that allow for external connectivity would be your best option.
As You mentioned in comment: > > I ran - `/ # nslookup headless.default.svc.cluster.local` and got - `Server: 10.96.0.10 Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local nslookup: can't resolve 'headless.default.svc.cluster.local` > > > Problem is related with DNS in your environment as your environment cannot resolve [headless service](https://kubernetes.io/docs/concepts/services-networking/service/#headless-services). DNS component should provide Pod's DNS names. You should receive something like: ``` / # nslookup my-kafka-headless Server: 10.122.0.10 Address 1: 10.122.0.10 kube-dns.kube-system.svc.cluster.local Name: my-kafka-headless Address 1: 10.56.0.5 my-kafka-0.my-kafka-headless.default.svc.cluster.local ``` Treat is as sort of prerequisite if you want to refer to Pod's backing the Statefulset in Kubernetes based on DNS name (in your case: headless.default.svc.cluster.local). Verify if your services have set `.sepec.clusterIP: None` or if everything is ok with `kube-dns-XXXX` pod in `kube-system` namespace. [Here](https://unofficial-kubernetes.readthedocs.io/en/latest/concepts/services-networking/dns-pod-service/) you can find some information about troubleshooting your DNS issue. Also as @cricket\_007 advised you can use helm for deploying kafka. For example helm chart from [this source](https://github.com/bitnami/charts/tree/master/bitnami/kafka) which also contains HowTo.
60,223,840
As part of my system, I need to use Kafka and Zookeeper cluster on top of Kubernetes. I'm using Statefulset for deploying them and use headless service for Kafka's Broker to be able to talk with the Zookeeper servers. Its seems that the clusters are running - (by typing `kubectl get pods`) ``` NAME READY STATUS RESTARTS AGE kafka-statefulset-0 1/1 Running 14 5d10h kafka-statefulset-1 1/1 Running 14 5d10h kafka-statefulset-2 1/1 Running 16 5d10h kafka-statefulset-3 1/1 Running 14 5d10h kafka-statefulset-4 1/1 Running 14 5d10h zookeeper-statefulset-0 1/1 Running 5 5d10h zookeeper-statefulset-1 1/1 Running 5 5d10h zookeeper-statefulset-2 1/1 Running 5 5d10h ``` My problem is that I do not really understand how can I check if they can communicate properly. **What I have already tried -** I tried - ``` kafkacat -L -b kafka-statefulset-0.kafka headless.default.svc.cluster.local:9093 ``` and got - > > % ERROR: Failed to acquire metadata: Local: Broker transport failure > > > I tried - ``` kafkacat -b 172.17.0.10:9093 -t second_topic -P ``` and got - ``` % ERROR: Local: Host resolution failure: kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093/0: Failed to resolve 'kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093': Name or service not known % ERROR: Local: Host resolution failure: kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093/1: Failed to resolve 'kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093': Name or service not known % ERROR: Local: Host resolution failure: kafka-statefulset-3.kafka-headless.default.svc.cluster.local:9093/3: Failed to resolve 'kafka-statefulset-3.kafka-headless.default.svc.cluster.local:9093': Name or service not known % ERROR: Local: Host resolution failure: kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093/4: Failed to resolve 'kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093': Name or service not known % ERROR: Local: Host resolution failure: kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093/2: Failed to resolve 'kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093': Name or service not known ``` but when I ran - ``` kafkacat -L -b 172.17.0.10:9093 ``` I get - ``` Metadata for all topics (from broker -1: 172.17.0.10:9093/bootstrap): 5 brokers: broker 2 at kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093 broker 4 at kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093 broker 1 at kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093 broker 3 at kafka-statefulset-3.kafka-headless.default.svc.cluster.local:9093 broker 0 at kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093 4 topics: topic "second_topic" with 1 partitions: partition 0, leader 4, replicas: 4, isrs: 4 ``` As I understand right now, I have not configured the services correctly for connecting with them from outside the cluster, but I can connect to them from within the cluster. Although I can communicate with them from within the cluster, I keep getting errors I can't understand. For example (installing Kafkacat inside the pod's container and trying to talk with other Kafka's broker) - ``` > kubectl exec -it kafka-statefulset-0 bash > apt-get install kafkacat > kafkacat -b kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093 -t TOPIC -P > kafkacat -L -b kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093 ``` I got the right metadata but with error in the end - ``` etadata for all topics (from broker -1: kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093/bootstrap): 5 brokers: broker 2 at kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093 broker 4 at kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093 broker 1 at kafka-statefulset-1.kafka-headless.default.svc.cluster.local:9093 broker 3 at kafka-statefulset-3.kafka-headless.default.svc.cluster.local:9093 broker 0 at kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093 5 topics: topic "TOPIC" with 1 partitions: partition 0, leader 2, replicas: 2, isrs: 2 topic "second_topic" with 1 partitions: partition 0, leader 4, replicas: 4, isrs: 4 topic "first_topic" with 1 partitions: partition 0, leader 2, replicas: 2, isrs: 2 topic "nir_topic" with 1 partitions: partition 0, leader 0, replicas: 0, isrs: 0 topic "first" with 1 partitions: partition 0, leader 3, replicas: 3, isrs: 3 %3|1581685918.022|FAIL|rdkafka#producer-0| kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093/0: Failed to connect to broker at kafka-statefulset-0.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.022|ERROR|rdkafka#producer-0| kafka-statefulset-0.kafka-headless.default.svc.cluster.local:9093/0: Failed to connect to broker at kafka-statefulset-0.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.022|FAIL|rdkafka#producer-0| kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093/2: Failed to connect to broker at kafka-statefulset-2.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.022|ERROR|rdkafka#producer-0| kafka-statefulset-2.kafka-headless.default.svc.cluster.local:9093/2: Failed to connect to broker at kafka-statefulset-2.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.023|FAIL|rdkafka#producer-0| kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093/4: Failed to connect to broker at kafka-statefulset-4.kafka-headless.default.svc.cluster.local:: Interrupted system call %3|1581685918.023|ERROR|rdkafka#producer-0| kafka-statefulset-4.kafka-headless.default.svc.cluster.local:9093/4: Failed to connect to broker at kafka-statefulset-4.kafka-headless.default.svc.cluster.local:: Interrupted system call ``` What cloud be the problem? How can I check the communication between them and check the functionalities correctness of both of them - Kafka and Zookeeper? **Some more information about the system (I can copy all the YAML configuration if needed, but it is pretty long)**- 1. There is a Statefulset of Kafka and Statefulset of Zookeeper. 2. Kafka's Broker can talk with the zookeeper through port 2181. My configuration is - > > -override zookeeper.connect=zookeeper-statefulset-0.zookeeper-headless.default.svc.cluster.local:2181 ... > > > 3. I also built headless service for talking with each Kafka's Broker through port 9093 4. Zookeeper ports: a. 2181 - client port b. 2888 - server port c. 3888 - port for leader election 5.The services which run - ``` NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kafka-headless ClusterIP None <none> 9093/TCP 5d10h kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 5d11h zookeeper-cs ClusterIP 10.106.99.170 <none> 2181/TCP 5d11h zookeeper-headless ClusterIP None <none> 2888/TCP,3888/TCP 5d11h ``` **UPDATE - Adding Kafka and Zookeeper configuration files** kafka - ``` apiVersion: apps/v1 kind: StatefulSet metadata: spec: selector: matchLabels: app: kafka-app serviceName: kafka-headless replicas: 5 podManagementPolicy: Parallel template: metadata: labels: app: kafka-app kafkaMinReplicas: need-supervision spec: affinity: podAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 1 podAffinityTerm: labelSelector: matchExpressions: - key: "app" operator: In values: - zookeeper-app topologyKey: "kubernetes.io/hostname" terminationGracePeriodSeconds: 300 containers: - name: k8skafka imagePullPolicy: Always image: gcr.io/google_containers/kubernetes-kafka:1.0-10.2.1 resources: requests: memory: "1Gi" cpu: 500m ports: - containerPort: 9093 name: server command: - sh - -c - "exec kafka-server-start.sh /opt/kafka/config/server.properties --override broker.id=${HOSTNAME##*-} \ --override listeners=PLAINTEXT://:9093 \ --override zookeeper.connect=zookeeper-statefulset-0.zookeeper-headless.default.svc.cluster.local:2181,zookeeper-statefulset-1.zookeeper-headless.default.svc.cluster.local:2181,zookeeper-statefulset-2.zookeeper-headless.default.svc.cluster.local:2181 \ --override log.dir=/var/lib/kafka \ --override auto.create.topics.enable=true \ --override auto.leader.rebalance.enable=true \ --override background.threads=10 \ --override compression.type=producer \ --override delete.topic.enable=false \ --override leader.imbalance.check.interval.seconds=300 \ --override leader.imbalance.per.broker.percentage=10 \ --override log.flush.interval.messages=9223372036854775807 \ --override log.flush.offset.checkpoint.interval.ms=60000 \ --override log.flush.scheduler.interval.ms=9223372036854775807 \ --override log.retention.bytes=-1 \ --override log.retention.hours=168 \ --override log.roll.hours=168 \ --override log.roll.jitter.hours=0 \ --override log.segment.bytes=1073741824 \ --override log.segment.delete.delay.ms=60000 \ --override message.max.bytes=1000012 \ --override min.insync.replicas=1 \ --override num.io.threads=8 \ --override num.network.threads=3 \ --override num.recovery.threads.per.data.dir=1 \ --override num.replica.fetchers=1 \ --override offset.metadata.max.bytes=4096 \ --override offsets.commit.required.acks=-1 \ --override offsets.commit.timeout.ms=5000 \ --override offsets.load.buffer.size=5242880 \ --override offsets.retention.check.interval.ms=600000 \ --override offsets.retention.minutes=1440 \ --override offsets.topic.compression.codec=0 \ --override offsets.topic.num.partitions=50 \ --override offsets.topic.replication.factor=3 \ --override offsets.topic.segment.bytes=104857600 \ --override queued.max.requests=500 \ --override quota.consumer.default=9223372036854775807 \ --override quota.producer.default=9223372036854775807 \ --override replica.fetch.min.bytes=1 \ --override replica.fetch.wait.max.ms=500 \ --override replica.high.watermark.checkpoint.interval.ms=5000 \ --override replica.lag.time.max.ms=10000 \ --override replica.socket.receive.buffer.bytes=65536 \ --override replica.socket.timeout.ms=30000 \ --override request.timeout.ms=30000 \ --override socket.receive.buffer.bytes=102400 \ --override socket.request.max.bytes=104857600 \ --override socket.send.buffer.bytes=102400 \ --override unclean.leader.election.enable=true \ --override zookeeper.session.timeout.ms=30000 \ --override zookeeper.set.acl=false \ --override broker.id.generation.enable=true \ --override connections.max.idle.ms=600000 \ --override controlled.shutdown.enable=true \ --override controlled.shutdown.max.retries=3 \ --override controlled.shutdown.retry.backoff.ms=5000 \ --override controller.socket.timeout.ms=30000 \ --override default.replication.factor=1 \ --override fetch.purgatory.purge.interval.requests=1000 \ --override group.max.session.timeout.ms=300000 \ --override group.min.session.timeout.ms=6000 \ --override inter.broker.protocol.version=0.10.2-IV0 \ --override log.cleaner.backoff.ms=15000 \ --override log.cleaner.dedupe.buffer.size=134217728 \ --override log.cleaner.delete.retention.ms=86400000 \ --override log.cleaner.enable=true \ --override log.cleaner.io.buffer.load.factor=0.9 \ --override log.cleaner.io.buffer.size=524288 \ --override log.cleaner.io.max.bytes.per.second=1.7976931348623157E308 \ --override log.cleaner.min.cleanable.ratio=0.5 \ --override log.cleaner.min.compaction.lag.ms=0 \ --override log.cleaner.threads=1 \ --override log.cleanup.policy=delete \ --override log.index.interval.bytes=4096 \ --override log.index.size.max.bytes=10485760 \ --override log.message.timestamp.difference.max.ms=9223372036854775807 \ --override log.message.timestamp.type=CreateTime \ --override log.preallocate=false \ --override log.retention.check.interval.ms=300000 \ --override max.connections.per.ip=2147483647 \ --override num.partitions=1 \ --override producer.purgatory.purge.interval.requests=1000 \ --override replica.fetch.backoff.ms=1000 \ --override replica.fetch.max.bytes=1048576 \ --override replica.fetch.response.max.bytes=10485760 \ --override reserved.broker.max.id=1000 " env: - name: KAFKA_HEAP_OPTS value : "-Xmx512M -Xms512M" - name: KAFKA_OPTS value: "-Dlogging.level=INFO" volumeMounts: - name: datadir mountPath: /var/lib/kafka readinessProbe: exec: command: - sh - -c - "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server=localhost:9093" securityContext: fsGroup: 1000 volumeClaimTemplates: - metadata: name: datadir spec: accessModes: - ReadWriteOnce resources: requests: storage: 1Gi ``` Zookeeper - ``` apiVersion: apps/v1 kind: StatefulSet metadata: name: zookeeper-statefulset spec: selector: matchLabels: app: zookeeper-app serviceName: zookeeper-headless replicas: 5 updateStrategy: type: RollingUpdate podManagementPolicy: OrderedReady template: metadata: labels: app: zookeeper-app spec: containers: - name: kubernetes-zookeeper imagePullPolicy: Always image: "k8s.gcr.io/kubernetes-zookeeper:1.0-3.4.10" resources: requests: memory: "1Gi" cpu: "0.5" ports: # Expose by zookeeper-cs to the client - containerPort: 2181 name: client # Expose by zookeeper-headless to the other replicas of the set - containerPort: 2888 name: server - containerPort: 3888 name: leader-election command: - sh - -c - "start-zookeeper \ --servers=3 \ --data_dir=/var/lib/zookeeper/data \ --data_log_dir=/var/lib/zookeeper/data/log \ --conf_dir=/opt/zookeeper/conf \ --client_port=2181 \ --election_port=3888 \ --server_port=2888 \ --tick_time=2000 \ --init_limit=10 \ --sync_limit=5 \ --heap=512M \ --max_client_cnxns=60 \ --snap_retain_count=3 \ --purge_interval=12 \ --max_session_timeout=40000 \ --min_session_timeout=4000 \ --log_level=INFO" readinessProbe: exec: command: ["sh", "-c", "zookeeper-ready 2181"] initialDelaySeconds: 60 timeoutSeconds: 10 livenessProbe: exec: command: - sh - -c - "zookeeper-ready 2181" initialDelaySeconds: 60 timeoutSeconds: 10 volumeMounts: - name: zookeeper-volume mountPath: /var/lib/zookeeper securityContext: fsGroup: 1000 volumeClaimTemplates: - metadata: name: zookeeper-volume spec: accessModes: [ "ReadWriteOnce" ] resources: requests: storage: 1Gi ```
2020/02/14
[ "https://Stackoverflow.com/questions/60223840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10535123/" ]
`kafkacat -L -b kafka-statefulset-0.kafka headless.default.svc.cluster.local:9093` Doesn't work. There is a space in there after the first `-b` flag --- `kafkacat -b 172.17.0.10:9093 -t second_topic -P` Without the correct `advertised.listeners` that return the resolvable addresses of brokers, this won't work. --- `kafkacat -L -b 172.17.0.10:9093` This is a step in the right direction, but you're using the Docker network IP, and not a Cluster / Node Port of any of the services, still isn't portable to other machines outside your cluster. --- > > installing Kafkacat inside the pod's container and trying to talk with other Kafka's broker > > > That's a good test to make sure that replication will at least work, but doesn't solve the external client issue. --- > > I got the right metadata but with error in the end > > > That could be a sign that your healthcheck on the broker or zookeeper is failing and the pod is restarting. Notice that the error cycles from 0,2,4... > > I also built headless service for talking with each Kafka's Broker through port 9093 > > > Okay, great, but you need to set `advertised.listeners` of each broker to now accept connections on 9093. --- All in all, I think just using existing Kafka Helm charts that allow for external connectivity would be your best option.
I had a similar issue and I fixed it by adding the following changes in the client OS `hostfile`. (in mac it's in `private/etc/host` with root access. Then you should `sudo dscacheutil -flushcache`) ``` 127.0.0.1 my-cluster-kafka-0.my-cluster-kafka-brokers.kafka.svc localhost my-cluster-kafka-0.my-cluster-kafka-brokers.kafka.svc ``` Kafkacat is already telling you what's the resolved address looks like its: ``` kafka-statefulset-0.kafka-headless.default.svc.cluster.local ``` you can also add any IP that resolves the domain(if it's routed to the domain)
16,667,659
I've been working on a rather large program, and thought it was time to split up my classes. 1 .java file for the GUI code, and 1 .java file for the mechanics behind the functions the GUI presents. But here's my issue, I've created an instance of each class inside each other, and the program then refuses to launch, so I'm clearly doing something wrong. In my `RPG` class I have the following line of code: ``` public Mechanics mechanics = new Mechanics(); ``` And for my `Mechanics` class, I have this code: ``` public RPG rpg = new RPG(); ``` The reason why I'm doing this WAS to try this: A lot of my variables are in the `RPG` class, and I want to be able to call them from my `rpg` and manipulate them, then send them back to `RPG` Here is the code I used to test this function (from my `Mechanics` class): ``` class Mechanics{ public RPG rpg = new RPG(); public Mechanics(){ } public void helloWorld(){ System.out.println("Hello World!"); System.out.println("Health before:"+rpg.Health); rpg.Health = rpg.Health - 5; System.out.println("Health after:"+rpg.Health); } } ``` Yes, `Health` is a public `int` in my `RPG` class. And in my `RPG` class, this is the code I am using to test my `Mechanics` class: ``` mechanics.helloWorld(); ``` Here's my problem: The code compiles, but then when I try to run it, I get this error: ``` at Mechanics.<init>(Mechanics.java:15) at RPG.<init>(RPG.java:127) ``` ![enter image description here](https://i.stack.imgur.com/IIOJy.png) Here's my question. Am I even doing this right? Whats wrong with my code that's making my program not want to run? **ADDED:** I have tried called my other classes as a `private` as well, and the program will compile, and still refuses to launch, and feeds me the same error Line 15 of `Mechanics`: ``` public RPG rpg = new RPG(); ``` line 127 of `RPG`: ``` public Mechanics mechanics = new Mechanics(); ```
2013/05/21
[ "https://Stackoverflow.com/questions/16667659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2388169/" ]
It's because you instantiating a new `Mechanics` class inside of the `RPG` class. Then instantiating a new `RPG` class inside the `Mechanics` class. The result is an infinite loop of instantiation. For your specific example, I personally think the best way to fix the issue would be to pass the RPG instance directly into the hello world method. ``` class Mechanics { public void helloWorld(RPG rpg) { ... } } ``` And then in your RPG class would look something like: ``` class RPG { // passing a mechanics object in via the constructor would be better than hard-coding it here public Mechanics mechanics = new Mechanics(); public int Health = 100; ... public void someMethod() { mechanics.helloWorld(this); // pass in the rpg instance } } ```
You are producing an infinite loop when initializing an instance of either RPG or Mechanics. Object-oriented programming means seperation of concerns and low coupling. Change your class dependencies so that only one of them needs the other.
16,667,659
I've been working on a rather large program, and thought it was time to split up my classes. 1 .java file for the GUI code, and 1 .java file for the mechanics behind the functions the GUI presents. But here's my issue, I've created an instance of each class inside each other, and the program then refuses to launch, so I'm clearly doing something wrong. In my `RPG` class I have the following line of code: ``` public Mechanics mechanics = new Mechanics(); ``` And for my `Mechanics` class, I have this code: ``` public RPG rpg = new RPG(); ``` The reason why I'm doing this WAS to try this: A lot of my variables are in the `RPG` class, and I want to be able to call them from my `rpg` and manipulate them, then send them back to `RPG` Here is the code I used to test this function (from my `Mechanics` class): ``` class Mechanics{ public RPG rpg = new RPG(); public Mechanics(){ } public void helloWorld(){ System.out.println("Hello World!"); System.out.println("Health before:"+rpg.Health); rpg.Health = rpg.Health - 5; System.out.println("Health after:"+rpg.Health); } } ``` Yes, `Health` is a public `int` in my `RPG` class. And in my `RPG` class, this is the code I am using to test my `Mechanics` class: ``` mechanics.helloWorld(); ``` Here's my problem: The code compiles, but then when I try to run it, I get this error: ``` at Mechanics.<init>(Mechanics.java:15) at RPG.<init>(RPG.java:127) ``` ![enter image description here](https://i.stack.imgur.com/IIOJy.png) Here's my question. Am I even doing this right? Whats wrong with my code that's making my program not want to run? **ADDED:** I have tried called my other classes as a `private` as well, and the program will compile, and still refuses to launch, and feeds me the same error Line 15 of `Mechanics`: ``` public RPG rpg = new RPG(); ``` line 127 of `RPG`: ``` public Mechanics mechanics = new Mechanics(); ```
2013/05/21
[ "https://Stackoverflow.com/questions/16667659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2388169/" ]
It's because you instantiating a new `Mechanics` class inside of the `RPG` class. Then instantiating a new `RPG` class inside the `Mechanics` class. The result is an infinite loop of instantiation. For your specific example, I personally think the best way to fix the issue would be to pass the RPG instance directly into the hello world method. ``` class Mechanics { public void helloWorld(RPG rpg) { ... } } ``` And then in your RPG class would look something like: ``` class RPG { // passing a mechanics object in via the constructor would be better than hard-coding it here public Mechanics mechanics = new Mechanics(); public int Health = 100; ... public void someMethod() { mechanics.helloWorld(this); // pass in the rpg instance } } ```
"I've created an instance of each class inside each other" This is your problem, the net results is this: Class A is constructed, it has a class B within it, it creates a new Class B Class B is constructed, it has a class A within it, it creates a new Class A Class A is constructed, it has a class B within it, it creates a new Class B Class B is constructed, it has a class A within it, it creates a new Class A Class A is constructed, it has a class B within it, it creates a new Class B Class B is constructed, it has a class A within it, it creates a new Class A etc etc forever, getting deeper and deeper until your program crashes. Theres nothing (horribly) wrong with `class A` having a *reference* to `class B` and `class B` having a *reference* to `class A` (although it may not be ideal), but there is something horribly wrong with `class A` encapsulating `class B` and `class B` encapsulating `class A`. In the case that both have references to each other then a reference to one or both would be passed into one or both's constructor, thereby not using the `new` keyword (avoid even this if possible though). An example of this I often (guiltily) use is the following: ``` public class OwnerClass { SubordinateClass subOrdinate; public OwnerClass(){ subOrdinate=new SubordinateClass(this); } } public class SubordinateClass { OwnerClass owner; public SubordinateClass(OwnerClass owner){ this.owner=owner; } } ``` Disclaimer: I'm not presenting this as good practice, *but* assuming that class A must talk to class B and vice versa then this achieves that
16,667,659
I've been working on a rather large program, and thought it was time to split up my classes. 1 .java file for the GUI code, and 1 .java file for the mechanics behind the functions the GUI presents. But here's my issue, I've created an instance of each class inside each other, and the program then refuses to launch, so I'm clearly doing something wrong. In my `RPG` class I have the following line of code: ``` public Mechanics mechanics = new Mechanics(); ``` And for my `Mechanics` class, I have this code: ``` public RPG rpg = new RPG(); ``` The reason why I'm doing this WAS to try this: A lot of my variables are in the `RPG` class, and I want to be able to call them from my `rpg` and manipulate them, then send them back to `RPG` Here is the code I used to test this function (from my `Mechanics` class): ``` class Mechanics{ public RPG rpg = new RPG(); public Mechanics(){ } public void helloWorld(){ System.out.println("Hello World!"); System.out.println("Health before:"+rpg.Health); rpg.Health = rpg.Health - 5; System.out.println("Health after:"+rpg.Health); } } ``` Yes, `Health` is a public `int` in my `RPG` class. And in my `RPG` class, this is the code I am using to test my `Mechanics` class: ``` mechanics.helloWorld(); ``` Here's my problem: The code compiles, but then when I try to run it, I get this error: ``` at Mechanics.<init>(Mechanics.java:15) at RPG.<init>(RPG.java:127) ``` ![enter image description here](https://i.stack.imgur.com/IIOJy.png) Here's my question. Am I even doing this right? Whats wrong with my code that's making my program not want to run? **ADDED:** I have tried called my other classes as a `private` as well, and the program will compile, and still refuses to launch, and feeds me the same error Line 15 of `Mechanics`: ``` public RPG rpg = new RPG(); ``` line 127 of `RPG`: ``` public Mechanics mechanics = new Mechanics(); ```
2013/05/21
[ "https://Stackoverflow.com/questions/16667659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2388169/" ]
You are producing an infinite loop when initializing an instance of either RPG or Mechanics. Object-oriented programming means seperation of concerns and low coupling. Change your class dependencies so that only one of them needs the other.
"I've created an instance of each class inside each other" This is your problem, the net results is this: Class A is constructed, it has a class B within it, it creates a new Class B Class B is constructed, it has a class A within it, it creates a new Class A Class A is constructed, it has a class B within it, it creates a new Class B Class B is constructed, it has a class A within it, it creates a new Class A Class A is constructed, it has a class B within it, it creates a new Class B Class B is constructed, it has a class A within it, it creates a new Class A etc etc forever, getting deeper and deeper until your program crashes. Theres nothing (horribly) wrong with `class A` having a *reference* to `class B` and `class B` having a *reference* to `class A` (although it may not be ideal), but there is something horribly wrong with `class A` encapsulating `class B` and `class B` encapsulating `class A`. In the case that both have references to each other then a reference to one or both would be passed into one or both's constructor, thereby not using the `new` keyword (avoid even this if possible though). An example of this I often (guiltily) use is the following: ``` public class OwnerClass { SubordinateClass subOrdinate; public OwnerClass(){ subOrdinate=new SubordinateClass(this); } } public class SubordinateClass { OwnerClass owner; public SubordinateClass(OwnerClass owner){ this.owner=owner; } } ``` Disclaimer: I'm not presenting this as good practice, *but* assuming that class A must talk to class B and vice versa then this achieves that
16,667,659
I've been working on a rather large program, and thought it was time to split up my classes. 1 .java file for the GUI code, and 1 .java file for the mechanics behind the functions the GUI presents. But here's my issue, I've created an instance of each class inside each other, and the program then refuses to launch, so I'm clearly doing something wrong. In my `RPG` class I have the following line of code: ``` public Mechanics mechanics = new Mechanics(); ``` And for my `Mechanics` class, I have this code: ``` public RPG rpg = new RPG(); ``` The reason why I'm doing this WAS to try this: A lot of my variables are in the `RPG` class, and I want to be able to call them from my `rpg` and manipulate them, then send them back to `RPG` Here is the code I used to test this function (from my `Mechanics` class): ``` class Mechanics{ public RPG rpg = new RPG(); public Mechanics(){ } public void helloWorld(){ System.out.println("Hello World!"); System.out.println("Health before:"+rpg.Health); rpg.Health = rpg.Health - 5; System.out.println("Health after:"+rpg.Health); } } ``` Yes, `Health` is a public `int` in my `RPG` class. And in my `RPG` class, this is the code I am using to test my `Mechanics` class: ``` mechanics.helloWorld(); ``` Here's my problem: The code compiles, but then when I try to run it, I get this error: ``` at Mechanics.<init>(Mechanics.java:15) at RPG.<init>(RPG.java:127) ``` ![enter image description here](https://i.stack.imgur.com/IIOJy.png) Here's my question. Am I even doing this right? Whats wrong with my code that's making my program not want to run? **ADDED:** I have tried called my other classes as a `private` as well, and the program will compile, and still refuses to launch, and feeds me the same error Line 15 of `Mechanics`: ``` public RPG rpg = new RPG(); ``` line 127 of `RPG`: ``` public Mechanics mechanics = new Mechanics(); ```
2013/05/21
[ "https://Stackoverflow.com/questions/16667659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2388169/" ]
Line 15 of `Mechanics` might be more like: ``` public RPG rpg = new RPG(this); // must be in constructor or non static method ``` In RPG: ``` public Mechanics mechanics; ``` in the constructor: ``` this.mechanics = mechanics; ```
You are producing an infinite loop when initializing an instance of either RPG or Mechanics. Object-oriented programming means seperation of concerns and low coupling. Change your class dependencies so that only one of them needs the other.
16,667,659
I've been working on a rather large program, and thought it was time to split up my classes. 1 .java file for the GUI code, and 1 .java file for the mechanics behind the functions the GUI presents. But here's my issue, I've created an instance of each class inside each other, and the program then refuses to launch, so I'm clearly doing something wrong. In my `RPG` class I have the following line of code: ``` public Mechanics mechanics = new Mechanics(); ``` And for my `Mechanics` class, I have this code: ``` public RPG rpg = new RPG(); ``` The reason why I'm doing this WAS to try this: A lot of my variables are in the `RPG` class, and I want to be able to call them from my `rpg` and manipulate them, then send them back to `RPG` Here is the code I used to test this function (from my `Mechanics` class): ``` class Mechanics{ public RPG rpg = new RPG(); public Mechanics(){ } public void helloWorld(){ System.out.println("Hello World!"); System.out.println("Health before:"+rpg.Health); rpg.Health = rpg.Health - 5; System.out.println("Health after:"+rpg.Health); } } ``` Yes, `Health` is a public `int` in my `RPG` class. And in my `RPG` class, this is the code I am using to test my `Mechanics` class: ``` mechanics.helloWorld(); ``` Here's my problem: The code compiles, but then when I try to run it, I get this error: ``` at Mechanics.<init>(Mechanics.java:15) at RPG.<init>(RPG.java:127) ``` ![enter image description here](https://i.stack.imgur.com/IIOJy.png) Here's my question. Am I even doing this right? Whats wrong with my code that's making my program not want to run? **ADDED:** I have tried called my other classes as a `private` as well, and the program will compile, and still refuses to launch, and feeds me the same error Line 15 of `Mechanics`: ``` public RPG rpg = new RPG(); ``` line 127 of `RPG`: ``` public Mechanics mechanics = new Mechanics(); ```
2013/05/21
[ "https://Stackoverflow.com/questions/16667659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2388169/" ]
Line 15 of `Mechanics` might be more like: ``` public RPG rpg = new RPG(this); // must be in constructor or non static method ``` In RPG: ``` public Mechanics mechanics; ``` in the constructor: ``` this.mechanics = mechanics; ```
"I've created an instance of each class inside each other" This is your problem, the net results is this: Class A is constructed, it has a class B within it, it creates a new Class B Class B is constructed, it has a class A within it, it creates a new Class A Class A is constructed, it has a class B within it, it creates a new Class B Class B is constructed, it has a class A within it, it creates a new Class A Class A is constructed, it has a class B within it, it creates a new Class B Class B is constructed, it has a class A within it, it creates a new Class A etc etc forever, getting deeper and deeper until your program crashes. Theres nothing (horribly) wrong with `class A` having a *reference* to `class B` and `class B` having a *reference* to `class A` (although it may not be ideal), but there is something horribly wrong with `class A` encapsulating `class B` and `class B` encapsulating `class A`. In the case that both have references to each other then a reference to one or both would be passed into one or both's constructor, thereby not using the `new` keyword (avoid even this if possible though). An example of this I often (guiltily) use is the following: ``` public class OwnerClass { SubordinateClass subOrdinate; public OwnerClass(){ subOrdinate=new SubordinateClass(this); } } public class SubordinateClass { OwnerClass owner; public SubordinateClass(OwnerClass owner){ this.owner=owner; } } ``` Disclaimer: I'm not presenting this as good practice, *but* assuming that class A must talk to class B and vice versa then this achieves that
68,905,094
I have figured out how to query a database using js/ajax for a single drop-down [How to query database using dropdown value in WHERE clause](https://stackoverflow.com/questions/68880651/how-to-query-database-using-dropdown-value-in-where-clause) I now want to add in many more identical drop-downs and have the same info called when an option is selected (I have already prevented duplicate selection) The idea being that many choices are made which I will eventually write to a database. Do I have to repeat the code 10 times or can I change the code to call the same query with whichever drop-down is chosen? My solution uses Id, think i may need to use classes, which i tried but couldn't get the single drop-down result with what i tried. Code below show the single drop-down solution. **selectplayer.php** ``` <!--player1--> <tr> <td style="width:50%;"> <select name="player1" class="player"> <option disabled selected value></option> <?php $sql = "SELECT * FROM players ORDER BY value DESC"; $result = mysqli_query($conn, $sql); $resultCheck = mysqli_num_rows($result); if ($resultCheck > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>"; } } ?> </select> </td> <td style="width:50%;" class="value"> </td> </tr> <!--player2--> <tr> <td style="width:50%;"> <select name="player2" class="player"> <option disabled selected value></option> <?php $sql = "SELECT * FROM players ORDER BY value DESC"; $result = mysqli_query($conn, $sql); $resultCheck = mysqli_num_rows($result); if ($resultCheck > 0) { while ($row = mysqli_fetch_assoc($result)) { echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>"; } } ?> </select> </td> <td style="width:50%;" class="value"> </td> </tr> ``` **js/ajax.js** ``` $("select").on("change"), function() { var dropdown = this; var id = dropdown.value; $.ajax({ url:"../showvalue.php", method: "POST", data: { id: id }, success:function(data) { $(this).closest("td").next().html(data); // or remove the class if it's always the next td and // $(this).closest("td").next().html(data); // $(this).closest("tr").find("td.value").html(data); } }); } ``` **showvalue.php** ``` <?php ...db connection... $pl = $_POST['id']; $pl = trim($pl); $sql = "SELECT value FROM players WHERE playername='{$pl}'"; $result = mysqli_query($conn, $sql); while($rows = mysqli_fetch_array($result)){ echo $rows['value']; } ?> ```
2021/08/24
[ "https://Stackoverflow.com/questions/68905094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15945113/" ]
This is trivial with `std::regex_iterator`: ``` string command = "hello world=\"i love coding\" abc=123 end"; std::regex words_regex(R"([^ ="]+|"[^"]+"|=)"); for (auto it = std::sregex_iterator(command.begin(), command.end(), words_regex); it != std::sregex_iterator(); it++) { std::string token = (*it).str(); if (token == "end") { break; } if (token[0] == '"') token = token.substr(1, token.length()-2); cout << "Token: " << token << endl; } ``` Output: ``` Token: hello Token: world Token: = Token: i love coding Token: abc Token: = Token: 123 ```
Even more simple is: ``` #include <iostream> #include <string> #include <regex> #include <vector> #include <algorithm> #include <iterator> const std::string com = "hello world=\"i love coding\" abc=123 end"; const std::regex re(R"(\"(.*?)\"|(\w+)|([=]))"); int main() { // Here we will store the results of the splitting std::vector<std::string> result{}; // Split std::transform(std::sregex_token_iterator(com.begin(), com.end(), re), {}, std::back_inserter(result), [](std::string s) { return std::regex_replace(s, std::regex("\""), ""); }); // Output std::copy(result.begin(), result.end(), std::ostream_iterator<std::string>(std::cout, "\n")); return 0; } ``` A typical one statement with Lambda approach ...
28,380,157
I can only think an iterative version for the problem statement below. It works, but is very slow. It's an example of flattening data. For every row in my data frame, I compute this - I have a few values stored in 'agevalues'. There is also an equivalent column for each of these age values, such that, if the value is 50, the equivalent column name is age\_50. I check if any of the columns from 'age1' to 'age3' contain values in 'agevalues'. If yes, as in, if the value 50 is present, I set age\_250 to 1 for this row. Please see my solution below ``` age1=c(20,30,30) age2=c(10,20,45) age3=c(50,60,70) df = data.frame(age1,age2,age3) #finding unique values of age1...age3 columns agevalues = NULL for(i in which(names(df) == "age1"):which(names(df) == "age3")) { agevalues = c(agevalues, unique(df[,i])) } uniqueagevalues = unique(agevalues) #creating a column for each of these age buckets count = 0; for(i in 1:length(uniqueagevalues)) { newcol = paste("age_",as.character(uniqueagevalues[i]),sep=""); print(newcol) df[newcol] = 0 count = count + 1; } #putting 1 if present, else 0 count = 0; for(i in 1:nrow(df)) { for(j in 1:length(uniqueagevalues)) { if(length(which(df[i,which(names(df) == "age1"):which(names(df) == "age3")] == uniqueagevalues[j]))) { coltoaddone = paste("age_",as.character(uniqueagevalues[j]),sep=""); print(coltoaddone) df[i,coltoaddone] = 1; } count = count + 1; } } ``` Input ``` > df age1 age2 age3 1 20 10 50 2 30 20 60 3 30 45 70 ``` Output ``` > df age1 age2 age3 age_20 age_30 age_10 age_45 age_50 age_60 age_70 1 20 10 50 1 0 1 0 1 0 0 2 30 20 60 1 1 0 0 0 1 0 3 30 45 70 0 1 0 1 0 0 1 ```
2015/02/07
[ "https://Stackoverflow.com/questions/28380157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3969791/" ]
Here's an alternative implementation using just one `sapply` loop and some vectorization before and after: ``` # get the unique age values: agevalues <- unique(unname(unlist(df))) # check which agevalues are present in which row: m <- sapply(agevalues, function(x) as.integer(rowSums(df == x) > 0L)) # add the result to the original data and set column names: df <- setNames(cbind(df, m), c(names(df), paste0("age_", agevalues))) df # age1 age2 age3 age_20 age_30 age_10 age_45 age_50 age_60 age_70 #1 20 10 50 1 0 1 0 1 0 0 #2 30 20 60 1 1 0 0 0 1 0 #3 30 45 70 0 1 0 1 0 0 1 ``` ### data: ``` age1=c(20,30,30) age2=c(10,20,45) age3=c(50,60,70) df = data.frame(age1,age2,age3) ``` Edit note: adjusted for cases of multiple matches per row to only return 1 (not the number of matches) --- Edit after comment: The conversion to matrix is done by `sapply` because it uses its default `simplify = TRUE` setting. To understand what happens, look at it step by step: * `sapply(agevalues, ... )` is a loop that feeds one element of agevalues per loop, i.e. it starts at the first element which is 20 in this case. What happens next is: ``` df == 20 # (because x == 20 in the first loop) # age1 age2 age3 #[1,] TRUE FALSE FALSE # 1 TRUE in this row #[2,] FALSE TRUE FALSE # 1 TRUE in this row #[3,] FALSE FALSE FALSE # 0 TRUE in this row ``` At this stage you already have a matrix indicating where the condition is TRUE. Then, you wrap this in `rowSums` and what happens is: ``` rowSums(df == 20) #[1] 1 1 0 ``` It tells you how many matches there were per row. Note that, if there were 2 or more matches in a row, `rowSums` would return a value >1 for that row. Because you only want 0 or 1 entries returned, you can check on the `rowSums` whether the elements are 0 (no matches) or >0 (any number of matches greater than or equal to 1): ``` rowSums(df == agevalues[1]) > 0L #[1] TRUE TRUE FALSE ``` As you see, this returns a logical vector with TRUE/FALSE entries. Since you want 0/1 in your final output, you can convert the logicals to integers using: ``` as.integer(rowSums(df == agevalues[1]) > 0L) # [1] 1 1 0 ``` These are the values you see in the sapply output. And since you do it for each element in agevalues, sapply is able to simplify the result from a list to a matrix like this: ``` sapply(agevalues, function(x) as.integer(rowSums(df == x) > 0L)) # [,1] [,2] [,3] [,4] [,5] [,6] [,7] #[1,] 1 0 1 0 1 0 0 #[2,] 1 1 0 0 0 1 0 #[3,] 0 1 0 1 0 0 1 ``` Note that, if you specified `simplify = FALSE` in the `sapply`, you would get a list in return: ``` sapply(agevalues, function(x) as.integer(rowSums(df == x) > 0L), simplify = FALSE) [[1]] [1] 1 1 0 [[2]] [1] 0 1 1 [[3]] [1] 1 0 0 [[4]] [1] 0 0 1 [[5]] [1] 1 0 0 [[6]] [1] 0 1 0 [[7]] [1] 0 0 1 ``` Hope that helps.
Try: ``` labels = paste("age",unique(unlist(df)), sep='_') lst = lapply(data.frame(t(df)), function(u) as.integer(labels %in% paste("age",u,sep='_'))) setNames(cbind(df,do.call(rbind, lst)),c(names(df),labels)) # age1 age2 age3 age_20 age_30 age_10 age_45 age_50 age_60 age_70 #X1 20 10 50 1 0 1 0 1 0 0 #X2 30 20 60 1 1 0 0 0 1 0 #X3 30 45 70 0 1 0 1 0 0 1 ```
28,380,157
I can only think an iterative version for the problem statement below. It works, but is very slow. It's an example of flattening data. For every row in my data frame, I compute this - I have a few values stored in 'agevalues'. There is also an equivalent column for each of these age values, such that, if the value is 50, the equivalent column name is age\_50. I check if any of the columns from 'age1' to 'age3' contain values in 'agevalues'. If yes, as in, if the value 50 is present, I set age\_250 to 1 for this row. Please see my solution below ``` age1=c(20,30,30) age2=c(10,20,45) age3=c(50,60,70) df = data.frame(age1,age2,age3) #finding unique values of age1...age3 columns agevalues = NULL for(i in which(names(df) == "age1"):which(names(df) == "age3")) { agevalues = c(agevalues, unique(df[,i])) } uniqueagevalues = unique(agevalues) #creating a column for each of these age buckets count = 0; for(i in 1:length(uniqueagevalues)) { newcol = paste("age_",as.character(uniqueagevalues[i]),sep=""); print(newcol) df[newcol] = 0 count = count + 1; } #putting 1 if present, else 0 count = 0; for(i in 1:nrow(df)) { for(j in 1:length(uniqueagevalues)) { if(length(which(df[i,which(names(df) == "age1"):which(names(df) == "age3")] == uniqueagevalues[j]))) { coltoaddone = paste("age_",as.character(uniqueagevalues[j]),sep=""); print(coltoaddone) df[i,coltoaddone] = 1; } count = count + 1; } } ``` Input ``` > df age1 age2 age3 1 20 10 50 2 30 20 60 3 30 45 70 ``` Output ``` > df age1 age2 age3 age_20 age_30 age_10 age_45 age_50 age_60 age_70 1 20 10 50 1 0 1 0 1 0 0 2 30 20 60 1 1 0 0 0 1 0 3 30 45 70 0 1 0 1 0 0 1 ```
2015/02/07
[ "https://Stackoverflow.com/questions/28380157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3969791/" ]
Here's an alternative implementation using just one `sapply` loop and some vectorization before and after: ``` # get the unique age values: agevalues <- unique(unname(unlist(df))) # check which agevalues are present in which row: m <- sapply(agevalues, function(x) as.integer(rowSums(df == x) > 0L)) # add the result to the original data and set column names: df <- setNames(cbind(df, m), c(names(df), paste0("age_", agevalues))) df # age1 age2 age3 age_20 age_30 age_10 age_45 age_50 age_60 age_70 #1 20 10 50 1 0 1 0 1 0 0 #2 30 20 60 1 1 0 0 0 1 0 #3 30 45 70 0 1 0 1 0 0 1 ``` ### data: ``` age1=c(20,30,30) age2=c(10,20,45) age3=c(50,60,70) df = data.frame(age1,age2,age3) ``` Edit note: adjusted for cases of multiple matches per row to only return 1 (not the number of matches) --- Edit after comment: The conversion to matrix is done by `sapply` because it uses its default `simplify = TRUE` setting. To understand what happens, look at it step by step: * `sapply(agevalues, ... )` is a loop that feeds one element of agevalues per loop, i.e. it starts at the first element which is 20 in this case. What happens next is: ``` df == 20 # (because x == 20 in the first loop) # age1 age2 age3 #[1,] TRUE FALSE FALSE # 1 TRUE in this row #[2,] FALSE TRUE FALSE # 1 TRUE in this row #[3,] FALSE FALSE FALSE # 0 TRUE in this row ``` At this stage you already have a matrix indicating where the condition is TRUE. Then, you wrap this in `rowSums` and what happens is: ``` rowSums(df == 20) #[1] 1 1 0 ``` It tells you how many matches there were per row. Note that, if there were 2 or more matches in a row, `rowSums` would return a value >1 for that row. Because you only want 0 or 1 entries returned, you can check on the `rowSums` whether the elements are 0 (no matches) or >0 (any number of matches greater than or equal to 1): ``` rowSums(df == agevalues[1]) > 0L #[1] TRUE TRUE FALSE ``` As you see, this returns a logical vector with TRUE/FALSE entries. Since you want 0/1 in your final output, you can convert the logicals to integers using: ``` as.integer(rowSums(df == agevalues[1]) > 0L) # [1] 1 1 0 ``` These are the values you see in the sapply output. And since you do it for each element in agevalues, sapply is able to simplify the result from a list to a matrix like this: ``` sapply(agevalues, function(x) as.integer(rowSums(df == x) > 0L)) # [,1] [,2] [,3] [,4] [,5] [,6] [,7] #[1,] 1 0 1 0 1 0 0 #[2,] 1 1 0 0 0 1 0 #[3,] 0 1 0 1 0 0 1 ``` Note that, if you specified `simplify = FALSE` in the `sapply`, you would get a list in return: ``` sapply(agevalues, function(x) as.integer(rowSums(df == x) > 0L), simplify = FALSE) [[1]] [1] 1 1 0 [[2]] [1] 0 1 1 [[3]] [1] 1 0 0 [[4]] [1] 0 0 1 [[5]] [1] 1 0 0 [[6]] [1] 0 1 0 [[7]] [1] 0 0 1 ``` Hope that helps.
You could try `mtabulate` from **qdapTools** ``` library(qdapTools) df1 <- mtabulate(as.data.frame(t(df))) names(df1) <- paste('age', names(df1), sep="_") cbind(df, df1) # age1 age2 age3 age_10 age_20 age_30 age_45 age_50 age_60 age_70 #1 20 10 50 1 1 0 0 1 0 0 #2 30 20 60 0 1 1 0 0 1 0 #3 30 45 70 0 0 1 1 0 0 1 ``` ### data ``` df <- structure(list(age1 = c(20L, 30L, 30L), age2 = c(10L, 20L, 45L ), age3 = c(50L, 60L, 70L)), .Names = c("age1", "age2", "age3" ), class = "data.frame", row.names = c("1", "2", "3")) ```
53,191,900
I am somewhat stumped on a seemingly simple problem. I have a table set up such as, ``` CREATE TABLE cities ( column_1 TEXT, column_2 TEXT); ``` Where the contents of these tables look like ``` column_1 | column_2 --------------------- Atlanta | Atlanta Boston | Chicago Chicago | Los Angeles Seattle | Tacoma NULL | Seattle ``` What query could I run that would look at both of these columns, and despite their order, return where the two columns matchup? The result I am looking for would be: ``` column_1 | column_2 --------------------- Atlanta | Atlanta Chicago | Chicago Seattle | Seattle ``` I have tried: ``` SELECT * FROM cities WHERE column_1 = column_2; ``` But this only returns the EXACT matches: ``` column_1 | column_2 --------------------- Atlanta | Atlanta ```
2018/11/07
[ "https://Stackoverflow.com/questions/53191900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10251211/" ]
You just need a self join: ``` SELECT c1.column_1, c2.column_2 FROM cities c1 JOIN cities c2 ON c1.column_1 = c2.column_2 ```
your query is asking the question where is column\_1 == column\_2 in the same row. If you want to retrieve all instances of cities existing in both columns you would need to do a self join like so. ``` SELECT t1.column_1, t2.column_2 FROM cities t1 join cities t2 on (t1.column_1 = t2.column_2) ```
371,318
The original problem was to consider how many ways to make a wiring diagram out of $n$ resistors. When I thought about this I realized that if you can only connect in series and shunt. - Then this is the same as dividing an area with $n-1$ horizontal and vertical lines. When each line only divides one of the current area sections into two smaller ones. This is also the same as the number of ways to make a set of $n$ (and only $n$) rectangles into a bigger rectangle. If the rectangles can be drawn by dividing the big rectangle, line by line, into the set of rectangles without lose endpoints of the line. - Can someone come to think of "a expression of $n$" which equals this amount, independent of the order of the rectangles or position? (It is only the relations between the area sections that matters and not left or right, up or down. However dividing an area with a horizontal line is not the same as dividing it with a vertical line.)
2013/04/24
[ "https://math.stackexchange.com/questions/371318", "https://math.stackexchange.com", "https://math.stackexchange.com/users/74120/" ]
In the ordinary calculus, there are *no* infinitesimals. Abraham Robinson and others, from the $1950$'s on, developed *non-standard analysis*, which does have infinitesimals, and also "infinite" number-like objects, that one can work with in ways that are closely analogous to the way we deal with ordinary real numbers. In non-standard analysis, an infinitesimal times an infinite number can have various values, depending on their relative sizes. The product can be an ordinary real number. But it can also be infinitesimal, or infinite. Similarly, the ratio of two "infinite" objects in a non-standard model of analysis can be an ordinary real number, but need not be. The calculus can be developed rigorously using Robinson's infinitesimals. There are even some courses in calculus that are based on non-standard models of analysis. Some have argued that this captures the intuition of the founders of calculus better than the traditional limit-based approach. For further reading, you may want to start with the Wikipedia article on [Non-standard Analysis.](http://en.wikipedia.org/wiki/Non-standard_analysis)
This is a question for surreal numbers. Surreal numbers are a really amazing thing invented by John Conway that include numbers like 0 and 3/4, but also things like "twice the square root of infinity, all plus an infinitesimal". This question depends on the values of the infinite and infinitesimal, but the way it works is this. The number ω is defined as the number of items in the set {0,1,2,3,4,5...}, so it's infinite. The number ε is defined as 1/ω. So ω\*ε is obviously one. If you think about it a bit, it makes sense that 2ε^2 \* ω is 2ε, and so on. ``` http://en.wikipedia.org/wiki/Surreal_number ```
371,318
The original problem was to consider how many ways to make a wiring diagram out of $n$ resistors. When I thought about this I realized that if you can only connect in series and shunt. - Then this is the same as dividing an area with $n-1$ horizontal and vertical lines. When each line only divides one of the current area sections into two smaller ones. This is also the same as the number of ways to make a set of $n$ (and only $n$) rectangles into a bigger rectangle. If the rectangles can be drawn by dividing the big rectangle, line by line, into the set of rectangles without lose endpoints of the line. - Can someone come to think of "a expression of $n$" which equals this amount, independent of the order of the rectangles or position? (It is only the relations between the area sections that matters and not left or right, up or down. However dividing an area with a horizontal line is not the same as dividing it with a vertical line.)
2013/04/24
[ "https://math.stackexchange.com/questions/371318", "https://math.stackexchange.com", "https://math.stackexchange.com/users/74120/" ]
In the ordinary calculus, there are *no* infinitesimals. Abraham Robinson and others, from the $1950$'s on, developed *non-standard analysis*, which does have infinitesimals, and also "infinite" number-like objects, that one can work with in ways that are closely analogous to the way we deal with ordinary real numbers. In non-standard analysis, an infinitesimal times an infinite number can have various values, depending on their relative sizes. The product can be an ordinary real number. But it can also be infinitesimal, or infinite. Similarly, the ratio of two "infinite" objects in a non-standard model of analysis can be an ordinary real number, but need not be. The calculus can be developed rigorously using Robinson's infinitesimals. There are even some courses in calculus that are based on non-standard models of analysis. Some have argued that this captures the intuition of the founders of calculus better than the traditional limit-based approach. For further reading, you may want to start with the Wikipedia article on [Non-standard Analysis.](http://en.wikipedia.org/wiki/Non-standard_analysis)
For $x$ > 0, define an infinite number by the divergent geometric series: $\displaystyle\sum\_{i=0}^{n\rightarrow\infty} \left(\frac{x+1}{x}\right)^i $ and define an infinitesimal number as the difference between a convergent geometric series and its sum: $ x+1 -\displaystyle\sum\_{i=0}^{n\rightarrow\infty} \left(\frac{x}{x+1}\right)^i$ If the x is the same in both the infinity and the infinitesimal their product will converge to the finite number x(x+1) as n increases without bound. If the x in the infinity is smaller than the x in the infinitesimal their product in the limit will be an infinity. If the x in the infinity is larger than the x in the infinitesimal their product in the limit will be an infinitesimal. Division of infinity by infinity as defined by these divergent geometric series will result in the limit (1) an infinity if the numerator has a smaller x, (2) an infinitesimal if the numerator has a larger x, (3) the finite value 1 if numerator and denominator have the same x.
371,318
The original problem was to consider how many ways to make a wiring diagram out of $n$ resistors. When I thought about this I realized that if you can only connect in series and shunt. - Then this is the same as dividing an area with $n-1$ horizontal and vertical lines. When each line only divides one of the current area sections into two smaller ones. This is also the same as the number of ways to make a set of $n$ (and only $n$) rectangles into a bigger rectangle. If the rectangles can be drawn by dividing the big rectangle, line by line, into the set of rectangles without lose endpoints of the line. - Can someone come to think of "a expression of $n$" which equals this amount, independent of the order of the rectangles or position? (It is only the relations between the area sections that matters and not left or right, up or down. However dividing an area with a horizontal line is not the same as dividing it with a vertical line.)
2013/04/24
[ "https://math.stackexchange.com/questions/371318", "https://math.stackexchange.com", "https://math.stackexchange.com/users/74120/" ]
In the ordinary calculus, there are *no* infinitesimals. Abraham Robinson and others, from the $1950$'s on, developed *non-standard analysis*, which does have infinitesimals, and also "infinite" number-like objects, that one can work with in ways that are closely analogous to the way we deal with ordinary real numbers. In non-standard analysis, an infinitesimal times an infinite number can have various values, depending on their relative sizes. The product can be an ordinary real number. But it can also be infinitesimal, or infinite. Similarly, the ratio of two "infinite" objects in a non-standard model of analysis can be an ordinary real number, but need not be. The calculus can be developed rigorously using Robinson's infinitesimals. There are even some courses in calculus that are based on non-standard models of analysis. Some have argued that this captures the intuition of the founders of calculus better than the traditional limit-based approach. For further reading, you may want to start with the Wikipedia article on [Non-standard Analysis.](http://en.wikipedia.org/wiki/Non-standard_analysis)
Nothing happens, forget infinitesimals and infinity as numbers. Math was built with limits in the last centuries so we don't need to try to define these things.
48,393,532
im trying to do something like below,which is when **manual put "red" in data-type,** then it will **add class red** after cm-coupon ,and **if hasClass red, then will show the css for red.** Same else if **data-type in div is "green"**, then it will **add class green after cm-coupon**, and **display the css for green**. but i no idea to how call the data-type from html to script? is it need using find(); or attr(); ? ``` <div class="cm-coupon data-type="red"></div> $( document ).ready(function() { // document var coupon = $('div.cm-coupon'); $('.cm-coupon').append('<div class="cm-cp-title"></div>'); //if data-type = "red" $(this).addClass('red'); $('.cm-coupon').append('<div class="cm-cp-title">title-01</div>'); // if data-type = "green" $(this).addClass('green'); $('.cm-coupon').append('<div class="cm-cp-title">title-02</div>'); // Call each css with different class if (coupon.hasClass('red')) { $('.cm-coupon').css({"background" : "red", "padding": "20px 0"}); } else if (coupon.hasClass('green')) { $('.cm-coupon').css({"background" : "green", "padding": "20px 0"}); } else { return coupon; } });//end ```
2018/01/23
[ "https://Stackoverflow.com/questions/48393532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9180177/" ]
You cannot create a broadcast variable from the worker nodes. In your case, basically you need [Accumulators](https://spark.apache.org/docs/2.2.0/rdd-programming-guide.html#accumulators). Define the accumulator on the Driver. On the worker nodes you can update the accumulator value. Again you can fetch the updated value on the Driver. Note:you cannot retrieve the value of accumulator on the worker nodes. Only updated of value is possible from worker nodes. Below an example from spark docs: ``` // creating the accumulator on driver scala> val accum = sc.longAccumulator("My Accumulator") accum: org.apache.spark.util.LongAccumulator = LongAccumulator(id: 0, name: Some(My Accumulator), value: 0) // updating the accumulator on worker nodes scala> sc.parallelize(Array(1, 2, 3, 4)).foreach(x => accum.add(x)) ... 10/09/29 18:41:08 INFO SparkContext: Tasks finished in 0.317106 s // fetaching the value scala> accum.value res2: Long = 10 ```
First: Update the spark to spark2.3 Second: Make the stampListMap as file stream (`sparkStream.readStream.textFile('/../my.txt')...load()`), the file stream can self update the content itself. And if now you use stream join static,you can use stream join stream in spark2.3+.
36,000
Is he saying he doesn’t like the playful attitude? Or is he cynically referring to part of the joke? I’m reading a Harry Potter book and found ‘I don’t care …’ in a scene. For the moment, I have three interpretations for that. > > 1. I don’t care for your joke. I don’t like your attitude. Don’t make fun of me when I’m worrying seriously. > 2. I don’t care if you are attacked by a dragon or whatever. (He is replying by a little cynical comment.) > 3. (Either is possible. Only the speaker knows the truth.) > > > Would you read the following citation and tell me what it means? (It’d be nice if you could also tell me how you knew that; it’ll help me a lot when I read other books.) > > “Now listen …” He looked particularly hard at Harry. “I don’t want you lot sneaking out of school to see me, all right? Just send notes to me here. I still want to hear about anything odd. But you’re not to go leaving Hogwarts without permission; it would be an ideal opportunity for someone to attack you.” > > > ”No one’s tried to attack me so far, except a dragon and a couple of grindylows,” Harry said, but Sirius scowled at him. > > > "**I don’t care …** I’ll breathe freely again when this tournament’s over, and that’s not until June. And don’t forget, if you’re talking about me among yourselves, call me Snuffles, okay? (*Harry Potter 4* [US Version]: p.41)[Bold font is mine] > > > **N.B.:** Sirius is Harry’s godfather, a wanted person for a crime he didn’t commit, seriously worrying that villains could attack Harry any moment. Harry is a little annoyed with his parental affection as teenagers often do. So he is trying to turn Sirius’s earnest words into ridicule, by referring to a dragon and grindylows, which Harry has already gotten over through the wizard tournament.
2011/07/29
[ "https://english.stackexchange.com/questions/36000", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
In computing, "macro" was first used with assemblers, which are utilities that perform simple translation of readable mnemonics into machine instructions. Normally a single line in an input to a basic assembler produces a single machine instruction output; the line is commonly referred to as an instruction. Productivity was increased when the use of what were termed *macro-instructions* were invented. *Macro-* is of course a standard prefix from the Greek meaning large, and a macroinstruction was a new kind of input line which would generate several machine instructions. The OED shows a revealing quote from 1959: > > The built-in system macro instructions in SCAT presently consist of (1) two macros for generating the‥standard entry and exit from subroutines, (2) a set of debugging macros. > > > This shows use of both the full form, *macro instruction*, and the abbreviated form, *macro*. (Quote is from Greenwald & Kane, "The Share 709 System: Programming and Modification", *Journal of the ACM* 6:133. SCAT ("Symbolic Coder And Translator") was an early macro-assembler.)
From the [Computing Dictionary:](http://dictionary.reference.com/browse/macro) > > The term "macro" originated in early assemblers, which encouraged the use of macros as a structuring and information-hiding device. During the early 1970s, macro assemblers became ubiquitous, and sometimes quite as powerful and expensive as HLLs, only to fall from favour as improving compiler technology marginalised assembly language programming (see languages of choice). Nowadays the term is most often used in connection with the C preprocessor, Lisp, or one of several special-purpose languages built around a macro-expansion facility (such as TeX or Unix's troff suite). > Indeed, the meaning has drifted enough that the collective "macros" is now sometimes used for code in any special-purpose application control language (whether or not the language is actually translated by text expansion), and for macro-like entities such as the "keyboard macros" supported in some text editors (and PC TSRs or Macintosh INIT/CDEV keyboard enhancers). > > > Another explanation is that it is a shortening of ["macroinstruction"](http://dictionary.reference.com/browse/macro) which means: > > a single computer instruction that initiates a set of instructions to perform a specific task > > >
36,000
Is he saying he doesn’t like the playful attitude? Or is he cynically referring to part of the joke? I’m reading a Harry Potter book and found ‘I don’t care …’ in a scene. For the moment, I have three interpretations for that. > > 1. I don’t care for your joke. I don’t like your attitude. Don’t make fun of me when I’m worrying seriously. > 2. I don’t care if you are attacked by a dragon or whatever. (He is replying by a little cynical comment.) > 3. (Either is possible. Only the speaker knows the truth.) > > > Would you read the following citation and tell me what it means? (It’d be nice if you could also tell me how you knew that; it’ll help me a lot when I read other books.) > > “Now listen …” He looked particularly hard at Harry. “I don’t want you lot sneaking out of school to see me, all right? Just send notes to me here. I still want to hear about anything odd. But you’re not to go leaving Hogwarts without permission; it would be an ideal opportunity for someone to attack you.” > > > ”No one’s tried to attack me so far, except a dragon and a couple of grindylows,” Harry said, but Sirius scowled at him. > > > "**I don’t care …** I’ll breathe freely again when this tournament’s over, and that’s not until June. And don’t forget, if you’re talking about me among yourselves, call me Snuffles, okay? (*Harry Potter 4* [US Version]: p.41)[Bold font is mine] > > > **N.B.:** Sirius is Harry’s godfather, a wanted person for a crime he didn’t commit, seriously worrying that villains could attack Harry any moment. Harry is a little annoyed with his parental affection as teenagers often do. So he is trying to turn Sirius’s earnest words into ridicule, by referring to a dragon and grindylows, which Harry has already gotten over through the wizard tournament.
2011/07/29
[ "https://english.stackexchange.com/questions/36000", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
From the [Computing Dictionary:](http://dictionary.reference.com/browse/macro) > > The term "macro" originated in early assemblers, which encouraged the use of macros as a structuring and information-hiding device. During the early 1970s, macro assemblers became ubiquitous, and sometimes quite as powerful and expensive as HLLs, only to fall from favour as improving compiler technology marginalised assembly language programming (see languages of choice). Nowadays the term is most often used in connection with the C preprocessor, Lisp, or one of several special-purpose languages built around a macro-expansion facility (such as TeX or Unix's troff suite). > Indeed, the meaning has drifted enough that the collective "macros" is now sometimes used for code in any special-purpose application control language (whether or not the language is actually translated by text expansion), and for macro-like entities such as the "keyboard macros" supported in some text editors (and PC TSRs or Macintosh INIT/CDEV keyboard enhancers). > > > Another explanation is that it is a shortening of ["macroinstruction"](http://dictionary.reference.com/browse/macro) which means: > > a single computer instruction that initiates a set of instructions to perform a specific task > > >
To follow on from mgkrebbs' fine [answer](https://english.stackexchange.com/questions/35984/how-did-the-word-macro-as-used-in-computer-programming-come-about/35987#35987), the SCAT in question is a SHARE 709 assembly program: "SHARE Compiler, Assembler, Translator". Both *SCAT* and *macro* are mentioned in papers presented to the Association for Computing Machinery and IIT Research Institute in [1958](https://www.google.com/search?q=SCAT%20macro&btnG=Search%20Books&tbm=bks&tbo=1#sclient=psy-ab&hl=en&tbs=cdr:1,cd_min:1/1/1958,cd_max:1958&tbm=bks&source=hp&q=SCAT%20macros&pbx=1&oq=SCAT%20macros&aq=f&aqi=&aql=1&gs_sm=e&gs_upl=344941l345666l3l345804l3l2l1l0l0l1l258l500l2-2l2l0&bav=on.2,or.r_gc.r_pw.,cf.osb&fp=7baf74d1a3d9fd6c&biw=1920&bih=1057). The earliest, [ACM](http://books.google.com/books?ei=BnSxTt27JoKmhAe51pXcAg&ct=result&id=zuYOAAAAIAAJ&dq=SCAT%20macros&q=macros%20OR%20macro#search_anchor)'s *Preprints of summaries of papers presented at the national meeting*, tells us "The compiler expands each macro into one or more words of machine code ..." ([1958 confirmation](http://dl.acm.org/citation.cfm?id=610937.610952&coll=DL&dl=GUIDE&CFID=66307764&CFTOKEN=58918686)): ![The compiler expands each macro into one or more words of machine code](https://i.stack.imgur.com/mAJX8.png) The next, [IITRI](http://books.google.com/books?ei=BnSxTt27JoKmhAe51pXcAg&ct=result&id=t_kCX_hC34cC&dq=SCAT%20macros&q=macro%20OR%20macros#search_anchor)'s *Computer Applications: Proceedings*, shows we might have called them *pseudos*: ![pseudo- or macro-instructions](https://i.stack.imgur.com/q9Zla.png) Finally, *macroinstruction* is found in [1956](http://books.google.com/books?ei=_FGyTvHoDoz_-gbnnNX9Aw&ct=result&id=nDxNAAAAYAAJ&dq=%22macro-instruction%22&q=%22macroinstructions%22+OR+%22macro-instruction%22#search_anchor)'s *Proceedings of the Western Joint Computer Conference*: ![The macroinstruction is like an open-ended subroutine in that it calls forth from a library...](https://i.stack.imgur.com/MpmtH.png)
36,000
Is he saying he doesn’t like the playful attitude? Or is he cynically referring to part of the joke? I’m reading a Harry Potter book and found ‘I don’t care …’ in a scene. For the moment, I have three interpretations for that. > > 1. I don’t care for your joke. I don’t like your attitude. Don’t make fun of me when I’m worrying seriously. > 2. I don’t care if you are attacked by a dragon or whatever. (He is replying by a little cynical comment.) > 3. (Either is possible. Only the speaker knows the truth.) > > > Would you read the following citation and tell me what it means? (It’d be nice if you could also tell me how you knew that; it’ll help me a lot when I read other books.) > > “Now listen …” He looked particularly hard at Harry. “I don’t want you lot sneaking out of school to see me, all right? Just send notes to me here. I still want to hear about anything odd. But you’re not to go leaving Hogwarts without permission; it would be an ideal opportunity for someone to attack you.” > > > ”No one’s tried to attack me so far, except a dragon and a couple of grindylows,” Harry said, but Sirius scowled at him. > > > "**I don’t care …** I’ll breathe freely again when this tournament’s over, and that’s not until June. And don’t forget, if you’re talking about me among yourselves, call me Snuffles, okay? (*Harry Potter 4* [US Version]: p.41)[Bold font is mine] > > > **N.B.:** Sirius is Harry’s godfather, a wanted person for a crime he didn’t commit, seriously worrying that villains could attack Harry any moment. Harry is a little annoyed with his parental affection as teenagers often do. So he is trying to turn Sirius’s earnest words into ridicule, by referring to a dragon and grindylows, which Harry has already gotten over through the wizard tournament.
2011/07/29
[ "https://english.stackexchange.com/questions/36000", "https://english.stackexchange.com", "https://english.stackexchange.com/users/-1/" ]
In computing, "macro" was first used with assemblers, which are utilities that perform simple translation of readable mnemonics into machine instructions. Normally a single line in an input to a basic assembler produces a single machine instruction output; the line is commonly referred to as an instruction. Productivity was increased when the use of what were termed *macro-instructions* were invented. *Macro-* is of course a standard prefix from the Greek meaning large, and a macroinstruction was a new kind of input line which would generate several machine instructions. The OED shows a revealing quote from 1959: > > The built-in system macro instructions in SCAT presently consist of (1) two macros for generating the‥standard entry and exit from subroutines, (2) a set of debugging macros. > > > This shows use of both the full form, *macro instruction*, and the abbreviated form, *macro*. (Quote is from Greenwald & Kane, "The Share 709 System: Programming and Modification", *Journal of the ACM* 6:133. SCAT ("Symbolic Coder And Translator") was an early macro-assembler.)
To follow on from mgkrebbs' fine [answer](https://english.stackexchange.com/questions/35984/how-did-the-word-macro-as-used-in-computer-programming-come-about/35987#35987), the SCAT in question is a SHARE 709 assembly program: "SHARE Compiler, Assembler, Translator". Both *SCAT* and *macro* are mentioned in papers presented to the Association for Computing Machinery and IIT Research Institute in [1958](https://www.google.com/search?q=SCAT%20macro&btnG=Search%20Books&tbm=bks&tbo=1#sclient=psy-ab&hl=en&tbs=cdr:1,cd_min:1/1/1958,cd_max:1958&tbm=bks&source=hp&q=SCAT%20macros&pbx=1&oq=SCAT%20macros&aq=f&aqi=&aql=1&gs_sm=e&gs_upl=344941l345666l3l345804l3l2l1l0l0l1l258l500l2-2l2l0&bav=on.2,or.r_gc.r_pw.,cf.osb&fp=7baf74d1a3d9fd6c&biw=1920&bih=1057). The earliest, [ACM](http://books.google.com/books?ei=BnSxTt27JoKmhAe51pXcAg&ct=result&id=zuYOAAAAIAAJ&dq=SCAT%20macros&q=macros%20OR%20macro#search_anchor)'s *Preprints of summaries of papers presented at the national meeting*, tells us "The compiler expands each macro into one or more words of machine code ..." ([1958 confirmation](http://dl.acm.org/citation.cfm?id=610937.610952&coll=DL&dl=GUIDE&CFID=66307764&CFTOKEN=58918686)): ![The compiler expands each macro into one or more words of machine code](https://i.stack.imgur.com/mAJX8.png) The next, [IITRI](http://books.google.com/books?ei=BnSxTt27JoKmhAe51pXcAg&ct=result&id=t_kCX_hC34cC&dq=SCAT%20macros&q=macro%20OR%20macros#search_anchor)'s *Computer Applications: Proceedings*, shows we might have called them *pseudos*: ![pseudo- or macro-instructions](https://i.stack.imgur.com/q9Zla.png) Finally, *macroinstruction* is found in [1956](http://books.google.com/books?ei=_FGyTvHoDoz_-gbnnNX9Aw&ct=result&id=nDxNAAAAYAAJ&dq=%22macro-instruction%22&q=%22macroinstructions%22+OR+%22macro-instruction%22#search_anchor)'s *Proceedings of the Western Joint Computer Conference*: ![The macroinstruction is like an open-ended subroutine in that it calls forth from a library...](https://i.stack.imgur.com/MpmtH.png)
966,550
I am trying to write a regular expression such as it has /admin in the middle and ends with .css or .js or other formats. `http://example.com/admin/static/style.css` (SHOULD WORK) `http://example.com/admin/static/vendor.js` (SHOULD WORK) `http://example.com/static/style.css` (SHOULD NOT WORK) I am trying to use this in nginx location block. I tried this ``` location /admin/\.(css|js)${ } ``` but not working. Any ideas?
2019/05/09
[ "https://serverfault.com/questions/966550", "https://serverfault.com", "https://serverfault.com/users/522838/" ]
The source of the traffic isn't your Telstra TID link, it's ANY. The Telstra TID link isn't the originator of the inbound traffic and as such the source ip address of the incoming traffic is not the Telstra TID link. The source ip address of the traffic is ANY web browser coming from the WAN (public) that's trying to get to your internal website. Change the inbound rule source to ANY and that should fix it.
This isn't a WatchGuard issue, had a support session with them and also setup a temp IIS server on a server and all worked. Must be a server thing
67,959,404
I have been trying to replace part of the texts in a Pandas dataframe column with keys from a dictionary based on multiple values; though I have achieved the desired result, the process or loop is very very slow in large dataset. I would appreciate it if someone could advise me of a more 'Pythonic' way or more efficient way of achieving the result. Pls see below example: ``` df = pd.DataFrame({'Dish': ['A', 'B','C'], 'Price': [15,8,20], 'Ingredient': ['apple banana apricot lamb ', 'wheat pork venison', 'orange lamb guinea'] }) ``` | Dish | Price | Ingredient | | --- | --- | --- | | A | 15 | apple banana apricot lamb | | B | 8 | wheat pork venison | | C | 20 | orange lamb guinea | The dictionary is below: ``` CountryList = {'FRUIT': [['apple'], ['orange'], ['banana']], 'CEREAL': [['oat'], ['wheat'], ['corn']], 'MEAT': [['chicken'], ['lamb'], ['pork'], ['turkey'], ['duck']]} ``` I am trying to replace text in the 'Ingredient' column with key based on dictionary values. For example, 'apple' in the first row wound be replaced by dictionary key: 'FRUIT'.. The desired table is shown below: | Dish | Price | Ingredient | | --- | --- | --- | | A | 15 | FRUIT FRUIT apricot MEAT | | B | 8 | CEREAL MEAT venison | | C | 20 | FRUIT MEAT guinea | I have seen some related queries here where each key has one value; but in this case, there are multiple values for any given key in the dictionary. So far, I have been able to achieve the desired result but it is painfully slow when working with a large dataset. The code I have used so far to achieve the result is shown below: ``` countries = list(CountryList.keys()) for country in countries: for i in range(len(CountryList[country])): lender = CountryList[country][i] country = str(country) lender = str(lender).replace("['",'',).replace("']",'') df['Ingredient'] = df['Ingredient'].str.replace(lender,country) ``` Perhaps this could do with multiprocessing? Needless to say, my knowledge of Python needs a lot to be desired. Any suggestion to speed up the process would be highly appreciated. Thanking in advance, Edit: just to add, some keys have more than 60000 values in the dictionary; and about 200 keys in the dictionary, which is making the code very inefficient time-wise.
2021/06/13
[ "https://Stackoverflow.com/questions/67959404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16214945/" ]
You can build a reverse index of product to type, by creating a dictionary where the keys are the values of the sublists ``` product_to_type = {} for typ, product_lists in CountryList.items(): for product_list in product_lists: for product in product_list: product_to_type[product] = typ ``` A little python magic lets you compress this step into a generator that creates the dict ``` product_to_type = {product:typ for typ, product_lists in CountryList.items() for product_list in product_lists for product in product_list} ``` Then you can create a function that splits the ingredients and maps them to type and apply that to the dataframe. ``` import pandas as pd CountryList = {'FRUIT': [['apple'], ['orange'], ['banana']], 'CEREAL': [['oat'], ['wheat'], ['corn']], 'MEAT': [['chicken'], ['lamb'], ['pork'], ['turkey'], ['duck']]} product_to_type = {product:typ for typ, product_lists in CountryList.items() for product_list in product_lists for product in product_list} def convert_product_to_type(products): return " ".join(product_to_type.get(product, product) for product in products.split(" ")) df = pd.DataFrame({'Dish': ['A', 'B','C'], 'Price': [15,8,20], 'Ingredient': ['apple banana apricot lamb ', 'wheat pork venison', 'orange lamb guinea'] }) df["Ingredient"] = df["Ingredient"].apply(convert_product_to_type) print(df) ``` Note: This solution splits the ingredient list on word boundaries which assumes that ingredients themselves don't have spaces in them.
Change the format of CountryList: ``` import itertools CountryList2 = {} for k, v in CountryList.items(): for i in (itertools.chain.from_iterable(v)): CountryList2[i] = k ``` ``` >>> CountryList2 {'apple': 'FRUIT', 'orange': 'FRUIT', 'banana': 'FRUIT', 'oat': 'CEREAL', 'wheat': 'CEREAL', 'corn': 'CEREAL', 'chicken': 'MEAT', 'lamb': 'MEAT', 'pork': 'MEAT', 'turkey': 'MEAT', 'duck': 'MEAT'} ``` Now you can use `replace`: ``` df['Ingredient'] = df['Ingredient'].replace(CountryList2, regex=True) ``` ``` >>> df Dish Price Ingredient 0 A 15 FRUIT FRUIT apricot MEAT 1 B 8 CEREAL MEAT venison 2 C 20 FRUIT MEAT guinea ```
67,959,404
I have been trying to replace part of the texts in a Pandas dataframe column with keys from a dictionary based on multiple values; though I have achieved the desired result, the process or loop is very very slow in large dataset. I would appreciate it if someone could advise me of a more 'Pythonic' way or more efficient way of achieving the result. Pls see below example: ``` df = pd.DataFrame({'Dish': ['A', 'B','C'], 'Price': [15,8,20], 'Ingredient': ['apple banana apricot lamb ', 'wheat pork venison', 'orange lamb guinea'] }) ``` | Dish | Price | Ingredient | | --- | --- | --- | | A | 15 | apple banana apricot lamb | | B | 8 | wheat pork venison | | C | 20 | orange lamb guinea | The dictionary is below: ``` CountryList = {'FRUIT': [['apple'], ['orange'], ['banana']], 'CEREAL': [['oat'], ['wheat'], ['corn']], 'MEAT': [['chicken'], ['lamb'], ['pork'], ['turkey'], ['duck']]} ``` I am trying to replace text in the 'Ingredient' column with key based on dictionary values. For example, 'apple' in the first row wound be replaced by dictionary key: 'FRUIT'.. The desired table is shown below: | Dish | Price | Ingredient | | --- | --- | --- | | A | 15 | FRUIT FRUIT apricot MEAT | | B | 8 | CEREAL MEAT venison | | C | 20 | FRUIT MEAT guinea | I have seen some related queries here where each key has one value; but in this case, there are multiple values for any given key in the dictionary. So far, I have been able to achieve the desired result but it is painfully slow when working with a large dataset. The code I have used so far to achieve the result is shown below: ``` countries = list(CountryList.keys()) for country in countries: for i in range(len(CountryList[country])): lender = CountryList[country][i] country = str(country) lender = str(lender).replace("['",'',).replace("']",'') df['Ingredient'] = df['Ingredient'].str.replace(lender,country) ``` Perhaps this could do with multiprocessing? Needless to say, my knowledge of Python needs a lot to be desired. Any suggestion to speed up the process would be highly appreciated. Thanking in advance, Edit: just to add, some keys have more than 60000 values in the dictionary; and about 200 keys in the dictionary, which is making the code very inefficient time-wise.
2021/06/13
[ "https://Stackoverflow.com/questions/67959404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16214945/" ]
Change the format of CountryList: ``` import itertools CountryList2 = {} for k, v in CountryList.items(): for i in (itertools.chain.from_iterable(v)): CountryList2[i] = k ``` ``` >>> CountryList2 {'apple': 'FRUIT', 'orange': 'FRUIT', 'banana': 'FRUIT', 'oat': 'CEREAL', 'wheat': 'CEREAL', 'corn': 'CEREAL', 'chicken': 'MEAT', 'lamb': 'MEAT', 'pork': 'MEAT', 'turkey': 'MEAT', 'duck': 'MEAT'} ``` Now you can use `replace`: ``` df['Ingredient'] = df['Ingredient'].replace(CountryList2, regex=True) ``` ``` >>> df Dish Price Ingredient 0 A 15 FRUIT FRUIT apricot MEAT 1 B 8 CEREAL MEAT venison 2 C 20 FRUIT MEAT guinea ```
If you want to use regex, just join all the values in the `CountryList` by pipe `|` for each of the keys, and then call [`Series.str.replace`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html) for each of the keys, it will be a way faster than the way you are trying. ```py joined={key: '|'.join(item[0] for item in value) for key,value in CountryList.items()} for key in joined: df['Ingredient'] = df['Ingredient'].str.replace(joined[key], key, regex=True) ``` **OUTPUT**: ```py Dish Price Ingredient 0 A 15 FRUIT FRUIT apricot MEAT 1 B 8 CEREAL MEAT venison 2 C 20 FRUIT MEAT guinea ``` Another approach would be to reverse the key,value in the dictionary, and then to use `dict.get` for each `key` with default value as `key` splitting the words in `Ingredient` column: ```py reversedContries={item[0]:key for key,value in CountryList.items() for item in value} df['Ingredient'].apply(lambda x: ' '.join(reversedContries.get(y,y) for y in x.split())) ```
67,959,404
I have been trying to replace part of the texts in a Pandas dataframe column with keys from a dictionary based on multiple values; though I have achieved the desired result, the process or loop is very very slow in large dataset. I would appreciate it if someone could advise me of a more 'Pythonic' way or more efficient way of achieving the result. Pls see below example: ``` df = pd.DataFrame({'Dish': ['A', 'B','C'], 'Price': [15,8,20], 'Ingredient': ['apple banana apricot lamb ', 'wheat pork venison', 'orange lamb guinea'] }) ``` | Dish | Price | Ingredient | | --- | --- | --- | | A | 15 | apple banana apricot lamb | | B | 8 | wheat pork venison | | C | 20 | orange lamb guinea | The dictionary is below: ``` CountryList = {'FRUIT': [['apple'], ['orange'], ['banana']], 'CEREAL': [['oat'], ['wheat'], ['corn']], 'MEAT': [['chicken'], ['lamb'], ['pork'], ['turkey'], ['duck']]} ``` I am trying to replace text in the 'Ingredient' column with key based on dictionary values. For example, 'apple' in the first row wound be replaced by dictionary key: 'FRUIT'.. The desired table is shown below: | Dish | Price | Ingredient | | --- | --- | --- | | A | 15 | FRUIT FRUIT apricot MEAT | | B | 8 | CEREAL MEAT venison | | C | 20 | FRUIT MEAT guinea | I have seen some related queries here where each key has one value; but in this case, there are multiple values for any given key in the dictionary. So far, I have been able to achieve the desired result but it is painfully slow when working with a large dataset. The code I have used so far to achieve the result is shown below: ``` countries = list(CountryList.keys()) for country in countries: for i in range(len(CountryList[country])): lender = CountryList[country][i] country = str(country) lender = str(lender).replace("['",'',).replace("']",'') df['Ingredient'] = df['Ingredient'].str.replace(lender,country) ``` Perhaps this could do with multiprocessing? Needless to say, my knowledge of Python needs a lot to be desired. Any suggestion to speed up the process would be highly appreciated. Thanking in advance, Edit: just to add, some keys have more than 60000 values in the dictionary; and about 200 keys in the dictionary, which is making the code very inefficient time-wise.
2021/06/13
[ "https://Stackoverflow.com/questions/67959404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16214945/" ]
You can build a reverse index of product to type, by creating a dictionary where the keys are the values of the sublists ``` product_to_type = {} for typ, product_lists in CountryList.items(): for product_list in product_lists: for product in product_list: product_to_type[product] = typ ``` A little python magic lets you compress this step into a generator that creates the dict ``` product_to_type = {product:typ for typ, product_lists in CountryList.items() for product_list in product_lists for product in product_list} ``` Then you can create a function that splits the ingredients and maps them to type and apply that to the dataframe. ``` import pandas as pd CountryList = {'FRUIT': [['apple'], ['orange'], ['banana']], 'CEREAL': [['oat'], ['wheat'], ['corn']], 'MEAT': [['chicken'], ['lamb'], ['pork'], ['turkey'], ['duck']]} product_to_type = {product:typ for typ, product_lists in CountryList.items() for product_list in product_lists for product in product_list} def convert_product_to_type(products): return " ".join(product_to_type.get(product, product) for product in products.split(" ")) df = pd.DataFrame({'Dish': ['A', 'B','C'], 'Price': [15,8,20], 'Ingredient': ['apple banana apricot lamb ', 'wheat pork venison', 'orange lamb guinea'] }) df["Ingredient"] = df["Ingredient"].apply(convert_product_to_type) print(df) ``` Note: This solution splits the ingredient list on word boundaries which assumes that ingredients themselves don't have spaces in them.
If you want to use regex, just join all the values in the `CountryList` by pipe `|` for each of the keys, and then call [`Series.str.replace`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html) for each of the keys, it will be a way faster than the way you are trying. ```py joined={key: '|'.join(item[0] for item in value) for key,value in CountryList.items()} for key in joined: df['Ingredient'] = df['Ingredient'].str.replace(joined[key], key, regex=True) ``` **OUTPUT**: ```py Dish Price Ingredient 0 A 15 FRUIT FRUIT apricot MEAT 1 B 8 CEREAL MEAT venison 2 C 20 FRUIT MEAT guinea ``` Another approach would be to reverse the key,value in the dictionary, and then to use `dict.get` for each `key` with default value as `key` splitting the words in `Ingredient` column: ```py reversedContries={item[0]:key for key,value in CountryList.items() for item in value} df['Ingredient'].apply(lambda x: ' '.join(reversedContries.get(y,y) for y in x.split())) ```
10,870,527
I'm looking for a way to replace all dots in a line except the last one. Example: `Blah - whatever - foo.bar.baz.avi` should become `Blah - whatever - foo bar bar.avi` Since I'll have more than one line in the file and the amount of dots varies in each line I'm looking for a generic solution and not something like "Replace the first X matches" with X being a constant.
2012/06/03
[ "https://Stackoverflow.com/questions/10870527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298479/" ]
This seems to do the trick: ``` %s/\.\(.*\.\)\@=/ /g ``` `\@=` is a [lookahead](http://www.regular-expressions.info/lookaround.html). It only matches a full stop if there are any following full stops. See `:help zero-width`.
As a variation on the first answer you may prefer this syntax: ``` %s/\.\ze.*\./ /g ``` It let's you put the assertion that there be a following full stop after the search operator.
10,870,527
I'm looking for a way to replace all dots in a line except the last one. Example: `Blah - whatever - foo.bar.baz.avi` should become `Blah - whatever - foo bar bar.avi` Since I'll have more than one line in the file and the amount of dots varies in each line I'm looking for a generic solution and not something like "Replace the first X matches" with X being a constant.
2012/06/03
[ "https://Stackoverflow.com/questions/10870527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298479/" ]
This seems to do the trick: ``` %s/\.\(.*\.\)\@=/ /g ``` `\@=` is a [lookahead](http://www.regular-expressions.info/lookaround.html). It only matches a full stop if there are any following full stops. See `:help zero-width`.
Another way that might be useful to learn (replace inside visual selection) would be: `:g/^/normal $F.hv0:s/\%V\./ /g`**`^M`** where `^M` is entered with `CTRL-V`, `Enter`. This means: for each line (`g/^/`) type `$F.`(go to last dot), visually select from character to the left till beginning of line (`hv0`), and then replace dots (`:s/\./ /g^M`) only inside visual selection (`\%V`).
10,870,527
I'm looking for a way to replace all dots in a line except the last one. Example: `Blah - whatever - foo.bar.baz.avi` should become `Blah - whatever - foo bar bar.avi` Since I'll have more than one line in the file and the amount of dots varies in each line I'm looking for a generic solution and not something like "Replace the first X matches" with X being a constant.
2012/06/03
[ "https://Stackoverflow.com/questions/10870527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298479/" ]
As a variation on the first answer you may prefer this syntax: ``` %s/\.\ze.*\./ /g ``` It let's you put the assertion that there be a following full stop after the search operator.
Another way that might be useful to learn (replace inside visual selection) would be: `:g/^/normal $F.hv0:s/\%V\./ /g`**`^M`** where `^M` is entered with `CTRL-V`, `Enter`. This means: for each line (`g/^/`) type `$F.`(go to last dot), visually select from character to the left till beginning of line (`hv0`), and then replace dots (`:s/\./ /g^M`) only inside visual selection (`\%V`).