qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
132,064 | >
> A blast furnace makes pig iron containing $3.6\% \; \ce{C}$, $1.4\% \; \ce{Si}$, and $95\% \; \ce{Fe}$. The ore is $80\% \; \ce{Fe2O3}$, $12\% \; \ce{SiO2}$, and $\ce{Al2O3}$. The blast furnace gas contains $28\% \; \ce{CO}$ and $12\% \; \ce{CO2}$. Assume that there is no iron loss through the slag. The atomic mass of $\ce{Fe}$, $\ce{Si}$, and $\ce{Ca}$ are $56$, $28$, and $\pu{40 g/mol}$, respectively.
>
>
> 1. What is the weight of the ore used per ton of pig iron?
> 2. What is the volume of the blast furnace gas produced per ton of pig iron?
>
>
>
The first question involved finding the weight of ore used (Exact quote: "The weight of the ore used per ton of pig iron is \_"). I was able to do that using algebraic method to generate equations. The method that I applied was very much similar to [this](https://chemistry.stackexchange.com/questions/40074/finding-moles-of-different-compounds-using-balancing). However, a follow up question is asked about the volume of the blast furnace gas (Exact quote: "The volume of the blast furnace gas produced per ton of pig iron is\_\_\_"). I do not know how to do that. All that I would prefer is to use a similar approach that has been used. | 2020/04/18 | [
"https://chemistry.stackexchange.com/questions/132064",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/71058/"
] | The double bond consists of a sigma and pi bond, which is formed between two p orbitals. When the molecule has enough energy, obtained by random collisions in solution, the pi bond can break leaving just the single sigma bond. At this point should the double bond reform it is as if nothing has happened, however, if there is a slight rotation of the end group when only the single bond exists (close to the transition state) then cis-trans conversion can take place and the pi bond reforms after 180 degree rotation of one half of the molecule.
(Recall that a molecule's bonds vibrate and groups have have bending/ rotational motion also. The actual motion during isomerisation is more complex involving a stretching of the double bond first, which weakens it as the transition state is approached, and then oscillatory motion around the transition state.) | The breaking of double bond requires a sufficently large energy which may also dissociate the compound also first breaking double bond and then again reforming through a reduction reaction is not feasible...pls comment if this helps you |
538,545 | I am interested in recursively grepping for a string in a directory for a pattern and then cp'ing the matching file to a destination directory. I thought I could do something like the following, but it doesn't seem to make sense with linux's find tool:
`find . -type f -exec grep -ilR "MY PATTERN" | xargs cp /dest/dir`
Is there a better way of going about this? Or a way that even works would be a solid start. | 2013/09/12 | [
"https://serverfault.com/questions/538545",
"https://serverfault.com",
"https://serverfault.com/users/19432/"
] | Do `man xargs` and look at the `-I` flag.
```
find . -type f -exec grep -ilR "MY PATTERN" {} \; | xargs -I % cp % /dest/dir/
```
Also, `find` expects a `\;` or `+` after the `-exec` flag. | `xargs` reads its standard input and puts them at the end of the command to be executed. As you've written it, you would end up executing
```
cp /dest/dir sourcefile1 sourcefile2 sourcefile3
```
which is backwards from what you want.
You could use the `-I` option to specify a placeholder for `xargs`, like this: `xargs -I '{}' cp '{}' /dest/dir`.
Also, `find` takes care of the recursion, so your `grep` does not need `-R`.
Final solution:
```
find . -type f -exec grep -il "MY PATTERN" '{}' + | xargs -I '{}' cp '{}' /dest/dir
``` |
538,545 | I am interested in recursively grepping for a string in a directory for a pattern and then cp'ing the matching file to a destination directory. I thought I could do something like the following, but it doesn't seem to make sense with linux's find tool:
`find . -type f -exec grep -ilR "MY PATTERN" | xargs cp /dest/dir`
Is there a better way of going about this? Or a way that even works would be a solid start. | 2013/09/12 | [
"https://serverfault.com/questions/538545",
"https://serverfault.com",
"https://serverfault.com/users/19432/"
] | Do `man xargs` and look at the `-I` flag.
```
find . -type f -exec grep -ilR "MY PATTERN" {} \; | xargs -I % cp % /dest/dir/
```
Also, `find` expects a `\;` or `+` after the `-exec` flag. | I don't think you need find. Recursive grep:
```
grep -rl "MY PATTERN" .
``` |
538,545 | I am interested in recursively grepping for a string in a directory for a pattern and then cp'ing the matching file to a destination directory. I thought I could do something like the following, but it doesn't seem to make sense with linux's find tool:
`find . -type f -exec grep -ilR "MY PATTERN" | xargs cp /dest/dir`
Is there a better way of going about this? Or a way that even works would be a solid start. | 2013/09/12 | [
"https://serverfault.com/questions/538545",
"https://serverfault.com",
"https://serverfault.com/users/19432/"
] | Do `man xargs` and look at the `-I` flag.
```
find . -type f -exec grep -ilR "MY PATTERN" {} \; | xargs -I % cp % /dest/dir/
```
Also, `find` expects a `\;` or `+` after the `-exec` flag. | None of the examples above takes into account the possibility of `grep`'s `-l` generating duplicated results (files with the same name, but in different places), and therefore `find`'s `exec`'s hook overwriting files in the destination directory.
An attempt to solve this:
```
$ tree foo
foo
├── bar
│ ├── baz
│ │ └── file
│ └── file
├── destdir
└── file
3 directories, 3 files
$ while read a; do mv $a foo/destdir/$(basename $a).$RANDOM; done < <(grep -rl content foo)
$ tree foo
foo
├── bar
│ └── baz
└── destdir
├── file.10171
├── file.10842
└── file.25404
3 directories, 3 files
``` |
555,474 | I was asking myself how I can ease writing of long commands/phrases that are used very often in the exact same way.
Example: How can I write the following:
```
\begin{mdframed}\begin{lstlisting}[style=mystyle]
bla bla bla
\end{lstlisting}\end{mdframed}
```
In a shorter way like:
```
\mycommand{
bla bla bla
}
```
**Edit:**
As requested I will add an update to my origin question below:
Here is the missing style definition:
```
\lstdefinestyle{mystyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0
}
```
So as you can see I also want to have the option for mathescape inside in order to do stuff like:
```
\mycommand{
bla bla bla $1+2=3$
}
```
Which should **not** result into text `"$1+2=3$"` but into `1+2=3` as math interpretation. | 2020/07/29 | [
"https://tex.stackexchange.com/questions/555474",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/214232/"
] | I'd not recommend making the `mdframed`–`lstlisting` into a command with argument instead of a proper environment.
For one thing, line breaks ***cannot*** be preserved in the argument version.
I'd also suggest `tcolorbox` rather than `mdframed`, because it offers better integration with `listings`. Anyway, you can do
```latex
\documentclass{article}
\usepackage{listings,mdframed}
\lstnewenvironment{mylisting}
{\mdframed\lstset{}}
{\endmdframed}
\begin{document}
\begin{mylisting}
bla bla bla
\end{mylisting}
\end{document}
```
Note the auxiliary commands `\mdframed` and `\endmdframed`, otherwise the `\lstnewenvironment` declaration would produce something that doesn't work at all. I removed `style=mystyle` because I have no idea of how the style is defined. Add all the necessary options you need in the argument of `\lstset`.
### Extended version with a style
```latex
\documentclass{article}
\usepackage{listings,mdframed}
\usepackage[svgnames]{xcolor}
\lstdefinestyle{tmstyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0,
}
\lstnewenvironment{mylisting}
{\mdframed\lstset{style=tmstyle}}
{\endmdframed}
\begin{document}
\begin{mylisting}
Send bla bla bla $1+2=3$
\end{mylisting}
\end{document}
```
[](https://i.stack.imgur.com/kQLno.png) | In general, you can do something like this:
```
\newcommand{\mycommand}[1]{
\begin{environment}
#1
\end{environment}
}
```
However, the `lstlisting` environment relies on changing category codes to work so the category codes won't be what they need to be when the argument is expanded.
Fortunately, this is something that was foreseen as an issue. Instead, you'll need to use the `\lstnewenvironment` command so you could do something like:
```
\lstnewenvironment{mylisting}
{\begin{mdframed}\lstset{style=mystyle}}
{\end{mdframed}}
```
and then use it with
```
\begin{mylisting}
bla bla bla
\end{mylisting}
``` |
555,474 | I was asking myself how I can ease writing of long commands/phrases that are used very often in the exact same way.
Example: How can I write the following:
```
\begin{mdframed}\begin{lstlisting}[style=mystyle]
bla bla bla
\end{lstlisting}\end{mdframed}
```
In a shorter way like:
```
\mycommand{
bla bla bla
}
```
**Edit:**
As requested I will add an update to my origin question below:
Here is the missing style definition:
```
\lstdefinestyle{mystyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0
}
```
So as you can see I also want to have the option for mathescape inside in order to do stuff like:
```
\mycommand{
bla bla bla $1+2=3$
}
```
Which should **not** result into text `"$1+2=3$"` but into `1+2=3` as math interpretation. | 2020/07/29 | [
"https://tex.stackexchange.com/questions/555474",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/214232/"
] | With the upcoming LaTeX kernel, due to be released in October, you can add to 'hooks' to achieve this. For example
```
\documentclass{article}
\usepackage{listings}
\usepackage{mdframed}
\AddToHook{env/lstlisting/before}{\begin{mdframed}}
\AddToHook{env/lstlisting/after}{\end{mdframed}}
\begin{document}
\begin{lstlisting}
bla bla bla
\end{lstlisting}
\end{document}
```
(You'll need to run e.g. `pdflatex-dev` at present for this to work: that uses the pre-release version of the kernel.) | In general, you can do something like this:
```
\newcommand{\mycommand}[1]{
\begin{environment}
#1
\end{environment}
}
```
However, the `lstlisting` environment relies on changing category codes to work so the category codes won't be what they need to be when the argument is expanded.
Fortunately, this is something that was foreseen as an issue. Instead, you'll need to use the `\lstnewenvironment` command so you could do something like:
```
\lstnewenvironment{mylisting}
{\begin{mdframed}\lstset{style=mystyle}}
{\end{mdframed}}
```
and then use it with
```
\begin{mylisting}
bla bla bla
\end{mylisting}
``` |
555,474 | I was asking myself how I can ease writing of long commands/phrases that are used very often in the exact same way.
Example: How can I write the following:
```
\begin{mdframed}\begin{lstlisting}[style=mystyle]
bla bla bla
\end{lstlisting}\end{mdframed}
```
In a shorter way like:
```
\mycommand{
bla bla bla
}
```
**Edit:**
As requested I will add an update to my origin question below:
Here is the missing style definition:
```
\lstdefinestyle{mystyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0
}
```
So as you can see I also want to have the option for mathescape inside in order to do stuff like:
```
\mycommand{
bla bla bla $1+2=3$
}
```
Which should **not** result into text `"$1+2=3$"` but into `1+2=3` as math interpretation. | 2020/07/29 | [
"https://tex.stackexchange.com/questions/555474",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/214232/"
] | I'd not recommend making the `mdframed`–`lstlisting` into a command with argument instead of a proper environment.
For one thing, line breaks ***cannot*** be preserved in the argument version.
I'd also suggest `tcolorbox` rather than `mdframed`, because it offers better integration with `listings`. Anyway, you can do
```latex
\documentclass{article}
\usepackage{listings,mdframed}
\lstnewenvironment{mylisting}
{\mdframed\lstset{}}
{\endmdframed}
\begin{document}
\begin{mylisting}
bla bla bla
\end{mylisting}
\end{document}
```
Note the auxiliary commands `\mdframed` and `\endmdframed`, otherwise the `\lstnewenvironment` declaration would produce something that doesn't work at all. I removed `style=mystyle` because I have no idea of how the style is defined. Add all the necessary options you need in the argument of `\lstset`.
### Extended version with a style
```latex
\documentclass{article}
\usepackage{listings,mdframed}
\usepackage[svgnames]{xcolor}
\lstdefinestyle{tmstyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0,
}
\lstnewenvironment{mylisting}
{\mdframed\lstset{style=tmstyle}}
{\endmdframed}
\begin{document}
\begin{mylisting}
Send bla bla bla $1+2=3$
\end{mylisting}
\end{document}
```
[](https://i.stack.imgur.com/kQLno.png) | With the upcoming LaTeX kernel, due to be released in October, you can add to 'hooks' to achieve this. For example
```
\documentclass{article}
\usepackage{listings}
\usepackage{mdframed}
\AddToHook{env/lstlisting/before}{\begin{mdframed}}
\AddToHook{env/lstlisting/after}{\end{mdframed}}
\begin{document}
\begin{lstlisting}
bla bla bla
\end{lstlisting}
\end{document}
```
(You'll need to run e.g. `pdflatex-dev` at present for this to work: that uses the pre-release version of the kernel.) |
555,474 | I was asking myself how I can ease writing of long commands/phrases that are used very often in the exact same way.
Example: How can I write the following:
```
\begin{mdframed}\begin{lstlisting}[style=mystyle]
bla bla bla
\end{lstlisting}\end{mdframed}
```
In a shorter way like:
```
\mycommand{
bla bla bla
}
```
**Edit:**
As requested I will add an update to my origin question below:
Here is the missing style definition:
```
\lstdefinestyle{mystyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0
}
```
So as you can see I also want to have the option for mathescape inside in order to do stuff like:
```
\mycommand{
bla bla bla $1+2=3$
}
```
Which should **not** result into text `"$1+2=3$"` but into `1+2=3` as math interpretation. | 2020/07/29 | [
"https://tex.stackexchange.com/questions/555474",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/214232/"
] | I'd not recommend making the `mdframed`–`lstlisting` into a command with argument instead of a proper environment.
For one thing, line breaks ***cannot*** be preserved in the argument version.
I'd also suggest `tcolorbox` rather than `mdframed`, because it offers better integration with `listings`. Anyway, you can do
```latex
\documentclass{article}
\usepackage{listings,mdframed}
\lstnewenvironment{mylisting}
{\mdframed\lstset{}}
{\endmdframed}
\begin{document}
\begin{mylisting}
bla bla bla
\end{mylisting}
\end{document}
```
Note the auxiliary commands `\mdframed` and `\endmdframed`, otherwise the `\lstnewenvironment` declaration would produce something that doesn't work at all. I removed `style=mystyle` because I have no idea of how the style is defined. Add all the necessary options you need in the argument of `\lstset`.
### Extended version with a style
```latex
\documentclass{article}
\usepackage{listings,mdframed}
\usepackage[svgnames]{xcolor}
\lstdefinestyle{tmstyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0,
}
\lstnewenvironment{mylisting}
{\mdframed\lstset{style=tmstyle}}
{\endmdframed}
\begin{document}
\begin{mylisting}
Send bla bla bla $1+2=3$
\end{mylisting}
\end{document}
```
[](https://i.stack.imgur.com/kQLno.png) | As long as `\mycommand` is used on document-level only, not from within arguments of other macros, not from within definition-texts of other macros, not from within token-registers, not as part of a a moving argument, you can have LaTeX read things as verbatim-arguments and pass these to `\scantokens`.
But I cannot recommend this because indenting the code that is to be displayed will definitely not be easier this way:
```
\documentclass{article}
\usepackage{xparse}
\usepackage{listings}
\usepackage{mdframed}
\lstdefinestyle{mystyle}{%
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0
}
\newcommand\mycommand{%
\begingroup
\catcode`\^^I=12 %
\newlinechar=\endlinechar
\MyReadVerbatimArgument
}%
\begingroup
\NewDocumentCommand\MyReadVerbatimArgument{+v +v}{%
\endgroup
\NewDocumentCommand\MyReadVerbatimArgument{+v}{%
\scantokens{\endgroup#1##1#2}%
}%
}%
\MyReadVerbatimArgument|\begin{mdframed}
\begin{lstlisting}[style=mystyle]
||
\end{lstlisting}
\end{mdframed}
%|
\begin{document}
\mycommand{bla bla bla
bla bla bla
bla bla bla}
\end{document}
```
[](https://i.stack.imgur.com/RaG6a.jpg)
---
---
If you wish, this can be extended to remove a leading endline-character from the entire verbatim-argument if present and a trailing endline-character from the entire verbatim-argument if present.
This way
```
\mycommand{
bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla
}
```
and
```
\mycommand{ bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla
}
```
and
```
\mycommand{
bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla}
```
and
```
\mycommand{ bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla}
```
will all yield the same output.
The tricks for removing a leading/trailing endline-character, i.e., a leading/trailing `^^M`-character of category code 12(other)=a leading/trailing return-character of category code 12(other) are the same as the tricks for a removing leading/trailing space-token from a macro-argument.
With the helper-macros just don't use space-tokens as argument-delimiters but use explicit return-character-tokens of category code 12(other).
The latter (removal of a leading/trailing space) is discussed in Exercise 15 of Michael Downes' "Around the Bend"-collection of TeX challenges.
A pdf-file by Peter Wilson containing all challenges/exercises and all solutions/answers belonging to the "Around the Bend"-collection of TeX challenges can be found at:
[http://mirrors.ctan.org/info/challenges/AroBend/AroundTheBend.pdf](http://mirrors.ctan.org/info/challenges/AroBend/AroundTheBend.pdf#chapter.15)
The original text of the challenge/exercise can be found at:
<http://mirrors.ctan.org/info/challenges/aro-bend/exercise.015>
The original text of the discussion of submitted solutions/answers can be found at:
<http://mirrors.ctan.org/info/challenges/aro-bend/answer.015>
```
\documentclass{article}
\usepackage{xparse}
\usepackage{listings}
\usepackage{mdframed}
%%/////////////////////////////////////////////////////////////////////////////
%% Begin of code for \UDRemoveLeadingNTrailingEndl
%%/////////////////////////////////////////////////////////////////////////////
\makeatletter
%%=============================================================================
%% Check whether argument is empty:
%%=============================================================================
%% \UD@CheckWhetherNull{<Argument which is to be checked>}%
%% {<Tokens to be delivered in case that argument
%% which is to be checked is empty>}%
%% {<Tokens to be delivered in case that argument
%% which is to be checked is not empty>}%
\newcommand\UD@CheckWhetherNull[1]{%
\romannumeral0\if\relax\detokenize{#1}\relax
\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi
{\@firstoftwo{\expandafter}{} \@firstoftwo}%
{\@firstoftwo{\expandafter}{} \@secondoftwo}%
}%
%%=============================================================================
%% Exchange arguments
%%=============================================================================
\newcommand\UDExchange[2]{#2#1}%
\begingroup
% Dummy-definition, will be overridden. Is used only to get ^^M of
% category code 12(other) as #1 into subsequent definition-texts:
\NewDocumentCommand\UD@CheckWhetherLeadingEndl{+m}{%
\endgroup
%%===========================================================================
%% Check whether_verbatimized_ argument starts with a endline-character
%%===========================================================================
%% \UD@CheckWhetherLeadingEndl{<Argument which is to be checked>}%
%% {<Tokens to be delivered in case <argument
%% which is to be checked>'s 1st token is a
%% endline-charactern>}%
%% {<Tokens to be delivered in case <argument
%% which is to be checked>'s 1st token is not
%% a endline-character>}%
\newcommand\UD@CheckWhetherLeadingEndl[1]{%
\UD@@CheckWhetherLeadingEndl\UD@SelDom##1\UD@SelDom#1\UD@@SelDom
}%
\@ifdefinable\UD@@CheckWhetherLeadingEndl{%
\long\def\UD@@CheckWhetherLeadingEndl##1\UD@SelDom#1##2\UD@@SelDom{%
\UD@CheckWhetherNull{##2}{\@secondoftwo}{\@firstoftwo}%
}%
}%
%%===========================================================================
%% Remove one leading endline-character from _verbatimized_ argument
%%===========================================================================
\@ifdefinable\UD@@TrimLeadingEndl{\long\def\UD@@TrimLeadingEndl#1{}}%
%%===========================================================================
%% Check whether _verbatimized_ argument ends with a endline-character
%%===========================================================================
%% \UD@CheckWhetherTrailingEndl{<Argument which is to be checked>}%
%% {<Tokens to be delivered in case <argument
%% which is to be checked>'s last token is a
%% endline-charactern>}%
%% {<Tokens to be delivered in case <argument
%% which is to be checked>'s last token is not
%% a endline-character>}%
\newcommand\UD@CheckWhetherTrailingEndl[1]{%
\UD@@CheckWhetherTrailingEndl##1\UD@SelDom#1\UD@SelDom\UD@@SelDom
}%
\@ifdefinable\UD@@CheckWhetherTrailingEndl{%
\long\def\UD@@CheckWhetherTrailingEndl##1#1\UD@SelDom##2\UD@@SelDom{%
\UD@CheckWhetherNull{##2}{\@secondoftwo}{\@firstoftwo}%
}%
}%
%%===========================================================================
%% Remove one trailing endline-character from _verbatimized_ argument
%%===========================================================================
\newcommand\UD@TrimTrailingEndl[1]{\UD@@TrimTrailingEndl##1\UD@SelDom}%
\@ifdefinable\UD@@TrimTrailingEndl{%
\long\def\UD@@TrimTrailingEndl##1#1\UD@SelDom{##1}%
}%
%%===========================================================================
%% Remove one leading and one trailing endline-character from _verbatimized_
%% argument if present. Due to \romannumeral0-expansion the result is
%% delivered in 2 expansion-steps:
%%===========================================================================
\newcommand\UDRemoveLeadingNTrailingEndl[1]{%
\romannumeral0%
\UD@CheckWhetherLeadingEndl{##1}{%
\UD@CheckWhetherTrailingEndl{##1}{%
\UDExchange{ }{%
\expandafter\expandafter\expandafter\expandafter
\expandafter\expandafter\expandafter
}%
\expandafter\UD@TrimTrailingEndl\expandafter{\UD@@TrimLeadingEndl##1}%
}{%
\UDExchange{ }{\expandafter}%
\UD@@TrimLeadingEndl##1%
}%
}{%
\UD@CheckWhetherTrailingEndl{##1}{%
\UDExchange{ }{\expandafter\expandafter\expandafter}%
\UD@TrimTrailingEndl{##1}%
}{ ##1}%
}%
}%
}%
%%-----------------------------------------------------------------------------
%% Now let's change the catcode of ^^M and then call the dummy-definition
%% of \UD@CheckWhetherLeadingEndl so that it can fetch the catcode-12-^^M,
%% close the group, override itself and define all those macros where that
%% catcode-12-^^M is needed:
\catcode`\^^M=12 %
\UD@CheckWhetherLeadingEndl{^^M}%
\makeatother
%%/////////////////////////////////////////////////////////////////////////////
%% End of code for \UDRemoveLeadingNTrailingEndl
%%/////////////////////////////////////////////////////////////////////////////
\lstdefinestyle{mystyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0
}
\newcommand\mycommand{%
\begingroup
\catcode`\^^I=12 %
\newlinechar=\endlinechar
\MyReadVerbatimArgument
}%
\begingroup
\NewDocumentCommand\MyReadVerbatimArgument{+v +v}{%
\endgroup
\NewDocumentCommand\MyReadVerbatimArgument{+v}{%
\scantokens\expandafter{\romannumeral0%
\expandafter\expandafter\expandafter\UDExchange
\expandafter\expandafter\expandafter{%
\UDRemoveLeadingNTrailingEndl{##1}%
}{ \endgroup#1}#2}%
}%
}%
\MyReadVerbatimArgument|\begin{mdframed}
\begin{lstlisting}[style=mystyle]
||
\end{lstlisting}
\end{mdframed}
%|
\begin{document}
\mycommand{
bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla
}
\mycommand{ bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla
}
\mycommand{
bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla}
\mycommand{ bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla}
\end{document}
```
[](https://i.stack.imgur.com/XVlh2.jpg)
*Some remarks about subtleties with the ways in which TeX works:*
*TeX's mechanism for reading and tokenizing input in any case discards all space-characters at the end of a line of .tex-input and then adds a character whose coding-point-number in the TeX-engine's internal character-encoding scheme (which either is ASCII with traditional engines or is UTF‑8/Unicode with engines based on XeTeX/LuaTeX; ASCII can be considered a strict subset of Unicode) equals the value of the integer-parameter `\endlinechar` before starting to tokenize that line. Usually the value of the `\endlinechar`-parameter is 13, denoting the return-character which in TeX's `^^`-notation is also accessible as `^^M`. (M is the 13th letter in the latin alphabet.)*
*This implies that .tex-input-lines containing space-characters (ASCII 32(dec)/Unicode 32(dec)) only will in any case be treated as empty lines.*
*This also implies that with .tex-input-lines ending with space-characters (ASCII 32(dec)/Unicode 32(dec)) these space-characters will be discarded.
You can test this by putting lines of text that end with a sequence of space-characters into the `verbatim*`-environment.* |
555,474 | I was asking myself how I can ease writing of long commands/phrases that are used very often in the exact same way.
Example: How can I write the following:
```
\begin{mdframed}\begin{lstlisting}[style=mystyle]
bla bla bla
\end{lstlisting}\end{mdframed}
```
In a shorter way like:
```
\mycommand{
bla bla bla
}
```
**Edit:**
As requested I will add an update to my origin question below:
Here is the missing style definition:
```
\lstdefinestyle{mystyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0
}
```
So as you can see I also want to have the option for mathescape inside in order to do stuff like:
```
\mycommand{
bla bla bla $1+2=3$
}
```
Which should **not** result into text `"$1+2=3$"` but into `1+2=3` as math interpretation. | 2020/07/29 | [
"https://tex.stackexchange.com/questions/555474",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/214232/"
] | With the upcoming LaTeX kernel, due to be released in October, you can add to 'hooks' to achieve this. For example
```
\documentclass{article}
\usepackage{listings}
\usepackage{mdframed}
\AddToHook{env/lstlisting/before}{\begin{mdframed}}
\AddToHook{env/lstlisting/after}{\end{mdframed}}
\begin{document}
\begin{lstlisting}
bla bla bla
\end{lstlisting}
\end{document}
```
(You'll need to run e.g. `pdflatex-dev` at present for this to work: that uses the pre-release version of the kernel.) | As long as `\mycommand` is used on document-level only, not from within arguments of other macros, not from within definition-texts of other macros, not from within token-registers, not as part of a a moving argument, you can have LaTeX read things as verbatim-arguments and pass these to `\scantokens`.
But I cannot recommend this because indenting the code that is to be displayed will definitely not be easier this way:
```
\documentclass{article}
\usepackage{xparse}
\usepackage{listings}
\usepackage{mdframed}
\lstdefinestyle{mystyle}{%
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0
}
\newcommand\mycommand{%
\begingroup
\catcode`\^^I=12 %
\newlinechar=\endlinechar
\MyReadVerbatimArgument
}%
\begingroup
\NewDocumentCommand\MyReadVerbatimArgument{+v +v}{%
\endgroup
\NewDocumentCommand\MyReadVerbatimArgument{+v}{%
\scantokens{\endgroup#1##1#2}%
}%
}%
\MyReadVerbatimArgument|\begin{mdframed}
\begin{lstlisting}[style=mystyle]
||
\end{lstlisting}
\end{mdframed}
%|
\begin{document}
\mycommand{bla bla bla
bla bla bla
bla bla bla}
\end{document}
```
[](https://i.stack.imgur.com/RaG6a.jpg)
---
---
If you wish, this can be extended to remove a leading endline-character from the entire verbatim-argument if present and a trailing endline-character from the entire verbatim-argument if present.
This way
```
\mycommand{
bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla
}
```
and
```
\mycommand{ bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla
}
```
and
```
\mycommand{
bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla}
```
and
```
\mycommand{ bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla}
```
will all yield the same output.
The tricks for removing a leading/trailing endline-character, i.e., a leading/trailing `^^M`-character of category code 12(other)=a leading/trailing return-character of category code 12(other) are the same as the tricks for a removing leading/trailing space-token from a macro-argument.
With the helper-macros just don't use space-tokens as argument-delimiters but use explicit return-character-tokens of category code 12(other).
The latter (removal of a leading/trailing space) is discussed in Exercise 15 of Michael Downes' "Around the Bend"-collection of TeX challenges.
A pdf-file by Peter Wilson containing all challenges/exercises and all solutions/answers belonging to the "Around the Bend"-collection of TeX challenges can be found at:
[http://mirrors.ctan.org/info/challenges/AroBend/AroundTheBend.pdf](http://mirrors.ctan.org/info/challenges/AroBend/AroundTheBend.pdf#chapter.15)
The original text of the challenge/exercise can be found at:
<http://mirrors.ctan.org/info/challenges/aro-bend/exercise.015>
The original text of the discussion of submitted solutions/answers can be found at:
<http://mirrors.ctan.org/info/challenges/aro-bend/answer.015>
```
\documentclass{article}
\usepackage{xparse}
\usepackage{listings}
\usepackage{mdframed}
%%/////////////////////////////////////////////////////////////////////////////
%% Begin of code for \UDRemoveLeadingNTrailingEndl
%%/////////////////////////////////////////////////////////////////////////////
\makeatletter
%%=============================================================================
%% Check whether argument is empty:
%%=============================================================================
%% \UD@CheckWhetherNull{<Argument which is to be checked>}%
%% {<Tokens to be delivered in case that argument
%% which is to be checked is empty>}%
%% {<Tokens to be delivered in case that argument
%% which is to be checked is not empty>}%
\newcommand\UD@CheckWhetherNull[1]{%
\romannumeral0\if\relax\detokenize{#1}\relax
\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi
{\@firstoftwo{\expandafter}{} \@firstoftwo}%
{\@firstoftwo{\expandafter}{} \@secondoftwo}%
}%
%%=============================================================================
%% Exchange arguments
%%=============================================================================
\newcommand\UDExchange[2]{#2#1}%
\begingroup
% Dummy-definition, will be overridden. Is used only to get ^^M of
% category code 12(other) as #1 into subsequent definition-texts:
\NewDocumentCommand\UD@CheckWhetherLeadingEndl{+m}{%
\endgroup
%%===========================================================================
%% Check whether_verbatimized_ argument starts with a endline-character
%%===========================================================================
%% \UD@CheckWhetherLeadingEndl{<Argument which is to be checked>}%
%% {<Tokens to be delivered in case <argument
%% which is to be checked>'s 1st token is a
%% endline-charactern>}%
%% {<Tokens to be delivered in case <argument
%% which is to be checked>'s 1st token is not
%% a endline-character>}%
\newcommand\UD@CheckWhetherLeadingEndl[1]{%
\UD@@CheckWhetherLeadingEndl\UD@SelDom##1\UD@SelDom#1\UD@@SelDom
}%
\@ifdefinable\UD@@CheckWhetherLeadingEndl{%
\long\def\UD@@CheckWhetherLeadingEndl##1\UD@SelDom#1##2\UD@@SelDom{%
\UD@CheckWhetherNull{##2}{\@secondoftwo}{\@firstoftwo}%
}%
}%
%%===========================================================================
%% Remove one leading endline-character from _verbatimized_ argument
%%===========================================================================
\@ifdefinable\UD@@TrimLeadingEndl{\long\def\UD@@TrimLeadingEndl#1{}}%
%%===========================================================================
%% Check whether _verbatimized_ argument ends with a endline-character
%%===========================================================================
%% \UD@CheckWhetherTrailingEndl{<Argument which is to be checked>}%
%% {<Tokens to be delivered in case <argument
%% which is to be checked>'s last token is a
%% endline-charactern>}%
%% {<Tokens to be delivered in case <argument
%% which is to be checked>'s last token is not
%% a endline-character>}%
\newcommand\UD@CheckWhetherTrailingEndl[1]{%
\UD@@CheckWhetherTrailingEndl##1\UD@SelDom#1\UD@SelDom\UD@@SelDom
}%
\@ifdefinable\UD@@CheckWhetherTrailingEndl{%
\long\def\UD@@CheckWhetherTrailingEndl##1#1\UD@SelDom##2\UD@@SelDom{%
\UD@CheckWhetherNull{##2}{\@secondoftwo}{\@firstoftwo}%
}%
}%
%%===========================================================================
%% Remove one trailing endline-character from _verbatimized_ argument
%%===========================================================================
\newcommand\UD@TrimTrailingEndl[1]{\UD@@TrimTrailingEndl##1\UD@SelDom}%
\@ifdefinable\UD@@TrimTrailingEndl{%
\long\def\UD@@TrimTrailingEndl##1#1\UD@SelDom{##1}%
}%
%%===========================================================================
%% Remove one leading and one trailing endline-character from _verbatimized_
%% argument if present. Due to \romannumeral0-expansion the result is
%% delivered in 2 expansion-steps:
%%===========================================================================
\newcommand\UDRemoveLeadingNTrailingEndl[1]{%
\romannumeral0%
\UD@CheckWhetherLeadingEndl{##1}{%
\UD@CheckWhetherTrailingEndl{##1}{%
\UDExchange{ }{%
\expandafter\expandafter\expandafter\expandafter
\expandafter\expandafter\expandafter
}%
\expandafter\UD@TrimTrailingEndl\expandafter{\UD@@TrimLeadingEndl##1}%
}{%
\UDExchange{ }{\expandafter}%
\UD@@TrimLeadingEndl##1%
}%
}{%
\UD@CheckWhetherTrailingEndl{##1}{%
\UDExchange{ }{\expandafter\expandafter\expandafter}%
\UD@TrimTrailingEndl{##1}%
}{ ##1}%
}%
}%
}%
%%-----------------------------------------------------------------------------
%% Now let's change the catcode of ^^M and then call the dummy-definition
%% of \UD@CheckWhetherLeadingEndl so that it can fetch the catcode-12-^^M,
%% close the group, override itself and define all those macros where that
%% catcode-12-^^M is needed:
\catcode`\^^M=12 %
\UD@CheckWhetherLeadingEndl{^^M}%
\makeatother
%%/////////////////////////////////////////////////////////////////////////////
%% End of code for \UDRemoveLeadingNTrailingEndl
%%/////////////////////////////////////////////////////////////////////////////
\lstdefinestyle{mystyle}{
language = C,
basicstyle=\footnotesize\ttfamily,
keywordstyle = {\color{DarkGreen}\bfseries},
morekeywords = {Send,Receive},
mathescape=true,
columns=fullflexible,
prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\rhookswarrow}},
breakindent=0
}
\newcommand\mycommand{%
\begingroup
\catcode`\^^I=12 %
\newlinechar=\endlinechar
\MyReadVerbatimArgument
}%
\begingroup
\NewDocumentCommand\MyReadVerbatimArgument{+v +v}{%
\endgroup
\NewDocumentCommand\MyReadVerbatimArgument{+v}{%
\scantokens\expandafter{\romannumeral0%
\expandafter\expandafter\expandafter\UDExchange
\expandafter\expandafter\expandafter{%
\UDRemoveLeadingNTrailingEndl{##1}%
}{ \endgroup#1}#2}%
}%
}%
\MyReadVerbatimArgument|\begin{mdframed}
\begin{lstlisting}[style=mystyle]
||
\end{lstlisting}
\end{mdframed}
%|
\begin{document}
\mycommand{
bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla
}
\mycommand{ bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla
}
\mycommand{
bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla}
\mycommand{ bla bla bla
bla bla bla
This line is not indented.
bla bla bla
bla bla bla}
\end{document}
```
[](https://i.stack.imgur.com/XVlh2.jpg)
*Some remarks about subtleties with the ways in which TeX works:*
*TeX's mechanism for reading and tokenizing input in any case discards all space-characters at the end of a line of .tex-input and then adds a character whose coding-point-number in the TeX-engine's internal character-encoding scheme (which either is ASCII with traditional engines or is UTF‑8/Unicode with engines based on XeTeX/LuaTeX; ASCII can be considered a strict subset of Unicode) equals the value of the integer-parameter `\endlinechar` before starting to tokenize that line. Usually the value of the `\endlinechar`-parameter is 13, denoting the return-character which in TeX's `^^`-notation is also accessible as `^^M`. (M is the 13th letter in the latin alphabet.)*
*This implies that .tex-input-lines containing space-characters (ASCII 32(dec)/Unicode 32(dec)) only will in any case be treated as empty lines.*
*This also implies that with .tex-input-lines ending with space-characters (ASCII 32(dec)/Unicode 32(dec)) these space-characters will be discarded.
You can test this by putting lines of text that end with a sequence of space-characters into the `verbatim*`-environment.* |
71,820,908 | I want to hit an API inside my cloud functions so I'm using `axios` to make my http multipart/form-data post request.
When I by-pass my cloud functions and put my endpoint API directly inside Postman, everything works as expected.
But when I put the function endpoint in Postman, it fails.
I also took a look at the node-js axios code builder in Postman and my code should be correct.
I read all others related posts but unable to solve my issue.
I also read this document from Google <https://cloud.google.com/blog/topics/developers-practitioners/avoiding-gcf-anti-patterns-part-4-how-handle-promises-correctly-your-nodejs-cloud-function> and I noticed that I have almost the same request, at the only difference that mine fails.
I thought that it was `axios` but replacing it by `node-fetch` didn't change anything.
Any help would be appreciated.
Here is my function :
```
exports.submit = functions.https.onRequest(async (req, res) => {
try {
const form = new FormData();
form.append('holder', '{firstName:XXX, birthName:XXXX, birthDate:XXXX-XX-XX}');
const response = await axios({
method: 'post',
url: 'https://integration.xxx.io/v2',
data: form,
headers: {
'accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': 'Basic XXX=',
},
});
console.log(response);
res.status(200).send({
success: true,
data: response.data
});
} catch (error) {
console.log(error);
res.status(400).send({
success: false,
error: error,
});
}
});
```
The error printed on Postman :
```
{
"success": false,
"error": {
"message": "socket hang up",
"name": "Error",
"stack": "Error: socket hang up\n at connResetException (node:internal/errors:691:14)\n at TLSSocket.socketOnEnd (node:_http_client:471:23)\n at TLSSocket.emit (node:events:402:35)\n at TLSSocket.emit (node:domain:537:15)\n at endReadableNT (node:internal/streams/readable:1343:12)\n at processTicksAndRejections (node:internal/process/task_queues:83:21)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"headers": {
"Accept": "application/json",
"Content-Type": "multipart/form-data",
"Authorization": "Basic XXX=",
"User-Agent": "axios/0.26.1"
},
"method": "post",
"url": "https://integration.xxx.io/v2",
"data": {
"_overheadLength": 211,
"_valueLength": 120,
"_valuesToMeasure": [],
"writable": false,
"readable": true,
"dataSize": 0,
"maxDataSize": 2097152,
"pauseStreams": true,
"_released": true,
"_streams": [],
"_currentStream": null,
"_insideLoop": false,
"_pendingNext": false,
"_boundary": "--------------------------045202360965403790737146",
"_events": {},
"_eventsCount": 1
}
},
"code": "ECONNRESET",
"status": null
},
```
**EDIT:** Adding Cloud functions logs
```
submit
Error: socket hang up
at connResetException(node: internal / errors: 691: 14)
at TLSSocket.socketOnEnd(node: _http_client: 471: 23)
at TLSSocket.emit(node: events: 402: 35)
at TLSSocket.emit(node: domain: 537: 15)
at endReadableNT(node: internal / streams / readable: 1343: 12)
at processTicksAndRejections(node: internal / process / task_queues: 83: 21) {
code: 'ECONNRESET',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [
[Function: transformRequest]
],
transformResponse: [
[Function: transformResponse]
],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
Authorization: 'Basic XXX=',
'User-Agent': 'axios/0.26.1'
},
method: 'post',
url: 'https://integration.xxx.io/v2',
data: FormData {
_overheadLength: 211,
_valueLength: 120,
_valuesToMeasure: [],
writable: false,
readable: true,
dataSize: 0,
maxDataSize: 2097152,
pauseStreams: true,
_released: true,
_streams: [],
_currentStream: null,
_insideLoop: false,
_pendingNext: false,
_boundary: '--------------------------196369661580838061893871',
_events: [Object: null prototype],
_eventsCount: 1
}
},
request: < ref * 1 > Writable {
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
afterWriteTickInfo: null,
buffered: [],
bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 0,
constructed: true,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
errored: null,
closed: false,
closeEmitted: false,
[Symbol(kOnFinished)]: []
},
_events: [Object: null prototype] {
response: [Function: handleResponse],
error: [Function: handleRequestError],
socket: [Function: handleRequestSocket]
},
_eventsCount: 3,
_maxListeners: undefined,
_options: {
maxRedirects: 21,
maxBodyLength: 10485760,
protocol: 'https:',
path: '/v2',
method: 'POST',
headers: [Object],
agent: undefined,
agents: [Object],
auth: undefined,
hostname: 'integration.xxx.io',
port: null,
nativeProtocols: [Object],
pathname: '/v2'
},
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 387,
_requestBodyBuffers: [
[Object],
[Object],
[Object],
[Object],
[Object],
[Object]
],
_onNativeResponse: [Function(anonymous)],
_currentRequest: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: true,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: [TLSSocket],
_header: 'POST /v2 HTTP/1.1\r\n' +
'Accept: application/json\r\n' +
'Content-Type: multipart/form-data\r\n' +
'Authorization: Basic XXX=\r\n' +
'User-Agent: axios/0.26.1\r\n' +
'Host: integration.xxx.io\r\n' +
'Connection: close\r\n' +
'Transfer-Encoding: chunked\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/v2',
_ended: false,
res: null,
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'integration.xxx.io',
protocol: 'https:',
_redirectable: [Circular * 1],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
_currentUrl: 'https://integration.xxx.io/v2',
[Symbol(kCapture)]: false
},
response: undefined,
isAxiosError: true,
toJSON: [Function: toJSON]
}
Function execution took 1127 ms. Finished with status: response error
``` | 2022/04/10 | [
"https://Stackoverflow.com/questions/71820908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13775978/"
] | Ok, so after one whole day lost looking for the solution, for others facing the same issue, this is my workaround :
As my logs pointed out showing an axios error `isAxiosError: true`, I decided to replace `axios` by `unirest` npm package. There is couple of HTTP librairies in npm using approximatively the same methodology (take a look to this answer : <https://stackoverflow.com/a/55841420/13775978>).
So, I still don't know where I'm wrong using the axios package, but works as expected using `unirest` package. It doesn't look like a cloud function error.
I accept this answer until a real solution is suggested.
Here is my functional function using `unirest`:
```
exports.submit = functions.https.onRequest(async (req, res) => {
try {
const response = await unirest
.post('https://integration.xxx.io/v2')
.headers({
'accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': 'Basic XXX=',
})
.field('holder', '{firstName:XXX, birthName:XXX, birthDate:XXX}');
functions.logger.log(response);
res.status(200).send({
success: true,
response: response.body,
});
} catch (error) {
functions.logger.log(error);
res.status(400).send({
success: false,
error: error,
});
}
});
``` | Faced with same behaviour.
In my case problew was with my lambda function.
I declared variables like `API_LINK, REQ_FORM_DATA` and etc. outside `exports.handler`. So, first time on lambda init i got success response with correct data, and then all next requests failed with ***socket hang up*** because alive lambda did not see variables declared out of `exports.handler` function body. |
33,376,795 | This used to work fine:
```
<?xml version="1.0" encoding="UTF-8"?>
<web-bnd xmlns="http://websphere.ibm.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd" version="1.0">
<virtual-host name="default_host" />
</web-bnd>
```
And at deploy-time it still does but Eclipse's validator keeps show annoying "errors" because <http://websphere.ibm.com/xml/ns/javaee> does not point to a valid site anymore (redirects to some search site),when trying to download the schemas.
I know that probably I'll just have to turn off validation for these files, but let me try asking first:
* Is there a new home for those schemas?
* Or somewhere to alert IBM that they are failing miserably on that regard...? | 2015/10/27 | [
"https://Stackoverflow.com/questions/33376795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231350/"
] | Install WebSphere Developer Tools via Eclipse Marketplace. It will add required schema to the XML Catalog in the Eclipse. You can check if you have them via `Preferences > XML > XML catalog`. These schemas are in one of the jars from plugin (the exact filename can be different depending on tools version)
```
Location: schemas\ibm-web-bnd_1_0.xsd in jar file C:\eclipse\plugins\com.ibm.jee.was.descriptors.schemas_1.1.100.v20141119_2034.jar.
``` | For Websphere Application Server:
You can find all the schemas here...
**WAS\_INSTALL\_ROOT/properties/schemas** |
28,396,650 | Say for example I have a data frame with a column `a` and I want to create columns `a^i` for several values of `i`.
```
> dat <- data.frame(a=1:5)
> dat
a
1 1
2 2
3 3
4 4
5 5
```
As an example, the output I want for `i=2:5`:
```
a power_2 power_3 power_4 power_5
1 1 1 1 1 1
2 2 4 8 16 32
3 3 9 27 81 243
4 4 16 64 256 1024
5 5 25 125 625 3125
```
Currently I get this output with `data.table` as follows:
```
DT <- data.table(dat)
exponents <- 2:5
DT[, paste0("power_",exponents):=lapply(exponents, function(p) a^p)]
```
How to do with `plyr`/`dplyr` ? Of course I could do as below by typing `power_i=a^i` for each `i` but this is not what I want.
```
mutate(dat, power_2=a^2, power_3=a^3, ...)
```
Conclusion after answers
------------------------
Several answers have been proposed, and have been compared by @docendo discimus. I'm just adding the comparison with `data.table`.
```
library(data.table)
library(dplyr)
set.seed(2015)
dat <- data.frame(a = sample(1000))
i <- 2:5
n <- c(names(dat), paste0("power_", i))
DT <- data.table(dat)
library(microbenchmark)
microbenchmark(
data.table = DT[, paste0("power_",i):=lapply(i, function(k) a^k)],
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
times = 30,
unit = "relative"
)
Unit: relative
expr min lq mean median uq max neval cld
data.table 1.022945 1.039674 1.108558 1.026319 1.083644 2.370180 30 a
Henrik 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 30 a
dd.do 1.149195 1.160735 1.167672 1.158141 1.150280 1.268279 30 a
dd.bc 14.350034 13.982658 13.737964 13.632361 13.606221 15.866711 30 b
```
**Updated benchmark** with two `base` solutions, Henrik2 and josh (from his comment), which are fastest:
```
set.seed(2015)
dat <- data.frame(a = sample(1000))
microbenchmark(
data.table = DT[, paste0("power_",i):=lapply(i, function(k) a^k)],
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
Henrik2 = cbind(dat, outer(dat$a, setNames(i, paste0("power_", i)), `^`)),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
josh = data.frame(dat, setNames(lapply(2:5, function(X) dat$a^X), paste0("power_", 2:5))),
times = 30,
unit = "relative"
)
# Unit: relative
# expr min lq mean median uq max neval cld
# data.table 1.991613 2.029778 1.982169 1.990417 1.946677 1.694030 30 bc
# Henrik 2.026345 2.017179 1.996419 2.003189 2.030176 1.733583 30 bc
# Henrik2 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 30 a
# dd.do 2.356886 2.375713 2.322452 2.348053 2.304826 2.101494 30 c
# dd.bc 37.445491 36.081298 34.791638 34.783854 34.787655 27.832116 30 d
# josh 1.725750 1.699887 1.641290 1.625331 1.637823 1.330598 30 b
``` | 2015/02/08 | [
"https://Stackoverflow.com/questions/28396650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100107/"
] | Here's an option using `do`:
```
i <- 2:5
n <- c(names(dat), paste0("power_", i))
dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n)
# a power_2 power_3 power_4 power_5
#1 1 1 1 1 1
#2 2 4 8 16 32
#3 3 9 27 81 243
#4 4 16 64 256 1024
#5 5 25 125 625 3125
```
Another option, using `bind_cols`:
```
dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n)
# a power_2 power_3 power_4 power_5
#1 1 1 1 1 1
#2 2 4 8 16 32
#3 3 9 27 81 243
#4 4 16 64 256 1024
#5 5 25 125 625 3125
```
---
Edit after comment:
The solution by @Henrik is faster than mine:
```
set.seed(2015)
dat <- data.frame(a = sample(1000))
i <- 2:5
n <- c(names(dat), paste0("power_", i))
library(microbenchmark)
microbenchmark(
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
times = 30,
unit = "relative"
)
Unit: relative
expr min lq median uq max neval
Henrik 1.000000 1.000000 1.000000 1.000000 1.000000 30
dd.do 1.138506 1.179104 1.173298 1.149581 2.660237 30
dd.bc 18.862923 18.702178 18.058984 17.537727 16.426538 30
``` | One possibility is to use `outer` in `do`, and then set the names with `setNames`
```
i <- 2:5
dat %>%
do(data.frame(., outer(.$a, i, `^`))) %>%
setNames(., c("a", paste0("power_", i)))
# a power_2 power_3 power_4 power_5
# 1 1 1 1 1 1
# 2 2 4 8 16 32
# 3 3 9 27 81 243
# 4 4 16 64 256 1024
# 5 5 25 125 625 3125
```
If you name the 'power vector' "i" first, you can call `cbind` instead of `do` and `data.frame`, and I see no immediate need for `dplyr` functions in this particular case.
```
cbind(dat, outer(dat$a, setNames(i, paste0("power_", i)), `^`))
# a power_2 power_3 power_4 power_5
# 1 1 1 1 1 1
# 2 2 4 8 16 32
# 3 3 9 27 81 243
# 4 4 16 64 256 1024
# 5 5 25 125 625 3125
```
The `base`, non-`do` code is faster for your larger sample data. I also added the `base` solution by @Josh O'Brien.
```
set.seed(2015)
dat <- data.frame(a = sample(1000))
microbenchmark(
data.table = DT[, paste0("power_",i):=lapply(i, function(k) a^k)],
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
Henrik2 = cbind(dat, outer(dat$a, setNames(i, paste0("power_", i)), `^`)),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
josh = data.frame(dat, setNames(lapply(2:5, function(X) dat$a^X), paste0("power_", 2:5))),
times = 30,
unit = "relative"
)
# Unit: relative
# expr min lq mean median uq max neval cld
# data.table 1.991613 2.029778 1.982169 1.990417 1.946677 1.694030 30 bc
# Henrik 2.026345 2.017179 1.996419 2.003189 2.030176 1.733583 30 bc
# Henrik2 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 30 a
# dd.do 2.356886 2.375713 2.322452 2.348053 2.304826 2.101494 30 c
# dd.bc 37.445491 36.081298 34.791638 34.783854 34.787655 27.832116 30 d
# josh 1.725750 1.699887 1.641290 1.625331 1.637823 1.330598 30 b
``` |
28,396,650 | Say for example I have a data frame with a column `a` and I want to create columns `a^i` for several values of `i`.
```
> dat <- data.frame(a=1:5)
> dat
a
1 1
2 2
3 3
4 4
5 5
```
As an example, the output I want for `i=2:5`:
```
a power_2 power_3 power_4 power_5
1 1 1 1 1 1
2 2 4 8 16 32
3 3 9 27 81 243
4 4 16 64 256 1024
5 5 25 125 625 3125
```
Currently I get this output with `data.table` as follows:
```
DT <- data.table(dat)
exponents <- 2:5
DT[, paste0("power_",exponents):=lapply(exponents, function(p) a^p)]
```
How to do with `plyr`/`dplyr` ? Of course I could do as below by typing `power_i=a^i` for each `i` but this is not what I want.
```
mutate(dat, power_2=a^2, power_3=a^3, ...)
```
Conclusion after answers
------------------------
Several answers have been proposed, and have been compared by @docendo discimus. I'm just adding the comparison with `data.table`.
```
library(data.table)
library(dplyr)
set.seed(2015)
dat <- data.frame(a = sample(1000))
i <- 2:5
n <- c(names(dat), paste0("power_", i))
DT <- data.table(dat)
library(microbenchmark)
microbenchmark(
data.table = DT[, paste0("power_",i):=lapply(i, function(k) a^k)],
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
times = 30,
unit = "relative"
)
Unit: relative
expr min lq mean median uq max neval cld
data.table 1.022945 1.039674 1.108558 1.026319 1.083644 2.370180 30 a
Henrik 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 30 a
dd.do 1.149195 1.160735 1.167672 1.158141 1.150280 1.268279 30 a
dd.bc 14.350034 13.982658 13.737964 13.632361 13.606221 15.866711 30 b
```
**Updated benchmark** with two `base` solutions, Henrik2 and josh (from his comment), which are fastest:
```
set.seed(2015)
dat <- data.frame(a = sample(1000))
microbenchmark(
data.table = DT[, paste0("power_",i):=lapply(i, function(k) a^k)],
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
Henrik2 = cbind(dat, outer(dat$a, setNames(i, paste0("power_", i)), `^`)),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
josh = data.frame(dat, setNames(lapply(2:5, function(X) dat$a^X), paste0("power_", 2:5))),
times = 30,
unit = "relative"
)
# Unit: relative
# expr min lq mean median uq max neval cld
# data.table 1.991613 2.029778 1.982169 1.990417 1.946677 1.694030 30 bc
# Henrik 2.026345 2.017179 1.996419 2.003189 2.030176 1.733583 30 bc
# Henrik2 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 30 a
# dd.do 2.356886 2.375713 2.322452 2.348053 2.304826 2.101494 30 c
# dd.bc 37.445491 36.081298 34.791638 34.783854 34.787655 27.832116 30 d
# josh 1.725750 1.699887 1.641290 1.625331 1.637823 1.330598 30 b
``` | 2015/02/08 | [
"https://Stackoverflow.com/questions/28396650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100107/"
] | Here's an option using `do`:
```
i <- 2:5
n <- c(names(dat), paste0("power_", i))
dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n)
# a power_2 power_3 power_4 power_5
#1 1 1 1 1 1
#2 2 4 8 16 32
#3 3 9 27 81 243
#4 4 16 64 256 1024
#5 5 25 125 625 3125
```
Another option, using `bind_cols`:
```
dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n)
# a power_2 power_3 power_4 power_5
#1 1 1 1 1 1
#2 2 4 8 16 32
#3 3 9 27 81 243
#4 4 16 64 256 1024
#5 5 25 125 625 3125
```
---
Edit after comment:
The solution by @Henrik is faster than mine:
```
set.seed(2015)
dat <- data.frame(a = sample(1000))
i <- 2:5
n <- c(names(dat), paste0("power_", i))
library(microbenchmark)
microbenchmark(
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
times = 30,
unit = "relative"
)
Unit: relative
expr min lq median uq max neval
Henrik 1.000000 1.000000 1.000000 1.000000 1.000000 30
dd.do 1.138506 1.179104 1.173298 1.149581 2.660237 30
dd.bc 18.862923 18.702178 18.058984 17.537727 16.426538 30
``` | May be this also helps
```
nm1 <- paste('power', 2:5, sep="_")
lst <- setNames(as.list(2:5), nm1)
dat1 <- setNames(as.data.frame(replicate(4, 1:5)),c('a', nm1) )
mutate_each_(dat1, funs(.^lst$.), nm1)
# a power_2 power_3 power_4 power_5
#1 1 1 1 1 1
#2 2 4 8 16 32
#3 3 9 27 81 243
#4 4 16 64 256 1024
#5 5 25 125 625 3125
``` |
28,396,650 | Say for example I have a data frame with a column `a` and I want to create columns `a^i` for several values of `i`.
```
> dat <- data.frame(a=1:5)
> dat
a
1 1
2 2
3 3
4 4
5 5
```
As an example, the output I want for `i=2:5`:
```
a power_2 power_3 power_4 power_5
1 1 1 1 1 1
2 2 4 8 16 32
3 3 9 27 81 243
4 4 16 64 256 1024
5 5 25 125 625 3125
```
Currently I get this output with `data.table` as follows:
```
DT <- data.table(dat)
exponents <- 2:5
DT[, paste0("power_",exponents):=lapply(exponents, function(p) a^p)]
```
How to do with `plyr`/`dplyr` ? Of course I could do as below by typing `power_i=a^i` for each `i` but this is not what I want.
```
mutate(dat, power_2=a^2, power_3=a^3, ...)
```
Conclusion after answers
------------------------
Several answers have been proposed, and have been compared by @docendo discimus. I'm just adding the comparison with `data.table`.
```
library(data.table)
library(dplyr)
set.seed(2015)
dat <- data.frame(a = sample(1000))
i <- 2:5
n <- c(names(dat), paste0("power_", i))
DT <- data.table(dat)
library(microbenchmark)
microbenchmark(
data.table = DT[, paste0("power_",i):=lapply(i, function(k) a^k)],
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
times = 30,
unit = "relative"
)
Unit: relative
expr min lq mean median uq max neval cld
data.table 1.022945 1.039674 1.108558 1.026319 1.083644 2.370180 30 a
Henrik 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 30 a
dd.do 1.149195 1.160735 1.167672 1.158141 1.150280 1.268279 30 a
dd.bc 14.350034 13.982658 13.737964 13.632361 13.606221 15.866711 30 b
```
**Updated benchmark** with two `base` solutions, Henrik2 and josh (from his comment), which are fastest:
```
set.seed(2015)
dat <- data.frame(a = sample(1000))
microbenchmark(
data.table = DT[, paste0("power_",i):=lapply(i, function(k) a^k)],
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
Henrik2 = cbind(dat, outer(dat$a, setNames(i, paste0("power_", i)), `^`)),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
josh = data.frame(dat, setNames(lapply(2:5, function(X) dat$a^X), paste0("power_", 2:5))),
times = 30,
unit = "relative"
)
# Unit: relative
# expr min lq mean median uq max neval cld
# data.table 1.991613 2.029778 1.982169 1.990417 1.946677 1.694030 30 bc
# Henrik 2.026345 2.017179 1.996419 2.003189 2.030176 1.733583 30 bc
# Henrik2 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 30 a
# dd.do 2.356886 2.375713 2.322452 2.348053 2.304826 2.101494 30 c
# dd.bc 37.445491 36.081298 34.791638 34.783854 34.787655 27.832116 30 d
# josh 1.725750 1.699887 1.641290 1.625331 1.637823 1.330598 30 b
``` | 2015/02/08 | [
"https://Stackoverflow.com/questions/28396650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100107/"
] | One possibility is to use `outer` in `do`, and then set the names with `setNames`
```
i <- 2:5
dat %>%
do(data.frame(., outer(.$a, i, `^`))) %>%
setNames(., c("a", paste0("power_", i)))
# a power_2 power_3 power_4 power_5
# 1 1 1 1 1 1
# 2 2 4 8 16 32
# 3 3 9 27 81 243
# 4 4 16 64 256 1024
# 5 5 25 125 625 3125
```
If you name the 'power vector' "i" first, you can call `cbind` instead of `do` and `data.frame`, and I see no immediate need for `dplyr` functions in this particular case.
```
cbind(dat, outer(dat$a, setNames(i, paste0("power_", i)), `^`))
# a power_2 power_3 power_4 power_5
# 1 1 1 1 1 1
# 2 2 4 8 16 32
# 3 3 9 27 81 243
# 4 4 16 64 256 1024
# 5 5 25 125 625 3125
```
The `base`, non-`do` code is faster for your larger sample data. I also added the `base` solution by @Josh O'Brien.
```
set.seed(2015)
dat <- data.frame(a = sample(1000))
microbenchmark(
data.table = DT[, paste0("power_",i):=lapply(i, function(k) a^k)],
Henrik = dat %>% do(data.frame(., outer(.$a, i, `^`))) %>% setNames(n),
Henrik2 = cbind(dat, outer(dat$a, setNames(i, paste0("power_", i)), `^`)),
dd.do = dat %>% do(data.frame(., sapply(i, function(x) .$a^x))) %>% setNames(n),
dd.bc = dat %>% bind_cols(as.data.frame(lapply(i, function(x) .$a^x))) %>% setNames(n),
josh = data.frame(dat, setNames(lapply(2:5, function(X) dat$a^X), paste0("power_", 2:5))),
times = 30,
unit = "relative"
)
# Unit: relative
# expr min lq mean median uq max neval cld
# data.table 1.991613 2.029778 1.982169 1.990417 1.946677 1.694030 30 bc
# Henrik 2.026345 2.017179 1.996419 2.003189 2.030176 1.733583 30 bc
# Henrik2 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 30 a
# dd.do 2.356886 2.375713 2.322452 2.348053 2.304826 2.101494 30 c
# dd.bc 37.445491 36.081298 34.791638 34.783854 34.787655 27.832116 30 d
# josh 1.725750 1.699887 1.641290 1.625331 1.637823 1.330598 30 b
``` | May be this also helps
```
nm1 <- paste('power', 2:5, sep="_")
lst <- setNames(as.list(2:5), nm1)
dat1 <- setNames(as.data.frame(replicate(4, 1:5)),c('a', nm1) )
mutate_each_(dat1, funs(.^lst$.), nm1)
# a power_2 power_3 power_4 power_5
#1 1 1 1 1 1
#2 2 4 8 16 32
#3 3 9 27 81 243
#4 4 16 64 256 1024
#5 5 25 125 625 3125
``` |
5,595,566 | For this implementation, should I be using a MotionEvent or DragEvent for moving the ball in the meter?  | 2011/04/08 | [
"https://Stackoverflow.com/questions/5595566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/448005/"
] | instead of manipulating the visibility of the span, if an error message is to come up you could add the `er` class to the parent `section` element itself
from there you can control the visibility of the actual `li` that contains your message e.g.
```
section li:first-child {display: none;}
section.er li:first-child {display: block;}
```
and also the hover transitions at the same time:
```
section {
display: block;
opacity: 0.5;
transition: all 1s ease-in-out;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
}
section.er, section:hover {
opacity: 100;
transition: all 1s ease-in-out;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1 ease-in-out;
-o-transition: all 1s ease-in-out;
}
```
all the jQuery would need to do is add or remove the class name from the section dependant on if the form does/doesn't pass validation | ```
$('form').mouseover(function (){
$('span.er').css('opacty':1);
if(!$("span.er:visible")){
$('form').css({'opacity',0.5});
}
});
```
And you are very difficult to understand you have confused the hell out of us, put it on bullet points the actions and their priority if you find it that difficult
as for the code above when user mouses over the `<form>` tag it will change opacity to one unless its visible which will be 0.5 or 50% |
11,800 | Dark mode was introduced to StackOverflow about a year ago ([blog post](https://stackoverflow.blog/2020/03/30/introducing-dark-mode-for-stack-overflow/)), but as of now, it still isn't available on our site (or any other site as far as I know).
Back then, it was stated that
>
> For now, we have no plans to bring dark mode to the many sites across the Stack Exchange network. Many of the designs on our sites have been around long enough that converting them to dark mode would require redoing the artwork completely. We would prefer to avoid giving anyone across our network a substandard experience and we don’t want to change those elements without the input of these communities.
>
>
>
and in the [corresponding meta question](https://meta.stackoverflow.com/questions/395949/dark-mode-beta-help-us-root-out-low-contrast-and-un-converted-bits):
>
> At this point, the focus of Dark Mode is on Stack Overflow and we’ll eventually bring it to MSO. While the retheming we did across the network two years ago makes updating our LESS easier, creating dark versions of all of our sites, particularly the custom-designed ones, is going to be a huge challenge we’re not able to contemplate at this time. The artwork on some of those sites simply can’t be made dark because we don’t have access to the original art files and, to be honest, some of the themes will always be better as-is.
>
>
>
Personally, I'm a huge fan of dark mode and I would love to see it on RPG SE. However, the issues mentioned in the blog post *are* present on this site. Compared to other sites, I think we have an average\* amount of artwork (in fact, I can't think of anything other than the top banner, "Role-playing Games" text, and the "boxy" background on the front page). Of those, I'd expect the banner to be the most difficult to modify, but there's already a
black-and-white-version on meta, which could probably be turned into something dark-mode-compatible.
The remaining page elements are mostly of uniform colour, and as such should be fairly easy to modify. Also, as [controversial as the change was](https://rpg.meta.stackexchange.com/questions/8391/role-playing-gamess-updated-site-theme-is-live), the introduction of the new network-wide unified themes does make the implementation of a dark mode easier.
\*for example, worldbuilding has more artwork, while Board & Card Games has none at all
Based on the phrasing in the blog & meta posts, I don't expect SE itself to approach us with a dark mode design. Therefore, we would need to manually create at least a first draft that solves potential issues with our front page artwork and thereby proves the viability of a dark mode on this site. This, of course, still doesn't guarantee that Stack Exchange Inc. cares at all about implementing a dark mode provided by us users. However, as a consolation prize, we'd at least still have a community-designed dark theme that I'm sure could be applied individually with the appropriate browser extensions.
Being somewhat experienced in web design, I'd be happy to tinker with CSS variables and the like myself, but I'm unsure what to do about the front page artwork. And either way, I don't want to create a makeshift dark mode just for myself - the goal is to end up with a (more or less) full-fledged dark mode *with support from the community* that we would have an easy/easier time convincing SE to implement.
---
Therefore, before I create a draft that at least styles the front page (excluding the artwork), I want to query your opinion.
Do you approve of the potential introduction of a dark mode and would you use it? Do you think we should aim to approach SE Inc. with a community-designed draft at all, or do you think aiming for a theme that can be applied individually with the help of (for example) browser extensions is more realistic? Do you perhaps already have a custom dark mode script because you have to think of [The Weeknd](https://www.youtube.com/watch?v=fHI8X4OXluQ) whenever you open RPG SE?
Obviously, any feedback from SE officials (especially on whether or not a community-supplied draft is helpful at all for them) is also welcome, although I personally wouldn't actively contact them without a usable first draft.
---
Given the fact that I managed to create a [proof of concept](https://rpg.meta.stackexchange.com/a/11804/38495) (= it doesn't look great, but it proves that a dark mode is feasible), I consider the "realistically possible" aspect to be solved.
However, that still leaves the task of actually creating the respective style sheet and subsequently the task of attempting to get SE to implement a possibility for site-specific dark mode styling (as unlikely as getting them to do that is).
Concerning the former issue: I'll probably create a stylesheet either way, but I would very much appreciate support from others, especially if you have web development or design experience (as I'm unsure which colors would be well-suited). | 2021/10/25 | [
"https://rpg.meta.stackexchange.com/questions/11800",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/38495/"
] | ### Yes, I want dark mode on RPG.SE
I don't really have anything else interesting to say, nor do I have any knowledge about what it takes to implement it. I'm leaving this answer to simply measure support for "Yes, I want dark mode". | ### RPG SE is almost-certainly one of those sites that “would require redoing the artwork completely”
Our banner includes material that probably cannot be “automagically” converted to a darker background. It includes gradients that fade into the light site background, and which will probably not “just work” against a dark background. The gradients use transparency, so there might be *some* hope, but even fading to transparent usually requires designing with at least some sense of what you’re fading to—and light or dark is one of the most basic things you’d need to know. [PixelMaster has a demonstration of what it might look like](https://rpg.meta.stackexchange.com/a/11804/4563), and it doesn’t look *terrible*, but there are some issues there and it seems likely to me that SE won’t go for it.
>
> The artwork on some of those sites simply can’t be made dark because we don’t have access to the original art files
>
>
>
And this applies to us, I believe; I seem to recall having heard this before, specifically about our site. Any editing of the end file we see would likely look atrocious, so if “as is” doesn’t work for SE, they’re gonna be stuck. I believe the artist who created it no longer works for or with the company, as well.
They also probably want a consistent look and feel across both versions of the site, which means they want the same banner for both. If they cannot create a dark-mode version of the existing banner, that very likely means this would require a new banner altogether.
And they aren’t doing new banners like this, as far as I know.
So unless they substantially degraded the light-mode version of the site, they cannot provide a (consistent, good-looking) dark mode. It may be that they’re only willing to enable dark mode for us if we ditch the banner—in both dark and light mode.
### I, for one, vehemently oppose losing our theme for the sake of dark mode
I don’t really care about dark mode one way or the other; I might use it if it’s there, but it’s not important to me. I certainly wouldn’t want to see the excellent theming of this site lost for the sake of dark mode. I would be fine with inconsistent theming for light and dark mode, but I suspect Stack Exchange would not, so this may be the choice we’re stuck with.
### The point is largely moot for now
>
> creating dark versions of all of our sites, particularly the custom-designed ones, is going to be a huge challenge we’re not able to contemplate at this time.
>
>
>
Stack Exchange isn’t offering to provide dark mode to anybody, not even the “easy” ones—and we’re one of the hard ones. We can’t realistically even decide what we, as a community, want, because we don’t even know what we’d be choosing between. If we got a true dark-mode version of what we currently have, I doubt anyone would have objections—but that may never be on offer. If there are some trade-offs involved, people have to know what they are before they can really vote on it.
### Unofficially, maybe it could work
PixelMaster has suggested an “unofficial dark mode” created via user styles—that has some merit. Some other SE sites have things like that, e.g. SOUP (Stack Overflow Unofficial Patch) or the various Magic: The Gathering functionality for Board & Card Games. Code Golf even had an unofficial theme before they got their official one. Something like this may be plausible, but is unlikely to help much or in any way accelerate the launch of an official theme. |
11,800 | Dark mode was introduced to StackOverflow about a year ago ([blog post](https://stackoverflow.blog/2020/03/30/introducing-dark-mode-for-stack-overflow/)), but as of now, it still isn't available on our site (or any other site as far as I know).
Back then, it was stated that
>
> For now, we have no plans to bring dark mode to the many sites across the Stack Exchange network. Many of the designs on our sites have been around long enough that converting them to dark mode would require redoing the artwork completely. We would prefer to avoid giving anyone across our network a substandard experience and we don’t want to change those elements without the input of these communities.
>
>
>
and in the [corresponding meta question](https://meta.stackoverflow.com/questions/395949/dark-mode-beta-help-us-root-out-low-contrast-and-un-converted-bits):
>
> At this point, the focus of Dark Mode is on Stack Overflow and we’ll eventually bring it to MSO. While the retheming we did across the network two years ago makes updating our LESS easier, creating dark versions of all of our sites, particularly the custom-designed ones, is going to be a huge challenge we’re not able to contemplate at this time. The artwork on some of those sites simply can’t be made dark because we don’t have access to the original art files and, to be honest, some of the themes will always be better as-is.
>
>
>
Personally, I'm a huge fan of dark mode and I would love to see it on RPG SE. However, the issues mentioned in the blog post *are* present on this site. Compared to other sites, I think we have an average\* amount of artwork (in fact, I can't think of anything other than the top banner, "Role-playing Games" text, and the "boxy" background on the front page). Of those, I'd expect the banner to be the most difficult to modify, but there's already a
black-and-white-version on meta, which could probably be turned into something dark-mode-compatible.
The remaining page elements are mostly of uniform colour, and as such should be fairly easy to modify. Also, as [controversial as the change was](https://rpg.meta.stackexchange.com/questions/8391/role-playing-gamess-updated-site-theme-is-live), the introduction of the new network-wide unified themes does make the implementation of a dark mode easier.
\*for example, worldbuilding has more artwork, while Board & Card Games has none at all
Based on the phrasing in the blog & meta posts, I don't expect SE itself to approach us with a dark mode design. Therefore, we would need to manually create at least a first draft that solves potential issues with our front page artwork and thereby proves the viability of a dark mode on this site. This, of course, still doesn't guarantee that Stack Exchange Inc. cares at all about implementing a dark mode provided by us users. However, as a consolation prize, we'd at least still have a community-designed dark theme that I'm sure could be applied individually with the appropriate browser extensions.
Being somewhat experienced in web design, I'd be happy to tinker with CSS variables and the like myself, but I'm unsure what to do about the front page artwork. And either way, I don't want to create a makeshift dark mode just for myself - the goal is to end up with a (more or less) full-fledged dark mode *with support from the community* that we would have an easy/easier time convincing SE to implement.
---
Therefore, before I create a draft that at least styles the front page (excluding the artwork), I want to query your opinion.
Do you approve of the potential introduction of a dark mode and would you use it? Do you think we should aim to approach SE Inc. with a community-designed draft at all, or do you think aiming for a theme that can be applied individually with the help of (for example) browser extensions is more realistic? Do you perhaps already have a custom dark mode script because you have to think of [The Weeknd](https://www.youtube.com/watch?v=fHI8X4OXluQ) whenever you open RPG SE?
Obviously, any feedback from SE officials (especially on whether or not a community-supplied draft is helpful at all for them) is also welcome, although I personally wouldn't actively contact them without a usable first draft.
---
Given the fact that I managed to create a [proof of concept](https://rpg.meta.stackexchange.com/a/11804/38495) (= it doesn't look great, but it proves that a dark mode is feasible), I consider the "realistically possible" aspect to be solved.
However, that still leaves the task of actually creating the respective style sheet and subsequently the task of attempting to get SE to implement a possibility for site-specific dark mode styling (as unlikely as getting them to do that is).
Concerning the former issue: I'll probably create a stylesheet either way, but I would very much appreciate support from others, especially if you have web development or design experience (as I'm unsure which colors would be well-suited). | 2021/10/25 | [
"https://rpg.meta.stackexchange.com/questions/11800",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/38495/"
] | ### Yes, I want dark mode on RPG.SE
I don't really have anything else interesting to say, nor do I have any knowledge about what it takes to implement it. I'm leaving this answer to simply measure support for "Yes, I want dark mode". | *Disclaimer since there seems to have been some confusion: yes, the proof of concept is fairly ugly. That doesn't matter, it's just a proof of concept - it doesn't have to look nice, just prove that the styling is possible. For a real theme, obviously, more effort than the 15-30 minutes of work I spent on the POC is required to get it done properly.*
### Proof of concept
I decided to starting tinkering a little bit with the CSS. Turns out it's probably easier than I thought; with the exception of some elements (that I'd probably figure out if I spent more time debugging), most of the page can be restyled by changing just a few variables.
My findings concerning artwork:
* The header gradient is part of the image, aka it's preserved if you change the background (and the result looks good enough imho).
* The background is composed of many small images. This image can't be directly styled via the browser, of course, but it can easily be modified with an image editing tool. For the proof of concept below, I simply inverted the colours to get a quick usable example, which took less than a minute (most of which was actually the GIMP startup time xD). Either way, if implemented by SE, hosting is trivial, and even if not, we could just upload the desired version to something like Imgur (although copyright has to be considered here).
* The "Role-playing Games" header text is also an image, and while I didn't bother switching it out, it would probably only be marginally more complicated than adapting the background tile.
* Figuring out viable dark mode colors is not trivial. Consider the colors used in the draft below temporary placeholders to showcase the possibilities.
In conclusion, I can only assume that the reason why SE doesn't want to introduce a dark mode network-wide is because
1. it would probably require site-specific theming, which is obviously a significant amount of initial work, and would likely multiply the required effort whenever the design changes in one way or another
2. some sites are likely REALLY difficult to style due to their artwork (which, as mentioned above, isn't the case for RPGSE in my opinion). It would, however, be difficult to justify styling just some sites while ignoring others with complicated artwork, and SE probably doesn't want to incentivize removing artwork in favor of dark mode support, as that would likely create drastic rifts in each site's community.
Either way, here's my draft/proof of concept:
[](https://i.stack.imgur.com/AcR1d.jpg)
The bright sidebar on the right is one of the tricky elements that I couldn't easily style (although I'm sure it can be styled somehow). I'm also aware that the text is mostly hard to read, but that's just because I was too lazy to edit every single detail. I'm certain that the text color can be changed as well. |
11,800 | Dark mode was introduced to StackOverflow about a year ago ([blog post](https://stackoverflow.blog/2020/03/30/introducing-dark-mode-for-stack-overflow/)), but as of now, it still isn't available on our site (or any other site as far as I know).
Back then, it was stated that
>
> For now, we have no plans to bring dark mode to the many sites across the Stack Exchange network. Many of the designs on our sites have been around long enough that converting them to dark mode would require redoing the artwork completely. We would prefer to avoid giving anyone across our network a substandard experience and we don’t want to change those elements without the input of these communities.
>
>
>
and in the [corresponding meta question](https://meta.stackoverflow.com/questions/395949/dark-mode-beta-help-us-root-out-low-contrast-and-un-converted-bits):
>
> At this point, the focus of Dark Mode is on Stack Overflow and we’ll eventually bring it to MSO. While the retheming we did across the network two years ago makes updating our LESS easier, creating dark versions of all of our sites, particularly the custom-designed ones, is going to be a huge challenge we’re not able to contemplate at this time. The artwork on some of those sites simply can’t be made dark because we don’t have access to the original art files and, to be honest, some of the themes will always be better as-is.
>
>
>
Personally, I'm a huge fan of dark mode and I would love to see it on RPG SE. However, the issues mentioned in the blog post *are* present on this site. Compared to other sites, I think we have an average\* amount of artwork (in fact, I can't think of anything other than the top banner, "Role-playing Games" text, and the "boxy" background on the front page). Of those, I'd expect the banner to be the most difficult to modify, but there's already a
black-and-white-version on meta, which could probably be turned into something dark-mode-compatible.
The remaining page elements are mostly of uniform colour, and as such should be fairly easy to modify. Also, as [controversial as the change was](https://rpg.meta.stackexchange.com/questions/8391/role-playing-gamess-updated-site-theme-is-live), the introduction of the new network-wide unified themes does make the implementation of a dark mode easier.
\*for example, worldbuilding has more artwork, while Board & Card Games has none at all
Based on the phrasing in the blog & meta posts, I don't expect SE itself to approach us with a dark mode design. Therefore, we would need to manually create at least a first draft that solves potential issues with our front page artwork and thereby proves the viability of a dark mode on this site. This, of course, still doesn't guarantee that Stack Exchange Inc. cares at all about implementing a dark mode provided by us users. However, as a consolation prize, we'd at least still have a community-designed dark theme that I'm sure could be applied individually with the appropriate browser extensions.
Being somewhat experienced in web design, I'd be happy to tinker with CSS variables and the like myself, but I'm unsure what to do about the front page artwork. And either way, I don't want to create a makeshift dark mode just for myself - the goal is to end up with a (more or less) full-fledged dark mode *with support from the community* that we would have an easy/easier time convincing SE to implement.
---
Therefore, before I create a draft that at least styles the front page (excluding the artwork), I want to query your opinion.
Do you approve of the potential introduction of a dark mode and would you use it? Do you think we should aim to approach SE Inc. with a community-designed draft at all, or do you think aiming for a theme that can be applied individually with the help of (for example) browser extensions is more realistic? Do you perhaps already have a custom dark mode script because you have to think of [The Weeknd](https://www.youtube.com/watch?v=fHI8X4OXluQ) whenever you open RPG SE?
Obviously, any feedback from SE officials (especially on whether or not a community-supplied draft is helpful at all for them) is also welcome, although I personally wouldn't actively contact them without a usable first draft.
---
Given the fact that I managed to create a [proof of concept](https://rpg.meta.stackexchange.com/a/11804/38495) (= it doesn't look great, but it proves that a dark mode is feasible), I consider the "realistically possible" aspect to be solved.
However, that still leaves the task of actually creating the respective style sheet and subsequently the task of attempting to get SE to implement a possibility for site-specific dark mode styling (as unlikely as getting them to do that is).
Concerning the former issue: I'll probably create a stylesheet either way, but I would very much appreciate support from others, especially if you have web development or design experience (as I'm unsure which colors would be well-suited). | 2021/10/25 | [
"https://rpg.meta.stackexchange.com/questions/11800",
"https://rpg.meta.stackexchange.com",
"https://rpg.meta.stackexchange.com/users/38495/"
] | *Disclaimer since there seems to have been some confusion: yes, the proof of concept is fairly ugly. That doesn't matter, it's just a proof of concept - it doesn't have to look nice, just prove that the styling is possible. For a real theme, obviously, more effort than the 15-30 minutes of work I spent on the POC is required to get it done properly.*
### Proof of concept
I decided to starting tinkering a little bit with the CSS. Turns out it's probably easier than I thought; with the exception of some elements (that I'd probably figure out if I spent more time debugging), most of the page can be restyled by changing just a few variables.
My findings concerning artwork:
* The header gradient is part of the image, aka it's preserved if you change the background (and the result looks good enough imho).
* The background is composed of many small images. This image can't be directly styled via the browser, of course, but it can easily be modified with an image editing tool. For the proof of concept below, I simply inverted the colours to get a quick usable example, which took less than a minute (most of which was actually the GIMP startup time xD). Either way, if implemented by SE, hosting is trivial, and even if not, we could just upload the desired version to something like Imgur (although copyright has to be considered here).
* The "Role-playing Games" header text is also an image, and while I didn't bother switching it out, it would probably only be marginally more complicated than adapting the background tile.
* Figuring out viable dark mode colors is not trivial. Consider the colors used in the draft below temporary placeholders to showcase the possibilities.
In conclusion, I can only assume that the reason why SE doesn't want to introduce a dark mode network-wide is because
1. it would probably require site-specific theming, which is obviously a significant amount of initial work, and would likely multiply the required effort whenever the design changes in one way or another
2. some sites are likely REALLY difficult to style due to their artwork (which, as mentioned above, isn't the case for RPGSE in my opinion). It would, however, be difficult to justify styling just some sites while ignoring others with complicated artwork, and SE probably doesn't want to incentivize removing artwork in favor of dark mode support, as that would likely create drastic rifts in each site's community.
Either way, here's my draft/proof of concept:
[](https://i.stack.imgur.com/AcR1d.jpg)
The bright sidebar on the right is one of the tricky elements that I couldn't easily style (although I'm sure it can be styled somehow). I'm also aware that the text is mostly hard to read, but that's just because I was too lazy to edit every single detail. I'm certain that the text color can be changed as well. | ### RPG SE is almost-certainly one of those sites that “would require redoing the artwork completely”
Our banner includes material that probably cannot be “automagically” converted to a darker background. It includes gradients that fade into the light site background, and which will probably not “just work” against a dark background. The gradients use transparency, so there might be *some* hope, but even fading to transparent usually requires designing with at least some sense of what you’re fading to—and light or dark is one of the most basic things you’d need to know. [PixelMaster has a demonstration of what it might look like](https://rpg.meta.stackexchange.com/a/11804/4563), and it doesn’t look *terrible*, but there are some issues there and it seems likely to me that SE won’t go for it.
>
> The artwork on some of those sites simply can’t be made dark because we don’t have access to the original art files
>
>
>
And this applies to us, I believe; I seem to recall having heard this before, specifically about our site. Any editing of the end file we see would likely look atrocious, so if “as is” doesn’t work for SE, they’re gonna be stuck. I believe the artist who created it no longer works for or with the company, as well.
They also probably want a consistent look and feel across both versions of the site, which means they want the same banner for both. If they cannot create a dark-mode version of the existing banner, that very likely means this would require a new banner altogether.
And they aren’t doing new banners like this, as far as I know.
So unless they substantially degraded the light-mode version of the site, they cannot provide a (consistent, good-looking) dark mode. It may be that they’re only willing to enable dark mode for us if we ditch the banner—in both dark and light mode.
### I, for one, vehemently oppose losing our theme for the sake of dark mode
I don’t really care about dark mode one way or the other; I might use it if it’s there, but it’s not important to me. I certainly wouldn’t want to see the excellent theming of this site lost for the sake of dark mode. I would be fine with inconsistent theming for light and dark mode, but I suspect Stack Exchange would not, so this may be the choice we’re stuck with.
### The point is largely moot for now
>
> creating dark versions of all of our sites, particularly the custom-designed ones, is going to be a huge challenge we’re not able to contemplate at this time.
>
>
>
Stack Exchange isn’t offering to provide dark mode to anybody, not even the “easy” ones—and we’re one of the hard ones. We can’t realistically even decide what we, as a community, want, because we don’t even know what we’d be choosing between. If we got a true dark-mode version of what we currently have, I doubt anyone would have objections—but that may never be on offer. If there are some trade-offs involved, people have to know what they are before they can really vote on it.
### Unofficially, maybe it could work
PixelMaster has suggested an “unofficial dark mode” created via user styles—that has some merit. Some other SE sites have things like that, e.g. SOUP (Stack Overflow Unofficial Patch) or the various Magic: The Gathering functionality for Board & Card Games. Code Golf even had an unofficial theme before they got their official one. Something like this may be plausible, but is unlikely to help much or in any way accelerate the launch of an official theme. |
26,007,915 | I have a regular expression now that matches any number:
```
/(\d)/
```
Now I'd like to modify it to not pick up 1, so it should capture 238, 12, 41, but not 1.
Does anyone see a way to do that?
Thanks | 2014/09/24 | [
"https://Stackoverflow.com/questions/26007915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008834/"
] | Assuming Negative Lookahead is supported you could do:
```
^(?!1$)\d+$
```
Or simply use the alternation operator in context placing what you want to exclude on the left-hand side, and place what you want to match in a capturing group on the right-hand side.
```
\b1\b|(\d+)
```
[Live Demo](http://regex101.com/r/nX9aI9/3) | You can use `/(?!1$)\d+/`
Try this code in PHP:
```
$a ="1";
$b ="2";
$reg = "/(?!1$)\d+/";
echo preg_match($reg, $a);
echo preg_match($reg, $b);
``` |
26,007,915 | I have a regular expression now that matches any number:
```
/(\d)/
```
Now I'd like to modify it to not pick up 1, so it should capture 238, 12, 41, but not 1.
Does anyone see a way to do that?
Thanks | 2014/09/24 | [
"https://Stackoverflow.com/questions/26007915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008834/"
] | Use this regular expression
```
\b[02-9]\b|\d{2,}
``` | You can use `/(?!1$)\d+/`
Try this code in PHP:
```
$a ="1";
$b ="2";
$reg = "/(?!1$)\d+/";
echo preg_match($reg, $a);
echo preg_match($reg, $b);
``` |
26,007,915 | I have a regular expression now that matches any number:
```
/(\d)/
```
Now I'd like to modify it to not pick up 1, so it should capture 238, 12, 41, but not 1.
Does anyone see a way to do that?
Thanks | 2014/09/24 | [
"https://Stackoverflow.com/questions/26007915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008834/"
] | Assuming Negative Lookahead is supported you could do:
```
^(?!1$)\d+$
```
Or simply use the alternation operator in context placing what you want to exclude on the left-hand side, and place what you want to match in a capturing group on the right-hand side.
```
\b1\b|(\d+)
```
[Live Demo](http://regex101.com/r/nX9aI9/3) | Use this regular expression
```
\b[02-9]\b|\d{2,}
``` |
20,755,896 | ```
def OnClick(self,event):
print "a:", a
os.system('iperf -s -w a')
```
Here a is displayed correctly. But in the `os.system` command the value of a is taken as 0.
Could you please help me on this? | 2013/12/24 | [
"https://Stackoverflow.com/questions/20755896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131595/"
] | You are not passing the value of `a`, but you are passing `a` as it is. So, you might want to do this
```
os.system('iperf -s -w {}'.format(a))
```
Now, the value of `a` will be substituted at `{}`. You can see the difference between both the versions by printing them
```
print 'iperf -s -w {}'.format(a)
print 'iperf -s -w a'
``` | ```
os.system('iperf -s -w a')
```
takes literal a and not the value of the variable. I would use:
```
cmd = 'iperf -s -w %d' %a
os.system (cmd)
```
Refer [input output formatting in python](http://docs.python.org/2/tutorial/inputoutput.html) |
54,372,976 | I am trying to display some json data and keep getting this error:
**ERROR Error: Error trying to diff 'Leanne Graham'. Only arrays and iterables are allowed**
Here is the code:
The Data
```
{id: 1, name: "Leanne Graham"}
```
app.component.html
```
<ul>
<li *ngFor="let element of data">
{{element.name}}
</li>
</ul>
```
app.component.ts
```
export class AppComponent implements OnInit {
data = [];
constructor(private dataService: DataService) {}
ngOnInit() {
this.get_users_by_id(1);
}
get_users_by_id(id) {
this.dataService.get_users_by_id(id).subscribe((res: any[]) => {
this.data = res;
});
}
}
```
And Finally the service part
```
get_users_by_id(id) {
return this.http.get(this.baseUrl + '/users/' + id);
}
```
How can I fix this? | 2019/01/25 | [
"https://Stackoverflow.com/questions/54372976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Since you are just getting an *object*, not an array, try changing your code like this:
**Layout the structure of the returned data**
```
export interface User {
id: number;
name: string;
}
```
This defines the structure that the received data is mapped to.
**Retrieve the data into that structure (service)**
```
get_users_by_id(id) {
return this.http.get<User>(this.baseUrl + '/users/' + id);
}
```
Notice the generic argument: `this.http.get<User>`. By specifying `User` here, we are telling the built-in `http` service to retrieve the data into that structure.
**Subscribe in the client (component)**
```
export class AppComponent implements OnInit {
data: User;
constructor(private dataService: DataService) {}
ngOnInit() {
this.get_users_by_id(1);
}
get_users_by_id(id) {
this.dataService.get_users_by_id(id).subscribe((res: User) => {
this.data = res;
});
}
}
```
Now, when the response is returned to the first function passed to the `subscribe` method, the data is already mapped to a `User`.
**Display the single user in the UI (template)**
```
<ul>
<li>
{{data.name}}
</li>
</ul>
```
Then this does not really make sense as a list. Are you expecting the "get\_users\_by\_id" to normally return more than one user? | Do check out the [keyvalue](https://angular.io/api/common/KeyValuePipe) pipe.
Using `keyvalue` pipe:
```
<ul>
<ng-container *ngFor="let element of data | keyvalue">
<li *ngIf="element.key === 'name'">
<span>{{element.value }}</span>
</li>
</ng-container>
</ul>
```
Working demo: <https://stackblitz.com/edit/keyvalue-pipe-uvovp7> |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | I found it's not enough for the app and account to be added as owners. I would go into your storage account > IAM > Add role assignment, and add the special permissions for this type of request:
* Storage Blob Data Contributor
* Storage Queue Data Contributor | Be aware that if you want to apply "STORAGE BLOB DATA XXXX" role at the subscription level it will not work if your subscription has Azure DataBricks namespaces:
>
> If your subscription includes an Azure DataBricks namespace, roles assigned at the subscription scope will be blocked from granting access to blob and queue data.
>
>
>
Source: <https://learn.microsoft.com/en-us/azure/storage/common/storage-auth-aad-rbac-portal#determine-resource-scope> |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | I've just solved this by changing the resource requested in the GetAccessTokenAsync method from "<https://storage.azure.com>" to the url of my storage blob as in this snippet:
```
public async Task<StorageCredentials> CreateStorageCredentialsAsync()
{
var provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync(AzureStorageContainerUrl);
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
return storageCredentials;
}
```
where AzureStorageContainerUrl is set to <https://xxxxxxxxx.blob.core.windows.net/> | Used the following to connect using Azure AD to blob storage:
This is code uses SDK V11 since V12 still has issues with multi AD accounts
See this issue
<https://github.com/Azure/azure-sdk-for-net/issues/8658>
For further reading on V12 and V11 SDK
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet-legacy>
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet>
```
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.Queue;
[Fact]
public async Task TestStreamToContainer()
{
try
{
var accountName = "YourStorageAccountName";
var containerName = "YourContainerName";
var blobName = "File1";
var provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync($"https://{accountName}.blob.core.windows.net");
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
string containerEndpoint = $"https://{accountName}.blob.core.windows.net";
var blobClient = new CloudBlobClient(new Uri(containerEndpoint), storageCredentials);
var containerClient = blobClient.GetContainerReference(containerName);
var cloudBlob = containerClient.GetBlockBlobReference(blobName);
string blobContents = "This is a block blob contents.";
byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);
using (MemoryStream stream = new MemoryStream(byteArray))
{
await cloudBlob.UploadFromStreamAsync(stream);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
``` |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | I found it's not enough for the app and account to be added as owners. I would go into your storage account > IAM > Add role assignment, and add the special permissions for this type of request:
* Storage Blob Data Contributor
* Storage Queue Data Contributor | Used the following to connect using Azure AD to blob storage:
This is code uses SDK V11 since V12 still has issues with multi AD accounts
See this issue
<https://github.com/Azure/azure-sdk-for-net/issues/8658>
For further reading on V12 and V11 SDK
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet-legacy>
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet>
```
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.Queue;
[Fact]
public async Task TestStreamToContainer()
{
try
{
var accountName = "YourStorageAccountName";
var containerName = "YourContainerName";
var blobName = "File1";
var provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync($"https://{accountName}.blob.core.windows.net");
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
string containerEndpoint = $"https://{accountName}.blob.core.windows.net";
var blobClient = new CloudBlobClient(new Uri(containerEndpoint), storageCredentials);
var containerClient = blobClient.GetContainerReference(containerName);
var cloudBlob = containerClient.GetBlockBlobReference(blobName);
string blobContents = "This is a block blob contents.";
byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);
using (MemoryStream stream = new MemoryStream(byteArray))
{
await cloudBlob.UploadFromStreamAsync(stream);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
``` |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | Make sure to use Storage Blob Data Contributor and NOT Storage Account Contributor where the latter is only for managing the actual Storage Account and not the data in it. | Used the following to connect using Azure AD to blob storage:
This is code uses SDK V11 since V12 still has issues with multi AD accounts
See this issue
<https://github.com/Azure/azure-sdk-for-net/issues/8658>
For further reading on V12 and V11 SDK
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet-legacy>
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet>
```
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.Queue;
[Fact]
public async Task TestStreamToContainer()
{
try
{
var accountName = "YourStorageAccountName";
var containerName = "YourContainerName";
var blobName = "File1";
var provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync($"https://{accountName}.blob.core.windows.net");
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
string containerEndpoint = $"https://{accountName}.blob.core.windows.net";
var blobClient = new CloudBlobClient(new Uri(containerEndpoint), storageCredentials);
var containerClient = blobClient.GetContainerReference(containerName);
var cloudBlob = containerClient.GetBlockBlobReference(blobName);
string blobContents = "This is a block blob contents.";
byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);
using (MemoryStream stream = new MemoryStream(byteArray))
{
await cloudBlob.UploadFromStreamAsync(stream);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
``` |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | I found it's not enough for the app and account to be added as owners. I would go into your storage account > IAM > Add role assignment, and add the special permissions for this type of request:
* Storage Blob Data Contributor
* Storage Queue Data Contributor | I've just solved this by changing the resource requested in the GetAccessTokenAsync method from "<https://storage.azure.com>" to the url of my storage blob as in this snippet:
```
public async Task<StorageCredentials> CreateStorageCredentialsAsync()
{
var provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync(AzureStorageContainerUrl);
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
return storageCredentials;
}
```
where AzureStorageContainerUrl is set to <https://xxxxxxxxx.blob.core.windows.net/> |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | Make sure you add the `/Y` at the end of the command. | Used the following to connect using Azure AD to blob storage:
This is code uses SDK V11 since V12 still has issues with multi AD accounts
See this issue
<https://github.com/Azure/azure-sdk-for-net/issues/8658>
For further reading on V12 and V11 SDK
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet-legacy>
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet>
```
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.Queue;
[Fact]
public async Task TestStreamToContainer()
{
try
{
var accountName = "YourStorageAccountName";
var containerName = "YourContainerName";
var blobName = "File1";
var provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync($"https://{accountName}.blob.core.windows.net");
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
string containerEndpoint = $"https://{accountName}.blob.core.windows.net";
var blobClient = new CloudBlobClient(new Uri(containerEndpoint), storageCredentials);
var containerClient = blobClient.GetContainerReference(containerName);
var cloudBlob = containerClient.GetBlockBlobReference(blobName);
string blobContents = "This is a block blob contents.";
byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);
using (MemoryStream stream = new MemoryStream(byteArray))
{
await cloudBlob.UploadFromStreamAsync(stream);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
``` |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | Be aware that if you want to apply "STORAGE BLOB DATA XXXX" role at the subscription level it will not work if your subscription has Azure DataBricks namespaces:
>
> If your subscription includes an Azure DataBricks namespace, roles assigned at the subscription scope will be blocked from granting access to blob and queue data.
>
>
>
Source: <https://learn.microsoft.com/en-us/azure/storage/common/storage-auth-aad-rbac-portal#determine-resource-scope> | Used the following to connect using Azure AD to blob storage:
This is code uses SDK V11 since V12 still has issues with multi AD accounts
See this issue
<https://github.com/Azure/azure-sdk-for-net/issues/8658>
For further reading on V12 and V11 SDK
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet-legacy>
<https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet>
```
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.Queue;
[Fact]
public async Task TestStreamToContainer()
{
try
{
var accountName = "YourStorageAccountName";
var containerName = "YourContainerName";
var blobName = "File1";
var provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync($"https://{accountName}.blob.core.windows.net");
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
string containerEndpoint = $"https://{accountName}.blob.core.windows.net";
var blobClient = new CloudBlobClient(new Uri(containerEndpoint), storageCredentials);
var containerClient = blobClient.GetContainerReference(containerName);
var cloudBlob = containerClient.GetBlockBlobReference(blobName);
string blobContents = "This is a block blob contents.";
byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);
using (MemoryStream stream = new MemoryStream(byteArray))
{
await cloudBlob.UploadFromStreamAsync(stream);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
``` |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | Make sure to use Storage Blob Data Contributor and NOT Storage Account Contributor where the latter is only for managing the actual Storage Account and not the data in it. | Be aware that if you want to apply "STORAGE BLOB DATA XXXX" role at the subscription level it will not work if your subscription has Azure DataBricks namespaces:
>
> If your subscription includes an Azure DataBricks namespace, roles assigned at the subscription scope will be blocked from granting access to blob and queue data.
>
>
>
Source: <https://learn.microsoft.com/en-us/azure/storage/common/storage-auth-aad-rbac-portal#determine-resource-scope> |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | I found it's not enough for the app and account to be added as owners. I would go into your storage account > IAM > Add role assignment, and add the special permissions for this type of request:
* Storage Blob Data Contributor
* Storage Queue Data Contributor | Make sure to use Storage Blob Data Contributor and NOT Storage Account Contributor where the latter is only for managing the actual Storage Account and not the data in it. |
52,769,758 | I am building an Angular 6 application that will be able to make CRUD operation on Azure Blob Storage. I'm however using postman to test requests before implementing them inside the app and copy-pasting the token that I get from Angular for that resource.
When trying to read a file that I have inside the storage for test purposes, I'm getting: `<Code>AuthorizationPermissionMismatch</Code>
<Message>This request is not authorized to perform this operation using this permission.`
* All in production environment (although developing)
* Token acquired specifically for storage resource via Oauth
* Postman has the token strategy as "bearer "
* Application has "Azure Storage" delegated permissions granted.
* Both the app and the account I'm acquiring the token are added as "owners" in azure access control IAM
* My IP is added to CORS settings on the blob storage.
* StorageV2 (general purpose v2) - Standard - Hot
* x-ms-version header used is: `2018-03-28` because that's the latest I could find and I just created the storage account. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52769758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10064334/"
] | Make sure to use Storage Blob Data Contributor and NOT Storage Account Contributor where the latter is only for managing the actual Storage Account and not the data in it. | I've just solved this by changing the resource requested in the GetAccessTokenAsync method from "<https://storage.azure.com>" to the url of my storage blob as in this snippet:
```
public async Task<StorageCredentials> CreateStorageCredentialsAsync()
{
var provider = new AzureServiceTokenProvider();
var token = await provider.GetAccessTokenAsync(AzureStorageContainerUrl);
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
return storageCredentials;
}
```
where AzureStorageContainerUrl is set to <https://xxxxxxxxx.blob.core.windows.net/> |
1,779,428 | We have an application that has been deployed to 50+ websites. Across these sites we have noticed a piece of strange behaviour, we have now tracked this to one specific query. Very occasionally, once or twice a day usually, one of our debugging scripts reports
```
2006 : MySQL server has gone away
```
I know there are a number of reasons this error can be thrown but the thing that is most strange is that every single time it is thrown it happens from the same SQL query being run. There is nothing strange or complex about this query, it looks like this:
```
SELECT `advert_only` FROM `products` WHERE `id` = '6197'
```
This query must run tens of thousands of times a day, for various different product IDs so it certainly doesnt fail each time. It fails randomly on seemingly random sites across our 4 servers. There is seemingly no commonality, one small thing we have noticed is that it sometimes will happen on 2 or 3 page loads in a row for 1 specific person as we also track the IP of the person it has happened to.
This is on CentOS 5 servers running MySQL 5.0.81 | 2009/11/22 | [
"https://Stackoverflow.com/questions/1779428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112451/"
] | This is kind of in left field, but you should check your harddisk SMART for any errors. If there are issues reading from "that" sector then there may be issues. If you have a raid unit I wouldn't worry too much about this. I wouldn't give a high probability to this being the problem, but if you are really stumped then it might be worth it. | on <http://bugs.mysql.com/bug.php?id=1011> the second comment says that: "the 'MySQL server has gone away' error is caused by a query longer than the max\_allowed\_packet."
there is some more information on fixing it here: <http://bogdan.org.ua/2008/12/25/how-to-fix-mysql-server-has-gone-away-error-2006.html> |
1,779,428 | We have an application that has been deployed to 50+ websites. Across these sites we have noticed a piece of strange behaviour, we have now tracked this to one specific query. Very occasionally, once or twice a day usually, one of our debugging scripts reports
```
2006 : MySQL server has gone away
```
I know there are a number of reasons this error can be thrown but the thing that is most strange is that every single time it is thrown it happens from the same SQL query being run. There is nothing strange or complex about this query, it looks like this:
```
SELECT `advert_only` FROM `products` WHERE `id` = '6197'
```
This query must run tens of thousands of times a day, for various different product IDs so it certainly doesnt fail each time. It fails randomly on seemingly random sites across our 4 servers. There is seemingly no commonality, one small thing we have noticed is that it sometimes will happen on 2 or 3 page loads in a row for 1 specific person as we also track the IP of the person it has happened to.
This is on CentOS 5 servers running MySQL 5.0.81 | 2009/11/22 | [
"https://Stackoverflow.com/questions/1779428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112451/"
] | on <http://bugs.mysql.com/bug.php?id=1011> the second comment says that: "the 'MySQL server has gone away' error is caused by a query longer than the max\_allowed\_packet."
there is some more information on fixing it here: <http://bogdan.org.ua/2008/12/25/how-to-fix-mysql-server-has-gone-away-error-2006.html> | That means that sql connection was idle for too long. Check if there are some slow operations performed before your sql-query. |
1,779,428 | We have an application that has been deployed to 50+ websites. Across these sites we have noticed a piece of strange behaviour, we have now tracked this to one specific query. Very occasionally, once or twice a day usually, one of our debugging scripts reports
```
2006 : MySQL server has gone away
```
I know there are a number of reasons this error can be thrown but the thing that is most strange is that every single time it is thrown it happens from the same SQL query being run. There is nothing strange or complex about this query, it looks like this:
```
SELECT `advert_only` FROM `products` WHERE `id` = '6197'
```
This query must run tens of thousands of times a day, for various different product IDs so it certainly doesnt fail each time. It fails randomly on seemingly random sites across our 4 servers. There is seemingly no commonality, one small thing we have noticed is that it sometimes will happen on 2 or 3 page loads in a row for 1 specific person as we also track the IP of the person it has happened to.
This is on CentOS 5 servers running MySQL 5.0.81 | 2009/11/22 | [
"https://Stackoverflow.com/questions/1779428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112451/"
] | This is kind of in left field, but you should check your harddisk SMART for any errors. If there are issues reading from "that" sector then there may be issues. If you have a raid unit I wouldn't worry too much about this. I wouldn't give a high probability to this being the problem, but if you are really stumped then it might be worth it. | That means that sql connection was idle for too long. Check if there are some slow operations performed before your sql-query. |
9,280,649 | I have a page that mostly consists of HTML in a WebBrowser control. I was able to set the background quite easily using the PhoneLightThemeVisibility Resource because it's either Black or White.
I was wondering how to get the Accent brush and turn it into a HTML code so I can use it in my HTML. | 2012/02/14 | [
"https://Stackoverflow.com/questions/9280649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200015/"
] | ```
var brush = (App.Current.Resources["PhoneAccentBrush"] as SolidColorBrush);
string fullColourCode = brush.Color.ToString();
string HTMLColourCode = "#" + fullColourCode.Substring(3);
```
or access the component values individually and build from there....
```
string RedComponent = brush.Color.R.ToString();
string GreenComponent = brush.Color.G.ToString();
string BlueComponent = brush.Color.B.ToString();
```
Note that the red, green and blue component values will need to be manipulated in order to produce and HTML Colour code. | I think you could use the following (assuming that `AppWorkspaceColor` is the one required):
```
Color appColor = SystemColors.AppWorkspaceColor;
string strColorAsHTML = appColor.ToString();
```
Hope this helps. |
3,742,674 | 18 diplomats sit on a rectangular table. Three are from China, four are from Japan, six are from the United States and five are from France. In how many ways can we seat the diplomats at the table so that both the Chinese and the Japanese stay together, but separated from each other?
I thought I had this sorted out, but no.
My proposed solution was the following:
First I allocated the 11 diplomats (US + France) that can sit without restrictions: $$ 11! $$
Then I count the number of places between these diplomats in which the Chinese or the Japanese groups can sit: $$ 11 $$ , since that this is a closed arrangement, the 'last' diplomat is next to the 'first' one.
Then I started by allocating the Chinese group. The Chinese group can stay in 11 places between the $$ 11 $$ diplomats and they can be arranged in $$ 3! $$ ways within themselves: $$ 11 \* 3! $$
After the Chinese are seated, we have $$ 10 $$ places left between the diplomats where the Japanese can sit; the Japanese diplomats can be arranged in $$ 4! $$ ways amongst themselves: $$ 10 \* 4! $$ .
Lastly, we have to consider the symmetry of the rectangle, meaning that we have been counting these arrangements twice, as the sides of the rectangle are equal two-by-two.
So in my mind we should have in total $$ \frac{11! \* 11\* 3! \* 10 \* 4!}{2} = 316 141 056 000 $$ .
However, the number of ways is supposed to be $$ 379 369 267 200 $$ . Can you please help me find what is wrong in my thinking?
Thank you. | 2020/07/02 | [
"https://math.stackexchange.com/questions/3742674",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/439683/"
] | **Long solution**
The cartesian equation of the plane is $$\pi: 2x-5y-z-4=0$$
The parametric equations of the line $r$ which is perpendicular to $\pi$ and contains $A=(10,0,20)$ are $$r:\begin{cases}x=10+2t\\y=-5t\\z=20-t\end{cases}$$. This line also contains $B$ so the coordinates of $B$ are $(10+t,-5t,20-t)$ for some $t\in \Bbb R$.
The cartesian equations of $r$ are $$r:\begin{cases} y-5z+100=0 \\x+2z-50=0\end{cases}$$
The line $r$ intersects $\pi$ in the middle point $M$ between $A$ and $B$. Let's find the coordinates of $M$ by solving :$$\begin{cases} 2x-5y-z-4=0\\y-5z+100=0 \\x+2z-50=0\end{cases}$$
Once you've found the coordinates of $M=(x\_M,y\_M,z\_M)$ you solve for $t$ $$||A-M||=||B-M||$$ $$\sqrt{(10-x\_M)^2+(-y\_M)^2+(20-z\_M)^2}=\sqrt{(10+t-x\_M)^2+(-5t-y\_M)^2+(20-t-z\_M)^2}$$
Lastly substitute the value of $t$ you've just found in $(10+t,-5t,20-t)$ to find the coordinates of $B$.
**Shorter solution**
For each alternative point $P$ that the exercise gives you, calculate the vector $\vec{AP}$ and check if it's parallel to the vector $(2,-5,-1)$ which is perpendicular to the plane. If this is true for more then one of the alternatives calculate the distance of $A$ and $P$ from $\pi$ and check if they're equal. The one alternative that verifies these two conditions ($\vec {AP}$ perpendicular to $\pi$ and $A$ and $P$ at the same distance from $\pi$) is $B$. | An equation of the plane is
\begin{equation}
x = 2 + 3 y + (z-y)/2 \Longleftrightarrow 2 x - 5 y -z -4 = 0
\end{equation}
Let $A = (x\_0,y\_0,z\_0) = (10, 0, 20)$ and $B = (x\_1, y\_1, z\_1)= A + t (2, -5, -1)$ because the vector $(2, -5, -1)$ is perpendicular to the plane. We have $2 x\_0-5 y\_0 -z\_0 - 4 = -4$, hence we need $2 x\_1-5 y\_1 -z\_1 - 4 = +4$ in order to have the midpoint $(A + B)/2$ on the plane. This implies $t = 8/30 = 4/ 15$, hence
\begin{equation}
x\_1 = 10 + \frac{8}{15}=\frac{158}{15}\qquad
y\_1 = -\frac{20}{15}\qquad z\_1 = 20 -\frac{4}{15} = \frac{296}{15}
\end{equation} |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | This was caused by an incompatibility between `react-native-webview` and `react-native-screens`, which you must depend on if you are using `@react-navigation/*` packages.
**EDIT**: there seems to have been a regression since. [It's being tracked here](https://github.com/react-navigation/react-navigation/issues/9755).
Fixed in `react-native-screens@2.12.0`
--------------------------------------
See CHANGELOG in <https://github.com/software-mansion/react-native-screens/releases/tag/2.12.0>
If you can't upgrade react-native-screens
-----------------------------------------
There are 3 workarounds:
### WebView opacity
```js
const tagsStyles = {
iframe: {
opacity: 0.99
},
// If you are using @native-html/table-plugin
table: {
opacity: 0.99
}
}
```
And use this prop when rendering:
```js
return <HTML tagsStyles={tagsStyles} ... />
```
### Disabling hardware acceleration
In `android/app/src/main/AndroidManifest.xml`:
```xml
<activity
android:hardwareAccelerated="false"
/>
```
### Disabling native screens
From your `App.js` file:
```js
// import {enableScreens} from 'react-native-screens';
// enableScreens();
``` | Disabling the navigation animation for the screen worked for me. I just added `animationEnabled: false,` as shown below.
```
const StackNavigator = props => {
return (
<Stack.Navigator>
...
<Stack.Screen
name="WebViewScreen"
component={WebViewScreen}
options={{
animationEnabled: false, // <--- Add this option.
}}
/>
...
</Stack.Navigator>
);
};
``` |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | This was caused by an incompatibility between `react-native-webview` and `react-native-screens`, which you must depend on if you are using `@react-navigation/*` packages.
**EDIT**: there seems to have been a regression since. [It's being tracked here](https://github.com/react-navigation/react-navigation/issues/9755).
Fixed in `react-native-screens@2.12.0`
--------------------------------------
See CHANGELOG in <https://github.com/software-mansion/react-native-screens/releases/tag/2.12.0>
If you can't upgrade react-native-screens
-----------------------------------------
There are 3 workarounds:
### WebView opacity
```js
const tagsStyles = {
iframe: {
opacity: 0.99
},
// If you are using @native-html/table-plugin
table: {
opacity: 0.99
}
}
```
And use this prop when rendering:
```js
return <HTML tagsStyles={tagsStyles} ... />
```
### Disabling hardware acceleration
In `android/app/src/main/AndroidManifest.xml`:
```xml
<activity
android:hardwareAccelerated="false"
/>
```
### Disabling native screens
From your `App.js` file:
```js
// import {enableScreens} from 'react-native-screens';
// enableScreens();
``` | For me the error was triggered by social media iframes.
Applying `style = {{ opacity: 0.99 }}` was the only thing that worked for me:
```
<WebView
useWebKit={true}
scrollEnabled={false}
scalesPageToFit={true}
source={{ html: html }}
javaScriptEnabled={true}
bounces={false}
overScrollMode={'never'}
pagingEnabled={true}
style={{ opacity: 0.99 }} //<---------
/>
```
Source: <https://github.com/react-native-webview/react-native-webview/issues/811> |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | The updated solution for this is **androidLayerType="software"**, since **androidHardwareAccelerationDisabled** is now deprecated.
ex:-
```
<AutoHeightWebView
androidHardwareAccelerationDisabled // update here androidLayerType="software"
...
/>
``` | Disabling the navigation animation for the screen worked for me. I just added `animationEnabled: false,` as shown below.
```
const StackNavigator = props => {
return (
<Stack.Navigator>
...
<Stack.Screen
name="WebViewScreen"
component={WebViewScreen}
options={{
animationEnabled: false, // <--- Add this option.
}}
/>
...
</Stack.Navigator>
);
};
``` |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | One more fix is to disable animation for react-navigation in navigationOptions.
```
static navigationOptions = () => ({
animationEnabled: false,
});
``` | Another workaround is to add `androidLayerType: 'software'` in `webViewProps` inside `htmlProps` which pass to render HTML table as mentioned below.
```
const webViewProps = {
androidLayerType: 'software',
}
const htmlProps = {
WebView,
renderers: {
table: TableRenderer,
},
renderersProps: {
table: {
cssRules,
webViewProps,
computeContainerHeight() {
return null
},
},
},
customHTMLElementModels: {
table: tableModel,
},
}
```
<https://github.com/react-navigation/react-navigation/issues/6960#issuecomment-587418809> |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | The updated solution for this is **androidLayerType="software"**, since **androidHardwareAccelerationDisabled** is now deprecated.
ex:-
```
<AutoHeightWebView
androidHardwareAccelerationDisabled // update here androidLayerType="software"
...
/>
``` | Another workaround is to add `androidLayerType: 'software'` in `webViewProps` inside `htmlProps` which pass to render HTML table as mentioned below.
```
const webViewProps = {
androidLayerType: 'software',
}
const htmlProps = {
WebView,
renderers: {
table: TableRenderer,
},
renderersProps: {
table: {
cssRules,
webViewProps,
computeContainerHeight() {
return null
},
},
},
customHTMLElementModels: {
table: tableModel,
},
}
```
<https://github.com/react-navigation/react-navigation/issues/6960#issuecomment-587418809> |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | This was caused by an incompatibility between `react-native-webview` and `react-native-screens`, which you must depend on if you are using `@react-navigation/*` packages.
**EDIT**: there seems to have been a regression since. [It's being tracked here](https://github.com/react-navigation/react-navigation/issues/9755).
Fixed in `react-native-screens@2.12.0`
--------------------------------------
See CHANGELOG in <https://github.com/software-mansion/react-native-screens/releases/tag/2.12.0>
If you can't upgrade react-native-screens
-----------------------------------------
There are 3 workarounds:
### WebView opacity
```js
const tagsStyles = {
iframe: {
opacity: 0.99
},
// If you are using @native-html/table-plugin
table: {
opacity: 0.99
}
}
```
And use this prop when rendering:
```js
return <HTML tagsStyles={tagsStyles} ... />
```
### Disabling hardware acceleration
In `android/app/src/main/AndroidManifest.xml`:
```xml
<activity
android:hardwareAccelerated="false"
/>
```
### Disabling native screens
From your `App.js` file:
```js
// import {enableScreens} from 'react-native-screens';
// enableScreens();
``` | The updated solution for this is **androidLayerType="software"**, since **androidHardwareAccelerationDisabled** is now deprecated.
ex:-
```
<AutoHeightWebView
androidHardwareAccelerationDisabled // update here androidLayerType="software"
...
/>
``` |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | One more fix is to disable animation for react-navigation in navigationOptions.
```
static navigationOptions = () => ({
animationEnabled: false,
});
``` | For me the error was triggered by social media iframes.
Applying `style = {{ opacity: 0.99 }}` was the only thing that worked for me:
```
<WebView
useWebKit={true}
scrollEnabled={false}
scalesPageToFit={true}
source={{ html: html }}
javaScriptEnabled={true}
bounces={false}
overScrollMode={'never'}
pagingEnabled={true}
style={{ opacity: 0.99 }} //<---------
/>
```
Source: <https://github.com/react-native-webview/react-native-webview/issues/811> |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | The updated solution for this is **androidLayerType="software"**, since **androidHardwareAccelerationDisabled** is now deprecated.
ex:-
```
<AutoHeightWebView
androidHardwareAccelerationDisabled // update here androidLayerType="software"
...
/>
``` | For me the error was triggered by social media iframes.
Applying `style = {{ opacity: 0.99 }}` was the only thing that worked for me:
```
<WebView
useWebKit={true}
scrollEnabled={false}
scalesPageToFit={true}
source={{ html: html }}
javaScriptEnabled={true}
bounces={false}
overScrollMode={'never'}
pagingEnabled={true}
style={{ opacity: 0.99 }} //<---------
/>
```
Source: <https://github.com/react-native-webview/react-native-webview/issues/811> |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | One more fix is to disable animation for react-navigation in navigationOptions.
```
static navigationOptions = () => ({
animationEnabled: false,
});
``` | The updated solution for this is **androidLayerType="software"**, since **androidHardwareAccelerationDisabled** is now deprecated.
ex:-
```
<AutoHeightWebView
androidHardwareAccelerationDisabled // update here androidLayerType="software"
...
/>
``` |
63,171,131 | When enabling screens in `react-native-screens`, and having a screen which renders an `<HTML />` component passed with an `iframe` HTML element, the app crashes while pressing the back button to return to the home screen. [Full reproduction here](https://github.com/drb1/DemoForVideoCrashHtml).
Environment
-----------
* React Native: 0.61.5
* react-native-render-html: 4.2.2
* react-native-webview: 10.3.2
* react-native-screens: 2.8.0
* react-native-render-html-table-bridge: 0.6.1
Crash log
---------
```
07-29 17:41:49.173 6901 6901 F crashpad: dlopen: dlopen failed: library "libandroidicu.so" not found: needed by /system/lib/libharfbuzz_ng.so in namespace (default)
--------- beginning of crash
07-29 17:41:49.176 6410 6441 F libc : Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c in tid 6441 (RenderThread), pid 6410 (com.newmednav)
07-29 17:41:49.340 6904 6904 F DEBUG : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
07-29 17:41:49.340 6904 6904 F DEBUG : Build fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RPB2.200611.009/6625208:userdebug/dev-keys'
07-29 17:41:49.340 6904 6904 F DEBUG : Revision: '0'
07-29 17:41:49.340 6904 6904 F DEBUG : ABI: 'x86'
07-29 17:41:49.340 6904 6904 F DEBUG : Timestamp: 2020-07-29 17:41:49+0545
07-29 17:41:49.340 6904 6904 F DEBUG : pid: 6410, tid: 6441, name: RenderThread >>> com.newmednav <<<
07-29 17:41:49.340 6904 6904 F DEBUG : uid: 10152
07-29 17:41:49.340 6904 6904 F DEBUG : signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x1c
07-29 17:41:49.340 6904 6904 F DEBUG : Cause: null pointer dereference
07-29 17:41:49.340 6904 6904 F DEBUG : eax efbc2cb0 ebx eed5c69c ecx eed52a80 edx 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : edi d139ae90 esi 00000000
07-29 17:41:49.341 6904 6904 F DEBUG : ebp c086ed48 esp c086eb50 eip ee698c1c
07-29 17:41:49.425 6904 6904 F DEBUG : backtrace:
07-29 17:41:49.425 6904 6904 F DEBUG : #00 pc 00247c1c /system/lib/libhwui.so (android::uirenderer::skiapipeline::GLFunctorDrawable::onDraw(SkCanvas*)+1548) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #01 pc 00303a57 /system/lib/libhwui.so (SkDrawable::draw(SkCanvas*, SkMatrix const*)+87) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #02 pc 002f4606 /system/lib/libhwui.so (SkBaseDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+38) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #03 pc 00659291 /system/lib/libhwui.so (SkGpuDevice::drawDrawable(SkDrawable*, SkMatrix const*, SkCanvas*)+353) (BuildId: 434a9b68672e1dd2b15599730362463d)
07-29 17:41:49.425 6904 6904 F DEBUG : #04 pc 002d9dc0 /system/lib/libhwui.so (SkCanvas::onDrawDrawable(SkDrawable*, SkMatrix const*)+48) (BuildId: 434a9b68672e1dd2b15599730362463d)
``` | 2020/07/30 | [
"https://Stackoverflow.com/questions/63171131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13369047/"
] | One more fix is to disable animation for react-navigation in navigationOptions.
```
static navigationOptions = () => ({
animationEnabled: false,
});
``` | Disabling the navigation animation for the screen worked for me. I just added `animationEnabled: false,` as shown below.
```
const StackNavigator = props => {
return (
<Stack.Navigator>
...
<Stack.Screen
name="WebViewScreen"
component={WebViewScreen}
options={{
animationEnabled: false, // <--- Add this option.
}}
/>
...
</Stack.Navigator>
);
};
``` |
59,829,930 | I am trying to write unit test for the React functional component which has router hooks `useLocation()` like below.
```
//index.js
function MyComponent(props) {
const useQuery = () => new URLSearchParams(useLocation().search);
const status = useQuery().get('status');
if (status === 'success') {
return <ShowStatus message="OK" secret={props.secret} />;
} else {
return <ShowStatus message="NOT OK" secret={props.secret} />;
}
}
//index.spec.js
describe('Test MyComponent', () => {
it('should send OK when success', () => {
sinon.stub(reactRouter, 'useLocation').returns({
search: {
status: 'success'
}
});
const props = { secret: 'SECRET_KEY' };
const wrapper = enzyme.shallow(<MyComponent.WrappedComponent {...props}/>);
expect(wrapper.type()).to.have.length(MyComponent);
expect(wrapper.props().message).to.equal('OK');
expect(wrapper.props().secret).to.equal(props.secret);
});
it('should send NOT OK when error', () => {
sinon.stub(reactRouter, 'useLocation').returns({
search: {
status: 'error'
}
});
const props = { secret: 'SECRET_KEY' };
const wrapper = enzyme.shallow(<MyComponent.WrappedComponent {...props}/>);
expect(wrapper.type()).to.have.length(MyComponent);
expect(wrapper.props().message).to.equal('NOT OK);
expect(wrapper.props().secret).to.equal(props.secret);
});
});
```
Even I am stubbing `useLocation` I am getting error
```
TypeError: Cannot read property 'location' of undefined
at useLocation (node_modules\react-router\modules\hooks.js:28:10)
```
I am trying to test `ShowStatus` component is render with right props based on the query param.
Any suggestion/help is appreciated.
**Update:**
I am noticing even though I am importing from `react-router-dom` in both prod and test code. I am seeing prod one is taking from `react-router`. | 2020/01/20 | [
"https://Stackoverflow.com/questions/59829930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4035943/"
] | Use [MemoryRouter](https://reactrouter.com/web/api/MemoryRouter) component wraps your component is better than stub `useLocation` hook.
>
> keeps the history of your “URL” in memory (does not read or write to the address bar). Useful in tests and non-browser environments like React Native.
>
>
>
We can provide the "URL" to your component under test via [initialEntries](https://reactrouter.com/web/api/MemoryRouter/initialentries-array) props.
`index.tsx`:
```
import React from 'react';
import { useLocation } from 'react-router-dom';
export function ShowStatus({ message, secret }) {
return <div>{message}</div>;
}
export function MyComponent(props) {
const useQuery = () => new URLSearchParams(useLocation().search);
const status = useQuery().get('status');
if (status === 'success') {
return <ShowStatus message="OK" secret={props.secret} />;
} else {
return <ShowStatus message="NOT OK" secret={props.secret} />;
}
}
```
`index.test.tsx`:
```
import { mount } from 'enzyme';
import React from 'react';
import { MemoryRouter } from 'react-router';
import { MyComponent, ShowStatus } from './';
describe('MyComponent', () => {
it('should send OK when success', () => {
const props = { secret: 'SECRET_KEY' };
const wrapper = mount(
<MemoryRouter initialEntries={[{ search: '?status=success' }]}>
<MyComponent {...props} />
</MemoryRouter>
);
expect(wrapper.find(ShowStatus).props().message).toEqual('OK');
expect(wrapper.find(MyComponent).props().secret).toEqual(props.secret);
});
it('should send NOT OK when error', () => {
const props = { secret: 'SECRET_KEY' };
const wrapper = mount(
<MemoryRouter initialEntries={[{ search: '?status=error' }]}>
<MyComponent {...props} />
</MemoryRouter>
);
expect(wrapper.find(ShowStatus).props().message).toEqual('NOT OK');
expect(wrapper.find(MyComponent).props().secret).toEqual(props.secret);
});
});
```
test result:
```
PASS examples/59829930/index.test.tsx (8.239 s)
MyComponent
✓ should send OK when success (55 ms)
✓ should send NOT OK when error (8 ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 9.003 s
```
package versions:
```json
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"jest": "^26.6.3",
"react": "^16.14.0",
"react-router-dom": "^5.2.0",
``` | Have you got this to work? Its very similar to what I am doing and asked the question here:
[How do you mock useLocation() pathname using shallow test enzyme Reactjs?](https://stackoverflow.com/questions/59949052/how-do-you-mock-uselocation-pathname-using-shallow-test-enzyme-reactjs) |
35,026,459 | I have gone through the .trigger() document <http://api.jquery.com/trigger/> . But still not sure how this fiddle works. The link: <https://jsfiddle.net/LanceShi/s7pm43f3/2/>
**HTML:**
```
<input id="theInput"/>
```
**Javascript**
```
$(document).ready(function() {
$("#theInput").trigger("input");
});
$("#theInput").on("input", function() {
alert("Here");
});
```
Now the input event is fired on every keyup/paste event. But I don't see anywhere in the .trigger() document mentioning this. How does this work? | 2016/01/27 | [
"https://Stackoverflow.com/questions/35026459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018268/"
] | It's not trigger doing that. Your trigger is only being fired once.
The reason is that `input` event encompasses numerous other events such as keyup, change, paste and a few others also
As noted by others you need to correct your order of calling trigger before adding listener | You need to `register` the event before you can `invoke`. Since you have declare a DOM event ( something which is not registered as a jquery event ) , you need to use the function `trigger()`. For the ones which are pre-defined in jquery ( like `click`, `change` ) , you can invoke them directly without the need of `trigger`.
```
$(document).ready(function() {
$("#theInput").on("input", function() {
alert("Here");
});
$("#theInput").trigger("input");
});
```
Example : <https://jsfiddle.net/DinoMyte/s7pm43f3/3/> |
35,026,459 | I have gone through the .trigger() document <http://api.jquery.com/trigger/> . But still not sure how this fiddle works. The link: <https://jsfiddle.net/LanceShi/s7pm43f3/2/>
**HTML:**
```
<input id="theInput"/>
```
**Javascript**
```
$(document).ready(function() {
$("#theInput").trigger("input");
});
$("#theInput").on("input", function() {
alert("Here");
});
```
Now the input event is fired on every keyup/paste event. But I don't see anywhere in the .trigger() document mentioning this. How does this work? | 2016/01/27 | [
"https://Stackoverflow.com/questions/35026459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018268/"
] | It's not trigger doing that. Your trigger is only being fired once.
The reason is that `input` event encompasses numerous other events such as keyup, change, paste and a few others also
As noted by others you need to correct your order of calling trigger before adding listener | In your code, `.trigger()` have no any effect because your `trigger()` will fire before `input` event attached.
So your code should be like this
```
$(document).ready(function() {
$("#theInput").on("input", function() {
alert("Here");
}).trigger('input');
});
```
**[Fiddle](https://jsfiddle.net/s7pm43f3/4/)** |
35,026,459 | I have gone through the .trigger() document <http://api.jquery.com/trigger/> . But still not sure how this fiddle works. The link: <https://jsfiddle.net/LanceShi/s7pm43f3/2/>
**HTML:**
```
<input id="theInput"/>
```
**Javascript**
```
$(document).ready(function() {
$("#theInput").trigger("input");
});
$("#theInput").on("input", function() {
alert("Here");
});
```
Now the input event is fired on every keyup/paste event. But I don't see anywhere in the .trigger() document mentioning this. How does this work? | 2016/01/27 | [
"https://Stackoverflow.com/questions/35026459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018268/"
] | It's not trigger doing that. Your trigger is only being fired once.
The reason is that `input` event encompasses numerous other events such as keyup, change, paste and a few others also
As noted by others you need to correct your order of calling trigger before adding listener | Here the explanation
As you have read in the documentation of jQuery, the Trigger function execute a custom event, well see here is executed
```
$("#theInput").trigger("input");
```
And where the hanlder is added was here
```
$("#theInput").on("input", function() {
alert("Here");
});
```
include what you say, when you write something in the input element runs what is in the function
```
function() {
alert("Here");
}
```
This is confusing at first because at first glance do not know what happens.
By adding the handler to #theInput you are adding a listener to the event type "input"
In JavaScript there is an event of type "input"
It works for elements "input" and "textarea" and this is executed when its value is changed or in other words when we write about them.
So really what this code is doing that.
Add a listener to #theInput with an event type "input".
If you want more information you can read the following:
<https://developer.mozilla.org/en-US/docs/Web/Events/input> |
35,026,459 | I have gone through the .trigger() document <http://api.jquery.com/trigger/> . But still not sure how this fiddle works. The link: <https://jsfiddle.net/LanceShi/s7pm43f3/2/>
**HTML:**
```
<input id="theInput"/>
```
**Javascript**
```
$(document).ready(function() {
$("#theInput").trigger("input");
});
$("#theInput").on("input", function() {
alert("Here");
});
```
Now the input event is fired on every keyup/paste event. But I don't see anywhere in the .trigger() document mentioning this. How does this work? | 2016/01/27 | [
"https://Stackoverflow.com/questions/35026459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018268/"
] | You need to `register` the event before you can `invoke`. Since you have declare a DOM event ( something which is not registered as a jquery event ) , you need to use the function `trigger()`. For the ones which are pre-defined in jquery ( like `click`, `change` ) , you can invoke them directly without the need of `trigger`.
```
$(document).ready(function() {
$("#theInput").on("input", function() {
alert("Here");
});
$("#theInput").trigger("input");
});
```
Example : <https://jsfiddle.net/DinoMyte/s7pm43f3/3/> | In your code, `.trigger()` have no any effect because your `trigger()` will fire before `input` event attached.
So your code should be like this
```
$(document).ready(function() {
$("#theInput").on("input", function() {
alert("Here");
}).trigger('input');
});
```
**[Fiddle](https://jsfiddle.net/s7pm43f3/4/)** |
35,026,459 | I have gone through the .trigger() document <http://api.jquery.com/trigger/> . But still not sure how this fiddle works. The link: <https://jsfiddle.net/LanceShi/s7pm43f3/2/>
**HTML:**
```
<input id="theInput"/>
```
**Javascript**
```
$(document).ready(function() {
$("#theInput").trigger("input");
});
$("#theInput").on("input", function() {
alert("Here");
});
```
Now the input event is fired on every keyup/paste event. But I don't see anywhere in the .trigger() document mentioning this. How does this work? | 2016/01/27 | [
"https://Stackoverflow.com/questions/35026459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4018268/"
] | You need to `register` the event before you can `invoke`. Since you have declare a DOM event ( something which is not registered as a jquery event ) , you need to use the function `trigger()`. For the ones which are pre-defined in jquery ( like `click`, `change` ) , you can invoke them directly without the need of `trigger`.
```
$(document).ready(function() {
$("#theInput").on("input", function() {
alert("Here");
});
$("#theInput").trigger("input");
});
```
Example : <https://jsfiddle.net/DinoMyte/s7pm43f3/3/> | Here the explanation
As you have read in the documentation of jQuery, the Trigger function execute a custom event, well see here is executed
```
$("#theInput").trigger("input");
```
And where the hanlder is added was here
```
$("#theInput").on("input", function() {
alert("Here");
});
```
include what you say, when you write something in the input element runs what is in the function
```
function() {
alert("Here");
}
```
This is confusing at first because at first glance do not know what happens.
By adding the handler to #theInput you are adding a listener to the event type "input"
In JavaScript there is an event of type "input"
It works for elements "input" and "textarea" and this is executed when its value is changed or in other words when we write about them.
So really what this code is doing that.
Add a listener to #theInput with an event type "input".
If you want more information you can read the following:
<https://developer.mozilla.org/en-US/docs/Web/Events/input> |
29,549,141 | I am looking to learn about using the Java CountDownLatch to control the execution of a thread.
I have two classes. One is called `Poller` and the other is `Referendum`. The threads are created in the `Referendum` class and their `run()` methods are contained in the `Poller` class.
In the Poller and Referendum classes I have imported the java countdown latch via import `java.util.concurrent.CountDownLatch`.
I am mainly looking to understand why and where the the `*.countDown();` and `*.await();` statements need to be applied and also to understand if I have correctly initialised the countDownLatch within the `Poller` constructor.
The complete code for the two classes are:
```
import java.util.concurrent.CountDownLatch;
public class Poller extends Thread
{
private String id; // pollster id
private int pollSize; // number of samples
private int numberOfPolls; // number of times to perform a poll
private Referendum referendum; // the referendum (implies voting population)
private int sampledVotes[]; // the counts of votes for or against
static CountDownLatch pollsAreComplete; //the CountDownLatch
/**
* Constructor for polling organisation.
* @param r A referendum on which the poller is gathering stats
* @param id The name of this polling organisation
* @param pollSize The size of the poll this poller will use
* @param pollTimes The number of times this poller will conduct a poll
* @param aLatch The coutn down latch that prevents the referendum results from being published
*/
public Poller(Referendum r, String id, int pollSize, int pollTimes, CountDownLatch aLatch)
{
this.referendum = r;
this.id = id;
this.pollSize = pollSize;
this.numberOfPolls = pollTimes;
this.pollsAreComplete = aLatch;
aLatch = new CountDownLatch(3);
// for and against votes to be counted
sampledVotes = new int[2];
}
// getter for numberOfPolls
public int getNumberOfPolls()
{
return numberOfPolls;
}
@Override
//to use the countdown latch
public void run()
{
for (int i = 0; i < getNumberOfPolls(); i++)
{
resetVotes();
pollVotes();
publishPollResults();
}
}
// make sure all sampledVotes are reset to zero
protected void resetVotes()
{
// initialise the vote counts in the poll
for (int i = 0; i < sampledVotes.length; i++)
{
sampledVotes[i] = 0;
}
}
// sampling the way citizens will vote in a referendum
protected void pollVotes()
{
for (int n = 0; n < pollSize; n++)
{
Citizen c = referendum.pickRandomCitizen();
//As things stand, pickRandomCitizen can return null
//because we haven't protected access to the collection
if (c != null)
{
sampledVotes[c.voteFor()]++;
}
}
}
protected void publishPollResults()
{
int vfor = 100 * sampledVotes[Referendum.FOR] / pollSize;
int vagainst = 100 * sampledVotes[Referendum.AGAINST] / pollSize;
System.out.printf("According to %-20s \t(", this.id + ":");
System.out.print("FOR " + vfor);
try
{
Thread.sleep(1000);
} catch (Exception e)
{
e.printStackTrace();
}
System.out.println(", AGAINST " + vagainst + ")");
}
}
```
And
```
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class Referendum
{
private List<Citizen> citizens; //voters
private List<Poller> pollers; //vote samplers
public static final int FOR = 0; //index for votes array
public static final int AGAINST = 1; //index for votes array
private int votes[]; //for and against votes counters
public Referendum(int population)
{
citizens = new LinkedList<Citizen>();
pollers = new LinkedList<Poller>();
// initialise the referendum with the population
for (int i = 0; i < population; i++)
{
Citizen c = new Citizen(i % 4); //suppose equal party membership
citizens.add(c);
}
votes = new int[2]; //in this example, only For or Against
}
public void addPoller(Poller np)
{
pollers.add(np);
}
public Citizen removeCitizen(int i)
{
return citizens.remove(i);
}
public List<Poller> getPollers()
{
return pollers;
}
public void startPollsWithLatch()
{
//create some poller threads that use a latch
addPoller(new Poller(this, "The Daily Day", 100, 3, Poller.pollsAreComplete));
addPoller(new Poller(this, "Stats people", 100, 3, Poller.pollsAreComplete));
addPoller(new Poller(this, "TV Pundits", 100, 3, Poller.pollsAreComplete));
// start the polls
for (Poller p : pollers)
{
p.start();
}
}
// pick a citizen randomly - access not controlled yet
public Citizen pickRandomCitizen()
{
//TODO add code to this method for part (b)
Citizen randomCitizen;
// first get a random index
int index = (int) (Math.random() * getPopulationSize());
randomCitizen = citizens.remove(index);
return randomCitizen;
}
// Counting the actual votes cast in the referendum
public void castVotes()
{
for (int h = 0; h < getPopulationSize(); h++)
{
Citizen c = citizens.get(h);
votes[c.voteFor()]++;
}
}
// tell the size of population
public int getPopulationSize()
{
return citizens.size();
}
// display the referendum results
public void revealResults()
{
System.out.println(" **** The Referendum Results are out! ****");
System.out.println("FOR");
System.out.printf("\t %.2f %%\n", 100.0 * votes[FOR] / getPopulationSize());
System.out.println("AGAINST");
System.out.printf("\t %.2f %%\n", 100.0 * votes[AGAINST] / getPopulationSize());
}
public static void main(String[] args)
{
// Initialise referendum. The number of people
// has been made smaller here to reduce the simulation time.
Referendum r = new Referendum(50000);
r.startPollsWithLatch();
r.castVotes();
// reveal the results of referendum
r.revealResults();
}
}
```
In a nutshell...
All threads must execute the `publishPollResults();` statement BEFORE the `revealResults();` is executed. | 2015/04/09 | [
"https://Stackoverflow.com/questions/29549141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3554289/"
] | The question mark at the beginning of the regex doesn't follow anything that can be made optional. If you want to match a literal question mark there, write `\?`:
```
x = int(re.findall(r"\?ent\s*took\s*([^m]*)",message)[0])
``` | First of all you need to escape `?` at the leading of your pattern, because the `?` mark is a regex character and make a string optional and must precede by a string! so if you want to math `?` you need to use `\?` also as a more efficient way you can use `re.search` and `\d+` in your pattern,and refuse from extra indexing :
```
>>> int(re.search(r"\?ent\s*took\s*(\d+)",s).group(1))
4001
```
For second example you can do :
```
>>> re.search(r'\((\d+)',s).group(1)
'12343'
```
And for match in both cases use the following pattern :
```
(\d+)[\s\w]+\(|\((\d+)
```
[Demo](https://regex101.com/r/zG4iG5/1)
```
>>> s1="Page load for http://xxxx?roxy=www.yahoo.com&sendto=https://mywebsite?ent took too long (12343 ms Ne: 167 ms, Se: 2509 ms, Xe: 1325 ms)<br><br><br>Topic: Yahoo!! My website is a good website | Mywebsite<br>"
>>> s2="Page load for http://xxxx?roxy=www.yahoo.com&sendto=https://mywebsite?ent took 4001 ms (Ne: 167 ms, Se: 2509 ms, Xe: 1325 ms)<br><br><br>Topic: Yahoo!! My website is a good website | Mywebsite<br>"
>>> re.search(r'(\d+)[\s\w]+\(|\((\d+)',s1).group(2)
'12343'
>>> re.search(r'(\d+)[\s\w]+\(|\((\d+)',s2).group(1)
'4001'
``` |
29,549,141 | I am looking to learn about using the Java CountDownLatch to control the execution of a thread.
I have two classes. One is called `Poller` and the other is `Referendum`. The threads are created in the `Referendum` class and their `run()` methods are contained in the `Poller` class.
In the Poller and Referendum classes I have imported the java countdown latch via import `java.util.concurrent.CountDownLatch`.
I am mainly looking to understand why and where the the `*.countDown();` and `*.await();` statements need to be applied and also to understand if I have correctly initialised the countDownLatch within the `Poller` constructor.
The complete code for the two classes are:
```
import java.util.concurrent.CountDownLatch;
public class Poller extends Thread
{
private String id; // pollster id
private int pollSize; // number of samples
private int numberOfPolls; // number of times to perform a poll
private Referendum referendum; // the referendum (implies voting population)
private int sampledVotes[]; // the counts of votes for or against
static CountDownLatch pollsAreComplete; //the CountDownLatch
/**
* Constructor for polling organisation.
* @param r A referendum on which the poller is gathering stats
* @param id The name of this polling organisation
* @param pollSize The size of the poll this poller will use
* @param pollTimes The number of times this poller will conduct a poll
* @param aLatch The coutn down latch that prevents the referendum results from being published
*/
public Poller(Referendum r, String id, int pollSize, int pollTimes, CountDownLatch aLatch)
{
this.referendum = r;
this.id = id;
this.pollSize = pollSize;
this.numberOfPolls = pollTimes;
this.pollsAreComplete = aLatch;
aLatch = new CountDownLatch(3);
// for and against votes to be counted
sampledVotes = new int[2];
}
// getter for numberOfPolls
public int getNumberOfPolls()
{
return numberOfPolls;
}
@Override
//to use the countdown latch
public void run()
{
for (int i = 0; i < getNumberOfPolls(); i++)
{
resetVotes();
pollVotes();
publishPollResults();
}
}
// make sure all sampledVotes are reset to zero
protected void resetVotes()
{
// initialise the vote counts in the poll
for (int i = 0; i < sampledVotes.length; i++)
{
sampledVotes[i] = 0;
}
}
// sampling the way citizens will vote in a referendum
protected void pollVotes()
{
for (int n = 0; n < pollSize; n++)
{
Citizen c = referendum.pickRandomCitizen();
//As things stand, pickRandomCitizen can return null
//because we haven't protected access to the collection
if (c != null)
{
sampledVotes[c.voteFor()]++;
}
}
}
protected void publishPollResults()
{
int vfor = 100 * sampledVotes[Referendum.FOR] / pollSize;
int vagainst = 100 * sampledVotes[Referendum.AGAINST] / pollSize;
System.out.printf("According to %-20s \t(", this.id + ":");
System.out.print("FOR " + vfor);
try
{
Thread.sleep(1000);
} catch (Exception e)
{
e.printStackTrace();
}
System.out.println(", AGAINST " + vagainst + ")");
}
}
```
And
```
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class Referendum
{
private List<Citizen> citizens; //voters
private List<Poller> pollers; //vote samplers
public static final int FOR = 0; //index for votes array
public static final int AGAINST = 1; //index for votes array
private int votes[]; //for and against votes counters
public Referendum(int population)
{
citizens = new LinkedList<Citizen>();
pollers = new LinkedList<Poller>();
// initialise the referendum with the population
for (int i = 0; i < population; i++)
{
Citizen c = new Citizen(i % 4); //suppose equal party membership
citizens.add(c);
}
votes = new int[2]; //in this example, only For or Against
}
public void addPoller(Poller np)
{
pollers.add(np);
}
public Citizen removeCitizen(int i)
{
return citizens.remove(i);
}
public List<Poller> getPollers()
{
return pollers;
}
public void startPollsWithLatch()
{
//create some poller threads that use a latch
addPoller(new Poller(this, "The Daily Day", 100, 3, Poller.pollsAreComplete));
addPoller(new Poller(this, "Stats people", 100, 3, Poller.pollsAreComplete));
addPoller(new Poller(this, "TV Pundits", 100, 3, Poller.pollsAreComplete));
// start the polls
for (Poller p : pollers)
{
p.start();
}
}
// pick a citizen randomly - access not controlled yet
public Citizen pickRandomCitizen()
{
//TODO add code to this method for part (b)
Citizen randomCitizen;
// first get a random index
int index = (int) (Math.random() * getPopulationSize());
randomCitizen = citizens.remove(index);
return randomCitizen;
}
// Counting the actual votes cast in the referendum
public void castVotes()
{
for (int h = 0; h < getPopulationSize(); h++)
{
Citizen c = citizens.get(h);
votes[c.voteFor()]++;
}
}
// tell the size of population
public int getPopulationSize()
{
return citizens.size();
}
// display the referendum results
public void revealResults()
{
System.out.println(" **** The Referendum Results are out! ****");
System.out.println("FOR");
System.out.printf("\t %.2f %%\n", 100.0 * votes[FOR] / getPopulationSize());
System.out.println("AGAINST");
System.out.printf("\t %.2f %%\n", 100.0 * votes[AGAINST] / getPopulationSize());
}
public static void main(String[] args)
{
// Initialise referendum. The number of people
// has been made smaller here to reduce the simulation time.
Referendum r = new Referendum(50000);
r.startPollsWithLatch();
r.castVotes();
// reveal the results of referendum
r.revealResults();
}
}
```
In a nutshell...
All threads must execute the `publishPollResults();` statement BEFORE the `revealResults();` is executed. | 2015/04/09 | [
"https://Stackoverflow.com/questions/29549141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3554289/"
] | This one matches both patterns in one go and extracts the desired number:
```
tt = int(re.search(r"\?ent took (too long \()?(?P<num>\d+)",message).group('num'))
``` | First of all you need to escape `?` at the leading of your pattern, because the `?` mark is a regex character and make a string optional and must precede by a string! so if you want to math `?` you need to use `\?` also as a more efficient way you can use `re.search` and `\d+` in your pattern,and refuse from extra indexing :
```
>>> int(re.search(r"\?ent\s*took\s*(\d+)",s).group(1))
4001
```
For second example you can do :
```
>>> re.search(r'\((\d+)',s).group(1)
'12343'
```
And for match in both cases use the following pattern :
```
(\d+)[\s\w]+\(|\((\d+)
```
[Demo](https://regex101.com/r/zG4iG5/1)
```
>>> s1="Page load for http://xxxx?roxy=www.yahoo.com&sendto=https://mywebsite?ent took too long (12343 ms Ne: 167 ms, Se: 2509 ms, Xe: 1325 ms)<br><br><br>Topic: Yahoo!! My website is a good website | Mywebsite<br>"
>>> s2="Page load for http://xxxx?roxy=www.yahoo.com&sendto=https://mywebsite?ent took 4001 ms (Ne: 167 ms, Se: 2509 ms, Xe: 1325 ms)<br><br><br>Topic: Yahoo!! My website is a good website | Mywebsite<br>"
>>> re.search(r'(\d+)[\s\w]+\(|\((\d+)',s1).group(2)
'12343'
>>> re.search(r'(\d+)[\s\w]+\(|\((\d+)',s2).group(1)
'4001'
``` |
3,024,091 | Let $\mathbb{F}\_q$ be a field of order $q = p^m$, where $p$ is the characteristic of the field; a prime.
Consider the ring $$R\_n = \mathbb{F}\_q[x]/\langle x^n - 1 \rangle $$ Now, I've read that this ring is semi-simple when $p$ does not divide $n$, but no proof was given.
Does anyone know how to prove it or somewhere where I can read the proof? Thank you. | 2018/12/03 | [
"https://math.stackexchange.com/questions/3024091",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/285167/"
] | One way to look at it is that if $C=\{1, c, c^2,\ldots, c^{n-1}\}$ is the cyclic group of order $n$, then $x\mapsto c$ is an isomorphism of $R\_n\to F\_q[C]$, the group ring of $C$ over $F\_q$.
[Maschke's theorem](https://en.wikipedia.org/wiki/Maschke%27s_theorem) says that if $|G|=n<\infty$, then $F[G]$ is semisimple exactly when $|G|$ is a unit in $F$, and this would be the case only when $\gcd(p,n)=1$.
---
Another way to prove it would be to show that $x^n-1$ is square-free when factorized over $F\_q$. This says that the ring is semiprime, and since it is already obviously Artinian, that would make it semisimple. Sorry to say my cyclotomic factorization knowledge is too rusty to spell this out, but the same is true. | I'll give a proof. First we'll need some facts.
**Fact 1**
A commutative ring (possibly without identity) is semisimple if and only if it is a direct sum of fields.
*Proof:*
It is clear that a direct sum of fields is semisimple, so assume $R$ is a commutative semisimple ring. Then note that since $R$ is commutative maximal left ideals are simply maximal ideals of $R$, so every simple left $R$ module is in fact a quotient ring of $R$.
Now let $\phi : R\to \bigoplus\_i S\_i$ be the isomorphism demonstrating semisimplicity of $R$, with all of the $S\_i$ simple. Let $m\_i$ be the kernel of the composite map $R\to \bigoplus\_i S\_i\to S\_i$, so that we can identify $\phi$ with the canonical map $R\to \bigoplus\_i R/m\_i$. However, this canonical map is a ring homomorphism. Since $\phi$ was a bijection, and we can identify it with this map, this canonical map is a bijection. Thus $R\cong \bigoplus\_i R/m\_i$.
**Fact 2**
An Artinian ring is a finite product of (necessarily Artinian) local rings.
*Proof sketch:* See e.g. Atiyah and MacDonald for more details, but the idea is to prove the following lemma: An Artinian ring with no nontrivial idempotents is local. Then this implies that we can recursively break the ring up into a product of rings until we arrive at a local ring, and this process must terminate since the ring is Artinian.
**Fact 3**
An Artinian local ring is either a field or has nilpotents.
*Proof:* Let $m$ be the maximal ideal of the Artinian local ring. Since the descending chain $m\supseteq m^2 \supseteq \cdots \supseteq m^n\supseteq \cdots $ must stabilize,
for some $n$, we have $m^n=m^{n+1}$, so by Nakayama's lemma, we have $m^n=0$. Thus $m^n$ is nilpotent. Thus any nonzero element of $m$ is nilpotent, so either $m=0$ and the ring is a field, or the ring has nilpotents.
**Conclusion**
Combining facts 1, 2, and 3 we see that a commutative Artinian ring is semisimple if and only if it is reduced.
Then $k[x]/(x^n-1)$ is reduced if the characteristic of $k$ doesn't divide $n$, so being artinian, it is semisimple. |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | >
> this computation is very expensive
>
>
>
I assume this is the reason you created the cache and this should be your primary concern.
While the speed of the solutions might be slightly different << 100 ns, I suspect it is more important that you be able to share results between threads. i.e. ConcurrentHashMap is likely to be the best for your application is it is likely to save you more CPU time in the long run.
In short, the speed of you solution is likely to be tiny compared to the cost of computing the same thing multiple times (for multiple threads) | The lookup speed is probably similar in both solutions. If there are no other concerns, I'd prefer ThreadLocal, since the best solution to multi-threading problems is single-threading.
However, your main problem is you don't want concurrent calculations for the same key; so there should be a lock per key; such locks can usually be implemented by ConcurrentHashMap.
So my solution would be
```
class LazyValue
{
K key;
volatile V value;
V getValue() { lazy calculation, doubled-checked locking }
}
static ConcurrentHashMap<K, LazyValue> centralMap = ...;
static
{
for every key
centralMap.put( key, new LazyValue(key) );
}
static V lookup(K key)
{
V value = localMap.get(key);
if(value==null)
localMap.put(key, value=centralMap.get(key).getValue())
return value;
}
``` |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | Note that your ConcurrentHashMap implementation is not thread safe and could lead to one item being computed twice. It is actually quite complicated to get it right if you store the results directly without using explicit locking, which you certainly want to avoid if performance is a concern.
It is worth noting that ConcurrentHashMap is highly scalable and works well under high contention. I don't know if ThreadLocal would perform better.
Apart from using a library, you could take some inspiration from [Java Concurrency in Practice Listing 5.19](http://www.javaconcurrencyinpractice.com/listings/Memoizer.java). The idea is to save a `Future<V>` in your map instead of a `V`. That helps a lot in making the whole method thread safe while staying efficient (lock-free). I paste the implementation below for reference but the chapter is worth reading to understand that every detail counts.
```
public interface Computable<K, V> {
V compute(K arg) throws InterruptedException;
}
public class Memoizer<K, V> implements Computable<K, V> {
private final ConcurrentMap<K, Future<V>> cache = new ConcurrentHashMap<K, Future<V>>();
private final Computable<K, V> c;
public Memoizer(Computable<K, V> c) {
this.c = c;
}
public V compute(final K arg) throws InterruptedException {
while (true) {
Future<V> f = cache.get(arg);
if (f == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
f = cache.putIfAbsent(arg, ft);
if (f == null) {
f = ft;
ft.run();
}
}
try {
return f.get();
} catch (CancellationException e) {
cache.remove(arg, f);
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
}
}
}
``` | Given that it's relatively easy to implement both of these, I would suggest you try them both and test *at steady state load* to see which one performs the best for your application.
My guess is that the the `ConcurrentHashMap` will be a little faster since it does not have to make native calls to `Thread.currentThread()` like a `ThreadLocal` does. However, this may depend on the objects you are storing and how efficient their hash coding is.
I may also be worthwhile trying to tune the concurrent map's `concurrencyLevel` to the number of threads you need. It defaults to 16. |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | use ThreadLocal as cache is a not good practice
In most containers, threads are reused via thread pools and thus are never gc. this would lead something wired
use ConcurrentHashMap you have to manage it in order to prevent mem leak
if you insist, i suggest using week or soft ref and evict after rich maxsize
if you are finding a in mem cache solution ( do not reinventing the wheel )
try guava cache
<http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/CacheBuilder.html> | Given that it's relatively easy to implement both of these, I would suggest you try them both and test *at steady state load* to see which one performs the best for your application.
My guess is that the the `ConcurrentHashMap` will be a little faster since it does not have to make native calls to `Thread.currentThread()` like a `ThreadLocal` does. However, this may depend on the objects you are storing and how efficient their hash coding is.
I may also be worthwhile trying to tune the concurrent map's `concurrencyLevel` to the number of threads you need. It defaults to 16. |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | Note that your ConcurrentHashMap implementation is not thread safe and could lead to one item being computed twice. It is actually quite complicated to get it right if you store the results directly without using explicit locking, which you certainly want to avoid if performance is a concern.
It is worth noting that ConcurrentHashMap is highly scalable and works well under high contention. I don't know if ThreadLocal would perform better.
Apart from using a library, you could take some inspiration from [Java Concurrency in Practice Listing 5.19](http://www.javaconcurrencyinpractice.com/listings/Memoizer.java). The idea is to save a `Future<V>` in your map instead of a `V`. That helps a lot in making the whole method thread safe while staying efficient (lock-free). I paste the implementation below for reference but the chapter is worth reading to understand that every detail counts.
```
public interface Computable<K, V> {
V compute(K arg) throws InterruptedException;
}
public class Memoizer<K, V> implements Computable<K, V> {
private final ConcurrentMap<K, Future<V>> cache = new ConcurrentHashMap<K, Future<V>>();
private final Computable<K, V> c;
public Memoizer(Computable<K, V> c) {
this.c = c;
}
public V compute(final K arg) throws InterruptedException {
while (true) {
Future<V> f = cache.get(arg);
if (f == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
f = cache.putIfAbsent(arg, ft);
if (f == null) {
f = ft;
ft.run();
}
}
try {
return f.get();
} catch (CancellationException e) {
cache.remove(arg, f);
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
}
}
}
``` | The lookup speed is probably similar in both solutions. If there are no other concerns, I'd prefer ThreadLocal, since the best solution to multi-threading problems is single-threading.
However, your main problem is you don't want concurrent calculations for the same key; so there should be a lock per key; such locks can usually be implemented by ConcurrentHashMap.
So my solution would be
```
class LazyValue
{
K key;
volatile V value;
V getValue() { lazy calculation, doubled-checked locking }
}
static ConcurrentHashMap<K, LazyValue> centralMap = ...;
static
{
for every key
centralMap.put( key, new LazyValue(key) );
}
static V lookup(K key)
{
V value = localMap.get(key);
if(value==null)
localMap.put(key, value=centralMap.get(key).getValue())
return value;
}
``` |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | Note that your ConcurrentHashMap implementation is not thread safe and could lead to one item being computed twice. It is actually quite complicated to get it right if you store the results directly without using explicit locking, which you certainly want to avoid if performance is a concern.
It is worth noting that ConcurrentHashMap is highly scalable and works well under high contention. I don't know if ThreadLocal would perform better.
Apart from using a library, you could take some inspiration from [Java Concurrency in Practice Listing 5.19](http://www.javaconcurrencyinpractice.com/listings/Memoizer.java). The idea is to save a `Future<V>` in your map instead of a `V`. That helps a lot in making the whole method thread safe while staying efficient (lock-free). I paste the implementation below for reference but the chapter is worth reading to understand that every detail counts.
```
public interface Computable<K, V> {
V compute(K arg) throws InterruptedException;
}
public class Memoizer<K, V> implements Computable<K, V> {
private final ConcurrentMap<K, Future<V>> cache = new ConcurrentHashMap<K, Future<V>>();
private final Computable<K, V> c;
public Memoizer(Computable<K, V> c) {
this.c = c;
}
public V compute(final K arg) throws InterruptedException {
while (true) {
Future<V> f = cache.get(arg);
if (f == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
f = cache.putIfAbsent(arg, ft);
if (f == null) {
f = ft;
ft.run();
}
}
try {
return f.get();
} catch (CancellationException e) {
cache.remove(arg, f);
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
}
}
}
``` | The performance question is irrelevant, as the solutions are not equivalent.
The ThreadLocal hash map isn't shared between threads, so the question of thread safety doesn't even arise, but it also doesn't meet your specification, which doesn't say anything about each thread having its own cache.
The requirement for thread safety implies that a single cache is shared among all threads, which rules out ThreadLocal completely. |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | >
> this computation is very expensive
>
>
>
I assume this is the reason you created the cache and this should be your primary concern.
While the speed of the solutions might be slightly different << 100 ns, I suspect it is more important that you be able to share results between threads. i.e. ConcurrentHashMap is likely to be the best for your application is it is likely to save you more CPU time in the long run.
In short, the speed of you solution is likely to be tiny compared to the cost of computing the same thing multiple times (for multiple threads) | The performance question is irrelevant, as the solutions are not equivalent.
The ThreadLocal hash map isn't shared between threads, so the question of thread safety doesn't even arise, but it also doesn't meet your specification, which doesn't say anything about each thread having its own cache.
The requirement for thread safety implies that a single cache is shared among all threads, which rules out ThreadLocal completely. |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | use ThreadLocal as cache is a not good practice
In most containers, threads are reused via thread pools and thus are never gc. this would lead something wired
use ConcurrentHashMap you have to manage it in order to prevent mem leak
if you insist, i suggest using week or soft ref and evict after rich maxsize
if you are finding a in mem cache solution ( do not reinventing the wheel )
try guava cache
<http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/CacheBuilder.html> | Note that your ConcurrentHashMap implementation is not thread safe and could lead to one item being computed twice. It is actually quite complicated to get it right if you store the results directly without using explicit locking, which you certainly want to avoid if performance is a concern.
It is worth noting that ConcurrentHashMap is highly scalable and works well under high contention. I don't know if ThreadLocal would perform better.
Apart from using a library, you could take some inspiration from [Java Concurrency in Practice Listing 5.19](http://www.javaconcurrencyinpractice.com/listings/Memoizer.java). The idea is to save a `Future<V>` in your map instead of a `V`. That helps a lot in making the whole method thread safe while staying efficient (lock-free). I paste the implementation below for reference but the chapter is worth reading to understand that every detail counts.
```
public interface Computable<K, V> {
V compute(K arg) throws InterruptedException;
}
public class Memoizer<K, V> implements Computable<K, V> {
private final ConcurrentMap<K, Future<V>> cache = new ConcurrentHashMap<K, Future<V>>();
private final Computable<K, V> c;
public Memoizer(Computable<K, V> c) {
this.c = c;
}
public V compute(final K arg) throws InterruptedException {
while (true) {
Future<V> f = cache.get(arg);
if (f == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
f = cache.putIfAbsent(arg, ft);
if (f == null) {
f = ft;
ft.run();
}
}
try {
return f.get();
} catch (CancellationException e) {
cache.remove(arg, f);
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
}
}
}
``` |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | use ThreadLocal as cache is a not good practice
In most containers, threads are reused via thread pools and thus are never gc. this would lead something wired
use ConcurrentHashMap you have to manage it in order to prevent mem leak
if you insist, i suggest using week or soft ref and evict after rich maxsize
if you are finding a in mem cache solution ( do not reinventing the wheel )
try guava cache
<http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/CacheBuilder.html> | The performance question is irrelevant, as the solutions are not equivalent.
The ThreadLocal hash map isn't shared between threads, so the question of thread safety doesn't even arise, but it also doesn't meet your specification, which doesn't say anything about each thread having its own cache.
The requirement for thread safety implies that a single cache is shared among all threads, which rules out ThreadLocal completely. |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | use ThreadLocal as cache is a not good practice
In most containers, threads are reused via thread pools and thus are never gc. this would lead something wired
use ConcurrentHashMap you have to manage it in order to prevent mem leak
if you insist, i suggest using week or soft ref and evict after rich maxsize
if you are finding a in mem cache solution ( do not reinventing the wheel )
try guava cache
<http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/CacheBuilder.html> | The lookup speed is probably similar in both solutions. If there are no other concerns, I'd prefer ThreadLocal, since the best solution to multi-threading problems is single-threading.
However, your main problem is you don't want concurrent calculations for the same key; so there should be a lock per key; such locks can usually be implemented by ConcurrentHashMap.
So my solution would be
```
class LazyValue
{
K key;
volatile V value;
V getValue() { lazy calculation, doubled-checked locking }
}
static ConcurrentHashMap<K, LazyValue> centralMap = ...;
static
{
for every key
centralMap.put( key, new LazyValue(key) );
}
static V lookup(K key)
{
V value = localMap.get(key);
if(value==null)
localMap.put(key, value=centralMap.get(key).getValue())
return value;
}
``` |
14,294,798 | I have a datatable webpage that shows a list of user in a datatable. On the user page there is a button create new user. On clicking this launches a modal jQuery dialog box for the user to enter details off the new user. There is a Cancel button which just closes the dialog box and a Save User button which on clicking calls DoSaveUser method in my controller. I can see from debugging that I get into the DoSaveUser method which should at the end return to a PartialView if the create user was successful saying User was saved. However my dialog were you enter details is not getting replaced with the Success message - even though the user is getting created - i.e - after I hit the save button - if I then cancel the dialog and refresh the original user page I can see the datatable updated with my new user.
Code on UserList page (there are more fields in the dialog than just forename but have removed them to make question have less code). So when CreateUser button is clicked my newUserDialog is launched.
```
<div id="newUserDialog">
@using (Html.BeginForm("DoSaveUser", "MyController", FormMethod.Post, new { id = "saveForm" }))
{
<div id="resultContainer">
<table class="ui-widget-content" style="width: 565px; margin-top: 10px;">
<tr>
<td style="width: 100px;">
</td>
<td class="label">
Forename :
</td>
<td class="value">
@Html.TextBoxFor(model => model.Forename, new { style = "width:150px" })
</td>
</tr>
</table>
<div class="ui-widget-content Rounded" style="width: 565px; margin-top: 10px; text-align: center;">
<input id="Cancel" type="button" class="dialog-button" value="Cancel" style="margin: 5px" />
<input id="DoSaveUser" type="submit" class="dialog-button" value="Save User" style="margin: 5px" />
</div>
</div>
}
```
Javascript code for Save User on the dialog being clicked - submit the form.
```
$(function () {
$('#saveForm').submit(function () {
var formData = $("#saveForm").serializeArray();
$.ajax({
url: this.action,
type: this.method,
data: formData,
dataType: "json",
success: function (result) {
$('#resultContainer').html(result);
}
});
return false;
});
});
```
Now in My DoSaveUser method in my controller which I can set a breakpoint and hit and see all the values being sent in correctly for the corresponding fields - once I have saved to the DB this is return.
```
return PartialView("UserSuccess", model);
```
And this is all that view contains in the cshtml..note what I wanted was the result container Div which contains all my textbox fields and labels to be replaced with User Created successfully. And then I will need an ok on this page which on clicking will close the dialog box and refresh the UserList page and show the datatable updated with the new user. However when I click save the textboxes just stay on the Div and the Div does not get changed - but if I then cancel the dialog and refresh the page I can see the datatable updated with my new user. Is there something I am missing? (note - i have added jquery.unobtrusive-ajax.js to my \_Layout page)
```
@model MyProject.Models.UserModel
@{
ViewBag.Title = "UserSuccess";
}
<div id="resultContainer">
User Created Successfully
</div>
``` | 2013/01/12 | [
"https://Stackoverflow.com/questions/14294798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/846565/"
] | >
> this computation is very expensive
>
>
>
I assume this is the reason you created the cache and this should be your primary concern.
While the speed of the solutions might be slightly different << 100 ns, I suspect it is more important that you be able to share results between threads. i.e. ConcurrentHashMap is likely to be the best for your application is it is likely to save you more CPU time in the long run.
In short, the speed of you solution is likely to be tiny compared to the cost of computing the same thing multiple times (for multiple threads) | Given that it's relatively easy to implement both of these, I would suggest you try them both and test *at steady state load* to see which one performs the best for your application.
My guess is that the the `ConcurrentHashMap` will be a little faster since it does not have to make native calls to `Thread.currentThread()` like a `ThreadLocal` does. However, this may depend on the objects you are storing and how efficient their hash coding is.
I may also be worthwhile trying to tune the concurrent map's `concurrencyLevel` to the number of threads you need. It defaults to 16. |
68,888,423 | I have this sample data. What I am trying to do get p values and compare each Person in each dataframe. I tried piping the dataframe list in `kruskal.test()` and it worked but when passing the same data frame using `lapply()` in `aov()`, I am not getting the result. I am sorry I am new to R. I'm just trying to learn how to apply the `lapply()` function in a dataframe list. Another helpful info maybe is that all the values in height and weight columns are means computed from a previous larger dataframes.
```
df_list <- list(
`1.3.A` =
tibble::tribble(
~Person, ~Height, ~Weight,
"Alex", 175L, 75L,
"Gerard", 180L, 85L,
"Clyde", 179L, 79L,
"Alex", 175L, 75L,
"Gerard", 180L, 85L,
"Clyde", 179L, 79L
),
`2.2.A` =
tibble::tribble(
~Person, ~Height, ~Weight,
"Alex", 175L, 75L,
"Gerard", 180L, 85L,
"Clyde", 179L, 79L,
"Alex", 175L, 75L,
"Gerard", 180L, 85L,
"Clyde", 179L, 79L
),
`1.1.B` =
tibble::tribble(
~Person, ~Height, ~Weight,
"Alex", 175L, 75L,
"Gerard", 180L, 85L,
"Clyde", 179L, 79L,
"Alex", 175L, 75L,
"Gerard", 180L, 85L,
"Clyde", 179L, 79L
)
)
```
I hope someone can make me understand, when using `lapply()` with `kruskal.test()` I was able to get p values, but when I run `aov()` and perform `summary()`, I get a list with no p-values.
this is the output:
```
Length Class Mode
1.3.A 6 aov list
2.2.A 6 aov list
1.1.B 6 aov list
```
when running and accessing specific dataframe within the list I get a p- and f-value. This code gives me the correct output for the specific dataframe?.
this is the code I use:
```
cary <- aov(df_list[["1.3.A"]]$Height ~ df_list[["1.3.A"]]$Person)
summary(cary)
```
What I don't understand is why does `lapply()` worked differently on these two different tests? Why is it that when I use `lapply()` in `aov()`, it is not working but when I use `aov()` alone accessing a single dataframe, it gives me the expected results?
Failed attempts:
```
mut <- lapply(df_list, function(x) with(x, aov(Height ~ Person, data = x)))
mud <- summary(mut)
mud
```
```
cow <- purrr::map(df_list, ~ aov(Height ~ Person, data = .x))
cow
summary(cow)
```
```
tree <- function(df) {
aov(Height ~ Person)
}
shrub <- lapply(df_list, tree)
summary(shrub)
``` | 2021/08/23 | [
"https://Stackoverflow.com/questions/68888423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16685342/"
] | If your file contains mixed encodings, you can read it into memory as binary, or as a hack, open it as Latin-1 and then decode the *Title* field individually on each line.
If the majority of the data is encoded as UTF-8, you can attempt to decode it with
```
title.encode('latin-1').decode('utf-8 )
```
but fall back and keep it in Latin-1, or replace it with some sort of error message, if decoding fails.
I'm not a Pandas person, but quick googling gets me something like
```
import pandas as pd
df = pd.read_csv('myFile.csv', encoding='latin-1')
def attempt_decode(x):
try:
return x.encode('latin-1').decode('utf-8')
except UnicodeDecodeError:
return 'Unable to decode: %s' % x)
df['Title'] = df['Title'].apply(attempt_decode)
```
Latin-1 has the unique property that every input byte corresponds exactly to the Unicode code point with the same value, so you never get a decoding error (but, obviously, [mojibake](https://en.wikipedia.org/wiki/Mojibake) if the correct encoding is something else, and you fail to correct it). | If you want to exclude the column `title` alone, read all the columns and drop the column `title`.
Eg.
```py
df = pd.read_csv('filename')
df = data.drop('title', axis = 1)
```
To give the column a default value, use:
```py
df['title'] = 0 #(the value you want to provide by default)
```
or use:
```py
df['title'] = np.nan
```
to fill the column with null values.
Hope that answers your question! |
17,036,225 | I want to do some layout change when the devices rotate. So I implement `- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration` method to do the work. But I realize when this method is called the self.view.frame and self.view.bounds are different. The self.view.bounds.size is correct and the self.view.frame.size seems still not rotate.
For example, I created an empty singleView Project and implemented the method like follows:
```
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
NSLog(@"willAnimateRotationToInterfaceOrientation");
NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);
}
```
when the device rotates from portrait to landscape. the output is as follows:
```
2013-06-11 11:57:46.959 viewDemo[95658:707] willAnimateRotationToInterfaceOrientation
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.bounds.size width:1024.000000 height:748.000000
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.frame.size width:748.000000 height:1024.000000
```
I wonder why these sizes are different? They shouldn't be always the same? And when to choose which one to use?
Any help will be appreciated. | 2013/06/11 | [
"https://Stackoverflow.com/questions/17036225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1544790/"
] | **I wonder why these values are different? They shouldn't be always the same?**
The ***bounds*** of an UIView is the rectangle, expressed as a location (x, y) and size (width, height) *relative to its own coordinate system (0,0)*.
The ***frame*** of an UIView is the rectangle, expressed as a location (x, y) and size (width, height) *relative to the superview it is contained within*.
In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view
**And when to choose which one to use?**
Hopefully this helps clarify the circumstances where each property might get used.
[UIView's frame, bounds, center, origin, when to use what?](https://stackoverflow.com/a/1097175/790794) | please note that frame.size is not equal to bounds.size when the simulator is rotated
refer to this one [UIView frame, bounds and center](https://stackoverflow.com/questions/5361369/ios-programming-frame-bounds-and-center) |
17,036,225 | I want to do some layout change when the devices rotate. So I implement `- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration` method to do the work. But I realize when this method is called the self.view.frame and self.view.bounds are different. The self.view.bounds.size is correct and the self.view.frame.size seems still not rotate.
For example, I created an empty singleView Project and implemented the method like follows:
```
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
NSLog(@"willAnimateRotationToInterfaceOrientation");
NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);
}
```
when the device rotates from portrait to landscape. the output is as follows:
```
2013-06-11 11:57:46.959 viewDemo[95658:707] willAnimateRotationToInterfaceOrientation
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.bounds.size width:1024.000000 height:748.000000
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.frame.size width:748.000000 height:1024.000000
```
I wonder why these sizes are different? They shouldn't be always the same? And when to choose which one to use?
Any help will be appreciated. | 2013/06/11 | [
"https://Stackoverflow.com/questions/17036225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1544790/"
] | Look at the [answer by "tc."](https://stackoverflow.com/questions/3536253/self-view-frame-changed-size-ifself-unexpectedly-in-landscape-mode), which is accepted as of now. Copying few lines from that answer to here.
So, the "frame" is relative to the parent view, which in this case is the UIWindow. When you rotate device, the window doesn't rotate; the view controller's view does. From the window's perspective, everything is effectively in portrait mode. This is why even after device is rotated to landscape, self.view.frame will not change.
You should use `self.view.bounds` to perform any calculation as it gives you the correct values independent of your device orientation. | please note that frame.size is not equal to bounds.size when the simulator is rotated
refer to this one [UIView frame, bounds and center](https://stackoverflow.com/questions/5361369/ios-programming-frame-bounds-and-center) |
17,036,225 | I want to do some layout change when the devices rotate. So I implement `- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration` method to do the work. But I realize when this method is called the self.view.frame and self.view.bounds are different. The self.view.bounds.size is correct and the self.view.frame.size seems still not rotate.
For example, I created an empty singleView Project and implemented the method like follows:
```
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
NSLog(@"willAnimateRotationToInterfaceOrientation");
NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);
}
```
when the device rotates from portrait to landscape. the output is as follows:
```
2013-06-11 11:57:46.959 viewDemo[95658:707] willAnimateRotationToInterfaceOrientation
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.bounds.size width:1024.000000 height:748.000000
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.frame.size width:748.000000 height:1024.000000
```
I wonder why these sizes are different? They shouldn't be always the same? And when to choose which one to use?
Any help will be appreciated. | 2013/06/11 | [
"https://Stackoverflow.com/questions/17036225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1544790/"
] | Look at the [answer by "tc."](https://stackoverflow.com/questions/3536253/self-view-frame-changed-size-ifself-unexpectedly-in-landscape-mode), which is accepted as of now. Copying few lines from that answer to here.
So, the "frame" is relative to the parent view, which in this case is the UIWindow. When you rotate device, the window doesn't rotate; the view controller's view does. From the window's perspective, everything is effectively in portrait mode. This is why even after device is rotated to landscape, self.view.frame will not change.
You should use `self.view.bounds` to perform any calculation as it gives you the correct values independent of your device orientation. | **I wonder why these values are different? They shouldn't be always the same?**
The ***bounds*** of an UIView is the rectangle, expressed as a location (x, y) and size (width, height) *relative to its own coordinate system (0,0)*.
The ***frame*** of an UIView is the rectangle, expressed as a location (x, y) and size (width, height) *relative to the superview it is contained within*.
In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view
**And when to choose which one to use?**
Hopefully this helps clarify the circumstances where each property might get used.
[UIView's frame, bounds, center, origin, when to use what?](https://stackoverflow.com/a/1097175/790794) |
17,036,225 | I want to do some layout change when the devices rotate. So I implement `- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration` method to do the work. But I realize when this method is called the self.view.frame and self.view.bounds are different. The self.view.bounds.size is correct and the self.view.frame.size seems still not rotate.
For example, I created an empty singleView Project and implemented the method like follows:
```
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
NSLog(@"willAnimateRotationToInterfaceOrientation");
NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);
}
```
when the device rotates from portrait to landscape. the output is as follows:
```
2013-06-11 11:57:46.959 viewDemo[95658:707] willAnimateRotationToInterfaceOrientation
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.bounds.size width:1024.000000 height:748.000000
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.frame.size width:748.000000 height:1024.000000
```
I wonder why these sizes are different? They shouldn't be always the same? And when to choose which one to use?
Any help will be appreciated. | 2013/06/11 | [
"https://Stackoverflow.com/questions/17036225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1544790/"
] | **I wonder why these values are different? They shouldn't be always the same?**
The ***bounds*** of an UIView is the rectangle, expressed as a location (x, y) and size (width, height) *relative to its own coordinate system (0,0)*.
The ***frame*** of an UIView is the rectangle, expressed as a location (x, y) and size (width, height) *relative to the superview it is contained within*.
In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view
**And when to choose which one to use?**
Hopefully this helps clarify the circumstances where each property might get used.
[UIView's frame, bounds, center, origin, when to use what?](https://stackoverflow.com/a/1097175/790794) | Just use method did(The size is new) not will(The size is same as was in parent controller)
```
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
[halfView setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 120)];
NSLog(@"willAnimateRotationToInterfaceOrientation");
NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);
}
``` |
17,036,225 | I want to do some layout change when the devices rotate. So I implement `- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration` method to do the work. But I realize when this method is called the self.view.frame and self.view.bounds are different. The self.view.bounds.size is correct and the self.view.frame.size seems still not rotate.
For example, I created an empty singleView Project and implemented the method like follows:
```
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
NSLog(@"willAnimateRotationToInterfaceOrientation");
NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);
}
```
when the device rotates from portrait to landscape. the output is as follows:
```
2013-06-11 11:57:46.959 viewDemo[95658:707] willAnimateRotationToInterfaceOrientation
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.bounds.size width:1024.000000 height:748.000000
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.frame.size width:748.000000 height:1024.000000
```
I wonder why these sizes are different? They shouldn't be always the same? And when to choose which one to use?
Any help will be appreciated. | 2013/06/11 | [
"https://Stackoverflow.com/questions/17036225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1544790/"
] | Look at the [answer by "tc."](https://stackoverflow.com/questions/3536253/self-view-frame-changed-size-ifself-unexpectedly-in-landscape-mode), which is accepted as of now. Copying few lines from that answer to here.
So, the "frame" is relative to the parent view, which in this case is the UIWindow. When you rotate device, the window doesn't rotate; the view controller's view does. From the window's perspective, everything is effectively in portrait mode. This is why even after device is rotated to landscape, self.view.frame will not change.
You should use `self.view.bounds` to perform any calculation as it gives you the correct values independent of your device orientation. | Just use method did(The size is new) not will(The size is same as was in parent controller)
```
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
[halfView setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 120)];
NSLog(@"willAnimateRotationToInterfaceOrientation");
NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);
}
``` |
59,403,140 | I'm running a Jenkins declarative pipeline in which a stage runs on a docker container and outputs a file. I would like to copy this file from the container onto the host's git init path, so that I can commit the newly outputted file to the source git repository.
In-order to copy the outputted file from container to host's git init path, I can use the docker cp command for which I need the container ID and the destination path which in this case is the host's git init path.
Can someone share thoughts on how to get these 2 values? | 2019/12/19 | [
"https://Stackoverflow.com/questions/59403140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2101043/"
] | Generally you don't do either of these things. Docker is an isolation system that's intended to hide most of the details of the host system from the container (and *vice versa*); also the container filesystem tends to not be stored on the host in a way that's easy to extract.
When you're [Using Docker with Pipeline](https://jenkins.io/doc/book/pipeline/docker/), it knows how to mount the current working tree into containers, so the easiest way to do this is something like
```groovy
stage('Something') {
agent {
docker { image 'my-image' }
}
steps {
sh 'the_command'
}
}
```
or, if you're using scripted pipelines
```
docker.image('my-image').inside {
sh 'the_command'
}
```
In both of these cases `the_command` will run with its current working directory being the per-build workspace directory; it doesn't need to know that it's running inside Docker or to know anything about the host, and any changes it writes into this directory will be visible elsewhere in your build.
More broadly, if you want a process inside a container to produce files that are visible on the host, you need to use a `docker run -v` option to [mount a host directory](https://docs.docker.com/storage/bind-mounts/) into the container at the time you run it. (In the previous examples, the Jenkins logs will include a detailed `docker run` command that shows these options.) If the primary goal of your application is to produce host-visible files, running it outside Docker might be easier. If Jenkins is running inside Docker too, note that the first path option to `docker run -v` is always a path on the physical host, and there's no way to map one container's filesystem into another. | you can get docker container ID inside the container by this cmd:
```
cat /proc/self/cgroup | grep -o -e "docker-.*.scope" | head -n 1 | sed "s/docker-\(.*\).scope/\\1/"
``` |
33,226,860 | I have to write a page like the following, however, the scroll bar don't show in IE 11 and FireFox. What should I do to solve the problem?
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>test</title>
</head>
<body>
<table style="width: 100%; height: 100%;">
<tr>
first row
</tr>
<tr style="height:100%">
<td style="height:100%; width:100%">
<div style="height:100%; width:100%;overflow:auto;direction:rtl">
<div>
<table>
<%for(int i=0;i<10000;i++){%>
<tr>
<td><%=i%></td>
</tr>
<%}%>
</table>
</div>
</div>
</td>
</tr>
</table>
</body>
</html>
``` | 2015/10/20 | [
"https://Stackoverflow.com/questions/33226860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5465132/"
] | I think a nice solution for this one is to not try to recover "how many steps we still need to do" from the list getting constructed, but instead, to use `until` on a pair of the list and the number of remaining elements to be added:
```
(5, []) ->
(4, 5:[]) = (4, [5]) ->
(3, 4:[5]) = (3, [4, 5]) ->
(2, 3:[4, 5]) = (2, [3, 4, 5]) ->
(1, 2:[3, 4, 5]) = (1, [2, 3, 4, 5]) ->
(0, 1:[2, 3, 4, 5]) = (0, [1, 2, 3, 4, 5])
```
Note that when the number of remaining elements is 0, that exactly means that the list we have constructed is the one we are after.
So we can implement this idea by making an `until` over a pair, and checking if the first element of the pair is equal to 0 to decide if we've finished:
```
seq0 :: Int -> (Int, [Int])
seq0 n = until (\(i, is) -> i == 0) (\(i, is) -> (i-1, i:is)) (n, [])
```
Of course, this will return the full pair `(0, [1..n])`, so we need to keep only the second element of the pair:
```
seq :: Int -> [Int]
seq n = snd (seq0 n)
``` | Thanks for the replies. I found out another way of solving it:
```
seq :: Int -> [Int]
seq a = until (\l -> (length l) >= a) (\x -> x ++ [((last x) + 1)]) [1]
``` |
403,613 | I'm on 12.04LTS. I have an external USB HD cam that I run as default (preferably). To do this, after every reboot I have to run
```
sudo su -c 'echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue'
```
(1-1.4 is my laptop cam)
This disables my laptop cam.
Then in GUVCview I get:

Which is easily fixed by simply unplugging, and plugging the external cam's usb into port. Then my external cam works great,and is my default selection, and the only one listed in devices under GUVCview, and is marked as default in Multimedia selector.
Everytime I reboot Ubuntu, I have to go through this little process. Not a terrible problem, but is there a way to make my 1-1.4 value stay at "0" ?
EDIT:
EDIT 2:
Open Terminal
```
cd /etc
sudo nano rc.local
```
Edit File by placing command Before " Exit 0"
Press CTRL - X
Y to save
```
!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue
exit 0
``` | 2014/01/10 | [
"https://askubuntu.com/questions/403613",
"https://askubuntu.com",
"https://askubuntu.com/users/192473/"
] | Boot from the live CD and see if you can make a connection that way.
If wireless does work via the live CD, then you can try reconfiguring your network, or just copying over the network-manager config files:
* Re-configuring the network:
[Open a terminal](https://askubuntu.com/questions/183775/how-do-i-open-a-terminal) and type
```
sudo dpkg-reconfigure network-manager
```
---
OR
---
* Copying over the settings used by the liveCD:
Boot from a live CD, back up your old network settings, clear out any system connection file and copy over the ones from the live CD.
[Open a terminal](https://askubuntu.com/questions/183775/how-do-i-open-a-terminal) and type the following to become root:
```
sudo su
```
then backup,:
```
mv /media/<Name of your Ubuntu Partion>/etc/NetworkManager/NetworkManager.conf /media/<Name of your Ubuntu Partion>/etc/NetworkManager/NetworkManager.conf.broken
```
clear,:
```
rm /media/<Name of your Ubuntu Partion>/etc/NetworkManager/system-connections/*
```
and copy:
```
cp /etc/NetworkManager/NetworkManager.conf /media/<Name of your Ubuntu Partion>/etc/NetworkManager/NetworkManager.conf
cp /etc/NetworkManager/system-connections/* /media/<Name of your Ubuntu Partion>/etc/NetworkManager/system-connections/
```
Reboot the system without the live CD and you should be good to go. | Not sure if it works but you can try connecting through `Connect to a hidden Wi-Fi Network...` under the Network applet menu. Even if the connection is not hidden but you can connect to a specific Wi-Fi network. I tried this method with my wifi which is not hidden and it worked. |
403,613 | I'm on 12.04LTS. I have an external USB HD cam that I run as default (preferably). To do this, after every reboot I have to run
```
sudo su -c 'echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue'
```
(1-1.4 is my laptop cam)
This disables my laptop cam.
Then in GUVCview I get:

Which is easily fixed by simply unplugging, and plugging the external cam's usb into port. Then my external cam works great,and is my default selection, and the only one listed in devices under GUVCview, and is marked as default in Multimedia selector.
Everytime I reboot Ubuntu, I have to go through this little process. Not a terrible problem, but is there a way to make my 1-1.4 value stay at "0" ?
EDIT:
EDIT 2:
Open Terminal
```
cd /etc
sudo nano rc.local
```
Edit File by placing command Before " Exit 0"
Press CTRL - X
Y to save
```
!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue
exit 0
``` | 2014/01/10 | [
"https://askubuntu.com/questions/403613",
"https://askubuntu.com",
"https://askubuntu.com/users/192473/"
] | You could just try to manually add it. Go under your internet and click "edit connections" and add a server from there manually. Note you have to know the server's name and password in order to add it. | Not sure if it works but you can try connecting through `Connect to a hidden Wi-Fi Network...` under the Network applet menu. Even if the connection is not hidden but you can connect to a specific Wi-Fi network. I tried this method with my wifi which is not hidden and it worked. |
403,613 | I'm on 12.04LTS. I have an external USB HD cam that I run as default (preferably). To do this, after every reboot I have to run
```
sudo su -c 'echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue'
```
(1-1.4 is my laptop cam)
This disables my laptop cam.
Then in GUVCview I get:

Which is easily fixed by simply unplugging, and plugging the external cam's usb into port. Then my external cam works great,and is my default selection, and the only one listed in devices under GUVCview, and is marked as default in Multimedia selector.
Everytime I reboot Ubuntu, I have to go through this little process. Not a terrible problem, but is there a way to make my 1-1.4 value stay at "0" ?
EDIT:
EDIT 2:
Open Terminal
```
cd /etc
sudo nano rc.local
```
Edit File by placing command Before " Exit 0"
Press CTRL - X
Y to save
```
!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue
exit 0
``` | 2014/01/10 | [
"https://askubuntu.com/questions/403613",
"https://askubuntu.com",
"https://askubuntu.com/users/192473/"
] | Boot from the live CD and see if you can make a connection that way.
If wireless does work via the live CD, then you can try reconfiguring your network, or just copying over the network-manager config files:
* Re-configuring the network:
[Open a terminal](https://askubuntu.com/questions/183775/how-do-i-open-a-terminal) and type
```
sudo dpkg-reconfigure network-manager
```
---
OR
---
* Copying over the settings used by the liveCD:
Boot from a live CD, back up your old network settings, clear out any system connection file and copy over the ones from the live CD.
[Open a terminal](https://askubuntu.com/questions/183775/how-do-i-open-a-terminal) and type the following to become root:
```
sudo su
```
then backup,:
```
mv /media/<Name of your Ubuntu Partion>/etc/NetworkManager/NetworkManager.conf /media/<Name of your Ubuntu Partion>/etc/NetworkManager/NetworkManager.conf.broken
```
clear,:
```
rm /media/<Name of your Ubuntu Partion>/etc/NetworkManager/system-connections/*
```
and copy:
```
cp /etc/NetworkManager/NetworkManager.conf /media/<Name of your Ubuntu Partion>/etc/NetworkManager/NetworkManager.conf
cp /etc/NetworkManager/system-connections/* /media/<Name of your Ubuntu Partion>/etc/NetworkManager/system-connections/
```
Reboot the system without the live CD and you should be good to go. | Install ndiswrapper
```
sudo install ndiswrapper-common ndiswrapper-modules-1.9 ndiswrapper-utils-1.9
```
Install the WiFi driver (from Windows):
```
sudo ndiswrapper -i yourdriver.inf
```
Check the driver is working:
```
sudo ndiswrapper -l
```
Load the module:
```
sudo depmod -a
sudo modprobe ndiswrapper
```
Configure modprobe so that it loads ndiswrapper:
```
sudo ndiswrapper -m
```
Edit the modules to add ndiswrapper at the end:
```
sudo gedit /etc/modules
```
Remember to add ndiswrapper at the end.
Hope you now have your WiFi back! |
403,613 | I'm on 12.04LTS. I have an external USB HD cam that I run as default (preferably). To do this, after every reboot I have to run
```
sudo su -c 'echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue'
```
(1-1.4 is my laptop cam)
This disables my laptop cam.
Then in GUVCview I get:

Which is easily fixed by simply unplugging, and plugging the external cam's usb into port. Then my external cam works great,and is my default selection, and the only one listed in devices under GUVCview, and is marked as default in Multimedia selector.
Everytime I reboot Ubuntu, I have to go through this little process. Not a terrible problem, but is there a way to make my 1-1.4 value stay at "0" ?
EDIT:
EDIT 2:
Open Terminal
```
cd /etc
sudo nano rc.local
```
Edit File by placing command Before " Exit 0"
Press CTRL - X
Y to save
```
!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue
exit 0
``` | 2014/01/10 | [
"https://askubuntu.com/questions/403613",
"https://askubuntu.com",
"https://askubuntu.com/users/192473/"
] | You could just try to manually add it. Go under your internet and click "edit connections" and add a server from there manually. Note you have to know the server's name and password in order to add it. | Install ndiswrapper
```
sudo install ndiswrapper-common ndiswrapper-modules-1.9 ndiswrapper-utils-1.9
```
Install the WiFi driver (from Windows):
```
sudo ndiswrapper -i yourdriver.inf
```
Check the driver is working:
```
sudo ndiswrapper -l
```
Load the module:
```
sudo depmod -a
sudo modprobe ndiswrapper
```
Configure modprobe so that it loads ndiswrapper:
```
sudo ndiswrapper -m
```
Edit the modules to add ndiswrapper at the end:
```
sudo gedit /etc/modules
```
Remember to add ndiswrapper at the end.
Hope you now have your WiFi back! |
403,613 | I'm on 12.04LTS. I have an external USB HD cam that I run as default (preferably). To do this, after every reboot I have to run
```
sudo su -c 'echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue'
```
(1-1.4 is my laptop cam)
This disables my laptop cam.
Then in GUVCview I get:

Which is easily fixed by simply unplugging, and plugging the external cam's usb into port. Then my external cam works great,and is my default selection, and the only one listed in devices under GUVCview, and is marked as default in Multimedia selector.
Everytime I reboot Ubuntu, I have to go through this little process. Not a terrible problem, but is there a way to make my 1-1.4 value stay at "0" ?
EDIT:
EDIT 2:
Open Terminal
```
cd /etc
sudo nano rc.local
```
Edit File by placing command Before " Exit 0"
Press CTRL - X
Y to save
```
!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue
exit 0
``` | 2014/01/10 | [
"https://askubuntu.com/questions/403613",
"https://askubuntu.com",
"https://askubuntu.com/users/192473/"
] | Boot from the live CD and see if you can make a connection that way.
If wireless does work via the live CD, then you can try reconfiguring your network, or just copying over the network-manager config files:
* Re-configuring the network:
[Open a terminal](https://askubuntu.com/questions/183775/how-do-i-open-a-terminal) and type
```
sudo dpkg-reconfigure network-manager
```
---
OR
---
* Copying over the settings used by the liveCD:
Boot from a live CD, back up your old network settings, clear out any system connection file and copy over the ones from the live CD.
[Open a terminal](https://askubuntu.com/questions/183775/how-do-i-open-a-terminal) and type the following to become root:
```
sudo su
```
then backup,:
```
mv /media/<Name of your Ubuntu Partion>/etc/NetworkManager/NetworkManager.conf /media/<Name of your Ubuntu Partion>/etc/NetworkManager/NetworkManager.conf.broken
```
clear,:
```
rm /media/<Name of your Ubuntu Partion>/etc/NetworkManager/system-connections/*
```
and copy:
```
cp /etc/NetworkManager/NetworkManager.conf /media/<Name of your Ubuntu Partion>/etc/NetworkManager/NetworkManager.conf
cp /etc/NetworkManager/system-connections/* /media/<Name of your Ubuntu Partion>/etc/NetworkManager/system-connections/
```
Reboot the system without the live CD and you should be good to go. | Wireless drivers are updated from kernel to kernel, version to version - I remember 9.04 had poor support compared to 10.x and newer, for example.
You may need to install/upgrade 13.10 (or 14.04 in a couple months) and make sure you have the latest updates installed, for best support - especially if it's a newer laptop nic. |
403,613 | I'm on 12.04LTS. I have an external USB HD cam that I run as default (preferably). To do this, after every reboot I have to run
```
sudo su -c 'echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue'
```
(1-1.4 is my laptop cam)
This disables my laptop cam.
Then in GUVCview I get:

Which is easily fixed by simply unplugging, and plugging the external cam's usb into port. Then my external cam works great,and is my default selection, and the only one listed in devices under GUVCview, and is marked as default in Multimedia selector.
Everytime I reboot Ubuntu, I have to go through this little process. Not a terrible problem, but is there a way to make my 1-1.4 value stay at "0" ?
EDIT:
EDIT 2:
Open Terminal
```
cd /etc
sudo nano rc.local
```
Edit File by placing command Before " Exit 0"
Press CTRL - X
Y to save
```
!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue
exit 0
``` | 2014/01/10 | [
"https://askubuntu.com/questions/403613",
"https://askubuntu.com",
"https://askubuntu.com/users/192473/"
] | You could just try to manually add it. Go under your internet and click "edit connections" and add a server from there manually. Note you have to know the server's name and password in order to add it. | Wireless drivers are updated from kernel to kernel, version to version - I remember 9.04 had poor support compared to 10.x and newer, for example.
You may need to install/upgrade 13.10 (or 14.04 in a couple months) and make sure you have the latest updates installed, for best support - especially if it's a newer laptop nic. |
77,050 | I hit the edge of a cone yesterday when biking and had a pretty hard fall. Was looking at my bike to see what damage it took. Saw this crack on the rim, is this something really serious that I should be worried about? Last thing I want is to take another hard fall
This is the bike I have. <https://archive.fujibikes.com/2010/Fuji/roubaix-acr-20>
[](https://i.stack.imgur.com/dlDc5.jpg) | 2021/05/27 | [
"https://bicycles.stackexchange.com/questions/77050",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/57002/"
] | It may be worth glancing at [this more detailed answer](https://bicycles.stackexchange.com/questions/64829/what-is-this-aluminum-plate-that-started-rattling-inside-my-ksyrium-rims/64832#64832) that discussed how aluminum rims were constructed. But in brief, aluminum rims are first extruded in a flat bar, then they’re cut and rolled into hoops, then the ends of each hoop are joined somehow.
One method is to simply pin the ends together without smoothing out the joint. Your rim was built this way, and you’re looking at the seam where the ends were joined. Basically, this is there by design. Look in the corresponding location on the other rim and you should also find a seam.
On higher end rims, the joint is usually welded together and the weld is sanded down. For practical purposes, I believe that the advantages are mainly cosmetic. On pinned rims like yours, you might sometimes feel a bit of a pulse when braking (assuming rim brakes, which you have) when the brake pads pass the seam.
If you hit an obstacle, a more common failure mode would be for the rim’s bead hooks to get dented or to buckle. Rims that crack are more likely to do so around the spoke holes. If the rim cracked so as to look like a seam, I suspect the crack usually won’t be straight. If you can’t find on your bike’s spec sheet that your rims are pinned (may not always be obvious, including on the rim manufactuer’s site), this is one indicator I’d use to differentiate a crack from a pinned rim. Also, a crack may not propagate all the way through a rim, and you can check the other rim to see if there’s a seam in the same location. The photo below, [from a different question](https://bicycles.stackexchange.com/questions/84840/is-my-rim-cracked-or-is-it-something-else), looks like it could be a crack rather than a rim seam.
[](https://i.stack.imgur.com/XgLsy.jpg) | I suspect the rim will be just fine based on your description.
A cone is presumably an orange plastic road cone, which are fairly soft and squishy.
You as the rider had a hard fall, but the bike's wheel rim was already on the ground, and probably did not take much of an impact.
As long as the brake track is still flat, your rim is fine to ride.
If your tyre didn't puncture, its not a hard-enough impact to bend metal.
Just remember to check your rims periodically when doing monthly maintenance, and if things change, then stop and reevaluate. |
77,050 | I hit the edge of a cone yesterday when biking and had a pretty hard fall. Was looking at my bike to see what damage it took. Saw this crack on the rim, is this something really serious that I should be worried about? Last thing I want is to take another hard fall
This is the bike I have. <https://archive.fujibikes.com/2010/Fuji/roubaix-acr-20>
[](https://i.stack.imgur.com/dlDc5.jpg) | 2021/05/27 | [
"https://bicycles.stackexchange.com/questions/77050",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/57002/"
] | It may be worth glancing at [this more detailed answer](https://bicycles.stackexchange.com/questions/64829/what-is-this-aluminum-plate-that-started-rattling-inside-my-ksyrium-rims/64832#64832) that discussed how aluminum rims were constructed. But in brief, aluminum rims are first extruded in a flat bar, then they’re cut and rolled into hoops, then the ends of each hoop are joined somehow.
One method is to simply pin the ends together without smoothing out the joint. Your rim was built this way, and you’re looking at the seam where the ends were joined. Basically, this is there by design. Look in the corresponding location on the other rim and you should also find a seam.
On higher end rims, the joint is usually welded together and the weld is sanded down. For practical purposes, I believe that the advantages are mainly cosmetic. On pinned rims like yours, you might sometimes feel a bit of a pulse when braking (assuming rim brakes, which you have) when the brake pads pass the seam.
If you hit an obstacle, a more common failure mode would be for the rim’s bead hooks to get dented or to buckle. Rims that crack are more likely to do so around the spoke holes. If the rim cracked so as to look like a seam, I suspect the crack usually won’t be straight. If you can’t find on your bike’s spec sheet that your rims are pinned (may not always be obvious, including on the rim manufactuer’s site), this is one indicator I’d use to differentiate a crack from a pinned rim. Also, a crack may not propagate all the way through a rim, and you can check the other rim to see if there’s a seam in the same location. The photo below, [from a different question](https://bicycles.stackexchange.com/questions/84840/is-my-rim-cracked-or-is-it-something-else), looks like it could be a crack rather than a rim seam.
[](https://i.stack.imgur.com/XgLsy.jpg) | This is a seam from where the rim was manufactured. You are safe. There is no possible way a crack would be perfectly straight. Check other rims ( even new ones ) and you will see this seam. |
77,050 | I hit the edge of a cone yesterday when biking and had a pretty hard fall. Was looking at my bike to see what damage it took. Saw this crack on the rim, is this something really serious that I should be worried about? Last thing I want is to take another hard fall
This is the bike I have. <https://archive.fujibikes.com/2010/Fuji/roubaix-acr-20>
[](https://i.stack.imgur.com/dlDc5.jpg) | 2021/05/27 | [
"https://bicycles.stackexchange.com/questions/77050",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/57002/"
] | I suspect the rim will be just fine based on your description.
A cone is presumably an orange plastic road cone, which are fairly soft and squishy.
You as the rider had a hard fall, but the bike's wheel rim was already on the ground, and probably did not take much of an impact.
As long as the brake track is still flat, your rim is fine to ride.
If your tyre didn't puncture, its not a hard-enough impact to bend metal.
Just remember to check your rims periodically when doing monthly maintenance, and if things change, then stop and reevaluate. | This is a seam from where the rim was manufactured. You are safe. There is no possible way a crack would be perfectly straight. Check other rims ( even new ones ) and you will see this seam. |
59,395,080 | I got a method which receives 2 parameters:
```
function func(param1, param2){...
```
I got a React component which receives a function as a parameter and it has the information about the 2nd parameter, and I want to set the first parameter in this case as a constant.
What I'm doing is:
```
let myFuncToPass = func.bind("const value", null);
.
.
.
<ComponentName funcParam = { (res) => myFuncToPass(res) }
.
```
I was expecting that when the callback is invoked, the parameter will be called with "const value" as the first parameter and the `res` as the 2nd. What happens is that the res is received as it should to the 2nd parameter, but the first one is null instead of "const value"
What did I do wrong here? | 2019/12/18 | [
"https://Stackoverflow.com/questions/59395080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164004/"
] | There's some confusion in your code. You can properly use Javafx in the version 2 of Graphstream, but in this version, you can't do
```
Viewer viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_GUI_THREAD);
```
because Viewer became an abstract class as you can see [here](https://github.com/graphstream/gs-core/blob/2.0-alpha/src/org/graphstream/ui/view/Viewer.java) :
This means that you doesn't use the good version of graphstream. If you want to use javafx, then you should use [gs-core](https://github.com/graphstream/gs-core/tree/2.0-alpha), [gs-algo](https://github.com/graphstream/gs-algo/tree/2.0-alpha) and [gs-ui-javafx](https://github.com/graphstream/gs-ui-javafx/tree/2.0-alpha) at the 2.0-alpha version as explained in the README [here](https://github.com/graphstream/gs-ui-javafx/tree/2.0-alpha).
Then you can find some example [here](https://github.com/graphstream/gs-ui-javafx/tree/2.0-alpha/src-test/org/graphstream/ui/viewer_fx/test) to help you. | **Important Note:** If you want to use Maven to import the needed libraries (highly recommended) you need to first import the jitpack.io repository to maven. |
109,348 | In the puzzle game [Pipes](https://www.puzzle-pipes.com/), a space-filling [tree](https://en.wikipedia.org/wiki/Tree_(graph_theory)) of pipes (which may have either one, two, or three neighboring connections each, but not four) is scrambled by a series of tile rotations, and the goal is to reconstruct the solution. To do so, you may rotate any tile, including the "source" tile (marked with a red circle), any multiple of 90°. (Note: "space-filling tree" means every tile/square must have a pipe part on it, and no loops are allowed)
**Main puzzle statement:** Is it possible for a Pipes puzzle to have multiple solutions (equivalently: is it possible to transform one tree into another via rotations)? What might be the smallest $N$ for which this can happen on an $N \times N$ grid?
**Easier analogue:** Pipes Lite is a fictional alternative in which pipes may have only one or two neighboring connections each. Is it possible for a Pipes Lite puzzle to have multiple solutions?
**More difficult analogue:** Is it possible for a Pipes puzzle to have *no* possible tile orientation deductions from the outset? That is to say, any individual tile has at least two orientations belonging to separate solutions?
 | 2021/04/09 | [
"https://puzzling.stackexchange.com/questions/109348",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/10562/"
] | **Answer to the "more difficult" question:**
--------------------------------------------
I claim that
>
> yes, it is possible
>
>
>
and here's why:
>
> [](https://i.stack.imgur.com/uS5Cl.png)
>
> Here are two solutions to a Pipes puzzle where no pipe is in the same orientation in both solutions.
>
>
>
Easier analogue:
----------------
I claim that
>
> No, it is not possible.
>
>
>
and here's why:
>
> There is a single solution to any Pipes Lite, which can be found as follows:
>
> Say that each tile is labelled with "**s**traight", "**t**urn", or "**d**ead end".
>
>
>
> [](https://i.stack.imgur.com/CI34i.png)
>
> We're going to mark each border between two segments with "wall" or "pipe" to reconstruct the solution:
>
>
>
> Mark the edges all around the border with "wall". Then, for any straight tile, we can copy its marking to the other side; for any turn, we can copy *the other* marking to the other side.
>
> [](https://i.stack.imgur.com/X3Vvk.png)
>
> Here, I've marked the walls on the left side, and then done the transfer for the first column.
>
> And here, it's done for the second:
>
> [](https://i.stack.imgur.com/8ME3K.png)
>
>
>
> This can be repeated starting from all four directions, not doing transfers at dead ends:
>
>
>
> [](https://i.stack.imgur.com/HIcJc.png)
>
> And the solution is directly drawn out. (If the dead ends are in the same row or column, you may need to do transfers with the dead ends first - if all three sides are walls, draw a pipe in the remaining direction, otherwise draw a wall. Then you can continue as normal, and finish drawing the loop.)
>
>
>
Normal question:
----------------
>
> It's possible to do with 4×4:
>
> [](https://i.stack.imgur.com/BWFnB.png)
>
>
>
>
> It's not possible to do with 3×3:
>
> - **If a corner piece changes,** it must be a dead end; it forces the cell next to it to be a turn...
>
> [](https://i.stack.imgur.com/atqjy.png)
>
> ...and that forces the other corner to be a dead end. This continues around the whole board, and then the center is forced to be a +, which is disallowed.
>
> So no corner pieces can change between solutions, so no edge pieces can change between solutions, so the middle cannot change between solutions.
>
>
> | Here’s a solution that has only some non-unique pipes. My strategy is having that sort of outer parity loop, and filling in the middle in any way. This can be made for any odd square, and I believe the inner fill for a 5x5 is impossible using this strategy. Wouldn’t be shocked if you could do something similar with a 6x6, and I will look into it some more.
[](https://i.stack.imgur.com/KD2pj.jpg) |
54,689,111 | I want 2 dropdown lists:
1. university
2. college
If someone select the university according to that college name is shown to the user in second dropdown list and One more thing both university and college name are stored in one table like
```none
id,University_name,College_name
```
and we have fetch data from that only
```php
<?php
$mysqli = new mysqli("localhost", "root", "", "hr");
$query="SELECT DISTINCT University_Name FROM university";
$result =$mysqli->query($query);
$options="";
while($row = $result->fetch_array(MYSQLI_BOTH)) {
$University_Name = $row["University_Name"];
$options .= "<OPTION VALUE=\"$University_Name\" name='customer_email'>".$University_Name.'</option>';
}
?>
<div class="input-row">
<div> </div>
<label class="control-label">University Name <span style="color:red;">*</span></label>
<div class="input-group"> <span class="input-group-addon"></span>
<select name="university" id="university" class="form-control" onchange="contrychange()" required>
<option value="Select university">Select University</option>
<?=$options?>
</select>
</div>
</div>
<?php
$mysqli = new mysqli("localhost", "root", "", "hr");
$query="SELECT College_Name FROM university where University_Name='$University_Name'";
$result =$mysqli->query($query);
$options="";
while($row = $result->fetch_array(MYSQLI_BOTH)) {
$College_Name = $row["College_Name"];
$options .= "<OPTION VALUE=\"$College_Name\" name='customer_email'>".$College_Name.'</option>';
}
?>
<div class="input-row">
<div> </div>
<label class="control-label" for="field_12">College Name<span style="color:red;">*</span></label>
<div class="input-group"> <span class="input-group-addon"></span>
<select name="college" id="college" class="form-control" required>
<option value="Select college">Select College</option>
<?=$options?>
</select>
</div>
</div>
``` | 2019/02/14 | [
"https://Stackoverflow.com/questions/54689111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11016263/"
] | >
> Are the messages getting buffered somewhere?
>
>
>
Yes, when resource alarm is set, messages will be published into network buffers.
* Tiny messages will take some time to fill up Network buffer and then
block publishers.
* Less network buffer size will block publishers
soon. | It's better to ask questions about the behavior of RabbitMQ itself (and the Java client that Spring uses) on the rabbitmq-users Google group; that's where the RabbitMQ engineers hang out.
>
> (2) Spring Cloud Stream document says below. Does it mean the above behaviour?
>
>
>
That change was made so that if producers are blocked from producing, consumers can still consume.
>
> (4) If the producer's message will not be accepted by RabbitMQ, then is it possible to throw specific exception to the publisher from spring-cloud-stream (saying alarms are activated and message publish failed)?
>
>
>
Publishing is asynchronous by default; you can enable transactions (which can slow down performance a lot; or enable errors on the producer and you'll get an asynchronous message on the error channel if you enable publisher confirms and returns. |
35,714,070 | I'm trying to select the positions of some value and print the parts of that value by position in java when I'm working on android app.
for example if I have some number four-digit, 4375 if I select the 3rd one system will print 7, 4th one system will print 5.. | 2016/03/01 | [
"https://Stackoverflow.com/questions/35714070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4273929/"
] | Use a countif, if it's greater than zero then you know it exists in the list:
```
If Application.WorksheetFunction.CountIf(Sheets("Sheet1").Range("NamedRange"), Sheets("Sheet2").Cells(i, 2).Value) > 0 Then
Sheets("Sheet2").Cells(i, 2).EntireRow.Delete
End If
``` | Here is how you can achieve it in just one line
```
If Not IsError(Application.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
// Value found
End If
```
**Example:**
Search for Blah-Blah in column A of Sheet5
```
If Not IsError(Application.Match("Blah-Blah", Sheets("Sheet5").Range("A:A"), 0)) Then
'The value present in that range
End If
``` |
333,798 | When I am viewing a question, and it has been closed, this message will pop up:
>
> This question has been closed - no more answers will be accepted.
>
>
>
What it actually means is that I can't post an answer anymore. But don't you think the word `accepted` is ambiguous? "no more answers will be accepted" can also mean that the OP cannot click on the accept checkmark anymore, which the OP *can* do. I found this rather confusing.
What about changing the message to
>
> This question has been closed - no more answers can be posted.
>
>
>
or
>
> This question has been closed - you can't post an answer now.
>
>
> | 2016/09/03 | [
"https://meta.stackoverflow.com/questions/333798",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/5133585/"
] | Yes, *"accepted"* is ambiguous. Virtually any of the commentators' proposed replacements would be better. Suggested rewording:
>
> This question has been closed -- answers cannot be added to closed questions.
>
>
>
Or, more curtly:
>
> Question closed: answers can't be added.
>
>
>
Note: the word "*more*" is avoided because there may be no answers, and "*more*" implies at least one answer exists. | During the downtime a few moments ago, SE told me "This site is currently not accepting new answers." Seemed like good phrasing. Maybe we should use that here, too?
>
> This question has been closed - no new answers may be posted.
>
>
> |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | you can try this out if you want to pass more than one type of arguments, first add them all to an array of type Object and pass that object to RunWorkerAsync() here is an example :
```
some_Method(){
List<string> excludeList = new List<string>(); // list of strings
string newPath ="some path"; // normal string
Object[] args = {newPath,excludeList };
backgroundAnalyzer.RunWorkerAsync(args);
}
```
Now in the doWork method of background worker
```
backgroundAnalyzer_DoWork(object sender, DoWorkEventArgs e)
{
backgroundAnalyzer.ReportProgress(50);
Object[] arg = e.Argument as Object[];
string path= (string)arg[0];
List<string> lst = (List<string>) arg[1];
.......
// do something......
//.....
}
``` | You should always try to use a composite object with concrete types (using composite design pattern) rather than a list of object types. Who would remember what the heck each of those objects is? Think about maintenance of your code later on... Instead, try something like this:
```
Public (Class or Structure) MyPerson
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int ZipCode { get; set; }
End Class
```
And then:
```
Dim person as new MyPerson With { .FirstName = “Joe”,
.LastName = "Smith”,
...
}
backgroundWorker1.RunWorkerAsync(person)
```
and then:
```
private void backgroundWorker1_DoWork (object sender, DoWorkEventArgs e)
{
MyPerson person = e.Argument as MyPerson
string firstname = person.FirstName;
string lastname = person.LastName;
int zipcode = person.ZipCode;
}
``` |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | You start it like this:
```
int value = 123;
bgw1.RunWorkerAsync(argument: value); // the int will be boxed
```
and then
```
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
int value = (int) e.Argument; // the 'argument' parameter resurfaces here
...
// and to transport a result back to the main thread
double result = 0.1 * value;
e.Result = result;
}
// the Completed handler should follow this pattern
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// check error, check cancel, then use result
if (e.Error != null)
{
// handle the error
}
else if (e.Cancelled)
{
// handle cancellation
}
else
{
double result = (double) e.Result;
// use it on the UI thread
}
// general cleanup code, runs when there was an error or not.
}
``` | Check out the [DoWorkEventArgs.Argument Property](http://msdn.microsoft.com/en-us/library/system.componentmodel.doworkeventargs.argument%28VS.90%29.aspx):
```
...
backgroundWorker1.RunWorkerAsync(yourInt);
...
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Do not access the form's BackgroundWorker reference directly.
// Instead, use the reference provided by the sender parameter.
BackgroundWorker bw = sender as BackgroundWorker;
// Extract the argument.
int arg = (int)e.Argument;
// Start the time-consuming operation.
e.Result = TimeConsumingOperation(bw, arg);
// If the operation was canceled by the user,
// set the DoWorkEventArgs.Cancel property to true.
if (bw.CancellationPending)
{
e.Cancel = true;
}
}
``` |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
```
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
```
And on the handler method:
```
private void WorkerDoWork(int value, string text) {
...
}
``` | you can try this out if you want to pass more than one type of arguments, first add them all to an array of type Object and pass that object to RunWorkerAsync() here is an example :
```
some_Method(){
List<string> excludeList = new List<string>(); // list of strings
string newPath ="some path"; // normal string
Object[] args = {newPath,excludeList };
backgroundAnalyzer.RunWorkerAsync(args);
}
```
Now in the doWork method of background worker
```
backgroundAnalyzer_DoWork(object sender, DoWorkEventArgs e)
{
backgroundAnalyzer.ReportProgress(50);
Object[] arg = e.Argument as Object[];
string path= (string)arg[0];
List<string> lst = (List<string>) arg[1];
.......
// do something......
//.....
}
``` |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
```
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
```
And on the handler method:
```
private void WorkerDoWork(int value, string text) {
...
}
``` | You need [RunWorkerAsync(object)](http://msdn.microsoft.com/en-us/library/f00zz5b2.aspx) method and [DoWorkEventArgs.Argument](http://msdn.microsoft.com/en-us/library/system.componentmodel.doworkeventargs.argument.aspx) property.
```
worker.RunWorkerAsync(5);
private void worker_DoWork(object sender, DoWorkEventArgs e) {
int argument = (int)e.Argument; //5
}
``` |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | You start it like this:
```
int value = 123;
bgw1.RunWorkerAsync(argument: value); // the int will be boxed
```
and then
```
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
int value = (int) e.Argument; // the 'argument' parameter resurfaces here
...
// and to transport a result back to the main thread
double result = 0.1 * value;
e.Result = result;
}
// the Completed handler should follow this pattern
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// check error, check cancel, then use result
if (e.Error != null)
{
// handle the error
}
else if (e.Cancelled)
{
// handle cancellation
}
else
{
double result = (double) e.Result;
// use it on the UI thread
}
// general cleanup code, runs when there was an error or not.
}
``` | You need [RunWorkerAsync(object)](http://msdn.microsoft.com/en-us/library/f00zz5b2.aspx) method and [DoWorkEventArgs.Argument](http://msdn.microsoft.com/en-us/library/system.componentmodel.doworkeventargs.argument.aspx) property.
```
worker.RunWorkerAsync(5);
private void worker_DoWork(object sender, DoWorkEventArgs e) {
int argument = (int)e.Argument; //5
}
``` |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | You start it like this:
```
int value = 123;
bgw1.RunWorkerAsync(argument: value); // the int will be boxed
```
and then
```
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
int value = (int) e.Argument; // the 'argument' parameter resurfaces here
...
// and to transport a result back to the main thread
double result = 0.1 * value;
e.Result = result;
}
// the Completed handler should follow this pattern
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// check error, check cancel, then use result
if (e.Error != null)
{
// handle the error
}
else if (e.Cancelled)
{
// handle cancellation
}
else
{
double result = (double) e.Result;
// use it on the UI thread
}
// general cleanup code, runs when there was an error or not.
}
``` | You can use the `DoWorkEventArgs.Argument` property.
A full example (even using an int argument) can be found on Microsoft's site:
* [How to: Run an Operation in the Background](http://msdn.microsoft.com/en-us/library/hybbz6ke.aspx) |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
```
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
```
And on the handler method:
```
private void WorkerDoWork(int value, string text) {
...
}
``` | You should always try to use a composite object with concrete types (using composite design pattern) rather than a list of object types. Who would remember what the heck each of those objects is? Think about maintenance of your code later on... Instead, try something like this:
```
Public (Class or Structure) MyPerson
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int ZipCode { get; set; }
End Class
```
And then:
```
Dim person as new MyPerson With { .FirstName = “Joe”,
.LastName = "Smith”,
...
}
backgroundWorker1.RunWorkerAsync(person)
```
and then:
```
private void backgroundWorker1_DoWork (object sender, DoWorkEventArgs e)
{
MyPerson person = e.Argument as MyPerson
string firstname = person.FirstName;
string lastname = person.LastName;
int zipcode = person.ZipCode;
}
``` |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | You need [RunWorkerAsync(object)](http://msdn.microsoft.com/en-us/library/f00zz5b2.aspx) method and [DoWorkEventArgs.Argument](http://msdn.microsoft.com/en-us/library/system.componentmodel.doworkeventargs.argument.aspx) property.
```
worker.RunWorkerAsync(5);
private void worker_DoWork(object sender, DoWorkEventArgs e) {
int argument = (int)e.Argument; //5
}
``` | You should always try to use a composite object with concrete types (using composite design pattern) rather than a list of object types. Who would remember what the heck each of those objects is? Think about maintenance of your code later on... Instead, try something like this:
```
Public (Class or Structure) MyPerson
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public int ZipCode { get; set; }
End Class
```
And then:
```
Dim person as new MyPerson With { .FirstName = “Joe”,
.LastName = "Smith”,
...
}
backgroundWorker1.RunWorkerAsync(person)
```
and then:
```
private void backgroundWorker1_DoWork (object sender, DoWorkEventArgs e)
{
MyPerson person = e.Argument as MyPerson
string firstname = person.FirstName;
string lastname = person.LastName;
int zipcode = person.ZipCode;
}
``` |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | You start it like this:
```
int value = 123;
bgw1.RunWorkerAsync(argument: value); // the int will be boxed
```
and then
```
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
int value = (int) e.Argument; // the 'argument' parameter resurfaces here
...
// and to transport a result back to the main thread
double result = 0.1 * value;
e.Result = result;
}
// the Completed handler should follow this pattern
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e)
{
// check error, check cancel, then use result
if (e.Error != null)
{
// handle the error
}
else if (e.Cancelled)
{
// handle cancellation
}
else
{
double result = (double) e.Result;
// use it on the UI thread
}
// general cleanup code, runs when there was an error or not.
}
``` | You can pass multiple arguments like this.
```
List<object> arguments = new List<object>();
arguments.Add("first"); //argument 1
arguments.Add(new Object()); //argument 2
// ...
arguments.Add(10); //argument n
backgroundWorker.RunWorkerAsync(arguments);
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
List<object> genericlist = e.Argument as List<object>;
//extract your multiple arguments from
//this list and cast them and use them.
}
``` |
4,807,152 | Let's say I want to sent an int parameter to a background worker, how can this be accomplished?
```
private void worker_DoWork(object sender, DoWorkEventArgs e) {
}
```
I know when this is worker.RunWorkerAsync();, I don't understand how to define in worker\_DoWork that it should take an int parameter. | 2011/01/26 | [
"https://Stackoverflow.com/questions/4807152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281671/"
] | Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
```
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
```
And on the handler method:
```
private void WorkerDoWork(int value, string text) {
...
}
``` | Check out the [DoWorkEventArgs.Argument Property](http://msdn.microsoft.com/en-us/library/system.componentmodel.doworkeventargs.argument%28VS.90%29.aspx):
```
...
backgroundWorker1.RunWorkerAsync(yourInt);
...
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Do not access the form's BackgroundWorker reference directly.
// Instead, use the reference provided by the sender parameter.
BackgroundWorker bw = sender as BackgroundWorker;
// Extract the argument.
int arg = (int)e.Argument;
// Start the time-consuming operation.
e.Result = TimeConsumingOperation(bw, arg);
// If the operation was canceled by the user,
// set the DoWorkEventArgs.Cancel property to true.
if (bw.CancellationPending)
{
e.Cancel = true;
}
}
``` |
25,682,963 | I'm trying to mimic Windows 8 sidescrolling and multiple column layout using CSS3 columns, but I want columns to have a fixed width, or as I'm doing in [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/), viewport width.
Now, no matter what kind of unit I use, it seems columns auto-fit themselves into the container div, regardless of the width I set.
In [my fiddle](http://jsfiddle.net/noquierouser/u0u6k5ke/5/) I set columns to be `35vw`, and that gives me 2 columns of equal width. As far as I know, that should result in 2 fully visible columns and part of the third, but that is not happening. This behavior also happens if I set `px`, `em` or `%` as units.
Is this a browser default behavior or am I missing something? | 2014/09/05 | [
"https://Stackoverflow.com/questions/25682963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1061340/"
] | The timer works so that `TON.Q` goes high only if `TON.IN` is continuously high for at least the duration of `TON.PT`.
This makes sure that `TON.Q` only goes high if `TON.IN` is in a stable high state.
This could be useful for instance to ensure that the output is only enabled if a button is pressed for at least a duration of `TON.PT`. | We also have built our own timer structure with using milliseconds counter provided by PLC, so we could make arrays of timer (Schneider Electric) when we need and exceed PLC limitation.
```
TTIMER
Count: UINT
timclock :INT
OUT :BOOL
IN: BOOL
END_STRUCT;
TIM_SOD=ARRAY[0..1] OF TTIMER;
(*This part runs every cycle of PLC*)
FOR I:=0 TO 1 DO
IF TIM_SOD[I].IN (*timer on*)
THEN
IF (TIM_SOD[I].Count)>0 (*number of seconds left*)
THEN
IF ABS_INT(IN:=timclock-TIM_SOD[I].CLK)>=100 (*timclock -mSec counter*)
THEN aTIM_SOD[I].Count:=TIM_SOD[I].Count-1;
TIM_SOD[I].CLK:=TIM_SOD[I].CLK+100;
END_IF;
ELSE
TIM_SOD[I].IN:=0; (*timer off*)
TIM_SOD[I].Out:=1; (*Timer have run out*)
END_IF;
END_IF;
END_FOR;
(*-------------------------------------------------*)
(*This part runs once when we need start timer*)
TIM_SOD[0].COUNT:=H690; (*delay in seconds*)
TIM_SOD[0].CLK:=TIMCLOCK; (*current value of mSec counter*)
TIM_SOD[0].IN:=True;
(*-------------------------------------------------*)
(*This part runs once when we need stop timer*)
TIM_SOD[0].IN:=False;
(*Checking timer*)
IF TIM_SOD[0].OUT
THEN
(*doing smth......*)
END_IF;
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.