qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
29,226,198 | I'm looking for function that **Open window explorer in C language**. I have found this [answer]**([How can I open Windows Explorer to a certain directory from within a WPF app?](https://stackoverflow.com/questions/1746079/how-can-i-open-windows-explorer-to-a-certain-directory-from-within-a-wpf-app))**, but this is C# language. **C can't have these features**? I use VS 2010.
I'm a beginner of C. So my question may seem ridiculously easy. But if you give me the answer I really appreciate it. Thanks :) | 2015/03/24 | [
"https://Stackoverflow.com/questions/29226198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4427613/"
] | The simplest way to open a certain directory in an explorer (here c:\program files) may be:
```
system("start \"\" \"c:\\program files\"");
``` | Given the stslib.h library contains the system() function that let's you run shell commands, you should be able to run the command to open a new windows explorer window using the same command you would use in the terminal window.
A guideline: <http://www.programmingsimplified.com/c-program-shutdown-computer> |
155,822 | I'm having some problems getting my table and caption formatting to look right. Below is a sample of the code from my thesis. I've included all the packages that I'm using in my thesis, so that you can get an idea of what else might be affecting the look of the table. I've also attached a picture of my output.
The main issues that I have with the table are:
1. The caption text sits too close to the top of the table. Is there a way to get this to sit a little higher (0.5-1 line spaces) above the table?
2. The rows are too closely spaced, making it a little hard to read the nuclide and atomic mass numbers for the elements. Does line spacing not affect tables? How can I can increase the spacing between rows?
3. The text underneath the table needs to sit directly beneath the table and be no wider than the width of the table. How do I go about this?
Thanks for the help!
.
```
\documentclass[12pt,a4paper]{report}
\usepackage{setspace}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{layout}
\usepackage{lscape}
\usepackage[round]{natbib}
\usepackage{array}
\usepackage{booktabs}
\usepackage{siunitx}
\usepackage{tensor}
\begin{document}
\doublespacing
\begin{table}
\centering
\caption{Naturally occurring long-lived radionuclides and their stable radiogenic daughters frequently used in geochronology.}\label{tab:001}
\addtolength{\tabcolsep}{-2pt} % slight reduction of intercolumn space
\begin{tabular}{*{4}{c} >{\raggedright\arraybackslash}p{3.5cm}}
\toprule
Parent & Decay Modes$^a$ & Half-life (years) & Daughters \\
\midrule
$^{40}_{19}$K & $\varepsilon$: $10.72\%$, $\beta^{+}$: $1.0\times 10^{-3}\%$ & $1.248 \times 10^{9}$ & $^{40}_{18}$Ar \\
$^{40}_{19}$K & $\beta^{-}$: $89.28\%$ & $1.248 \times 10^{9}$ & $^{40}_{20}$Ca \\
$^{87}_{37}$Rb & $\beta^{-}$: $100\%$ & $4.81\times 10^{10}$ & $^{87}_{38}$Sr \\
$^{147}_{62}$Sm & $\alpha$: $100\%$ & $1.06\times 10^{11}$ & $^{143}_{60}$Nd \\
$^{176}_{71}$Lu & $\beta^{-}$: $100\%$ & $3.76\times 10^{10}$ & $^{176}_{72}$Hf \\
$^{187}_{75}$Re & $\alpha$: $1.0\times 10^{-4}\%$, $\beta^{-}: 100\%$ & $4.33\times 10^{10}$ & $^{187}_{76}$Os \\
$^{232}_{90}$Th & $\alpha$: $100\%$, SF: $1.1\times 10^{-9}\%$ & $1.40\times 10^{10}$ & $^{208}_{82}$Pb \\
$^{235}_{92}$U & $\alpha$: $100\%$, SF: $7.0\times 10^{-9}\%$ & $7.04\times 10^{8}$ & $^{207}_{82}$Pb \\
$^{238}_{92}$U & $\alpha$: $100\%$, SF: $5.5\times 10^{-5}\%$ & $4.468\times 10^{9}$ & $^{206}_{82}$Pb \\
\bottomrule
\end{tabular}
\end{table}
$^{a}$ $\varepsilon$ = electron capture decay; $\beta^{+}$ = positron decay; $\beta^{-}$ = negatron decay; $\alpha$ = alpha decay.
\end{document}
``` | 2014/01/24 | [
"https://tex.stackexchange.com/questions/155822",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/44564/"
] | 1. It's enough to load the [`caption`](http://www.ctan.org/pkg/caption) package (you could even set a bigger `skip`, if needed).
2. Redefine `\arraystretch` locally.
3. Build your table and its footnote using the [`ctable`](http://www.ctan.org/pkg/ctable) package.
The code:
```
\documentclass[12pt,a4paper]{report}
\usepackage{booktabs}
\usepackage{siunitx}
\usepackage{chemmacros}
\usepackage{caption}
\usepackage{ctable}
\begin{document}
{
\renewcommand\arraystretch{1.3}
\addtolength{\tabcolsep}{-2pt} % slight reduction of intercolumn space
\ctable[
caption = {Naturally occurring long-lived radionuclides and their stable radiogenic daughters frequently used in geochronology.},
label= {tab:001},
mincapwidth = \textwidth,
footerwidth
]
{ccS[table-figures-exponent=2,table-figures-integer=2,table-figures-decimal=3,table-number-alignment=center]c
}
{%
\tnote{$\varepsilon$ = electron capture decay; $\beta^{+}$ = positron decay; $\beta^{-}$ = negatron decay; \\ $\alpha$ = alpha decay.}%
}
{%
\toprule
Parent & Decay Modes & {Half-life (years)} & Daughters \\
\midrule
\ch{^{40}_{19}K} & $\varepsilon$: \SI{10.72}{\percent}, $\beta^{+}$: \SI{1.0e-3}{\percent} & 1.248e9 & \ch{^{40}_{18}Ar} \\
\ch{^{40}_{19}K} & $\beta^{-}$: \SI{89.28}{\percent} & 1.248e9 & \ch{^{40}_{20}Ca} \\
\ch{^{87}_{37}Rb} & $\beta^{-}$: $100\%$ & 4.81e10 & \ch{^{87}_{38}Sr} \\
\ch{^{147}_{62}Sm} & $\alpha$: \SI{100}{\percent} & 1.06e11 & \ch{^{143}_{60}Nd} \\
\ch{^{176}_{71}Lu} & $\beta^{-}$: \SI{100}{\percent} & 3.76e10 & \ch{^{176}_{72}Hf} \\
\ch{^{187}_{75}Re} & $\alpha$: \SI{1.0e-4}{\percent}, $\beta^{-}$: \SI{100}{\percent} & 4.33e10 & \ch{^{187}_{76}Os} \\
\ch{^{232}_{90}Th} & $\alpha$: \SI{100}{\percent}, SF: \SI{1.1e-9}{\percent} & 1.40e10 & \ch{^{208}_{82}Pb} \\
\ch{^{235}_{92}U} & $\alpha$: \SI{100}{\percent}, SF: \SI{7.0e-9}{\percent} & 7.04e8 & \ch{^{207}_{82}Pb} \\
\ch{^{238}_{92}U} & $\alpha$: \SI{100}{\percent}, SF: \SI{5.5e-5}{\percent} & 4.468e9 & \ch{^{206}_{82}Pb} \\
\bottomrule
}
}
\end{document}
```

### Additional improvements:
1. The `siunitx` package was used to format the entries in the third column.
2. The `chemmacros` package was used to properly format the sub/superscripts in the first and third columns. | Another approach for the third problem is to use the »[threeparttable](http://ctan.org/pkg/threeparttable)« package. For formatting and alignment of the numbers it is suggestive to let »[siunitx](http://ctan.org/pkg/siunitx)« do that job. The isotopes can be formatted easier by `chemformula` (from the »[chemmacros](http://ctan.org/pkg/chemmacros)« bundle).
```
\documentclass[12pt,a4paper]{report}
\usepackage[T1]{fontenc}
\usepackage{caption}
\usepackage{array,booktabs,threeparttable}
\usepackage{siunitx}
\usepackage{chemformula}
\begin{document}
\begin{table}[!ht]
\caption{Naturally occurring long-lived radionuclides and their stable radiogenic daughters frequently used in geochronology.}
\label{tab:nuclides}
\centering
\begin{threeparttable}
\renewcommand{\arraystretch}{1.5}
\begin{tabular}{
c
c
S[table-figures-exponent=2,table-figures-integer=2,table-figures-decimal=3,table-number-alignment=center]
c
} \toprule
Parent & Decay Modes\tnote{a} & {Half-life (years)} & Daughters \\ \midrule
\ch{^{40}_{19}K} & $\varepsilon$: \SI{10.72}{\percent}, $\beta^{+}$: \SI{1.0e-3}{\percent} & 1.248e9 & \ch{^{40}_{18}Ar} \\
\ch{^{40}_{19}K} & $\beta^{-}$: \SI{89.28}{\percent} & 1.248e9 & \ch{^{40}_{20}Ca} \\
\ch{^{87}_{37}Rb} & $\beta^{-}$: $100\%$ & 4.81e10 & \ch{^{87}_{38}Sr} \\
\ch{^{147}_{62}Sm} & $\alpha$: \SI{100}{\percent} & 1.06e11 & \ch{^{143}_{60}Nd} \\
\ch{^{176}_{71}Lu} & $\beta^{-}$: \SI{100}{\percent} & 3.76e10 & \ch{^{176}_{72}Hf} \\
\ch{^{187}_{75}Re} & $\alpha$: \SI{1.0e-4}{\percent}, $\beta^{-}$: \SI{100}{\percent} & 4.33e10 & \ch{^{187}_{76}Os} \\
\ch{^{232}_{90}Th} & $\alpha$: \SI{100}{\percent}, SF: \SI{1.1e-9}{\percent} & 1.40e10 & \ch{^{208}_{82}Pb} \\
\ch{^{235}_{92}U} & $\alpha$: \SI{100}{\percent}, SF: \SI{7.0e-9}{\percent} & 7.04e8 & \ch{^{207}_{82}Pb} \\
\ch{^{238}_{92}U} & $\alpha$: \SI{100}{\percent}, SF: \SI{5.5e-5}{\percent} & 4.468e9 & \ch{^{206}_{82}Pb} \\ \bottomrule
\end{tabular}
\begin{tablenotes}
\footnotesize
\item[a]$\varepsilon$ = electron capture decay; $\beta^{+}$ = positron decay; $\beta^{-}$ = negatron decay; $\alpha$ = alpha decay
\end{tablenotes}
\end{threeparttable}
\end{table}
\end{document}
```
---
 |
155,822 | I'm having some problems getting my table and caption formatting to look right. Below is a sample of the code from my thesis. I've included all the packages that I'm using in my thesis, so that you can get an idea of what else might be affecting the look of the table. I've also attached a picture of my output.
The main issues that I have with the table are:
1. The caption text sits too close to the top of the table. Is there a way to get this to sit a little higher (0.5-1 line spaces) above the table?
2. The rows are too closely spaced, making it a little hard to read the nuclide and atomic mass numbers for the elements. Does line spacing not affect tables? How can I can increase the spacing between rows?
3. The text underneath the table needs to sit directly beneath the table and be no wider than the width of the table. How do I go about this?
Thanks for the help!
.
```
\documentclass[12pt,a4paper]{report}
\usepackage{setspace}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{layout}
\usepackage{lscape}
\usepackage[round]{natbib}
\usepackage{array}
\usepackage{booktabs}
\usepackage{siunitx}
\usepackage{tensor}
\begin{document}
\doublespacing
\begin{table}
\centering
\caption{Naturally occurring long-lived radionuclides and their stable radiogenic daughters frequently used in geochronology.}\label{tab:001}
\addtolength{\tabcolsep}{-2pt} % slight reduction of intercolumn space
\begin{tabular}{*{4}{c} >{\raggedright\arraybackslash}p{3.5cm}}
\toprule
Parent & Decay Modes$^a$ & Half-life (years) & Daughters \\
\midrule
$^{40}_{19}$K & $\varepsilon$: $10.72\%$, $\beta^{+}$: $1.0\times 10^{-3}\%$ & $1.248 \times 10^{9}$ & $^{40}_{18}$Ar \\
$^{40}_{19}$K & $\beta^{-}$: $89.28\%$ & $1.248 \times 10^{9}$ & $^{40}_{20}$Ca \\
$^{87}_{37}$Rb & $\beta^{-}$: $100\%$ & $4.81\times 10^{10}$ & $^{87}_{38}$Sr \\
$^{147}_{62}$Sm & $\alpha$: $100\%$ & $1.06\times 10^{11}$ & $^{143}_{60}$Nd \\
$^{176}_{71}$Lu & $\beta^{-}$: $100\%$ & $3.76\times 10^{10}$ & $^{176}_{72}$Hf \\
$^{187}_{75}$Re & $\alpha$: $1.0\times 10^{-4}\%$, $\beta^{-}: 100\%$ & $4.33\times 10^{10}$ & $^{187}_{76}$Os \\
$^{232}_{90}$Th & $\alpha$: $100\%$, SF: $1.1\times 10^{-9}\%$ & $1.40\times 10^{10}$ & $^{208}_{82}$Pb \\
$^{235}_{92}$U & $\alpha$: $100\%$, SF: $7.0\times 10^{-9}\%$ & $7.04\times 10^{8}$ & $^{207}_{82}$Pb \\
$^{238}_{92}$U & $\alpha$: $100\%$, SF: $5.5\times 10^{-5}\%$ & $4.468\times 10^{9}$ & $^{206}_{82}$Pb \\
\bottomrule
\end{tabular}
\end{table}
$^{a}$ $\varepsilon$ = electron capture decay; $\beta^{+}$ = positron decay; $\beta^{-}$ = negatron decay; $\alpha$ = alpha decay.
\end{document}
``` | 2014/01/24 | [
"https://tex.stackexchange.com/questions/155822",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/44564/"
] | 1. It's enough to load the [`caption`](http://www.ctan.org/pkg/caption) package (you could even set a bigger `skip`, if needed).
2. Redefine `\arraystretch` locally.
3. Build your table and its footnote using the [`ctable`](http://www.ctan.org/pkg/ctable) package.
The code:
```
\documentclass[12pt,a4paper]{report}
\usepackage{booktabs}
\usepackage{siunitx}
\usepackage{chemmacros}
\usepackage{caption}
\usepackage{ctable}
\begin{document}
{
\renewcommand\arraystretch{1.3}
\addtolength{\tabcolsep}{-2pt} % slight reduction of intercolumn space
\ctable[
caption = {Naturally occurring long-lived radionuclides and their stable radiogenic daughters frequently used in geochronology.},
label= {tab:001},
mincapwidth = \textwidth,
footerwidth
]
{ccS[table-figures-exponent=2,table-figures-integer=2,table-figures-decimal=3,table-number-alignment=center]c
}
{%
\tnote{$\varepsilon$ = electron capture decay; $\beta^{+}$ = positron decay; $\beta^{-}$ = negatron decay; \\ $\alpha$ = alpha decay.}%
}
{%
\toprule
Parent & Decay Modes & {Half-life (years)} & Daughters \\
\midrule
\ch{^{40}_{19}K} & $\varepsilon$: \SI{10.72}{\percent}, $\beta^{+}$: \SI{1.0e-3}{\percent} & 1.248e9 & \ch{^{40}_{18}Ar} \\
\ch{^{40}_{19}K} & $\beta^{-}$: \SI{89.28}{\percent} & 1.248e9 & \ch{^{40}_{20}Ca} \\
\ch{^{87}_{37}Rb} & $\beta^{-}$: $100\%$ & 4.81e10 & \ch{^{87}_{38}Sr} \\
\ch{^{147}_{62}Sm} & $\alpha$: \SI{100}{\percent} & 1.06e11 & \ch{^{143}_{60}Nd} \\
\ch{^{176}_{71}Lu} & $\beta^{-}$: \SI{100}{\percent} & 3.76e10 & \ch{^{176}_{72}Hf} \\
\ch{^{187}_{75}Re} & $\alpha$: \SI{1.0e-4}{\percent}, $\beta^{-}$: \SI{100}{\percent} & 4.33e10 & \ch{^{187}_{76}Os} \\
\ch{^{232}_{90}Th} & $\alpha$: \SI{100}{\percent}, SF: \SI{1.1e-9}{\percent} & 1.40e10 & \ch{^{208}_{82}Pb} \\
\ch{^{235}_{92}U} & $\alpha$: \SI{100}{\percent}, SF: \SI{7.0e-9}{\percent} & 7.04e8 & \ch{^{207}_{82}Pb} \\
\ch{^{238}_{92}U} & $\alpha$: \SI{100}{\percent}, SF: \SI{5.5e-5}{\percent} & 4.468e9 & \ch{^{206}_{82}Pb} \\
\bottomrule
}
}
\end{document}
```

### Additional improvements:
1. The `siunitx` package was used to format the entries in the third column.
2. The `chemmacros` package was used to properly format the sub/superscripts in the first and third columns. | A solution using the caption and floatrow packages, so that the caption width is equal to the table width:
```
\documentclass[12pt,a4paper]{report}
\usepackage{amsmath}
\usepackage{array}
\usepackage{booktabs}
\usepackage[justification = centerlast]{caption}
\usepackage{floatrow}
\floatsetup[table]{footnoterule = none}
\renewcommand{\arraystretch}{1.5}
\begin{document}
\begin{table}
\addtolength{\tabcolsep}{-2pt} % slight reduction of intercolumn space
\centering
\ttabbox%
{\caption{Naturally occurring long-lived radionuclides and their stable radiogenic daughters frequently used in geochronology.}\label{tab:001}}
{\begin{tabular}{*{4}{c} >{\raggedright\arraybackslash}p{3.5cm}}
\toprule
Parent & Decay Modes\mpfootnotemark & Half-life (years) & Daughters \\
\midrule
$^{40}_{19}$K & $\varepsilon$: $10.72\%$, $\beta^{+}$: $1.0\times 10^{-3}\%$ & $1.248 \times 10^{9}$ & $^{40}_{18}$Ar \\
$^{40}_{19}$K & $\beta^{-}$: $89.28\%$ & $1.248 \times 10^{9}$ & $^{40}_{20}$Ca \\
$^{87}_{37}$Rb & $\beta^{-}$: $100\%$ & $4.81\times 10^{10}$ & $^{87}_{38}$Sr \\
$^{147}_{62}$Sm & $\alpha$: $100\%$ & $1.06\times 10^{11}$ & $^{143}_{60}$Nd \\
$^{176}_{71}$Lu & $\beta^{-}$: $100\%$ & $3.76\times 10^{10}$ & $^{176}_{72}$Hf \\
$^{187}_{75}$Re & $\alpha$: $1.0\times 10^{-4}\%$, $\beta^{-}: 100\%$ & $4.33\times 10^{10}$ & $^{187}_{76}$Os \\
$^{232}_{90}$Th & $\alpha$: $100\%$, SF: $1.1\times 10^{-9}\%$ & $1.40\times 10^{10}$ & $^{208}_{82}$Pb \\
$^{235}_{92}$U & $\alpha$: $100\%$, SF: $7.0\times 10^{-9}\%$ & $7.04\times 10^{8}$ & $^{207}_{82}$Pb \\
$^{238}_{92}$U & $\alpha$: $100\%$, SF: $5.5\times 10^{-5}\%$ & $4.468\times 10^{9}$ & $^{206}_{82}$Pb \\
\bottomrule
\end{tabular}
\floatfoot{\quad\textsuperscript{\thempfootnote}\:$\varepsilon$ = electron capture decay; $\beta^{+}$ = positron decay; $\beta^{-}$ = negatron decay; \\ $\alpha$ = alpha decay.}}
\end{table}
\end{document}
```
 |
801,940 | I have a parameterized hibernate dao that performs basic crud operations, and when parameterized is used as a delegate to fulfil basic crud operations for a given dao.
```
public class HibernateDao <T, ID extends Serializable> implements GenericDao<T, ID>
```
I want to be able to derive Class from T at runtime to create criteria queries in Hibernate, such that:
```
public T findByPrimaryKey(ID id) {
return (T) HibernateUtil.getSession().load(T.getClass(), id);
}
```
I know:
```
T.getClass()
```
does not exist, but is there any way to derive the correct Class object from T at runtime?
I have looked at generics and reflection but have not come up with a suitable solution, perhaps I am missing something.
Thanks. | 2009/04/29 | [
"https://Stackoverflow.com/questions/801940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49854/"
] | You could have the Class passed as a constructor argument.
```
public class HibernateDao <T, ID extends Serializable> implements GenericDao<T, ID> {
private final Class<? extends T> type;
public HibernateDao(Class<? extends T> type) {
this.type = type;
}
// ....
}
``` | There is the way how to figure out `class` of type argument `T` using reflection:
```
private Class<T> persistentClass = (Class<T>)
((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
```
Here is the way how I use it:
```
public class GenericDaoJPA<T> implements GenericDao<T> {
@PersistenceContext
protected EntityManager entityManager;
protected Class<T> persistentClass = figureOutPersistentClass();
private Class<T> figureOutPersistentClass() {
Class<T> clazz = (Class<T>)((ParameterizedType) (getClass().getGenericSuperclass())).getActualTypeArguments()[0];
log.debug("persistentClass set to {}", clazz.getName());
return clazz;
}
public List<T> findAll() {
Query q = entityManager.createQuery("SELECT e FROM " + persistentClass.getSimpleName() + " e");
return (List<T>) q.getResultList();
}
}
```
I suppose this only works when your `ConcreteEntityDao` is a direct superclass of `HibernateDao<ConcreteEntity,...>`.
I've found it here: www.greggbolinger.com/blog/2008/04/17/1208457000000.html |
58,576,631 | I want to learn to create a wrapper around a program in linux. How does one do this? A tutorial reference web-page/link or example will do. To clarify what I want to learn, I will explain with an example.
I use **vim** for editing text files. And use **rcs** as my simple revision control system. **rcs** allows you to check-in and checkout-files. I would like to create a warpper program named **vir** which when I type in the shell as:
```
$ vir temp.txt
```
will load the file temp.txt into rcs with `ci -u temp.txt` and then allows me to edit the file using vim.
When I get out and go back in, It will need to check out the file first, using `ci -u temp.txt` and allow me to edit the file as one normally does with vim, and then when I save and exit, it should check-in the file using `co -u temp.txt` and as part of that I should be able to add a version control comment.
Basically, all I want to be doing on the command line is:
```
$ vir temp.txt
```
as one would with vim. And the wrapper should take care of the version control for me. | 2019/10/27 | [
"https://Stackoverflow.com/questions/58576631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4567351/"
] | There are a few missing dependencies in your `create-react-app` project. This probably happened because you tried to export the project from codesandbox (I'm not sure though)
You have to fix those first.
**Dependency 1** (`react-scripts`):
```
npm install react-scripts --save-dev
```
**Dependency 2** (`node-sass` because you are using `scss` in your project)
```
npm install node-sass --save
```
**Dependency 3** (`gh-pages`)
```
npm install gh-pages --save-dev
```
After the above steps are completed, verify your package.json to match below structure
```
{
"name": "and-air",
"version": "1.0.0",
"description": "",
"keywords": [],
"main": "src/index.js",
"homepage": "https://develijahlee.github.io/andair/",
"dependencies": {
"@fortawesome/fontawesome-svg-core": "1.2.25",
"@fortawesome/free-regular-svg-icons": "5.11.2",
"@fortawesome/react-fontawesome": "0.1.5",
"node-sass": "^4.13.0",
"react": "16.9.0",
"react-dom": "16.8.6"
},
"devDependencies": {
"gh-pages": "^2.1.1",
"react-scripts": "^3.2.0",
"typescript": "3.3.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
```
Now you can run the **deploy** script
```
npm run deploy
```
After this step, verify that a new branch created with name `gh-pages`
[](https://i.stack.imgur.com/zDaAL.png)
Click on the **settings** tab in github
[](https://i.stack.imgur.com/URU21.png)
Scroll down to the **GitHub Pages** section and switch your branch to `gh-pages` branch.
[](https://i.stack.imgur.com/07Mj4.png)
You should get a success message when the page is live.
[](https://i.stack.imgur.com/PQ4Ls.png) | Here is what deploy script in your code:
```
"deploy": "gh-pages -d build"
```
Which is means gh-pages tool use build directory to make it deploy, so you need two things in order to make it work
* Create a build folder properly with the following command:
```
npm run build
```
* now install gh-pages tool for your add locally:
```
npm i gh-pages
```
Now you can run deploy command, and it'll work.
I hope this can be helpful to you. |
63,452,974 | I am trying to install Pylucene on my WSL Ubuntu 20.04 clean installation. I tried to follow tutorial on [the official page but it looks outdated](https://lucene.apache.org/pylucene/install.html). So I was wondering if anyone here managed to make it work on Ubuntu 20.04 and python 3.8.2
The commands I run:
```
sudo apt-get upgrade
sudo apt-get install -y default-jdk ant build-essential python3-dev
mkdir pylucene
cd pylucene
curl https://downloads.apache.org/lucene/pylucene/pylucene-8.3.0-src.tar.gz | tar -xz --strip-components=1
cd jcc
export JCC_JDK=/usr/lib/jvm/default-java
python3 setup.py build
```
^^^^^
Fails here on:
```
...
building 'jcc3' extension
x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -D_jcc_lib -DJCC_VER="3.7" -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux -I_jcc3 -Ijcc3/sources -I/usr/include/python3.8 -c jcc3/sources/jcc.cpp -o build/temp.linux-x86_64-3.8/jcc3/sources/jcc.o -DPYTHON -fno-strict-aliasing -Wno-write-strings
x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -D_jcc_lib -DJCC_VER="3.7" -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux -I_jcc3 -Ijcc3/sources -I/usr/include/python3.8 -c jcc3/sources/JCCEnv.cpp -o build/temp.linux-x86_64-3.8/jcc3/sources/JCCEnv.o -DPYTHON -fno-strict-aliasing -Wno-write-strings
x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fwrapv -O2 -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.8/jcc3/sources/jcc.o build/temp.linux-x86_64-3.8/jcc3/sources/JCCEnv.o -o build/lib.linux-x86_64-3.8/libjcc3.so -L/usr/lib/jvm/default-java/jre/lib/amd64 -ljava -L/usr/lib/jvm/default-java/jre/lib/amd64/server -ljvm -Wl,-rpath=/usr/lib/jvm/default-java/jre/lib/amd64:/usr/lib/jvm/default-java/jre/lib/amd64/server -Wl,-S
/usr/bin/ld: cannot find -ljava
/usr/bin/ld: cannot find -ljvm
collect2: error: ld returned 1 exit status
error: command 'x86_64-linux-gnu-g++' failed with exit status 1
```
Commands I plan to run afterwards:
```
sudo python3 --preserve-env=JCC_JDK setup.py install
cd ..
make
make test
sudo make install
``` | 2020/08/17 | [
"https://Stackoverflow.com/questions/63452974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5594539/"
] | Here are the steps that lead to the successful installation of pylucene on Ubuntu 18.04 - this may work for you:
1. Install openjdk-8:
`apt install openjdk-8-jre openjdk-8-jdk openjdk-8-doc`
Ensure that you have ant installed, if you don't run `apt install ant`. Note that if you had a different version of openjdk installed you need to either remove it or run `update-alternatives` so that version 1.8.0 is used.
2. Check that Java version is 1.8.0\* with `java -version`
3. After installing openjdk-8 create a symlink (you'll need it later):
```
cd /usr/lib/jvm
ln -s java-8-openjdk-amd64 java-8-oracle
```
4. Install python-dev: `sudo apt install python-dev`
In my case Python 3 didn't work so I ended up using Python 2. But this might not have been the actual reason of the problem, so you're welcome to try Python 3. If you go with Python 3, use `python3` instead of `python` in the commands below.
5. Install JCC (in jcc subfolder of your pylucene folder):
```
python setup.py build
python setup.py install
```
The symlink you created on step 3 will help here because this path is hardcoded into setup.py - you can check that.
6. Install pylucene (from the root of your pylucene folder).
Edit Makefile, uncomment/edit the variables according to your setup.
In my case it was
```
PREFIX_PYTHON=/usr
ANT=ant
PYTHON=$(PREFIX_PYTHON)/bin/python
JCC=$(PYTHON) -m jcc --shared
NUM_FILES=10
```
Then run
```
make
make test
sudo make install
```
7. If you see an error related to the shared mode of JCC remove `--shared` from Makefile. | Confirmed that the answer posted by @code-your-dream works also with Python3 (and in particular in a Ubuntu 18.04.1)
For me was important to install jcc that way. I tried installing via conda and there were conflicts in the make of pylucene.
In my case also was needed to modify the setup.py file from jcc changing
'linux': ['-fno-strict-aliasing', '-Wno-write-strings'],
by
'linux': ['-fno-strict-aliasing', '-Wno-write-strings','-D\_\_STDC\_FORMAT\_MACROS'],
as mentioned in this other thread [Issue with installing PyLucene 6.5.0 on Linux](https://stackoverflow.com/questions/46895399/issue-with-installing-pylucene-6-5-0-on-linux)
To confirm which is the version of java needed (in my case also 8, didn't work with 11), you can search in the pylucene folder /jcc/setup.py the block JDK = {...}. In my case with the reference:
'linux': '/usr/lib/jvm/java-8-oracle', |
63,452,974 | I am trying to install Pylucene on my WSL Ubuntu 20.04 clean installation. I tried to follow tutorial on [the official page but it looks outdated](https://lucene.apache.org/pylucene/install.html). So I was wondering if anyone here managed to make it work on Ubuntu 20.04 and python 3.8.2
The commands I run:
```
sudo apt-get upgrade
sudo apt-get install -y default-jdk ant build-essential python3-dev
mkdir pylucene
cd pylucene
curl https://downloads.apache.org/lucene/pylucene/pylucene-8.3.0-src.tar.gz | tar -xz --strip-components=1
cd jcc
export JCC_JDK=/usr/lib/jvm/default-java
python3 setup.py build
```
^^^^^
Fails here on:
```
...
building 'jcc3' extension
x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -D_jcc_lib -DJCC_VER="3.7" -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux -I_jcc3 -Ijcc3/sources -I/usr/include/python3.8 -c jcc3/sources/jcc.cpp -o build/temp.linux-x86_64-3.8/jcc3/sources/jcc.o -DPYTHON -fno-strict-aliasing -Wno-write-strings
x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -D_jcc_lib -DJCC_VER="3.7" -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux -I_jcc3 -Ijcc3/sources -I/usr/include/python3.8 -c jcc3/sources/JCCEnv.cpp -o build/temp.linux-x86_64-3.8/jcc3/sources/JCCEnv.o -DPYTHON -fno-strict-aliasing -Wno-write-strings
x86_64-linux-gnu-g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fwrapv -O2 -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.8/jcc3/sources/jcc.o build/temp.linux-x86_64-3.8/jcc3/sources/JCCEnv.o -o build/lib.linux-x86_64-3.8/libjcc3.so -L/usr/lib/jvm/default-java/jre/lib/amd64 -ljava -L/usr/lib/jvm/default-java/jre/lib/amd64/server -ljvm -Wl,-rpath=/usr/lib/jvm/default-java/jre/lib/amd64:/usr/lib/jvm/default-java/jre/lib/amd64/server -Wl,-S
/usr/bin/ld: cannot find -ljava
/usr/bin/ld: cannot find -ljvm
collect2: error: ld returned 1 exit status
error: command 'x86_64-linux-gnu-g++' failed with exit status 1
```
Commands I plan to run afterwards:
```
sudo python3 --preserve-env=JCC_JDK setup.py install
cd ..
make
make test
sudo make install
``` | 2020/08/17 | [
"https://Stackoverflow.com/questions/63452974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5594539/"
] | Here are the steps that lead to the successful installation of pylucene on Ubuntu 18.04 - this may work for you:
1. Install openjdk-8:
`apt install openjdk-8-jre openjdk-8-jdk openjdk-8-doc`
Ensure that you have ant installed, if you don't run `apt install ant`. Note that if you had a different version of openjdk installed you need to either remove it or run `update-alternatives` so that version 1.8.0 is used.
2. Check that Java version is 1.8.0\* with `java -version`
3. After installing openjdk-8 create a symlink (you'll need it later):
```
cd /usr/lib/jvm
ln -s java-8-openjdk-amd64 java-8-oracle
```
4. Install python-dev: `sudo apt install python-dev`
In my case Python 3 didn't work so I ended up using Python 2. But this might not have been the actual reason of the problem, so you're welcome to try Python 3. If you go with Python 3, use `python3` instead of `python` in the commands below.
5. Install JCC (in jcc subfolder of your pylucene folder):
```
python setup.py build
python setup.py install
```
The symlink you created on step 3 will help here because this path is hardcoded into setup.py - you can check that.
6. Install pylucene (from the root of your pylucene folder).
Edit Makefile, uncomment/edit the variables according to your setup.
In my case it was
```
PREFIX_PYTHON=/usr
ANT=ant
PYTHON=$(PREFIX_PYTHON)/bin/python
JCC=$(PYTHON) -m jcc --shared
NUM_FILES=10
```
Then run
```
make
make test
sudo make install
```
7. If you see an error related to the shared mode of JCC remove `--shared` from Makefile. | I wrote this dockerfile for PyLucene 8.11.0, Python 3.9, JDK11 (default-jdk) and ubuntu 20.04 (focal). Do extend with your favorite python package manager such as Poetry, Pipenv or Conda etc.
**Dockerfile**
```
FROM ubuntu:focal
ARG PYTHON_VERSION=3.9
ARG PYLUCENE_VERSION=8.11.0
# Uncomment to install specific version of poetry
ENV LANG=C.UTF-8
# ADD Python PPA Repository
RUN apt-get update && \
apt-get upgrade -y && \
apt-get install -y --no-install-recommends \
software-properties-common gpg-agent && \
add-apt-repository ppa:deadsnakes/ppa && \
apt-get update && \
apt-get remove -y software-properties-common && \
apt-get purge --auto-remove -y && \
apt-get clean
RUN which gpg-agent
# Install Python
RUN apt-get install -y --no-install-recommends \
"python$PYTHON_VERSION-dev" \
python3-setuptools \
python3-pip && \
apt-get remove -y gpg-agent && \
apt-get purge --auto-remove -y && \
apt-get clean
# ======================== START OF ADDITIONAL INSTALLATION ========================
# Install Java
RUN apt-get install -y --no-install-recommends \
build-essential \
ant \
jcc \
curl \
git \
default-jdk
RUN ls /usr/bin/ | grep "python"
RUN ln -s $(which python3.9) /usr/bin/python
RUN which python3.9 && which python && python --version
WORKDIR /usr/lib/jvm/default-java/jre/lib
RUN ln -s ../../lib amd64
# Java 11
RUN java --version && javac --version
# Installing PyLucene
RUN which ant && ant -version
RUN apt-get install -y --no-install-recommends \
libffi-dev \
zlib1g-dev
WORKDIR /usr/src/pylucene
RUN curl https://dlcdn.apache.org/lucene/pylucene/pylucene-$PYLUCENE_VERSION-src.tar.gz | tar -xz
ENV PREFIX_PYTHON=/usr \
JCC_JDK=/usr/lib/jvm/default-java \
ANT=ant \
JCC='python -m jcc' \
NUM_FILES=10 \
PYTHON=python \
NO_SHARED=1
RUN cd "pylucene-$PYLUCENE_VERSION/lucene-java-$PYLUCENE_VERSION/lucene" && \
ant ivy-bootstrap && \
ant && \
cd ../../../
RUN cd "pylucene-$PYLUCENE_VERSION/jcc" && \
ls -la && \
NO_SHARED=1 JCC_JDK=/usr/lib/jvm/default-java python setup.py build && \
NO_SHARED=1 JCC_JDK=/usr/lib/jvm/default-java python setup.py install && \
cd .. && \
make JCC="python -m jcc" ANT=ant PYTHON=python NUM_FILES=8&& \
make install JCC="python -m jcc" ANT=ant PYTHON=python NUM_FILES=8 && \
cd ../../
RUN apt-get remove -y gpg-agent ant jcc build-essential && \
apt-get purge --auto-remove -y && \
apt-get clean
WORKDIR /usr/src
RUN rm -rf pylucene
RUN python -c "import lucene; lucene.initVM()"
# ======================== END OF ADDITIONAL INSTALLATION ========================
WORKDIR /app
COPY . .
``` |
61,559,348 | I am integrating JWT authorization from Cognito into my Nestjs application and I am running into a sort of a chicken vs egg situation.
If a generate clientSecret for my Cognito client, I will get the following error:
>
> "Unable to verify secret hash for client {Client\_Id}"
>
>
>
If I uncheck clientScret generation when creating a new client in Cognito, I will get the following error when the application compiles:
>
> [ExceptionHandler] JwtStrategy requires a secret or key +0ms
>
>
>
I have been following this guide to implement it: <https://brightinventions.pl/blog/using-cognito-with-nest-js/>, but it does not really address any of these issues.
Could someone provide some guidance here? | 2020/05/02 | [
"https://Stackoverflow.com/questions/61559348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10603880/"
] | The tutorial you shared let the back-end side handle the user register, sign in, and sign out. I want to delegate the access token getting to AWS Cognito.
For a user to request protected resources, the backend side validates the access token passed as a bearer token in two ways:
* Use middleware: <https://github.com/katesroad/Cognito-as-Authentication-Provider-for-NestJs/blob/main/backend/src/common/middlewares/auth.middleware.ts>
Also, this link worth reading <https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html>.
How to validate the jwt token generated by an AWS Cognito pool.
If you don't want to access other user information, having the user being validate is enough by validating the user's access token.
If you want to get the user's other information (such as email and custom attributes), you can use the version shared by you or getting user information by the user's sub id stored in the JWT token.
Thanks, happy coding. Hope this could help you. | ```
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { passportJwtSecret } from 'jwks-rsa';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
secretOrKeyProvider: passportJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json
}),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
audience: 'client id',
issuer: https://cognito-idp.<region>.amazonaws.com/<userpoolID>.
algorithms: ['RS256'],
});
}
async validate(payload: any) {
console.debug('JWT VALIDATION')
return !!payload.sub;
}
}
``` |
24,491,420 | Is there any difference between these 2 quesries? This is from test and one asnwer is right and accordingly another wrong. For me, both are valid and similar.
```
B. SELECT Cust_No, Cust_Name, Emp_Name, Emp_Loc FROM
Customers, Employees WHERE Customers.Sales_Rep_No =
Employees.Sales_Rep_No;
C. SELECT Cust_No, Cust_Name, Emp_Name, Emp_Loc FROM
Customers, Employees WHERE Employees.Sales_Rep_No =
Customers.Sales_Rep_No;
``` | 2014/06/30 | [
"https://Stackoverflow.com/questions/24491420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2705336/"
] | Yes, they differ in their `WHERE`-clauses, but everything else (the Tables joined, the columns retrieved, is the same, and they also should really produce the same result):
`WHERE Customers.Sales_Rep_No = Employees.Sales_Rep_No;`
`WHERE Employees.Sales_Rep_No = Customers.Sales_Rep_No;` | There is no functional difference whatsoever. |
18,753 | My attendant and I met a year ago and had intercourse back then, we recently picked back up where we left off, but want to go about it the right way and get married.
Is there a time frame that we have to be apart from each other sexually and not sexual before marriage?
What is needed to be done for our marriage to be halal? | 2014/11/25 | [
"https://islam.stackexchange.com/questions/18753",
"https://islam.stackexchange.com",
"https://islam.stackexchange.com/users/9208/"
] | There's no time frame, but both of you must repent to Allah(SWT) and never commit that sin again.
You and your potential cannot be alone together privately anywhere and at anytime.
You must restrain your looks at each other.
You must have a **Wali** involved to go about your business with him.
You must be covered properly i.e. hijab, and he must have himself covered properly also.
There can't be any intimate conversations between the two of you.
Until you're married, you can't really have much physical contact. | If i understood what you said i think you write this advice to the person who will get married
Yes that's right but i just add to your spaech or i can say in the other word ...... tray to don't do the sins than allah will help you ...
And even you didn't have contact physical before get married , you will found the happiness in your life because whoever fears Allah - He will make for him of his matter ease.
my greetings ... your sister maryam |
102,339 | I want to buy the full version of Minecraft, but I'm one of those creative types. What are some of the differences in Creative mode in the full version of Minecraft? | 2013/01/22 | [
"https://gaming.stackexchange.com/questions/102339",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/41294/"
] | From [the wiki](http://www.minecraftwiki.net/wiki/Classic#Advantages_of_purchasing) about the classic version:
>
> Advantages of purchasing
>
>
> Although this mode is free to the public, there are several advantages
> made available to those who have purchased the game. Some of them are
> the ability to:
>
> - Use custom skins in both singleplayer and multiplayer.
>
> - Use mods that require placement of files in the original minecraft.jar folder.
>
> - **Build with more blocks and items.**
>
> - Use crafting and create items.
>
> - Combat mobs.
>
>
>
From a purely creative point of view, you will get more space, and more blocks to choose from, in the full version.
Keep in mind also that Minecraft classic is a prototype which has not been updated since 2009. From a technical point of view, the new version (full) will perform better, and look better (new lighting system). | You can play the free version, so I won't waste too many words about it. You have a small sandbox and a few kinds of blocks you can mess around and build with. You can explore the randomly generated world for caves, pockets of air, etc.; you can grief with water sources... It's the core of Minecraft.
The paid version features a world many times as large, with blocks that do actually something rather than just sitting there (with the exception of the sponge, the only "useful" block in the "free" version of Minecraft and is completely useless in the paid version\*).
There's also adventure mode, which lets people play through your map without their ability to modify it in ways that break it.
\*As of version 1.8, sponges soak up water in a 5x5 radius, similar to Miencraft Classic |
102,339 | I want to buy the full version of Minecraft, but I'm one of those creative types. What are some of the differences in Creative mode in the full version of Minecraft? | 2013/01/22 | [
"https://gaming.stackexchange.com/questions/102339",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/41294/"
] | You can play the free version, so I won't waste too many words about it. You have a small sandbox and a few kinds of blocks you can mess around and build with. You can explore the randomly generated world for caves, pockets of air, etc.; you can grief with water sources... It's the core of Minecraft.
The paid version features a world many times as large, with blocks that do actually something rather than just sitting there (with the exception of the sponge, the only "useful" block in the "free" version of Minecraft and is completely useless in the paid version\*).
There's also adventure mode, which lets people play through your map without their ability to modify it in ways that break it.
\*As of version 1.8, sponges soak up water in a 5x5 radius, similar to Miencraft Classic | There is only about a dozen blocks in Classic, and they don't really do much. The full version of Minecraft not only includes nearly 150 blocks, but also has Redstone (an extremely flexible system you can use to make machines in Minecraft), custom avatars, infinite worlds, enhanced multiplayer, and the awesome survival mode. You can give it a try using the [demo mode](http://minecraft.net/demo), which lets you try a survival map for five in-game days. |
102,339 | I want to buy the full version of Minecraft, but I'm one of those creative types. What are some of the differences in Creative mode in the full version of Minecraft? | 2013/01/22 | [
"https://gaming.stackexchange.com/questions/102339",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/41294/"
] | From [the wiki](http://www.minecraftwiki.net/wiki/Classic#Advantages_of_purchasing) about the classic version:
>
> Advantages of purchasing
>
>
> Although this mode is free to the public, there are several advantages
> made available to those who have purchased the game. Some of them are
> the ability to:
>
> - Use custom skins in both singleplayer and multiplayer.
>
> - Use mods that require placement of files in the original minecraft.jar folder.
>
> - **Build with more blocks and items.**
>
> - Use crafting and create items.
>
> - Combat mobs.
>
>
>
From a purely creative point of view, you will get more space, and more blocks to choose from, in the full version.
Keep in mind also that Minecraft classic is a prototype which has not been updated since 2009. From a technical point of view, the new version (full) will perform better, and look better (new lighting system). | There is only about a dozen blocks in Classic, and they don't really do much. The full version of Minecraft not only includes nearly 150 blocks, but also has Redstone (an extremely flexible system you can use to make machines in Minecraft), custom avatars, infinite worlds, enhanced multiplayer, and the awesome survival mode. You can give it a try using the [demo mode](http://minecraft.net/demo), which lets you try a survival map for five in-game days. |
9,119,233 | How can I initialize a val that is to be used in another scope? In the example below, I am forced to make `myOptimizedList` as a var, since it is initialized in the `if (iteration == 5){}` scope and used in the `if (iteration > 5){}` scope.
```
val myList:A = List(...)
var myOptimizedList:A = null
for (iteration <- 1 to 100) {
if (iteration < 5) {
process(myList)
} else if (iteration == 5)
myOptimizedList = optimize(myList)
}
if (iteration > 5) {
process(myOptimizedList)
}
}
```
This may have been asked [before](https://stackoverflow.com/questions/7425854/scala-create-val-for-outer-scope), but I wonder if there is an elegant solution that uses Option[A]. | 2012/02/02 | [
"https://Stackoverflow.com/questions/9119233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750995/"
] | Seems that you have taken this code example out of the context, so this solution can be not very suitable for your real context, but you can use `foldLeft` in order to simplify it:
```
val myOptimizedList = (1 to 100).foldLeft (myList) {
case (list, 5) => optimize(list)
case (list, _) => process(list); list
}
``` | It's often the case that you can rework your code to avoid the problem. Consider the simple, and common, example here:
```
var x = 0
if(something)
x = 5
else
x = 6
println(x)
```
This would be a pretty common pattern in most languages, but Scala has a better way of doing it. Specifically, if-statements can return values, so the better way is:
```
val x =
if(something)
5
else
6
println(x)
```
So we can make `x` a val after all.
Now, clearly your code can be rewritten to use all `val`s:
```
val myList:A = List(...)
for (iteration <- 1 to 5)
process(myList)
val myOptimizedList = optimize(myList)
for (iteration <- 5 to 100)
process(myOptimizedList)
```
But I suspect this is simply an example, not your real case. But if you're unsure how you might rearrange your real code to accomplish something similar, please show us what it looks like. |
9,119,233 | How can I initialize a val that is to be used in another scope? In the example below, I am forced to make `myOptimizedList` as a var, since it is initialized in the `if (iteration == 5){}` scope and used in the `if (iteration > 5){}` scope.
```
val myList:A = List(...)
var myOptimizedList:A = null
for (iteration <- 1 to 100) {
if (iteration < 5) {
process(myList)
} else if (iteration == 5)
myOptimizedList = optimize(myList)
}
if (iteration > 5) {
process(myOptimizedList)
}
}
```
This may have been asked [before](https://stackoverflow.com/questions/7425854/scala-create-val-for-outer-scope), but I wonder if there is an elegant solution that uses Option[A]. | 2012/02/02 | [
"https://Stackoverflow.com/questions/9119233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750995/"
] | Seems that you have taken this code example out of the context, so this solution can be not very suitable for your real context, but you can use `foldLeft` in order to simplify it:
```
val myOptimizedList = (1 to 100).foldLeft (myList) {
case (list, 5) => optimize(list)
case (list, _) => process(list); list
}
``` | You can almost always rewrite some sort of looping construct as a (tail) recursive function:
```
@annotation.tailrec def processLists(xs: List[A], start: Int, stop: Int) {
val next = start + 1
if (start < 5) { process(xs); processLists(xs, next, stop)
else if (start == 5) { processLists( optimize(xs), next, stop) }
else if (start <= stop) { process(xs); processLists( xs, next, stop ) }
}
processLists(myList, 100, 1)
```
Here, you pass forward that data which you would otherwise have mutated. If you need to mutate a huge number of things it becomes unwieldy, but for one or two it is often as clear or clearer than doing the mutation. |
9,119,233 | How can I initialize a val that is to be used in another scope? In the example below, I am forced to make `myOptimizedList` as a var, since it is initialized in the `if (iteration == 5){}` scope and used in the `if (iteration > 5){}` scope.
```
val myList:A = List(...)
var myOptimizedList:A = null
for (iteration <- 1 to 100) {
if (iteration < 5) {
process(myList)
} else if (iteration == 5)
myOptimizedList = optimize(myList)
}
if (iteration > 5) {
process(myOptimizedList)
}
}
```
This may have been asked [before](https://stackoverflow.com/questions/7425854/scala-create-val-for-outer-scope), but I wonder if there is an elegant solution that uses Option[A]. | 2012/02/02 | [
"https://Stackoverflow.com/questions/9119233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750995/"
] | Seems that you have taken this code example out of the context, so this solution can be not very suitable for your real context, but you can use `foldLeft` in order to simplify it:
```
val myOptimizedList = (1 to 100).foldLeft (myList) {
case (list, 5) => optimize(list)
case (list, _) => process(list); list
}
``` | There's another technique (perhaps trick in this case) to delay initialization of
`myOptimizedList` which is to use a lazy val. Your example is very specific but the principal is still obvious, delay assignment of a val until it is first referenced.
```
val myList = List(A(), A(), A())
lazy val myOptimizedList = optimize(myList)
for (iteration <- 1 to 100) {
if (iteration < 5)
process(myList)
else if (iteration > 5)
process(myOptimizedList)
}
```
Note that the case `iteration == 5` is ignored. |
1,320,991 | My textbook says: Suppose that $E$ is a convex region in the plane bounded by a curve $C$. [Where a convex region is defined as for all $x, y \in E, sx + ty \in E$ where $0 \le s, t \le 1$ and $s + t = 1$.] Show that $C$ has a tangent line except at a countable number of points.
So my thinking is roughly that points without tangent lines look like sharp corners with some angle $\theta < 180^\circ$ and so if $\theta\_m$ is the largest $\theta$ in $C$ then the most corners you can pack into $C$ is the regular $n$-gon with $n=\frac{2}{180-\theta\_m}$. Except that seems to suggest that $C$ must have a tangent line except at finitely many points whereas the question clearly asks about countably many. So what's the pathological convex curve with infinitely many discontinuities that thwarts my proof? | 2015/06/11 | [
"https://math.stackexchange.com/questions/1320991",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/204420/"
] | Line segments from $(n,n^2)$ to $((n+1),(n+1)^2)$ for each integer $n$ you should draw. A nice and simple convex region you will get. | Here's a compact example. Start with a circle of radius $1$. Cut off a minor segment with a chord of length $1$, and close the resulting major segment. From this major segment, cut off a minor segment with an adjacent chord of length $\frac12$, and close the rest. Continue this process, cutting off minor segments with adjacent chords successively of length $\frac14,\frac18,...,1/2^n,...$. The resulting figure is convex with no defined tangent at the infinitely many corners between the successive chords. |
70,811,590 | Let's say we have the following table:
```
city gender
abc m
abc f
def m
```
Required output:
---
```
city f_count m_count
abc 1 1
def 0 1
```
Please help me in writing a query either in Hive or MySQL or SQL Server syntax. Hive syntax is needed for me.
Thank You:) | 2022/01/22 | [
"https://Stackoverflow.com/questions/70811590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13345717/"
] | Try:
```
select city,sum(gender='f') as f_count,sum(gender='m') as m_count
from my_table
group by city;
```
>
> Result:
>
>
>
> ```
> city f_count m_count
> abc 1 1
> def 0 1
>
> ```
>
>
[Demo](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e9e64e17c116766877f1ba802492fac3) | ```
select city, sum(male),sum(female) from
(select city ,count(gender) as male,0 as female from temp where gender='M' group by city
union
select city , 0,count(gender) as female from temp where gender='F'group by city)
group by city;
``` |
70,811,590 | Let's say we have the following table:
```
city gender
abc m
abc f
def m
```
Required output:
---
```
city f_count m_count
abc 1 1
def 0 1
```
Please help me in writing a query either in Hive or MySQL or SQL Server syntax. Hive syntax is needed for me.
Thank You:) | 2022/01/22 | [
"https://Stackoverflow.com/questions/70811590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13345717/"
] | SQL Server:
```
select
city
,count(case when gender = 'm' then 1 else null end) as m_count
,count(case when gender <> 'm' then 1 else null end) as f_count
from table_name
group by city
```
>
> Result:
>
>
>
> ```
> city | f_count | m_count
> abc | 1 | 1
> def | 0 | 1
>
> ```
>
> | ```
select city, sum(male),sum(female) from
(select city ,count(gender) as male,0 as female from temp where gender='M' group by city
union
select city , 0,count(gender) as female from temp where gender='F'group by city)
group by city;
``` |
57,887,300 | My Github repo won't update after `git push -u origin master` command!
It says:
```
Branch 'master' set up to track remote branch 'master' from 'origin'. Everything up-to-date
```
The result for `git remote show origin` is:
```
* remote origin
Fetch URL: [email protected]:MyGithubID/RepoName.git
Push URL: [email protected]:MyGithubID/RepoName.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
```
and for `git status`:
```
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
I have no idea what is going on! I tried `git push --all origin` and it says: `Everything up-to-date` but it's not!
I'm new with git; I checked 'config' file in my .git directory and the information is correct. What is wrong with my git?! | 2019/09/11 | [
"https://Stackoverflow.com/questions/57887300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7522214/"
] | You have only staged the file for commit, but not actually committed the change. You have to commit the change to get a commit-id which is then used during the push/pull phase.
```
git commit
```
With `git`, committing a change is a two step process.
The first step is to add your change(s) to a so called staging area. This is local to the repo and will not participate when pushing a changes to the remote. In your case you have added a new file to the staging area and git push will not consider the changes in the staging area. Only changes that are committed are discussed during the push/pull process.
The second step is to commit the changes.. This step you don't get to choose what changes you can commit. All the changes that you have added in the staging area gets into the commit and git creates a commit-id which is now version controlled (in your local repo).. Once a commit is done, the staging area is clear.
some commands to add files to the staging are.
```
git add <file_name> #Add all changes made to this file.
git add <dir> #Add all changed files in that directory.
git add -i # This is interactive menu-type command
```
Instead of adding all the changes(called as hunks) made to a file, You can also choose to add selected changes in a file, using the patch option.
```
git add -i #choose patch option.
```
The changes in staging area is the delta from `HEAD`. To remove the changes from the staging area you have to reset the HEAD file as it was in HEAD. Once you reset, all changes are gone from the staging area but not lost, you will see the hunks in the un-staged area.
```
git reset HEAD <file>
``` | ```
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
That implies that you have to commit your changes. So, you've done well, you're almost there you just have to do a:
```
git commit -m "Here a short descriptive message" -m "Here a longer more detailed message"
```
and then you can do your push:
```
git push origin master
``` |
57,887,300 | My Github repo won't update after `git push -u origin master` command!
It says:
```
Branch 'master' set up to track remote branch 'master' from 'origin'. Everything up-to-date
```
The result for `git remote show origin` is:
```
* remote origin
Fetch URL: [email protected]:MyGithubID/RepoName.git
Push URL: [email protected]:MyGithubID/RepoName.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
```
and for `git status`:
```
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
I have no idea what is going on! I tried `git push --all origin` and it says: `Everything up-to-date` but it's not!
I'm new with git; I checked 'config' file in my .git directory and the information is correct. What is wrong with my git?! | 2019/09/11 | [
"https://Stackoverflow.com/questions/57887300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7522214/"
] | ```
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
That implies that you have to commit your changes. So, you've done well, you're almost there you just have to do a:
```
git commit -m "Here a short descriptive message" -m "Here a longer more detailed message"
```
and then you can do your push:
```
git push origin master
``` | if you are adding new project try below steps :
```
rm -rf .git/
git init
git remote add origin https://repository.remote.url
git add .
git commit -m “Commit message here”.
git push -f origin master
``` |
57,887,300 | My Github repo won't update after `git push -u origin master` command!
It says:
```
Branch 'master' set up to track remote branch 'master' from 'origin'. Everything up-to-date
```
The result for `git remote show origin` is:
```
* remote origin
Fetch URL: [email protected]:MyGithubID/RepoName.git
Push URL: [email protected]:MyGithubID/RepoName.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
```
and for `git status`:
```
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
I have no idea what is going on! I tried `git push --all origin` and it says: `Everything up-to-date` but it's not!
I'm new with git; I checked 'config' file in my .git directory and the information is correct. What is wrong with my git?! | 2019/09/11 | [
"https://Stackoverflow.com/questions/57887300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7522214/"
] | ```
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
That implies that you have to commit your changes. So, you've done well, you're almost there you just have to do a:
```
git commit -m "Here a short descriptive message" -m "Here a longer more detailed message"
```
and then you can do your push:
```
git push origin master
``` | You can also get a situation where you've pushed remotely, and if you do `git log` it'll show *(HEAD -> master)* next to your latest commit, but *origin/master* is seemingly out of date (showing several commit messages down).
To resolve this I verified the state of the repository I'd pushed to at the other end, then ran `git pull origin master` locally. |
57,887,300 | My Github repo won't update after `git push -u origin master` command!
It says:
```
Branch 'master' set up to track remote branch 'master' from 'origin'. Everything up-to-date
```
The result for `git remote show origin` is:
```
* remote origin
Fetch URL: [email protected]:MyGithubID/RepoName.git
Push URL: [email protected]:MyGithubID/RepoName.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
```
and for `git status`:
```
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
I have no idea what is going on! I tried `git push --all origin` and it says: `Everything up-to-date` but it's not!
I'm new with git; I checked 'config' file in my .git directory and the information is correct. What is wrong with my git?! | 2019/09/11 | [
"https://Stackoverflow.com/questions/57887300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7522214/"
] | You have only staged the file for commit, but not actually committed the change. You have to commit the change to get a commit-id which is then used during the push/pull phase.
```
git commit
```
With `git`, committing a change is a two step process.
The first step is to add your change(s) to a so called staging area. This is local to the repo and will not participate when pushing a changes to the remote. In your case you have added a new file to the staging area and git push will not consider the changes in the staging area. Only changes that are committed are discussed during the push/pull process.
The second step is to commit the changes.. This step you don't get to choose what changes you can commit. All the changes that you have added in the staging area gets into the commit and git creates a commit-id which is now version controlled (in your local repo).. Once a commit is done, the staging area is clear.
some commands to add files to the staging are.
```
git add <file_name> #Add all changes made to this file.
git add <dir> #Add all changed files in that directory.
git add -i # This is interactive menu-type command
```
Instead of adding all the changes(called as hunks) made to a file, You can also choose to add selected changes in a file, using the patch option.
```
git add -i #choose patch option.
```
The changes in staging area is the delta from `HEAD`. To remove the changes from the staging area you have to reset the HEAD file as it was in HEAD. Once you reset, all changes are gone from the staging area but not lost, you will see the hunks in the un-staged area.
```
git reset HEAD <file>
``` | Follow the official documentation:-
<https://git-scm.com/docs/gittutorial>
Before push you will have to first add all the resources where the changes you have done.
```
git add . or git add --all
```
Then commit it using
```
git commit -m "your message".
```
and push code using
```
git push origin master == replace master with your remote branch
name where you want to push.
``` |
57,887,300 | My Github repo won't update after `git push -u origin master` command!
It says:
```
Branch 'master' set up to track remote branch 'master' from 'origin'. Everything up-to-date
```
The result for `git remote show origin` is:
```
* remote origin
Fetch URL: [email protected]:MyGithubID/RepoName.git
Push URL: [email protected]:MyGithubID/RepoName.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
```
and for `git status`:
```
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
I have no idea what is going on! I tried `git push --all origin` and it says: `Everything up-to-date` but it's not!
I'm new with git; I checked 'config' file in my .git directory and the information is correct. What is wrong with my git?! | 2019/09/11 | [
"https://Stackoverflow.com/questions/57887300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7522214/"
] | Follow the official documentation:-
<https://git-scm.com/docs/gittutorial>
Before push you will have to first add all the resources where the changes you have done.
```
git add . or git add --all
```
Then commit it using
```
git commit -m "your message".
```
and push code using
```
git push origin master == replace master with your remote branch
name where you want to push.
``` | if you are adding new project try below steps :
```
rm -rf .git/
git init
git remote add origin https://repository.remote.url
git add .
git commit -m “Commit message here”.
git push -f origin master
``` |
57,887,300 | My Github repo won't update after `git push -u origin master` command!
It says:
```
Branch 'master' set up to track remote branch 'master' from 'origin'. Everything up-to-date
```
The result for `git remote show origin` is:
```
* remote origin
Fetch URL: [email protected]:MyGithubID/RepoName.git
Push URL: [email protected]:MyGithubID/RepoName.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
```
and for `git status`:
```
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
I have no idea what is going on! I tried `git push --all origin` and it says: `Everything up-to-date` but it's not!
I'm new with git; I checked 'config' file in my .git directory and the information is correct. What is wrong with my git?! | 2019/09/11 | [
"https://Stackoverflow.com/questions/57887300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7522214/"
] | Follow the official documentation:-
<https://git-scm.com/docs/gittutorial>
Before push you will have to first add all the resources where the changes you have done.
```
git add . or git add --all
```
Then commit it using
```
git commit -m "your message".
```
and push code using
```
git push origin master == replace master with your remote branch
name where you want to push.
``` | You can also get a situation where you've pushed remotely, and if you do `git log` it'll show *(HEAD -> master)* next to your latest commit, but *origin/master* is seemingly out of date (showing several commit messages down).
To resolve this I verified the state of the repository I'd pushed to at the other end, then ran `git pull origin master` locally. |
57,887,300 | My Github repo won't update after `git push -u origin master` command!
It says:
```
Branch 'master' set up to track remote branch 'master' from 'origin'. Everything up-to-date
```
The result for `git remote show origin` is:
```
* remote origin
Fetch URL: [email protected]:MyGithubID/RepoName.git
Push URL: [email protected]:MyGithubID/RepoName.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
```
and for `git status`:
```
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
I have no idea what is going on! I tried `git push --all origin` and it says: `Everything up-to-date` but it's not!
I'm new with git; I checked 'config' file in my .git directory and the information is correct. What is wrong with my git?! | 2019/09/11 | [
"https://Stackoverflow.com/questions/57887300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7522214/"
] | You have only staged the file for commit, but not actually committed the change. You have to commit the change to get a commit-id which is then used during the push/pull phase.
```
git commit
```
With `git`, committing a change is a two step process.
The first step is to add your change(s) to a so called staging area. This is local to the repo and will not participate when pushing a changes to the remote. In your case you have added a new file to the staging area and git push will not consider the changes in the staging area. Only changes that are committed are discussed during the push/pull process.
The second step is to commit the changes.. This step you don't get to choose what changes you can commit. All the changes that you have added in the staging area gets into the commit and git creates a commit-id which is now version controlled (in your local repo).. Once a commit is done, the staging area is clear.
some commands to add files to the staging are.
```
git add <file_name> #Add all changes made to this file.
git add <dir> #Add all changed files in that directory.
git add -i # This is interactive menu-type command
```
Instead of adding all the changes(called as hunks) made to a file, You can also choose to add selected changes in a file, using the patch option.
```
git add -i #choose patch option.
```
The changes in staging area is the delta from `HEAD`. To remove the changes from the staging area you have to reset the HEAD file as it was in HEAD. Once you reset, all changes are gone from the staging area but not lost, you will see the hunks in the un-staged area.
```
git reset HEAD <file>
``` | if you are adding new project try below steps :
```
rm -rf .git/
git init
git remote add origin https://repository.remote.url
git add .
git commit -m “Commit message here”.
git push -f origin master
``` |
57,887,300 | My Github repo won't update after `git push -u origin master` command!
It says:
```
Branch 'master' set up to track remote branch 'master' from 'origin'. Everything up-to-date
```
The result for `git remote show origin` is:
```
* remote origin
Fetch URL: [email protected]:MyGithubID/RepoName.git
Push URL: [email protected]:MyGithubID/RepoName.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
```
and for `git status`:
```
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: myFile.m
```
I have no idea what is going on! I tried `git push --all origin` and it says: `Everything up-to-date` but it's not!
I'm new with git; I checked 'config' file in my .git directory and the information is correct. What is wrong with my git?! | 2019/09/11 | [
"https://Stackoverflow.com/questions/57887300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7522214/"
] | You have only staged the file for commit, but not actually committed the change. You have to commit the change to get a commit-id which is then used during the push/pull phase.
```
git commit
```
With `git`, committing a change is a two step process.
The first step is to add your change(s) to a so called staging area. This is local to the repo and will not participate when pushing a changes to the remote. In your case you have added a new file to the staging area and git push will not consider the changes in the staging area. Only changes that are committed are discussed during the push/pull process.
The second step is to commit the changes.. This step you don't get to choose what changes you can commit. All the changes that you have added in the staging area gets into the commit and git creates a commit-id which is now version controlled (in your local repo).. Once a commit is done, the staging area is clear.
some commands to add files to the staging are.
```
git add <file_name> #Add all changes made to this file.
git add <dir> #Add all changed files in that directory.
git add -i # This is interactive menu-type command
```
Instead of adding all the changes(called as hunks) made to a file, You can also choose to add selected changes in a file, using the patch option.
```
git add -i #choose patch option.
```
The changes in staging area is the delta from `HEAD`. To remove the changes from the staging area you have to reset the HEAD file as it was in HEAD. Once you reset, all changes are gone from the staging area but not lost, you will see the hunks in the un-staged area.
```
git reset HEAD <file>
``` | You can also get a situation where you've pushed remotely, and if you do `git log` it'll show *(HEAD -> master)* next to your latest commit, but *origin/master* is seemingly out of date (showing several commit messages down).
To resolve this I verified the state of the repository I'd pushed to at the other end, then ran `git pull origin master` locally. |
37,711 | Comme l'on lit dans cette **excellente réponse**
[Quand peut-on mettre un adjectif avant ou après un nom ? — When do adjectives go before or after a noun?](https://french.stackexchange.com/questions/319/quand-peut-on-mettre-un-adjectif-avant-ou-apr%c3%a8s-un-nom-when-do-adjectives-go/323#323)
>
> La place de l'épithète par rapport au nom remplit plus d'une dizaine
> de pages du Grevisse (de §325 à §332 dans l'édition 2008).
>
>
>
Je me demande si des tournures comme **excellente réponse**, **excellente oeuvre** au lieu des plus traditionnelles **réponse excellente** et **oeuvre excellente** choqueraient les locuteurs natifs du français.
Par exemple
>
> Je vous félicite pour votre excellente oeuvre.
>
>
>
Ibid. pour l'adjectif **monumental**.
Par exemple.
>
> Le mécanicien et mathématicien Clifford Truesdell est l'auteur des monumentales oeuvres.
>
>
> | 2019/08/01 | [
"https://french.stackexchange.com/questions/37711",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/16020/"
] | Si on trouve ***excellent*** plutôt avant le nom ça tient au sens même de cet adjectif. L'adjectif exprimant un jugement, un réaction subjective, affective se place avant le nom. (Grevisse §398 10e édition, qui renvoie à l'article de Marouzeau « Encore la place de l'adjectif » dans *Le Français Moderne*, oct. 1953, [p. 241-243](https://fr.calameo.com/read/0009039473e627990eacf?authid=FcLgsii5nHaQ)) :
>
> C'est une excellente initiative.
>
>
>
On peut bien sûr trouver *excellent* après le nom.
>
> La belle matière, la maturité du Chenin a bien été saisie dans ce vin excellent qui a su jouer le jeu de la fraîcheur avec cette finale sapide et minérale. ([In Vino veritas](http://www.in-vino-veritas.fr/les-appellations-meconnues/))
>
>
>
Selon l'analyse de Mazureau à laquelle renvoie Grevisse, ici *excellent* exprime une valeur discriminative qui classe le vin en question dans une catégorie (celle des vins excellents).
Comme le dit @petitrien ***monumental*** se place quasi exclusivement après le nom parce que, comme le dit Grevisse (§398 10e édition), les adjectifs exprimant une qualité physique se placent après le nom.
Cependant la même analyse faite ci-dessus pour « excellent » peut s'appliquer aussi pour « monumental ».
>
> Ce monumental ouvrage d’art offre un spectacle incomparable sur les montagnes environnantes. ([Site de l'Office de tourisme de Grenoble-Alpes](https://www.grenoble-tourisme.com/de/katalog/activite/les-forts-de-la-bastille-et-du-saint-eynard-293867/))
>
>
>
Dans cet exemple il me semble que l'adjective placé avant reflète l'affectivité du locuteur qui cherche de surcroît à attirer l'attention des touristes.
Autre cas similaire :
>
> Ce monumental échafaudage érigé il y a huit mois sera démonté à partir du lundi 15 avril.[(*La Provence* 11/04/2019](https://www.laprovence.com/article/edition-vaucluse/5452721/le-mur-a-livre-certains-secrets.html))
>
>
> | *Excellent* est ambivalent, on le trouve avant ou après le nom. Lorsqu'il est associé à un nom et que les deux constituent à eux seuls une phrase autonome, je l'emploierais plutôt avant le nom :
* Excellente initiative!
* Excellente question!
* Excellente idée!
*Monumental* par contre s'emploie le plus souvent voire exclusivement après le nom :
* une architecture monumentale
* une œuvre monumentale
* une erreur/bourde monumentale |
69,299,965 | I don't know how to describe them, so here is a screenshot
[](https://i.stack.imgur.com/BZKHP.png) | 2021/09/23 | [
"https://Stackoverflow.com/questions/69299965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This is one method using css pseudo elements `:before` and `:after`.
I used the Horizontal bar Unicode character ― in the css `content:` declaration.
```css
div:before {
content: "― ";
}
div:after {
content: " ―";
}
```
```html
<div>TEST</div>
``` | Here it is the code
```css
p {
background-color: #ffffff;
position: relative;
z-index: 1;
width: max-content;
margin: auto;
padding: 0px 5px;
}
hr {
width: 100px;
position: absolute;
left: 50%;
transform: translatex(-50%);
top: 9px;
}
div {
postition: relative;
}
```
```html
<div>
<p>Hello</p>
<hr>
</div>
``` |
69,938,288 | I have a Vuetify treeview setup in a NuxtJS app like so:
```html
<v-treeview
open-all
color="white"
class="info-pool"
:load-children="loadChildren"
:search="search"
:filter="filter"
:items="items">
<template slot="label" slot-scope="{ item }">
<a @click="CHANGE_INFO_TOPIC(item)"
style="text-decoration: none; color: inherit;">{{ item.name }}</a>
</template>
</v-treeview>
```
Whenever a node is opened, it's meant to load its children from NuxtJS's content folder like so:
```js
async loadChildren(item) {
let topicChildren = await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch()
topicChildren.forEach((child) => {
let subChildren = child.children ? [] : null;
item.children.push({
id: child.id,
name: child.name,
location: child.location,
item_key: child.item_key,
children: subChildren
})
})
}
```
This method works as intended, and I can see the desired results in the console log after the load-children method kicks off. The parent node's children key is populated with objects as intended. However, the node in the treeview itself remains empty as if its children was still an empty array.
What could be the reason for this?
* I tried manually pasting the content objects into the node's children array, and they showed up in the treeview. So I know it isn't the formatting of the objects coming from the content fetch method. It must be that the treeview isn't updating after the push.
* The [official docs](https://vuetifyjs.com/en/components/treeview/#load-children) show them using a .json() method on the response, but my response is coming from content in array form so I don't believe I need to do that.
* While fetching from content is different than fetching from an API, I'm still populating the children array in the same manner.
Very confused as to why this method would successfully change the item's children array, but the treeview won't update to reflect it.
**Update**
This test method with a return is also not functioning
```js
async loadChildren(item) {
return await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch()
.then(res => {item.children.push(...res)})
}
```
This hardcoded method is also not working. I've tried it with both pushing an array with one object, as well as just an object.
```js
async loadChildren(item) {
return item.children.push({
id: 1,
name: 'blah'
});
},
```
The documentation states:
>
> You can dynamically load child data by supplying a Promise callback to
> the load-children prop.This callback will be executed the first time a
> user tries to expand an item that has a children property that is an
> empty array.
>
>
>
So perhaps the issue is that the method needs to return a Promise callback that would push the child objects into the array.
But nuxt-content's fetch() method DOES return a Promise. And I can inspect the node in the component's computed data and see that it has been populated with children. But the node on the treeview still remains empty. | 2021/11/12 | [
"https://Stackoverflow.com/questions/69938288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10029354/"
] | try this
Navigator.popUntil(context, ModalRoute.withName('/c'));
or you can simply pop 3 times like
Navigator.of(context)..pop()..pop()..pop(); | If you have a stack of pages A-B-C-D-E and want to push F onto the stack using get x it would look like this
```
Get.to(F())
```
or
```
Get.toName('/F')
```
Outside of that using named routes makes things easier
If you have a stack of pages A-B-C-D-E and want to push F onto the stack but pop D and E then it would look like this
```
Get.offNamedUntil('/F', ModalRoute.withName('/C')
```
This gives you a stack of A-B-C-F
If you have a stack of A-B-C-D-E-F and want to pop until C then it would look like this
```
Get.until((route) => Get.currentRoute == '/C')
```
This would give you a stack of A-B-C popping off D-E-F in one line of code
[Here is a video showing the above code working](https://imgur.com/a/5mfQSBv) |
69,938,288 | I have a Vuetify treeview setup in a NuxtJS app like so:
```html
<v-treeview
open-all
color="white"
class="info-pool"
:load-children="loadChildren"
:search="search"
:filter="filter"
:items="items">
<template slot="label" slot-scope="{ item }">
<a @click="CHANGE_INFO_TOPIC(item)"
style="text-decoration: none; color: inherit;">{{ item.name }}</a>
</template>
</v-treeview>
```
Whenever a node is opened, it's meant to load its children from NuxtJS's content folder like so:
```js
async loadChildren(item) {
let topicChildren = await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch()
topicChildren.forEach((child) => {
let subChildren = child.children ? [] : null;
item.children.push({
id: child.id,
name: child.name,
location: child.location,
item_key: child.item_key,
children: subChildren
})
})
}
```
This method works as intended, and I can see the desired results in the console log after the load-children method kicks off. The parent node's children key is populated with objects as intended. However, the node in the treeview itself remains empty as if its children was still an empty array.
What could be the reason for this?
* I tried manually pasting the content objects into the node's children array, and they showed up in the treeview. So I know it isn't the formatting of the objects coming from the content fetch method. It must be that the treeview isn't updating after the push.
* The [official docs](https://vuetifyjs.com/en/components/treeview/#load-children) show them using a .json() method on the response, but my response is coming from content in array form so I don't believe I need to do that.
* While fetching from content is different than fetching from an API, I'm still populating the children array in the same manner.
Very confused as to why this method would successfully change the item's children array, but the treeview won't update to reflect it.
**Update**
This test method with a return is also not functioning
```js
async loadChildren(item) {
return await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch()
.then(res => {item.children.push(...res)})
}
```
This hardcoded method is also not working. I've tried it with both pushing an array with one object, as well as just an object.
```js
async loadChildren(item) {
return item.children.push({
id: 1,
name: 'blah'
});
},
```
The documentation states:
>
> You can dynamically load child data by supplying a Promise callback to
> the load-children prop.This callback will be executed the first time a
> user tries to expand an item that has a children property that is an
> empty array.
>
>
>
So perhaps the issue is that the method needs to return a Promise callback that would push the child objects into the array.
But nuxt-content's fetch() method DOES return a Promise. And I can inspect the node in the component's computed data and see that it has been populated with children. But the node on the treeview still remains empty. | 2021/11/12 | [
"https://Stackoverflow.com/questions/69938288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10029354/"
] | Do this on your third route
---------------------------
```
Navigator.pushReplacement( context, MaterialPageRoute(settings: RouteSettings(name: "Foo")), );
```
**and at last screen you can call this.**
```
Navigator.popUntil(context, ModalRoute.withName("Foo"));
``` | If you have a stack of pages A-B-C-D-E and want to push F onto the stack using get x it would look like this
```
Get.to(F())
```
or
```
Get.toName('/F')
```
Outside of that using named routes makes things easier
If you have a stack of pages A-B-C-D-E and want to push F onto the stack but pop D and E then it would look like this
```
Get.offNamedUntil('/F', ModalRoute.withName('/C')
```
This gives you a stack of A-B-C-F
If you have a stack of A-B-C-D-E-F and want to pop until C then it would look like this
```
Get.until((route) => Get.currentRoute == '/C')
```
This would give you a stack of A-B-C popping off D-E-F in one line of code
[Here is a video showing the above code working](https://imgur.com/a/5mfQSBv) |
69,938,288 | I have a Vuetify treeview setup in a NuxtJS app like so:
```html
<v-treeview
open-all
color="white"
class="info-pool"
:load-children="loadChildren"
:search="search"
:filter="filter"
:items="items">
<template slot="label" slot-scope="{ item }">
<a @click="CHANGE_INFO_TOPIC(item)"
style="text-decoration: none; color: inherit;">{{ item.name }}</a>
</template>
</v-treeview>
```
Whenever a node is opened, it's meant to load its children from NuxtJS's content folder like so:
```js
async loadChildren(item) {
let topicChildren = await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch()
topicChildren.forEach((child) => {
let subChildren = child.children ? [] : null;
item.children.push({
id: child.id,
name: child.name,
location: child.location,
item_key: child.item_key,
children: subChildren
})
})
}
```
This method works as intended, and I can see the desired results in the console log after the load-children method kicks off. The parent node's children key is populated with objects as intended. However, the node in the treeview itself remains empty as if its children was still an empty array.
What could be the reason for this?
* I tried manually pasting the content objects into the node's children array, and they showed up in the treeview. So I know it isn't the formatting of the objects coming from the content fetch method. It must be that the treeview isn't updating after the push.
* The [official docs](https://vuetifyjs.com/en/components/treeview/#load-children) show them using a .json() method on the response, but my response is coming from content in array form so I don't believe I need to do that.
* While fetching from content is different than fetching from an API, I'm still populating the children array in the same manner.
Very confused as to why this method would successfully change the item's children array, but the treeview won't update to reflect it.
**Update**
This test method with a return is also not functioning
```js
async loadChildren(item) {
return await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch()
.then(res => {item.children.push(...res)})
}
```
This hardcoded method is also not working. I've tried it with both pushing an array with one object, as well as just an object.
```js
async loadChildren(item) {
return item.children.push({
id: 1,
name: 'blah'
});
},
```
The documentation states:
>
> You can dynamically load child data by supplying a Promise callback to
> the load-children prop.This callback will be executed the first time a
> user tries to expand an item that has a children property that is an
> empty array.
>
>
>
So perhaps the issue is that the method needs to return a Promise callback that would push the child objects into the array.
But nuxt-content's fetch() method DOES return a Promise. And I can inspect the node in the component's computed data and see that it has been populated with children. But the node on the treeview still remains empty. | 2021/11/12 | [
"https://Stackoverflow.com/questions/69938288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10029354/"
] | For skip two screen like - `A-B-C-D-F` screen in my stack and I want to go to `B` by removing all upper screen in stack then final stack is `A-B.`
**In Screen B**
```
Navigator.pushReplacement(
context,
MaterialPageRoute(
settings: RouteSettings(name: "Foo"),
builder: (BuildContext context) => Third()),
);
```
**And In Screen F**
```
Navigator.popUntil(context, ModalRoute.withName("Foo"));
```
It working perfectly fine But is there any option we can achieve this in GetX. | If you have a stack of pages A-B-C-D-E and want to push F onto the stack using get x it would look like this
```
Get.to(F())
```
or
```
Get.toName('/F')
```
Outside of that using named routes makes things easier
If you have a stack of pages A-B-C-D-E and want to push F onto the stack but pop D and E then it would look like this
```
Get.offNamedUntil('/F', ModalRoute.withName('/C')
```
This gives you a stack of A-B-C-F
If you have a stack of A-B-C-D-E-F and want to pop until C then it would look like this
```
Get.until((route) => Get.currentRoute == '/C')
```
This would give you a stack of A-B-C popping off D-E-F in one line of code
[Here is a video showing the above code working](https://imgur.com/a/5mfQSBv) |
69,938,288 | I have a Vuetify treeview setup in a NuxtJS app like so:
```html
<v-treeview
open-all
color="white"
class="info-pool"
:load-children="loadChildren"
:search="search"
:filter="filter"
:items="items">
<template slot="label" slot-scope="{ item }">
<a @click="CHANGE_INFO_TOPIC(item)"
style="text-decoration: none; color: inherit;">{{ item.name }}</a>
</template>
</v-treeview>
```
Whenever a node is opened, it's meant to load its children from NuxtJS's content folder like so:
```js
async loadChildren(item) {
let topicChildren = await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch()
topicChildren.forEach((child) => {
let subChildren = child.children ? [] : null;
item.children.push({
id: child.id,
name: child.name,
location: child.location,
item_key: child.item_key,
children: subChildren
})
})
}
```
This method works as intended, and I can see the desired results in the console log after the load-children method kicks off. The parent node's children key is populated with objects as intended. However, the node in the treeview itself remains empty as if its children was still an empty array.
What could be the reason for this?
* I tried manually pasting the content objects into the node's children array, and they showed up in the treeview. So I know it isn't the formatting of the objects coming from the content fetch method. It must be that the treeview isn't updating after the push.
* The [official docs](https://vuetifyjs.com/en/components/treeview/#load-children) show them using a .json() method on the response, but my response is coming from content in array form so I don't believe I need to do that.
* While fetching from content is different than fetching from an API, I'm still populating the children array in the same manner.
Very confused as to why this method would successfully change the item's children array, but the treeview won't update to reflect it.
**Update**
This test method with a return is also not functioning
```js
async loadChildren(item) {
return await this.$content(`${item.location}/${item.item_key}`).sortBy('id', 'asc').fetch()
.then(res => {item.children.push(...res)})
}
```
This hardcoded method is also not working. I've tried it with both pushing an array with one object, as well as just an object.
```js
async loadChildren(item) {
return item.children.push({
id: 1,
name: 'blah'
});
},
```
The documentation states:
>
> You can dynamically load child data by supplying a Promise callback to
> the load-children prop.This callback will be executed the first time a
> user tries to expand an item that has a children property that is an
> empty array.
>
>
>
So perhaps the issue is that the method needs to return a Promise callback that would push the child objects into the array.
But nuxt-content's fetch() method DOES return a Promise. And I can inspect the node in the component's computed data and see that it has been populated with children. But the node on the treeview still remains empty. | 2021/11/12 | [
"https://Stackoverflow.com/questions/69938288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10029354/"
] | When we move form one to another screen then use:
```
Get.toNamed(RoutersConst.third);
```
And to remove screen from stack then use
```
Get.until((route) => route.settings.name == RoutersConst.second);
``` | If you have a stack of pages A-B-C-D-E and want to push F onto the stack using get x it would look like this
```
Get.to(F())
```
or
```
Get.toName('/F')
```
Outside of that using named routes makes things easier
If you have a stack of pages A-B-C-D-E and want to push F onto the stack but pop D and E then it would look like this
```
Get.offNamedUntil('/F', ModalRoute.withName('/C')
```
This gives you a stack of A-B-C-F
If you have a stack of A-B-C-D-E-F and want to pop until C then it would look like this
```
Get.until((route) => Get.currentRoute == '/C')
```
This would give you a stack of A-B-C popping off D-E-F in one line of code
[Here is a video showing the above code working](https://imgur.com/a/5mfQSBv) |
27,871,573 | Im developing a WCF web service with receives always and only XML.
So i need to validate that input XML using their XSD. The question is, can i save them inside web service? Locally i can access XSD files via relative path into IIS Express root folder which i created manually. I tried add the XSD files in VS project but i just cant a find them on runtime.
I'm using the Shemas like this: [Image1 Link](http://s16.postimg.org/cmnm850lh/image.png)
IIS XSD'd Folder Path Workaround: [Image2 Link](http://i.stack.imgur.com/ePozA.png)
At the moment, its working fine, the problem will be when i try deploy the service somewhere on internet.
Thank you.
**tl;dr: Can i send some XSD when deploying the webservice or its just impossible?** | 2015/01/10 | [
"https://Stackoverflow.com/questions/27871573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3542287/"
] | You can add the XSD as a resource, then load it from your assembly. Add the XSD to your project, and under the "Properties Explorer", set the "Build Action" to "Embedded Resource". You can then read the file with:
```
var schemaSet = new XmlSchemaSet();
schemaSet.Add("", XmlReader.Create(typeof(SomeClassInTheSameAssembly).Assembly
.GetManifestResourceStream("Full.Namespace.XsdName.xsd")));
```
See [Working with Embedded Resources](http://blah.winsmarts.com/2006-12-Working_with_Embedded_Resources.aspx) or [Loading XmlSchema files out of Assembly Resources](http://www.hanselman.com/blog/LoadingXmlSchemaFilesOutOfAssemblyResources.aspx) for more. | One way you can do it is by using an application setting in your config file that will hold a base file location such as:
```
<appSettings>
<add key="BaseDir" value="C:\your\folder\names" />
</appSettings>
```
Then in your program, when you need a file, you would do something like this:
```
string fileLocation = System.Configuration.ConfigurationManager.AppSettings["BaseDir"] +
@"\your\file\location\file.xsd";
```
To use `System.Configuration.ConfigurationManager`, you will need to add a reference to `System.Configuration`. |
27,871,573 | Im developing a WCF web service with receives always and only XML.
So i need to validate that input XML using their XSD. The question is, can i save them inside web service? Locally i can access XSD files via relative path into IIS Express root folder which i created manually. I tried add the XSD files in VS project but i just cant a find them on runtime.
I'm using the Shemas like this: [Image1 Link](http://s16.postimg.org/cmnm850lh/image.png)
IIS XSD'd Folder Path Workaround: [Image2 Link](http://i.stack.imgur.com/ePozA.png)
At the moment, its working fine, the problem will be when i try deploy the service somewhere on internet.
Thank you.
**tl;dr: Can i send some XSD when deploying the webservice or its just impossible?** | 2015/01/10 | [
"https://Stackoverflow.com/questions/27871573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3542287/"
] | Files that belong to your solution should be **physically** part of it. Once that is the case you can use for instance [`HostingEnvironment.MapPath`](http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath%28v=vs.110%29.aspx); or look at the answers to [this question](https://stackoverflow.com/questions/791468/how-to-get-working-path-of-a-wcf-application). Note that there is [a possible issue](http://blogs.msmvps.com/theproblemsolver/2009/02/08/gotcha-with-hostingenvironment-mappath/) with HostingEnvironment.MapPath when the WCF service is self hosted.
A possible solution is this method:
```
public static string MapPath(string path)
{
if (HttpContext.Current != null)
return HttpContext.Current.Server.MapPath(path);
return HostingEnvironment.MapPath(path);
}
```
The parameter `path` needs to be of the format `"~/XSD/MyFile.xsd"`, with the folder "XSD" being located in the root of your WCF service.
NEVER create folders in `c:\program files (x86)\iis express`. | One way you can do it is by using an application setting in your config file that will hold a base file location such as:
```
<appSettings>
<add key="BaseDir" value="C:\your\folder\names" />
</appSettings>
```
Then in your program, when you need a file, you would do something like this:
```
string fileLocation = System.Configuration.ConfigurationManager.AppSettings["BaseDir"] +
@"\your\file\location\file.xsd";
```
To use `System.Configuration.ConfigurationManager`, you will need to add a reference to `System.Configuration`. |
27,871,573 | Im developing a WCF web service with receives always and only XML.
So i need to validate that input XML using their XSD. The question is, can i save them inside web service? Locally i can access XSD files via relative path into IIS Express root folder which i created manually. I tried add the XSD files in VS project but i just cant a find them on runtime.
I'm using the Shemas like this: [Image1 Link](http://s16.postimg.org/cmnm850lh/image.png)
IIS XSD'd Folder Path Workaround: [Image2 Link](http://i.stack.imgur.com/ePozA.png)
At the moment, its working fine, the problem will be when i try deploy the service somewhere on internet.
Thank you.
**tl;dr: Can i send some XSD when deploying the webservice or its just impossible?** | 2015/01/10 | [
"https://Stackoverflow.com/questions/27871573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3542287/"
] | Files that belong to your solution should be **physically** part of it. Once that is the case you can use for instance [`HostingEnvironment.MapPath`](http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath%28v=vs.110%29.aspx); or look at the answers to [this question](https://stackoverflow.com/questions/791468/how-to-get-working-path-of-a-wcf-application). Note that there is [a possible issue](http://blogs.msmvps.com/theproblemsolver/2009/02/08/gotcha-with-hostingenvironment-mappath/) with HostingEnvironment.MapPath when the WCF service is self hosted.
A possible solution is this method:
```
public static string MapPath(string path)
{
if (HttpContext.Current != null)
return HttpContext.Current.Server.MapPath(path);
return HostingEnvironment.MapPath(path);
}
```
The parameter `path` needs to be of the format `"~/XSD/MyFile.xsd"`, with the folder "XSD" being located in the root of your WCF service.
NEVER create folders in `c:\program files (x86)\iis express`. | You can add the XSD as a resource, then load it from your assembly. Add the XSD to your project, and under the "Properties Explorer", set the "Build Action" to "Embedded Resource". You can then read the file with:
```
var schemaSet = new XmlSchemaSet();
schemaSet.Add("", XmlReader.Create(typeof(SomeClassInTheSameAssembly).Assembly
.GetManifestResourceStream("Full.Namespace.XsdName.xsd")));
```
See [Working with Embedded Resources](http://blah.winsmarts.com/2006-12-Working_with_Embedded_Resources.aspx) or [Loading XmlSchema files out of Assembly Resources](http://www.hanselman.com/blog/LoadingXmlSchemaFilesOutOfAssemblyResources.aspx) for more. |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | Use "EMPTY":
```
<?php
function writeShoppingCart() {
$cart = !empty($_SESSION['cart']);
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | try initializing your $\_SESSION with something like:
```
$_SESSION['cart'] = 0; // zero items in cart
``` |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | If `$_SESSION['cart']` isn't set, it throws that warning.
Try:
```
$cart = isset($_SESSION['cart'])?$_SESSION['cart']:false;
``` | Try this:
```
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : NULL;
``` |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | Use "EMPTY":
```
<?php
function writeShoppingCart() {
$cart = !empty($_SESSION['cart']);
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | That means that your session does not contain `$_SESSION['cart']`
Try this instead:
```
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : false;
``` |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | This means that the key 'cart' does not exist in the $\_SESSION superglobal array.
If it's alright for this value to not exist, you should be doing this:
```
$cart = false;
if (isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
```
You could use something called the ternary operator, in PHP, but since you're a beginner, I don't want to bombard you.
In development mode, it's alright to display errors but you should read more about disabling errors (error\_reporting) and logging them (error\_log()) so that they can be inspected without alarming visitors. | try initializing your $\_SESSION with something like:
```
$_SESSION['cart'] = 0; // zero items in cart
``` |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | If `$_SESSION['cart']` isn't set, it throws that warning.
Try:
```
$cart = isset($_SESSION['cart'])?$_SESSION['cart']:false;
``` | That means that your session does not contain `$_SESSION['cart']`
Try this instead:
```
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : false;
``` |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | If `$_SESSION['cart']` isn't set, it throws that warning.
Try:
```
$cart = isset($_SESSION['cart'])?$_SESSION['cart']:false;
``` | This means that the key 'cart' does not exist in the $\_SESSION superglobal array.
If it's alright for this value to not exist, you should be doing this:
```
$cart = false;
if (isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
```
You could use something called the ternary operator, in PHP, but since you're a beginner, I don't want to bombard you.
In development mode, it's alright to display errors but you should read more about disabling errors (error\_reporting) and logging them (error\_log()) so that they can be inspected without alarming visitors. |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | If `$_SESSION['cart']` isn't set, it throws that warning.
Try:
```
$cart = isset($_SESSION['cart'])?$_SESSION['cart']:false;
``` | Use "EMPTY":
```
<?php
function writeShoppingCart() {
$cart = !empty($_SESSION['cart']);
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | Use "EMPTY":
```
<?php
function writeShoppingCart() {
$cart = !empty($_SESSION['cart']);
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | Try this:
```
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : NULL;
``` |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | This means that the key 'cart' does not exist in the $\_SESSION superglobal array.
If it's alright for this value to not exist, you should be doing this:
```
$cart = false;
if (isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
```
You could use something called the ternary operator, in PHP, but since you're a beginner, I don't want to bombard you.
In development mode, it's alright to display errors but you should read more about disabling errors (error\_reporting) and logging them (error\_log()) so that they can be inspected without alarming visitors. | That means that your session does not contain `$_SESSION['cart']`
Try this instead:
```
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : false;
``` |
9,709,688 | Heya I get this error message. I've been looking everywhere but I dont know how to fix it? Im a beginner so I'm really confued. Thanks in advance
Notice: Undefined index: cart in /nas/students/j/j39-green/unix/public\_html/ISD5/inc/functions.inc.php on line 3
You have no items in your shopping cart
```
<?php
function writeShoppingCart() {
$cart = $_SESSION['cart'];
if (!$cart) {
return '<p>You have no items in your shopping cart</p>';
} else {
// Parse the cart session variable
$items = explode(',',$cart);
$s = (count($items) > 1) ? 's':'';
return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>';
}
}
``` | 2012/03/14 | [
"https://Stackoverflow.com/questions/9709688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269822/"
] | This means that the key 'cart' does not exist in the $\_SESSION superglobal array.
If it's alright for this value to not exist, you should be doing this:
```
$cart = false;
if (isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
}
```
You could use something called the ternary operator, in PHP, but since you're a beginner, I don't want to bombard you.
In development mode, it's alright to display errors but you should read more about disabling errors (error\_reporting) and logging them (error\_log()) so that they can be inspected without alarming visitors. | Try this:
```
$cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : NULL;
``` |
200,627 | I'm using `standalone` document class and trying to draw a TikZ picture. The picture have border which is the border of the page. I do it [like this](http://papeeria.com/p/c6949888bcd012d5fcc4ca5bd8ba79a9#/without-fontspec.tex):
```
\documentclass{standalone}
\usepackage{tikz}
\def\W{220}
\def\H{250}
\begin{document}
\begin{tikzpicture}[x=1pt,y=1pt]
\draw[ultra thick] (0,0) -- (\W,0) -- (\W,\H) -- (0,\H) -- (0,0);
\end{tikzpicture}
\end{document}
```
And it looks like this (I've added red background just to make the difference visible, and I've done it using gimp, it's not a part of the question)

But if I just add `\usepackage{fontspec}` to the preamble then some left margin appears and it looks [like this](http://papeeria.com/p/c6949888bcd012d5fcc4ca5bd8ba79a9#/with-fontspec.tex)

So, where does it come from? How can I get rid of it? | 2014/09/11 | [
"https://tex.stackexchange.com/questions/200627",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/27682/"
] | I see the effect with TexLive 2013, but not with 2014 and miktex. So you will probably have to update something (fontspec?). The effect disappears if I add `\unskip` after `\begin{document}`. So it looks like an spurious space somewhere. | [Ulrike has shown](https://tex.stackexchange.com/a/200655) that this is a `fontspec` issue. The actually faulty code is
```
\tl_put_right:Nn \document
{
\tl_set_eq:NN \cyrillicencoding \g_fontspec_encoding_tl
\tl_set_eq:NN \latinencoding \g_fontspec_encoding_tl
}
```
which is used to do something 'really late', just before the start of the document. The problem is that this gets added after the `\ignorespaces` that is at the end of the standard `\document` macro. This causes issues as there is a space (line end) after `\begin{document}`. Newer versions of `fontspec` avoid this by using the standard `\AtBeginDocument` hook, so the issue goes away. In cases where you *really* need to hook right at the end of `\document`, you have to always add an `\ignorespaces` as well as what you need, or use a 'patch' approach to essentially do the same thing. |
39,065,933 | First and foremost, this is my 1st time writing PHP code, so please forgive my newbie'isms.
I have a login form with 3 submit buttons (post method) named login, register and forgot. If I select login button, the login function in the PHP code gets called, however, the same is not true for the register and forgot buttons. Its almost like the only submit button that is working is the login buttons. My best guess at this point is there is id/name that not correct. For the sake of brevity I've removed the CSS portion. Any points in the right direction will be most appreciated.
```
<?php
function login(){
//do stuff
echo "Login";
}
function register(){
// do stuff
echo "Register";
}
function forgot(){
//do stuff
echo "Forgot";
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['login'])) {
login();
}
if(isset($_POST['register'])) {
register();
}
if(isset($_POST['forgot'])) {
forgot();
}
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Login Page</title>
</head>
<body>
<div id="login">
<h1><strong>Welcome!</strong> Please login.</h1>
<form action="" method="post">
<fieldset>
<p><input type="text" name="username" required value="Username" onBlur="if(this.value=='')this.value='Username'" onFocus="if(this.value=='Username')this.value=''"></p>
<p><input type="password" name="password"></p>
<p><input type="submit" name= "login" value="Login"></p>
<p><input type="submit" name= "register" value="Register"></p>
<p><input type="submit" name= "forgot" value="Forgot Password"></p>
</fieldset>
</form>
</div> <!-- end login -->
</body>
</html>
``` | 2016/08/21 | [
"https://Stackoverflow.com/questions/39065933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3254596/"
] | HTML forms can not contain more than one input of type "submit" (which means others would not be functioning)
**register** and **forgot** are links rather than buttons.
Instead you could use:
```
<a href="/register.php">Register</a>
```
Another alternative is to use javascript to make these buttons act as links. | After copying and pasting my code into another file. It worked without any issues. The multiple submit buttons work without any issues. |
7,873,972 | I'm rewriting/converting some VB-Code:
```
Dim dt As New System.Data.DataTable()
Dim dr As System.Data.DataRow = dt.NewRow()
Dim item = dr.Item("myItem")
```
C#:
```
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataRow dr = dt.NewRow();
var item = dr.Item["myItem"];
```
I can't make it run under C#, the problems I have is the third row `var item = dr.Item["myItem"];`:
`System.Data.DataRow' does not contain a definition for 'Item' and no extension method 'Item' accepting a first argument of type 'System.Data.DataRow' could be found (are you missing a using directive or an assembly reference?)`
I referenced `System.Data` Version 4 in both projects. What am I missing here? Note: ItemArray exists in both... | 2011/10/24 | [
"https://Stackoverflow.com/questions/7873972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/598516/"
] | Try like this:
```
var item = dr["myItem"];
```
In C# you can access the [indexer property](http://msdn.microsoft.com/en-us/library/2549tw02.aspx) directly. And the [DataRow.Item](http://msdn.microsoft.com/en-us/library/system.data.datarow.item.aspx) property is defined as indexer. | There is actually no "Item" property in C#. In VB the DataRow cell access is defined like this:
```vb
Default Public Property Item (
column As DataColumn
) As Object
```
So there is a literal "Item" property. However, in C# it is defined like this:
```
public object this[
DataColumn column
] { get; set; }
```
So this is the default property of the class / object. So you access it with the object name. |
29,014 | There is an existing light fixture and switch for the light fixture. I want to add a bath fan with its own switch.
What is the easiest way? | 2013/06/24 | [
"https://diy.stackexchange.com/questions/29014",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/13644/"
] | If you're not comfortable working with electricity then hire a professional. Improper wiring and the resulting fire isn't worth saving a few bucks.
That said:
Your existing fan/light combo is likely connected using a 2-conductor cable (like 14-2)... but for two separately switched circuits you'll need three conductors (14-3) or two separate 14-2 wires.
At the gang box, one of the conductors goes to the light, and the other goes to the fan. | You need to check to see how many wires you have going into your current switch from the fan. It is most likely that you have a black and a white.
If this is the case you will need to run either 12-3 or 14-3 wiring from fan to switch. Size dependent on amperage of circuit. 15A gets 14 and 20A gets 12-3. 12-3 will actually work for either. You need to hook up the wiring for the fan part of the kit to the extra cable (red) and to power. The other side of the red powers your individual fan switch.
The hardest part of doing this is getting the cable from the fan to the box inside the wall. This usually consists of taking out and patching drywall. Not counting the drywall issues, this is a 30 min job.
Now if you have a white, black, and red (or two blacks) currently coming into your box then you are in luck. You simply need to install a bigger box where your current one is and take the fan power (red or extra black) to its own switch. |
10,373,163 | There a search service (PHP) which sends search query via POST. I would like to use that search engine in my app. The PHP service does not have a public API.
Is there a way to enter search query and to fetch a POST request to see the name of parameters? I would use then later to send a POST requests from my app and to catch POST responses.
This is an official search engine with governmental officials who do not reply to my requests to tell me the name of parameters. It's nothing illegal, app is free of charge, it's just that I can no longer wait for them as they will reply to me.
PS. I have access to Ubuntu shell and its admin tools.
**EDIT**
This is how the search form looks like in the source of the web page (seen via browser)
```
<form action="search.php" method="POST">
<input type="text" name="search" size=20><br>
SZ<input type="checkbox" checked name="sz">
NZ<input type="checkbox" checked name="nz">
<input type="submit" name="search_term" value="search" >
</form>
```
**EDIT 2**
Do not edit post as a guy suggested me the proper way to do this via linux command curl. | 2012/04/29 | [
"https://Stackoverflow.com/questions/10373163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437039/"
] | Have you tried viewing the source on the search form to get the POST parameters? i.e. the name of the input box
**Edit**
take for example the php form on tizag site
```
<html><body>
<h4>Tizag Art Supply Order Form</h4>
<form action="process.php" method="post">
<select name="item">
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit" />
</form>
</body></html>
```
the parameters are the input names i.e. quality and item
**Java code** (was using this for appengine)
```
HttpURLConnection connection = null;
String line = null;
BufferedReader rd = null;
String urlParameters = "search=search&submit=Submit";
serverAddress = new URL("http://www.search.com/search.php");
// set up out communications stuff
connection = null;
connection = (HttpURLConnection) serverAddress.openConnection();
// connection.setRequestMethod("GET");
connection.setRequestMethod("POST");
connection.setRequestProperty("Referer", "");
connection.setRequestProperty("User-Agent", "");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.connect();
if (connection.getResponseCode() == 404) {
throw new ErrorException();
}
ArrayList<String> ud = new ArrayList<String>();
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = rd.readLine()) != null) {
ud.add(line); // add response to arraylist
}
``` | Whilst this is certainly something you could do with [curl in PHP](http://php.net/manual/en/book.curl.php), you should consider the possible consequences of scraping a government site to collect and reuse it's data.
Of course, I don't know how you will use the data, the importance of the data, the frequency of the requests or if you'll be using proxies. So might be nothing to worry about.
You want to know that parameters returned by a third party search engine. So you'd use curl to POST to the SE in question. Then parse the returned page and extract the information you're after.
**Edit:** Ok, so you're a Java guy. If you'd be more comfortable using the shell, read a few of the examples of PHP's "[exec](http://uk3.php.net/exec)" command. There's also the similar "[system](http://uk3.php.net/manual/en/function.system.php)" and "[passthru](http://uk3.php.net/manual/en/function.passthru.php)" you might want to look at. |
377,443 | I was adventuring, and reset my spawn by accident, by interacting with a bed in a random village. I never wrote down the coordinates or followed a compass so I’m completely lost.
I worked really hard, and since I’m on a Nintendo switch it’s confusing with what everyone’s saying? How do I get back home? Is there any commands I can use? I even by accident changed the world spawn to a village? | 2020/11/02 | [
"https://gaming.stackexchange.com/questions/377443",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/260711/"
] | There are a few ways you may be able to get back home.
The simplest is to craft a compass which will point you to the world spawn. It's unclear from your post whether you used commands to change the spawn point to a village, or used a bed, but assuming you just used a bed then the compass would point you towards 0,0 which may be enough to help you navigate home once you reach the center of the map.
If you're willing to use commands then I'd recommend temporarily setting your game mode to creative and fly around until you're able to locate your base. In creative mode you'll be faster and able to fly over obstacles. You'll be able to find and identify landmarks more easily from a great altitude. | If you did it in Survival, you could make a copy of the world, find where you had as the spawn/your base, and write down the coordinates (using creative to find the base) |
377,443 | I was adventuring, and reset my spawn by accident, by interacting with a bed in a random village. I never wrote down the coordinates or followed a compass so I’m completely lost.
I worked really hard, and since I’m on a Nintendo switch it’s confusing with what everyone’s saying? How do I get back home? Is there any commands I can use? I even by accident changed the world spawn to a village? | 2020/11/02 | [
"https://gaming.stackexchange.com/questions/377443",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/260711/"
] | There are a few ways you may be able to get back home.
The simplest is to craft a compass which will point you to the world spawn. It's unclear from your post whether you used commands to change the spawn point to a village, or used a bed, but assuming you just used a bed then the compass would point you towards 0,0 which may be enough to help you navigate home once you reach the center of the map.
If you're willing to use commands then I'd recommend temporarily setting your game mode to creative and fly around until you're able to locate your base. In creative mode you'll be faster and able to fly over obstacles. You'll be able to find and identify landmarks more easily from a great altitude. | there are couple of ways you can make your way to your base
1 - craft a compass
crafting a compass which will point to the world spawn
[](https://i.stack.imgur.com/W00Kp.png)
2 - when you go to settings you should see your seed copy the seed and make a another world with the same seed and if you didnt change the spawn using commands in your orginal world then write your cords and go to the real game and follow that cords |
377,443 | I was adventuring, and reset my spawn by accident, by interacting with a bed in a random village. I never wrote down the coordinates or followed a compass so I’m completely lost.
I worked really hard, and since I’m on a Nintendo switch it’s confusing with what everyone’s saying? How do I get back home? Is there any commands I can use? I even by accident changed the world spawn to a village? | 2020/11/02 | [
"https://gaming.stackexchange.com/questions/377443",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/260711/"
] | There are a few ways you may be able to get back home.
The simplest is to craft a compass which will point you to the world spawn. It's unclear from your post whether you used commands to change the spawn point to a village, or used a bed, but assuming you just used a bed then the compass would point you towards 0,0 which may be enough to help you navigate home once you reach the center of the map.
If you're willing to use commands then I'd recommend temporarily setting your game mode to creative and fly around until you're able to locate your base. In creative mode you'll be faster and able to fly over obstacles. You'll be able to find and identify landmarks more easily from a great altitude. | `/tp @p 0 ~ 0`
This command will tp you to the world spawn. This should help you then navigate to your base, assuming your base is near the world spawn. And unless your base is underground it should help to make a bunch of maps and explore the area around spawn and look for any unusual blobs of color shaped like your base which should be, ta-da, your base.
If you don't want to use commands you can craft a compass to find world spawn instead. And I still recommend using maps to cover more area as you navigate back and around spawn. |
377,443 | I was adventuring, and reset my spawn by accident, by interacting with a bed in a random village. I never wrote down the coordinates or followed a compass so I’m completely lost.
I worked really hard, and since I’m on a Nintendo switch it’s confusing with what everyone’s saying? How do I get back home? Is there any commands I can use? I even by accident changed the world spawn to a village? | 2020/11/02 | [
"https://gaming.stackexchange.com/questions/377443",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/260711/"
] | there are couple of ways you can make your way to your base
1 - craft a compass
crafting a compass which will point to the world spawn
[](https://i.stack.imgur.com/W00Kp.png)
2 - when you go to settings you should see your seed copy the seed and make a another world with the same seed and if you didnt change the spawn using commands in your orginal world then write your cords and go to the real game and follow that cords | If you did it in Survival, you could make a copy of the world, find where you had as the spawn/your base, and write down the coordinates (using creative to find the base) |
377,443 | I was adventuring, and reset my spawn by accident, by interacting with a bed in a random village. I never wrote down the coordinates or followed a compass so I’m completely lost.
I worked really hard, and since I’m on a Nintendo switch it’s confusing with what everyone’s saying? How do I get back home? Is there any commands I can use? I even by accident changed the world spawn to a village? | 2020/11/02 | [
"https://gaming.stackexchange.com/questions/377443",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/260711/"
] | If you did it in Survival, you could make a copy of the world, find where you had as the spawn/your base, and write down the coordinates (using creative to find the base) | `/tp @p 0 ~ 0`
This command will tp you to the world spawn. This should help you then navigate to your base, assuming your base is near the world spawn. And unless your base is underground it should help to make a bunch of maps and explore the area around spawn and look for any unusual blobs of color shaped like your base which should be, ta-da, your base.
If you don't want to use commands you can craft a compass to find world spawn instead. And I still recommend using maps to cover more area as you navigate back and around spawn. |
377,443 | I was adventuring, and reset my spawn by accident, by interacting with a bed in a random village. I never wrote down the coordinates or followed a compass so I’m completely lost.
I worked really hard, and since I’m on a Nintendo switch it’s confusing with what everyone’s saying? How do I get back home? Is there any commands I can use? I even by accident changed the world spawn to a village? | 2020/11/02 | [
"https://gaming.stackexchange.com/questions/377443",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/260711/"
] | there are couple of ways you can make your way to your base
1 - craft a compass
crafting a compass which will point to the world spawn
[](https://i.stack.imgur.com/W00Kp.png)
2 - when you go to settings you should see your seed copy the seed and make a another world with the same seed and if you didnt change the spawn using commands in your orginal world then write your cords and go to the real game and follow that cords | `/tp @p 0 ~ 0`
This command will tp you to the world spawn. This should help you then navigate to your base, assuming your base is near the world spawn. And unless your base is underground it should help to make a bunch of maps and explore the area around spawn and look for any unusual blobs of color shaped like your base which should be, ta-da, your base.
If you don't want to use commands you can craft a compass to find world spawn instead. And I still recommend using maps to cover more area as you navigate back and around spawn. |
42,638,440 | I am having a hard time getting javascript to work without reloading a page. I believe the problem has to do with turbo links.
I am setting an onsubmit listener to a form like this
```
<%= form_for @cart, url: cart_path, html: {onsubmit: "addCart(event, #{@product.id})"} do |c| %>
```
I am then submitting the form via ajax like this
```
function addCart(event, id){
event.preventDefault();
var quantity = $("#"+id+'_product_quantity').val()
$.post('/cart/add', {
product_id: id,
quantity: quantity
}, function(data, status, xhr){
if(xhr.status !== 200){
alert("There was an error. Please try again")
}else {
$("#"+id+'_product_submit').val("Added");
}
})
}
```
Everything works perfectly when I reload the page but when I go to the page via a link the javascript does not get called. The weird thing is that the `event.preventDefault()` is working. When I remove the javascript completely the form will submit like a normal html form. I am a pretty new to jquery and cannot figure out how to get the javascript to load. | 2017/03/07 | [
"https://Stackoverflow.com/questions/42638440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1599104/"
] | This could be a turbolinks issue. In your javascript file, surround your javascript code with
```
$(document).on('turbolinks:load', function() {
// your code
});
``` | So this had to do with turbolinks. I couldn't figure out how to make it work with turbo links so I removed the `//= require turbolinks` line from `assets/javascripts/application.js` file. |
30,191,851 | I am trying to figure out if Python/Numpy is a viable alternative to develop my numerical software which is already available in C++. In order to get performance in Python/Numpy, one need to "vectorize" the code. But it turns out that as soon as I move away from very simple examples, I struggle to vectorize the code (I am not talking about SIMD instructions but "efficient Numpy code" without loops). Here is an algorithm that I want to get efficiently in Python/Numpy.
1. Create an numpy array containing: 1.0, 1.0 + 1/n, 1.0 + 2/n, ..., 2.0
2. For every u in the array, compute the root of x^2 - u, using a Newton method, stopping when |dx| <= 1.0e-7. Store the result in an array result.
3. Sum all the elements of the result array
Here is the algorithm in Python I want to speed up
```
import numpy as np
n = 1000000
data = np.arange(1.0, 2.0, 1.0 / n)
def newton(u):
x = 2.0
while True:
f = x**2 - u
df_dx = 2 * x
dx = f / df_dx
if (abs(dx) <= 1.0e-7):
break
x -= dx
return x
result = map(newton, data)
print result[n - 1]
```
Here is a version of the algorithm in C++11
```
#include <iostream>
#include <vector>
#include <cmath>
int main (int argc, char const *argv[]) {
auto n = std::size_t{100000000};
auto v = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
v[k] = 1.0 + static_cast<double>(k) / n;
}
auto result = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
auto x = double{2.0};
while(true) {
auto f = double{x * x - v[k]};
auto df_dx = double{2 * x};
auto dx = double{f / df_dx};
if (std::abs(dx) <= 1.0e-7) {
break;
}
x -= dx;
}
result[k] = x;
}
auto somme = double{0.0};
for(size_t k = 0; k < result.size(); ++k) {
somme += result[k];
}
std::cout << somme << std::endl;
return 0;
}
```
It takes 2.9 seconds to run on my machine. Is there a way to make a fast Python/Numpy algorithm that does the same thing (I am willing to get something that is less than 5 times slower).
Thanks. | 2015/05/12 | [
"https://Stackoverflow.com/questions/30191851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3763545/"
] | You can do step 1. with numpy efficiently:
```
1.0 + np.arange(n + 1) / n
```
however I think you would need the np.vectorize() method to feed back x into your calculated values and it's not an efficient function (basically a wrapper for a python loop). If you can use scipy then there are built in methods that might do what you want <http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.newton.html>
EDIT: Having thought a bit more about this I followed up on @ev-br's point and tried some alternatives. The masking uses too much processing but the abs().max() is pretty fast so a compromise might be to "divide the problem into blocks" both in the 1st dimension of the array and in iteration direction. The following doesn't do too badly (< 20s) on my pretty low power laptop - certainly much faster than np.vectorize() or any of the scipy solving systems I could find. (If I set m too big it runs out of something (memory?) and grinds to a complete halt!)
```
n = 100000000
m = 5000000
block = 3
u = 1.0 + np.arange(n + 1) / n
x = np.full(u.shape, 2.0)
dx = np.ones(u.shape)
for i in range(0, n, m):
while np.abs(dx[i:i+m]).max() > 1.0e-7:
for j in range(block):
dx[i:i+m] = (x[i:i+m] ** 2 - u[i:i+m]) / (2 * x[i:i+m])
x[i:i+m] -= dx[i:i+m]
``` | I'm not looking to wave small snippets of code as a solution, but here's something to get you started. I have a strong suspicion that you're having troubles just declaring such an array in python without spending too much time on it, so I'll mostly help you out there.
As far as the square roots come in, please add your example python code and I'll see what I can help optimize from that point on. In my example roots and sums are found with the default numpy functions/methods.
```
def summing():
n = 1000000
ar = np.arange(0, n)
ar = ar/float(n)
ar = ar + np.ones(n)
sqrt = np.sqrt(ar)
return np.sum(ar)
```
In short, to get the starting array it's best to use a "workaround".
* initialize an array `ar` with values `[1,2,3,....n]
* divide `ar` with `n`. This gets us the `1/n, 2/n ...` members
* add to that an array of same dimensions that contain just the number `1.0`
This gets us the full array `[ 1., 1.000001, 1.000002, ..., 1.999998, 1.999999])` we're after. If I understood you right.
* find square roots, sum it
Average of 10 sequential execution times is `0.018786` seconds. |
30,191,851 | I am trying to figure out if Python/Numpy is a viable alternative to develop my numerical software which is already available in C++. In order to get performance in Python/Numpy, one need to "vectorize" the code. But it turns out that as soon as I move away from very simple examples, I struggle to vectorize the code (I am not talking about SIMD instructions but "efficient Numpy code" without loops). Here is an algorithm that I want to get efficiently in Python/Numpy.
1. Create an numpy array containing: 1.0, 1.0 + 1/n, 1.0 + 2/n, ..., 2.0
2. For every u in the array, compute the root of x^2 - u, using a Newton method, stopping when |dx| <= 1.0e-7. Store the result in an array result.
3. Sum all the elements of the result array
Here is the algorithm in Python I want to speed up
```
import numpy as np
n = 1000000
data = np.arange(1.0, 2.0, 1.0 / n)
def newton(u):
x = 2.0
while True:
f = x**2 - u
df_dx = 2 * x
dx = f / df_dx
if (abs(dx) <= 1.0e-7):
break
x -= dx
return x
result = map(newton, data)
print result[n - 1]
```
Here is a version of the algorithm in C++11
```
#include <iostream>
#include <vector>
#include <cmath>
int main (int argc, char const *argv[]) {
auto n = std::size_t{100000000};
auto v = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
v[k] = 1.0 + static_cast<double>(k) / n;
}
auto result = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
auto x = double{2.0};
while(true) {
auto f = double{x * x - v[k]};
auto df_dx = double{2 * x};
auto dx = double{f / df_dx};
if (std::abs(dx) <= 1.0e-7) {
break;
}
x -= dx;
}
result[k] = x;
}
auto somme = double{0.0};
for(size_t k = 0; k < result.size(); ++k) {
somme += result[k];
}
std::cout << somme << std::endl;
return 0;
}
```
It takes 2.9 seconds to run on my machine. Is there a way to make a fast Python/Numpy algorithm that does the same thing (I am willing to get something that is less than 5 times slower).
Thanks. | 2015/05/12 | [
"https://Stackoverflow.com/questions/30191851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3763545/"
] | Here's a toy example. Notice that often vectorization means writing your code as if you're manipulating numbers, and letting numpy do its magic:
```
>>> import numpy as np
>>> a = np.array([1., 2., 3.])
>>> def f(x):
... return x**2 - a, 2.*x # function and derivative
>>>
>>> def newt(f, x0):
... x = np.asarray(x0)
... for _ in range(5): # hardcode the number of iterations (I know)
... v, dv = f(x)
... x -= v / dv
... return x
>>>
>>> newt(f, [1., 1., 1.])
array([ 1. , 1.41421356, 1.73205081])
```
If this is a performance bottleneck, this is unlikely to be competetive with hand-written C++ code: First of all, you're manipulating python objects with all the overhead; then numpy is likely doing a bunch of array allocations under the hood.
An often viable strategy is to start by writing things in python/numpy, and then move bottlenecks into a compiled code --- eg Cython or C++ wrapped by Cython. In this particular case since you already have the C++ code, just wrapping it with Cython is likely easiest but YMMV. | I'm not looking to wave small snippets of code as a solution, but here's something to get you started. I have a strong suspicion that you're having troubles just declaring such an array in python without spending too much time on it, so I'll mostly help you out there.
As far as the square roots come in, please add your example python code and I'll see what I can help optimize from that point on. In my example roots and sums are found with the default numpy functions/methods.
```
def summing():
n = 1000000
ar = np.arange(0, n)
ar = ar/float(n)
ar = ar + np.ones(n)
sqrt = np.sqrt(ar)
return np.sum(ar)
```
In short, to get the starting array it's best to use a "workaround".
* initialize an array `ar` with values `[1,2,3,....n]
* divide `ar` with `n`. This gets us the `1/n, 2/n ...` members
* add to that an array of same dimensions that contain just the number `1.0`
This gets us the full array `[ 1., 1.000001, 1.000002, ..., 1.999998, 1.999999])` we're after. If I understood you right.
* find square roots, sum it
Average of 10 sequential execution times is `0.018786` seconds. |
30,191,851 | I am trying to figure out if Python/Numpy is a viable alternative to develop my numerical software which is already available in C++. In order to get performance in Python/Numpy, one need to "vectorize" the code. But it turns out that as soon as I move away from very simple examples, I struggle to vectorize the code (I am not talking about SIMD instructions but "efficient Numpy code" without loops). Here is an algorithm that I want to get efficiently in Python/Numpy.
1. Create an numpy array containing: 1.0, 1.0 + 1/n, 1.0 + 2/n, ..., 2.0
2. For every u in the array, compute the root of x^2 - u, using a Newton method, stopping when |dx| <= 1.0e-7. Store the result in an array result.
3. Sum all the elements of the result array
Here is the algorithm in Python I want to speed up
```
import numpy as np
n = 1000000
data = np.arange(1.0, 2.0, 1.0 / n)
def newton(u):
x = 2.0
while True:
f = x**2 - u
df_dx = 2 * x
dx = f / df_dx
if (abs(dx) <= 1.0e-7):
break
x -= dx
return x
result = map(newton, data)
print result[n - 1]
```
Here is a version of the algorithm in C++11
```
#include <iostream>
#include <vector>
#include <cmath>
int main (int argc, char const *argv[]) {
auto n = std::size_t{100000000};
auto v = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
v[k] = 1.0 + static_cast<double>(k) / n;
}
auto result = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
auto x = double{2.0};
while(true) {
auto f = double{x * x - v[k]};
auto df_dx = double{2 * x};
auto dx = double{f / df_dx};
if (std::abs(dx) <= 1.0e-7) {
break;
}
x -= dx;
}
result[k] = x;
}
auto somme = double{0.0};
for(size_t k = 0; k < result.size(); ++k) {
somme += result[k];
}
std::cout << somme << std::endl;
return 0;
}
```
It takes 2.9 seconds to run on my machine. Is there a way to make a fast Python/Numpy algorithm that does the same thing (I am willing to get something that is less than 5 times slower).
Thanks. | 2015/05/12 | [
"https://Stackoverflow.com/questions/30191851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3763545/"
] | You can do step 1. with numpy efficiently:
```
1.0 + np.arange(n + 1) / n
```
however I think you would need the np.vectorize() method to feed back x into your calculated values and it's not an efficient function (basically a wrapper for a python loop). If you can use scipy then there are built in methods that might do what you want <http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.newton.html>
EDIT: Having thought a bit more about this I followed up on @ev-br's point and tried some alternatives. The masking uses too much processing but the abs().max() is pretty fast so a compromise might be to "divide the problem into blocks" both in the 1st dimension of the array and in iteration direction. The following doesn't do too badly (< 20s) on my pretty low power laptop - certainly much faster than np.vectorize() or any of the scipy solving systems I could find. (If I set m too big it runs out of something (memory?) and grinds to a complete halt!)
```
n = 100000000
m = 5000000
block = 3
u = 1.0 + np.arange(n + 1) / n
x = np.full(u.shape, 2.0)
dx = np.ones(u.shape)
for i in range(0, n, m):
while np.abs(dx[i:i+m]).max() > 1.0e-7:
for j in range(block):
dx[i:i+m] = (x[i:i+m] ** 2 - u[i:i+m]) / (2 * x[i:i+m])
x[i:i+m] -= dx[i:i+m]
``` | Here's a toy example. Notice that often vectorization means writing your code as if you're manipulating numbers, and letting numpy do its magic:
```
>>> import numpy as np
>>> a = np.array([1., 2., 3.])
>>> def f(x):
... return x**2 - a, 2.*x # function and derivative
>>>
>>> def newt(f, x0):
... x = np.asarray(x0)
... for _ in range(5): # hardcode the number of iterations (I know)
... v, dv = f(x)
... x -= v / dv
... return x
>>>
>>> newt(f, [1., 1., 1.])
array([ 1. , 1.41421356, 1.73205081])
```
If this is a performance bottleneck, this is unlikely to be competetive with hand-written C++ code: First of all, you're manipulating python objects with all the overhead; then numpy is likely doing a bunch of array allocations under the hood.
An often viable strategy is to start by writing things in python/numpy, and then move bottlenecks into a compiled code --- eg Cython or C++ wrapped by Cython. In this particular case since you already have the C++ code, just wrapping it with Cython is likely easiest but YMMV. |
30,191,851 | I am trying to figure out if Python/Numpy is a viable alternative to develop my numerical software which is already available in C++. In order to get performance in Python/Numpy, one need to "vectorize" the code. But it turns out that as soon as I move away from very simple examples, I struggle to vectorize the code (I am not talking about SIMD instructions but "efficient Numpy code" without loops). Here is an algorithm that I want to get efficiently in Python/Numpy.
1. Create an numpy array containing: 1.0, 1.0 + 1/n, 1.0 + 2/n, ..., 2.0
2. For every u in the array, compute the root of x^2 - u, using a Newton method, stopping when |dx| <= 1.0e-7. Store the result in an array result.
3. Sum all the elements of the result array
Here is the algorithm in Python I want to speed up
```
import numpy as np
n = 1000000
data = np.arange(1.0, 2.0, 1.0 / n)
def newton(u):
x = 2.0
while True:
f = x**2 - u
df_dx = 2 * x
dx = f / df_dx
if (abs(dx) <= 1.0e-7):
break
x -= dx
return x
result = map(newton, data)
print result[n - 1]
```
Here is a version of the algorithm in C++11
```
#include <iostream>
#include <vector>
#include <cmath>
int main (int argc, char const *argv[]) {
auto n = std::size_t{100000000};
auto v = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
v[k] = 1.0 + static_cast<double>(k) / n;
}
auto result = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
auto x = double{2.0};
while(true) {
auto f = double{x * x - v[k]};
auto df_dx = double{2 * x};
auto dx = double{f / df_dx};
if (std::abs(dx) <= 1.0e-7) {
break;
}
x -= dx;
}
result[k] = x;
}
auto somme = double{0.0};
for(size_t k = 0; k < result.size(); ++k) {
somme += result[k];
}
std::cout << somme << std::endl;
return 0;
}
```
It takes 2.9 seconds to run on my machine. Is there a way to make a fast Python/Numpy algorithm that does the same thing (I am willing to get something that is less than 5 times slower).
Thanks. | 2015/05/12 | [
"https://Stackoverflow.com/questions/30191851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3763545/"
] | You can do step 1. with numpy efficiently:
```
1.0 + np.arange(n + 1) / n
```
however I think you would need the np.vectorize() method to feed back x into your calculated values and it's not an efficient function (basically a wrapper for a python loop). If you can use scipy then there are built in methods that might do what you want <http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.newton.html>
EDIT: Having thought a bit more about this I followed up on @ev-br's point and tried some alternatives. The masking uses too much processing but the abs().max() is pretty fast so a compromise might be to "divide the problem into blocks" both in the 1st dimension of the array and in iteration direction. The following doesn't do too badly (< 20s) on my pretty low power laptop - certainly much faster than np.vectorize() or any of the scipy solving systems I could find. (If I set m too big it runs out of something (memory?) and grinds to a complete halt!)
```
n = 100000000
m = 5000000
block = 3
u = 1.0 + np.arange(n + 1) / n
x = np.full(u.shape, 2.0)
dx = np.ones(u.shape)
for i in range(0, n, m):
while np.abs(dx[i:i+m]).max() > 1.0e-7:
for j in range(block):
dx[i:i+m] = (x[i:i+m] ** 2 - u[i:i+m]) / (2 * x[i:i+m])
x[i:i+m] -= dx[i:i+m]
``` | Obviously I'm 6 years late to this party, but this question is a common stumbling block for people in effectively using numpy for real scientific work. The basic idea is covered in @ev-br's answer. The OP points out that the solution offered there (even modified to stop iterating when a convergence criterion is met rather than after a fixed number of iterations) takes the same number of passes for each element of u. I want to show how you can avoid that objection using pure numpy code, making explicit the mask suggestion in @ev-br's comment.
However, I also want to point out that in many real world situations, the number of passes for Newton-like iteration to converge varies so little that this general technique I illustrate here will actually slow numpy code down significantly. If the average number of iterations will be within a factor of two or three of the maximum number of iterations, you should stick with something closer to @ev-br's answer (including his first comment).
The numpy performance numbers you need to understand are these: Loops over array indices will run 200 to 500 times slower in pure numpy code than in compiled code. On the other hand, if you manage to use numpy's array syntax to avoid all index loops, you can get within about a factor of 5 of compiled speed. (The factor of 5 is partly because of memory management as @ev-br mentions, but also because optimized compiled code overlaps many different arithmetical operations inside each index loop, while numpy just performs a single arithmetic operation, storing everything back to memory after each operation.) The point is that factor of 100 difference means that it often pays to do substantial amounts of "extra" work in numpy code: Even if you do 10 times the number of floating point operations in vectorized numpy code, it will still run 10 times faster than the index-loop code that avoids the "extra" work. (Incidentally, the python map function is implemented as an interpreted index loop - it has nothing to do with numpy array operations.)
```
from numpy import asfarray, broadcast_arrays, arange
# Begin by defining the function to be inverted by Newton's method.
def f_dfdx(x):
x = asfarray(x) # always avoid repeated type conversions
return x**2, 2.*x
# First, the simplest algorithm to find x such that f(x)=y.
# We must supply a starting guess x0 for x.
def f_inverse0(f_dfdx, y, x0, tol=1.e-7):
y, x = broadcast_arrays(asfarray(y), asfarray(x0))
x = x.copy() # without this may clobber input x0
for npass in range(20):
f, dfdx = f_dfdx(x)
dx = (f - y) / dfdx
if (abs(dx) <= tol).all():
break # iterate all x until all have converged
x -= dx
else:
raise RuntimeError("failed to converge")
return x
# A frequently slower algorithm that avoids extra iterations.
def f_inverse1(f_dfdx, y, x0, tol=1.e-7):
y, x = broadcast_arrays(asfarray(y), asfarray(x0))
shape = x.shape
y, x = y.ravel(), x.flatten() # avoid clobbering x0
unconverged = arange(y.size)
for npass in range(20):
f, dfdx = f_dfdx(x[unconverged])
dx = (f - y[unconverged]) / dfdx
unc = abs(dx) > tol
unconverged = unconverged[unc]
if not unconverged.size:
break # iterate all x until all have converged
x[unconverged] -= dx[unc]
else:
raise RuntimeError("failed to converge")
return x.reshape(shape)
```
On my machine, the OP's C++ program runs in 2.03 s (1.64+0.38 user+sys). For n=100 million as for the C++ program, f\_inverse0 runs in 20.4 s (4.7+15.6 user+sys). As expected, f\_inverse1 is slower, 51.3 s (11.5+39.8 user+sys). Again, don't automatically try to minimize total operation count when you are writing numpy code. The high system overhead is probably due to heavy memory management - every vector temporary is 0.8 GB and the memory manager is struggling.
Cutting the array size to n = 1 million elements (8 MB), then multiplying the runtime by 100 brings the system time down by a large factor, f\_inverse0 now takes 16.1 s (12.5+3.6), while f\_inverse1 takes 22.3 s (16.2+5.1). This factor of 8 to 10 slower than compiled code is not unreasonable to expect for numpy performance. |
30,191,851 | I am trying to figure out if Python/Numpy is a viable alternative to develop my numerical software which is already available in C++. In order to get performance in Python/Numpy, one need to "vectorize" the code. But it turns out that as soon as I move away from very simple examples, I struggle to vectorize the code (I am not talking about SIMD instructions but "efficient Numpy code" without loops). Here is an algorithm that I want to get efficiently in Python/Numpy.
1. Create an numpy array containing: 1.0, 1.0 + 1/n, 1.0 + 2/n, ..., 2.0
2. For every u in the array, compute the root of x^2 - u, using a Newton method, stopping when |dx| <= 1.0e-7. Store the result in an array result.
3. Sum all the elements of the result array
Here is the algorithm in Python I want to speed up
```
import numpy as np
n = 1000000
data = np.arange(1.0, 2.0, 1.0 / n)
def newton(u):
x = 2.0
while True:
f = x**2 - u
df_dx = 2 * x
dx = f / df_dx
if (abs(dx) <= 1.0e-7):
break
x -= dx
return x
result = map(newton, data)
print result[n - 1]
```
Here is a version of the algorithm in C++11
```
#include <iostream>
#include <vector>
#include <cmath>
int main (int argc, char const *argv[]) {
auto n = std::size_t{100000000};
auto v = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
v[k] = 1.0 + static_cast<double>(k) / n;
}
auto result = std::vector<double>(n + 1);
for(size_t k = 0; k < v.size(); ++k) {
auto x = double{2.0};
while(true) {
auto f = double{x * x - v[k]};
auto df_dx = double{2 * x};
auto dx = double{f / df_dx};
if (std::abs(dx) <= 1.0e-7) {
break;
}
x -= dx;
}
result[k] = x;
}
auto somme = double{0.0};
for(size_t k = 0; k < result.size(); ++k) {
somme += result[k];
}
std::cout << somme << std::endl;
return 0;
}
```
It takes 2.9 seconds to run on my machine. Is there a way to make a fast Python/Numpy algorithm that does the same thing (I am willing to get something that is less than 5 times slower).
Thanks. | 2015/05/12 | [
"https://Stackoverflow.com/questions/30191851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3763545/"
] | Here's a toy example. Notice that often vectorization means writing your code as if you're manipulating numbers, and letting numpy do its magic:
```
>>> import numpy as np
>>> a = np.array([1., 2., 3.])
>>> def f(x):
... return x**2 - a, 2.*x # function and derivative
>>>
>>> def newt(f, x0):
... x = np.asarray(x0)
... for _ in range(5): # hardcode the number of iterations (I know)
... v, dv = f(x)
... x -= v / dv
... return x
>>>
>>> newt(f, [1., 1., 1.])
array([ 1. , 1.41421356, 1.73205081])
```
If this is a performance bottleneck, this is unlikely to be competetive with hand-written C++ code: First of all, you're manipulating python objects with all the overhead; then numpy is likely doing a bunch of array allocations under the hood.
An often viable strategy is to start by writing things in python/numpy, and then move bottlenecks into a compiled code --- eg Cython or C++ wrapped by Cython. In this particular case since you already have the C++ code, just wrapping it with Cython is likely easiest but YMMV. | Obviously I'm 6 years late to this party, but this question is a common stumbling block for people in effectively using numpy for real scientific work. The basic idea is covered in @ev-br's answer. The OP points out that the solution offered there (even modified to stop iterating when a convergence criterion is met rather than after a fixed number of iterations) takes the same number of passes for each element of u. I want to show how you can avoid that objection using pure numpy code, making explicit the mask suggestion in @ev-br's comment.
However, I also want to point out that in many real world situations, the number of passes for Newton-like iteration to converge varies so little that this general technique I illustrate here will actually slow numpy code down significantly. If the average number of iterations will be within a factor of two or three of the maximum number of iterations, you should stick with something closer to @ev-br's answer (including his first comment).
The numpy performance numbers you need to understand are these: Loops over array indices will run 200 to 500 times slower in pure numpy code than in compiled code. On the other hand, if you manage to use numpy's array syntax to avoid all index loops, you can get within about a factor of 5 of compiled speed. (The factor of 5 is partly because of memory management as @ev-br mentions, but also because optimized compiled code overlaps many different arithmetical operations inside each index loop, while numpy just performs a single arithmetic operation, storing everything back to memory after each operation.) The point is that factor of 100 difference means that it often pays to do substantial amounts of "extra" work in numpy code: Even if you do 10 times the number of floating point operations in vectorized numpy code, it will still run 10 times faster than the index-loop code that avoids the "extra" work. (Incidentally, the python map function is implemented as an interpreted index loop - it has nothing to do with numpy array operations.)
```
from numpy import asfarray, broadcast_arrays, arange
# Begin by defining the function to be inverted by Newton's method.
def f_dfdx(x):
x = asfarray(x) # always avoid repeated type conversions
return x**2, 2.*x
# First, the simplest algorithm to find x such that f(x)=y.
# We must supply a starting guess x0 for x.
def f_inverse0(f_dfdx, y, x0, tol=1.e-7):
y, x = broadcast_arrays(asfarray(y), asfarray(x0))
x = x.copy() # without this may clobber input x0
for npass in range(20):
f, dfdx = f_dfdx(x)
dx = (f - y) / dfdx
if (abs(dx) <= tol).all():
break # iterate all x until all have converged
x -= dx
else:
raise RuntimeError("failed to converge")
return x
# A frequently slower algorithm that avoids extra iterations.
def f_inverse1(f_dfdx, y, x0, tol=1.e-7):
y, x = broadcast_arrays(asfarray(y), asfarray(x0))
shape = x.shape
y, x = y.ravel(), x.flatten() # avoid clobbering x0
unconverged = arange(y.size)
for npass in range(20):
f, dfdx = f_dfdx(x[unconverged])
dx = (f - y[unconverged]) / dfdx
unc = abs(dx) > tol
unconverged = unconverged[unc]
if not unconverged.size:
break # iterate all x until all have converged
x[unconverged] -= dx[unc]
else:
raise RuntimeError("failed to converge")
return x.reshape(shape)
```
On my machine, the OP's C++ program runs in 2.03 s (1.64+0.38 user+sys). For n=100 million as for the C++ program, f\_inverse0 runs in 20.4 s (4.7+15.6 user+sys). As expected, f\_inverse1 is slower, 51.3 s (11.5+39.8 user+sys). Again, don't automatically try to minimize total operation count when you are writing numpy code. The high system overhead is probably due to heavy memory management - every vector temporary is 0.8 GB and the memory manager is struggling.
Cutting the array size to n = 1 million elements (8 MB), then multiplying the runtime by 100 brings the system time down by a large factor, f\_inverse0 now takes 16.1 s (12.5+3.6), while f\_inverse1 takes 22.3 s (16.2+5.1). This factor of 8 to 10 slower than compiled code is not unreasonable to expect for numpy performance. |
40,381,697 | Suppose that we perform DFS on this graph by obeying the following rules:
• Start from vertex 1.
• At every vertex, process its out-neighbors in ascending order of id.
• Whenever we need to restart, do it from the white vertex with the smallest
id
Show the resulting DFS forest. Furthermore, for every vertex, indicate its discovery time and finish time. also #/ = discovered and #/# = finished
[](https://i.stack.imgur.com/sXPng.png)
dfs tree as follows:
```
6
|
1--2--7--3--4--5--8
```
the question ask me to show the resulting forest, yet I'm only producing one tree, what have i done wrong? | 2016/11/02 | [
"https://Stackoverflow.com/questions/40381697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6821180/"
] | You need an `except` clause to use `else`:
>
> The `try ... except` statement has an optional `else` clause, which, when
> present, must **follow** all `except` clauses
> [*Emphasis mine*]
>
>
> | I just saw it from the python document page, so I'm just gonna quote what it says to you:
>
> The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:
>
>
>
> ```
> for arg in sys.argv[1:]:
> try:
> f = open(arg, 'r')
> except IOError:
> print('cannot open', arg)
> else:
> print(arg, 'has', len(f.readlines()), 'lines')
> f.close()
>
> ```
>
> |
57,546,337 | I want to open a file (`file`) that is stored in a folder (`Source`) which is in the same directory as the current workbook. I get a runtime error 1004 indicating that it the file can't be located. What am I doing worng?
```
Set x = Workbooks.Open(ThisWorkbook.Path & "\Source\file*.xlsx")
``` | 2019/08/18 | [
"https://Stackoverflow.com/questions/57546337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435347/"
] | Since you want the wildcard to stay, you need to loop through the files in the folder. Something like this may be of interest to you:
```
Sub FileOpen()
Dim sPath As String
Dim sFile As String
Dim wb As Workbook
sPath = ThisWorkbook.Path & "\Source\"
sFile = Dir(sPath & "file*.xlsx")
' Loops while there is a next file found in the specified directory
' When there is no next file the Dir() returns an empty string ""
Do While sFile <> ""
' Prints the full path of the found file
Debug.Print sPath & sFile
' Opens the currently found file
Set wb = Workbooks.Open(sPath & sFile)
' Place your code here
' Place your code here
' Place your code here
' Close the current workbook and move on to the next
wb.Close
' This line calls the Dir() function again to get the next file
sFile = Dir()
Loop
End Sub
```
Good luck! | Replace the wildcard with actual filename. |
57,546,337 | I want to open a file (`file`) that is stored in a folder (`Source`) which is in the same directory as the current workbook. I get a runtime error 1004 indicating that it the file can't be located. What am I doing worng?
```
Set x = Workbooks.Open(ThisWorkbook.Path & "\Source\file*.xlsx")
``` | 2019/08/18 | [
"https://Stackoverflow.com/questions/57546337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435347/"
] | Since you want the wildcard to stay, you need to loop through the files in the folder. Something like this may be of interest to you:
```
Sub FileOpen()
Dim sPath As String
Dim sFile As String
Dim wb As Workbook
sPath = ThisWorkbook.Path & "\Source\"
sFile = Dir(sPath & "file*.xlsx")
' Loops while there is a next file found in the specified directory
' When there is no next file the Dir() returns an empty string ""
Do While sFile <> ""
' Prints the full path of the found file
Debug.Print sPath & sFile
' Opens the currently found file
Set wb = Workbooks.Open(sPath & sFile)
' Place your code here
' Place your code here
' Place your code here
' Close the current workbook and move on to the next
wb.Close
' This line calls the Dir() function again to get the next file
sFile = Dir()
Loop
End Sub
```
Good luck! | Set x = Workbooks.Open(ThisWorkbook.Path & "\Source\file.xlsx"
I changed the file\*.xlsx to file. xlsx...hope your code works.
thanks. |
37,242,600 | I'm struggling with this and I'm not so clear about it.
Let's say I have a function in a class:
```
class my_class(osv.Model):
_name = 'my_class'
_description = 'my description'
def func (self, cr, uid, ids, name, arg, context=None):
res = dict((id, 0) for id in ids)
sur_res_obj = self.pool.get('contratos.user_input')
for id in ids:
res[id] = sur_res_obj.search(cr, uid, # SUPERUSER_ID,
[('contratos_id', '=', id), ('state', '=', 'done')],
context=context, count=True)
return res
columns = {
'function': fields.function(_get_func,
string="Number of completed Contratos", type="integer"),
my_class()
```
Now I want to call this very same function from another class-object:
```
class another_class(osv.Model):
_inherit = 'my_class'
_name = 'my_class'
columns = {
'another_field' : fields.related('function', 'state', type='char', string = "Related field which calls a function from another object"),
}
```
But this isn't working, I'm very confused about this, how can I call a function from another object in Odoov8?
I've heard about `self.pool.get` but I'm not really sure on how to invoke it.
Any ideas?
Thanks in advance! | 2016/05/15 | [
"https://Stackoverflow.com/questions/37242600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089267/"
] | Since you're using odoo8 you should use the new API. from the docs
>
> In the new API the notion of Environment is introduced. Its main
> objective is to provide an encapsulation around cursor, user\_id,
> model, and context, Recordset and caches
>
>
>
```
def my_func(self):
other_object = self.env['another_class']
other_object.create(vals) # just using create as an example
```
That means you don't need to explicity pass `cr`, `uid`, `ids`, `vals` and `context` in your methods anymore and you don't use `self.pool.get()` even though it's still there for backward compatibility
`env` is dictionary-like object that is used to store instances of the Odoo models and other information so you can access other objects and their methods from any Odoo model. | ```
def example(self, cr, uid, ids, context=None):
otherClass = self.pool.get('my_class')
...
otherClass.func(cr, uid, otherClassIds, name, arg, context)
```
[More information.](http://abhishek-jaiswal.github.io/blog/odoov8/2014/11/15/odoo-v8-decorator.html) |
37,916,763 | I need to remove a string ("DTE\_Field\_") from the id of elements in the dom.
```
<select id="DTE_Field_CD_PAIS" dependent-group="PAIS" dependent-group-level="1" class="form-control"></select>
var str=$(el).attr("id");
str.replace("DTE_Field_","");
``` | 2016/06/20 | [
"https://Stackoverflow.com/questions/37916763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883099/"
] | Use [**`attr()`** method with callback](http://api.jquery.com/attr/#attr-attributeName-function). That will iterate over element and you can get old attribute value as callback argument you can update attribute by returning string where `DTE_FIELD` using **[`String#replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)** method.
```
$('select').attr('id', function(i, oldId) {
return oldId.replace('DTE_field_', '');
});
```
```js
$('select').attr('id', function(i, oldId) {
return oldId.replace('DTE_Field_', '');
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="DTE_Field_CD_PAIS" dependent-group="PAIS" dependent-group-level="1" class="form-control"></select>
```
---
If the element is not always select then you can use **[`attribute contains selector`](https://api.jquery.com/attribute-contains-selector/)**(or if `DTE_field_` is always at the beginning then use **[`attribute starts with selector`](https://api.jquery.com/attribute-starts-with-selector/)**).
```
$('[id*="DTE_field_"]').attr('id', function(i, oldId) {
return oldId.replace('DTE_field_', '');
});
``` | ```
$('[id^="DTE_FIELD_"]').each(function () {
$(this).attr('id', $(this).attr('id').replace('DTE_FIELD_',''));
});
``` |
37,916,763 | I need to remove a string ("DTE\_Field\_") from the id of elements in the dom.
```
<select id="DTE_Field_CD_PAIS" dependent-group="PAIS" dependent-group-level="1" class="form-control"></select>
var str=$(el).attr("id");
str.replace("DTE_Field_","");
``` | 2016/06/20 | [
"https://Stackoverflow.com/questions/37916763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883099/"
] | You can split the string(`id`) and use `pop()` method to get the last element of the array
```
var str=$('#DTE_Field_CD_PAIS').attr("id");
alert(str.split("DTE_Field_").pop());
```
[**JSFIDDLE**](https://jsfiddle.net/vasi_32/g6Lu7ywr/1/) | ```
$('[id^="DTE_FIELD_"]').each(function () {
$(this).attr('id', $(this).attr('id').replace('DTE_FIELD_',''));
});
``` |
37,916,763 | I need to remove a string ("DTE\_Field\_") from the id of elements in the dom.
```
<select id="DTE_Field_CD_PAIS" dependent-group="PAIS" dependent-group-level="1" class="form-control"></select>
var str=$(el).attr("id");
str.replace("DTE_Field_","");
``` | 2016/06/20 | [
"https://Stackoverflow.com/questions/37916763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1883099/"
] | Use like this:
```
var string=$('#DTE_Field_CD_PAIS').attr("id");
console.log(str.split("DTE_Field_").pop());
``` | ```
$('[id^="DTE_FIELD_"]').each(function () {
$(this).attr('id', $(this).attr('id').replace('DTE_FIELD_',''));
});
``` |
2,880,293 | $$I=\large \int\_{0}^{\infty}\left(x^2-3x+1\right)e^{-x}\ln^3(x)\mathrm dx$$
$$e^{-x}=\sum\_{n=0}^{\infty}\frac{(-x)^n}{n!}$$
$$I=\large \sum\_{n=0}^{\infty}\frac{(-1)^n}{n!}\int\_{0}^{\infty}\left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
$$J=\int \left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
We can evaluate $J$ by integration by parts but problem, the limits does not work.
**How to evaluate integral $I?$** | 2018/08/12 | [
"https://math.stackexchange.com/questions/2880293",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Here's a way that only requires the identity $\Gamma'(1) = - \gamma$ , since all derivatives of higher order cancel:
\begin{align}
I &=\int \limits\_0^\infty (x^2 - 3x+1) \ln^3 (x) \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \left[\frac{\mathrm{d}^2}{\mathrm{d} t^2} + 3 \frac{\mathrm{d}}{\mathrm{d}t}+1 \right] \int \limits\_0^\infty \ln^3 (x) \mathrm{e}^{- t x} \, \mathrm{d} x ~\Bigg\vert\_{t=1}\\
&= \left[\frac{\mathrm{d}^2}{\mathrm{d} t^2} + 3 \frac{\mathrm{d}}{\mathrm{d}t}+1 \right] \frac{1}{t} \int \limits\_0^\infty \left[\ln^3 (y) - 3 \ln^2(y) \ln(t) + 3 \ln(y) \ln^2(t) - \ln^3 (t)\right] \mathrm{e}^{-y} \, \mathrm{d} y ~\Bigg\vert\_{t=1}\\
&= \left[\frac{\mathrm{d}^2}{\mathrm{d} t^2} + 3 \frac{\mathrm{d}}{\mathrm{d}t}+1 \right] \frac{1}{t} \left[\Gamma'''(1) - 3 \Gamma''(1) \ln(t) + 3 \Gamma'(1) \ln^2(t) - \ln^3 (t)\right] ~\Bigg\vert\_{t=1} \\
&= 2 \Gamma'''(1) + 6 \Gamma''(1) + 3 \Gamma''(1) + 6 \Gamma'(1) - 3 \Gamma'''(1) - 9 \Gamma''(1) + \Gamma'''(1) \\
&= 6 \Gamma'(1)\\
&= - 6 \gamma \, .
\end{align}
In fact, integration by parts yields the following generalisation:
\begin{align}
\gamma &= \int \limits\_0^\infty (-\ln (x)) \mathrm{e}^{-x} \, \mathrm{d} x
= \int \limits\_0^\infty \frac{-\ln (x)}{x} x \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \int \limits\_0^\infty (-\ln (x))^2 \frac{1-x}{2} \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \int \limits\_0^\infty (-\ln (x))^3 \frac{x^2 - 3x +1}{6} \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \dots \, \\
&= \int \limits\_0^\infty (-\ln (x))^{n+1} \frac{p\_n (x)}{(n+1)!} \mathrm{e}^{-x} \, \mathrm{d} x \, .
\end{align}
The polynomials $p\_n$ are defined recursively by $p\_0(x) = 1$ and
$$p\_n (x) = \mathrm{e}^{x} \frac{\mathrm{d}}{\mathrm{d}x} \left(x p\_{n-1} (x) \mathrm{e}^{-x}\right) \, , \, n \in \mathbb{N} \, ,$$
for $x \in \mathbb{R}$ . The exponential generating function
$$ \sum \limits\_{n=0}^\infty \frac{p\_n(x)}{n!} t^n = \mathrm{e}^{t+x(1-\mathrm{e}^t)}$$
can actually be computed from a PDE and it turns out that the polynomials are given by
$$p\_n(x) = \frac{B\_{n+1}(-x)}{-x} \, , \, x \in \mathbb{R} \, , \, n \in \mathbb{N}\_0 \, , $$
where $(B\_k)\_{k \in \mathbb{N}\_0}$ are the [Bell](http://mathworld.wolfram.com/BellPolynomial.html) or [Touchard](https://en.wikipedia.org/wiki/Touchard_polynomials) polynomials. | Though it's not good practice, we will ignore any constants when evaluating indefinite integrals, as the end result is definite.
**Step I:**
Let's start with the integral $$G\_1=\int\ln x\,dx=x(\ln x-1).$$ Integration by parts gives $$G\_2=\int\ln^2x\,dx=[x\ln x(\ln x-1)]-\int(\ln x-1)\,dx=x(\ln^2x-2\ln x+2)$$ and similarly, $$G\_3=\int\ln^3x\,dx=x(\ln^3x-3\ln^2x+6\ln x-6)$$
**Step II:**
Consider the integral $$H\_1=\int\frac{\ln x}{e^x}\,dx.$$ Integration by parts gives $$H\_1=\left[\frac{G\_1}{e^x}\right]+\int\frac{x(\ln x-1)}{e^x}\,dx\implies I\_1=\int\frac{x\ln x}{e^x}\,dx=H\_1-\frac{G\_1}{e^x}+\int\frac x{e^x}\,dx$$ Similarly, if we denote $I\_n$ as the integral of $xe^{-x}\ln^nx$ and $H\_n$ as the integral of $e^{-x}\ln^nx$, we get $$I\_2=H\_2-\frac{G\_2}{e^x}+2I\_1-2\int\frac x{e^x}\,dx$$ and $$I\_3=H\_3-\frac{G\_3}{e^x}+3I\_2-6I\_1+6\int\frac x{e^x}\,dx$$ which can be written as $$I\_3=H\_3+3H\_2-\frac1{e^x}(G\_3-3G\_2)$$
**Step III:**
Now integrate by parts $I\_3$. We will integrate the polynomial part of the integrand ($x$) and differentiate the rest ($e^{-x}\ln^3x$). So $$I\_3=\left[\frac{x^2\ln^3x}{2e^x}\right]-\int\frac{x\ln^2x(3-x\ln x)}{2e^x}\,dx=\frac{x^2\ln^3x}{2e^x}-\frac32I\_2+\frac12\int\frac{x^2\ln^3x}{e^x}\,dx$$ giving $$J\_3=\int\frac{x^2\ln^3x}{e^x}\,dx=2I\_3+3I\_2-\frac{x^2\ln^3x}{e^x}$$ Hence your indefinite integral is $$K=\int\frac{(x^2-3x+1)\ln^3x}{e^x}\,dx=J\_3-3I\_3+H\_3=\frac1{e^x}(G\_3-3G\_2-x^2\ln^3x)+3H\_2$$ |
2,880,293 | $$I=\large \int\_{0}^{\infty}\left(x^2-3x+1\right)e^{-x}\ln^3(x)\mathrm dx$$
$$e^{-x}=\sum\_{n=0}^{\infty}\frac{(-x)^n}{n!}$$
$$I=\large \sum\_{n=0}^{\infty}\frac{(-1)^n}{n!}\int\_{0}^{\infty}\left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
$$J=\int \left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
We can evaluate $J$ by integration by parts but problem, the limits does not work.
**How to evaluate integral $I?$** | 2018/08/12 | [
"https://math.stackexchange.com/questions/2880293",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Though it's not good practice, we will ignore any constants when evaluating indefinite integrals, as the end result is definite.
**Step I:**
Let's start with the integral $$G\_1=\int\ln x\,dx=x(\ln x-1).$$ Integration by parts gives $$G\_2=\int\ln^2x\,dx=[x\ln x(\ln x-1)]-\int(\ln x-1)\,dx=x(\ln^2x-2\ln x+2)$$ and similarly, $$G\_3=\int\ln^3x\,dx=x(\ln^3x-3\ln^2x+6\ln x-6)$$
**Step II:**
Consider the integral $$H\_1=\int\frac{\ln x}{e^x}\,dx.$$ Integration by parts gives $$H\_1=\left[\frac{G\_1}{e^x}\right]+\int\frac{x(\ln x-1)}{e^x}\,dx\implies I\_1=\int\frac{x\ln x}{e^x}\,dx=H\_1-\frac{G\_1}{e^x}+\int\frac x{e^x}\,dx$$ Similarly, if we denote $I\_n$ as the integral of $xe^{-x}\ln^nx$ and $H\_n$ as the integral of $e^{-x}\ln^nx$, we get $$I\_2=H\_2-\frac{G\_2}{e^x}+2I\_1-2\int\frac x{e^x}\,dx$$ and $$I\_3=H\_3-\frac{G\_3}{e^x}+3I\_2-6I\_1+6\int\frac x{e^x}\,dx$$ which can be written as $$I\_3=H\_3+3H\_2-\frac1{e^x}(G\_3-3G\_2)$$
**Step III:**
Now integrate by parts $I\_3$. We will integrate the polynomial part of the integrand ($x$) and differentiate the rest ($e^{-x}\ln^3x$). So $$I\_3=\left[\frac{x^2\ln^3x}{2e^x}\right]-\int\frac{x\ln^2x(3-x\ln x)}{2e^x}\,dx=\frac{x^2\ln^3x}{2e^x}-\frac32I\_2+\frac12\int\frac{x^2\ln^3x}{e^x}\,dx$$ giving $$J\_3=\int\frac{x^2\ln^3x}{e^x}\,dx=2I\_3+3I\_2-\frac{x^2\ln^3x}{e^x}$$ Hence your indefinite integral is $$K=\int\frac{(x^2-3x+1)\ln^3x}{e^x}\,dx=J\_3-3I\_3+H\_3=\frac1{e^x}(G\_3-3G\_2-x^2\ln^3x)+3H\_2$$ | The form of the integral takes on the form of the product of a power function, $e^{-x}$, and an integer power of a logarithm. This allows us to consider the integral
$$ \int\_{0}^{\infty}x^{s-1+\epsilon}\,e^{-x}\,\mathrm{d}x = \int\_{0}^{\infty}x^{s-1}e^{\epsilon\ln x}\,e^{-x}\,\mathrm{d}x = \sum\_{n=0}^{\infty}\frac{\epsilon^{n}}{n!}\int\_{0}^{\infty}x^{s-1}\,e^{-x}\,\ln^{n}x\,\mathrm{d}x. $$
Using the gamma function, this integral is also
$$ \int\_{0}^{\infty}x^{s-1+\epsilon}\,e^{-x}\,\mathrm{d}x = \Gamma(s + \epsilon). $$
Using the recursion relation, we may write this in terms of $\Gamma(1+\epsilon)$, which we have a Taylor series expansion for. For example, with $x^{2}$ in the integrand, $s = 3$, so we get $\Gamma(3+\epsilon) = (2+\epsilon)(1+\epsilon)\Gamma(1+\epsilon)$.
We have rewritten our integral as a coefficient in a series expansion. Our integral needs the coefficient of $\epsilon^{3}$ to get the integral with $\ln^{3}x$. We therefore have to obtain the corresponding $\epsilon^{3}$ coefficient in the expansion of the gamma function $\Gamma(1+\epsilon)$.
The usual way of tackling this integral would be to consider the three terms separately and then keep the appropriate terms, but we can do better by evaluating the gamma function terms directly first, which contribute in the following manner:
$$\begin{align} x^{2} - 3x + 1 &\to \Gamma(3 + \epsilon) - 3\Gamma(2+\epsilon) + \Gamma(1+\epsilon) \\
&\to \left((2+\epsilon)(1+\epsilon) - 3(1+\epsilon) + 1\right)\Gamma(1+\epsilon) \\
&\to \epsilon^{2}\,\Gamma(1 + \epsilon). \end{align}$$
Since all that is left is an $\epsilon^{2}$ out in front, we only need keep terms up to first order in $\epsilon$ in the expansion of the gamma function (where $\gamma$ is the Euler-Mascheroni constant and $\zeta(s)$ is the Riemann zeta function)
$$\begin{align} \ln\Gamma(1 + \epsilon) &= -\gamma\epsilon + \sum\_{k=2}^{\infty}\frac{(-1)^{k}\zeta(k)}{k}\epsilon^{k} \\
\Gamma(1 + \epsilon) &\approx e^{-\gamma\epsilon} \approx 1 - \gamma\epsilon. \end{align}$$
Our coefficient is therefore $-\gamma$. Remembering to multiply by $3! = 6$ to account for the factorial in the original series expansion, our answer is
$$ \int\_{0}^{\infty}\left(x^{2} - 3x + 1\right)e^{-x}\ln^{3}x\,\mathrm{d}x = -6\gamma. $$ |
2,880,293 | $$I=\large \int\_{0}^{\infty}\left(x^2-3x+1\right)e^{-x}\ln^3(x)\mathrm dx$$
$$e^{-x}=\sum\_{n=0}^{\infty}\frac{(-x)^n}{n!}$$
$$I=\large \sum\_{n=0}^{\infty}\frac{(-1)^n}{n!}\int\_{0}^{\infty}\left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
$$J=\int \left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
We can evaluate $J$ by integration by parts but problem, the limits does not work.
**How to evaluate integral $I?$** | 2018/08/12 | [
"https://math.stackexchange.com/questions/2880293",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Here's a way that only requires the identity $\Gamma'(1) = - \gamma$ , since all derivatives of higher order cancel:
\begin{align}
I &=\int \limits\_0^\infty (x^2 - 3x+1) \ln^3 (x) \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \left[\frac{\mathrm{d}^2}{\mathrm{d} t^2} + 3 \frac{\mathrm{d}}{\mathrm{d}t}+1 \right] \int \limits\_0^\infty \ln^3 (x) \mathrm{e}^{- t x} \, \mathrm{d} x ~\Bigg\vert\_{t=1}\\
&= \left[\frac{\mathrm{d}^2}{\mathrm{d} t^2} + 3 \frac{\mathrm{d}}{\mathrm{d}t}+1 \right] \frac{1}{t} \int \limits\_0^\infty \left[\ln^3 (y) - 3 \ln^2(y) \ln(t) + 3 \ln(y) \ln^2(t) - \ln^3 (t)\right] \mathrm{e}^{-y} \, \mathrm{d} y ~\Bigg\vert\_{t=1}\\
&= \left[\frac{\mathrm{d}^2}{\mathrm{d} t^2} + 3 \frac{\mathrm{d}}{\mathrm{d}t}+1 \right] \frac{1}{t} \left[\Gamma'''(1) - 3 \Gamma''(1) \ln(t) + 3 \Gamma'(1) \ln^2(t) - \ln^3 (t)\right] ~\Bigg\vert\_{t=1} \\
&= 2 \Gamma'''(1) + 6 \Gamma''(1) + 3 \Gamma''(1) + 6 \Gamma'(1) - 3 \Gamma'''(1) - 9 \Gamma''(1) + \Gamma'''(1) \\
&= 6 \Gamma'(1)\\
&= - 6 \gamma \, .
\end{align}
In fact, integration by parts yields the following generalisation:
\begin{align}
\gamma &= \int \limits\_0^\infty (-\ln (x)) \mathrm{e}^{-x} \, \mathrm{d} x
= \int \limits\_0^\infty \frac{-\ln (x)}{x} x \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \int \limits\_0^\infty (-\ln (x))^2 \frac{1-x}{2} \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \int \limits\_0^\infty (-\ln (x))^3 \frac{x^2 - 3x +1}{6} \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \dots \, \\
&= \int \limits\_0^\infty (-\ln (x))^{n+1} \frac{p\_n (x)}{(n+1)!} \mathrm{e}^{-x} \, \mathrm{d} x \, .
\end{align}
The polynomials $p\_n$ are defined recursively by $p\_0(x) = 1$ and
$$p\_n (x) = \mathrm{e}^{x} \frac{\mathrm{d}}{\mathrm{d}x} \left(x p\_{n-1} (x) \mathrm{e}^{-x}\right) \, , \, n \in \mathbb{N} \, ,$$
for $x \in \mathbb{R}$ . The exponential generating function
$$ \sum \limits\_{n=0}^\infty \frac{p\_n(x)}{n!} t^n = \mathrm{e}^{t+x(1-\mathrm{e}^t)}$$
can actually be computed from a PDE and it turns out that the polynomials are given by
$$p\_n(x) = \frac{B\_{n+1}(-x)}{-x} \, , \, x \in \mathbb{R} \, , \, n \in \mathbb{N}\_0 \, , $$
where $(B\_k)\_{k \in \mathbb{N}\_0}$ are the [Bell](http://mathworld.wolfram.com/BellPolynomial.html) or [Touchard](https://en.wikipedia.org/wiki/Touchard_polynomials) polynomials. | It is pretty straightforward to differentiate three times
$$ \int\_{0}^{+\infty}(x^2-3x+1)x^s e^{-x}\,dx = s^2\,\Gamma(s+1)$$
then consider the limit as $s\to 0^+$. The final outcome is $\color{red}{-6\,\gamma}=6\,\Gamma'(1)$ since $s^2\,\Gamma(s+1)$ clearly has a zero of order $2$ at the origin. |
2,880,293 | $$I=\large \int\_{0}^{\infty}\left(x^2-3x+1\right)e^{-x}\ln^3(x)\mathrm dx$$
$$e^{-x}=\sum\_{n=0}^{\infty}\frac{(-x)^n}{n!}$$
$$I=\large \sum\_{n=0}^{\infty}\frac{(-1)^n}{n!}\int\_{0}^{\infty}\left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
$$J=\int \left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
We can evaluate $J$ by integration by parts but problem, the limits does not work.
**How to evaluate integral $I?$** | 2018/08/12 | [
"https://math.stackexchange.com/questions/2880293",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | Here's a way that only requires the identity $\Gamma'(1) = - \gamma$ , since all derivatives of higher order cancel:
\begin{align}
I &=\int \limits\_0^\infty (x^2 - 3x+1) \ln^3 (x) \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \left[\frac{\mathrm{d}^2}{\mathrm{d} t^2} + 3 \frac{\mathrm{d}}{\mathrm{d}t}+1 \right] \int \limits\_0^\infty \ln^3 (x) \mathrm{e}^{- t x} \, \mathrm{d} x ~\Bigg\vert\_{t=1}\\
&= \left[\frac{\mathrm{d}^2}{\mathrm{d} t^2} + 3 \frac{\mathrm{d}}{\mathrm{d}t}+1 \right] \frac{1}{t} \int \limits\_0^\infty \left[\ln^3 (y) - 3 \ln^2(y) \ln(t) + 3 \ln(y) \ln^2(t) - \ln^3 (t)\right] \mathrm{e}^{-y} \, \mathrm{d} y ~\Bigg\vert\_{t=1}\\
&= \left[\frac{\mathrm{d}^2}{\mathrm{d} t^2} + 3 \frac{\mathrm{d}}{\mathrm{d}t}+1 \right] \frac{1}{t} \left[\Gamma'''(1) - 3 \Gamma''(1) \ln(t) + 3 \Gamma'(1) \ln^2(t) - \ln^3 (t)\right] ~\Bigg\vert\_{t=1} \\
&= 2 \Gamma'''(1) + 6 \Gamma''(1) + 3 \Gamma''(1) + 6 \Gamma'(1) - 3 \Gamma'''(1) - 9 \Gamma''(1) + \Gamma'''(1) \\
&= 6 \Gamma'(1)\\
&= - 6 \gamma \, .
\end{align}
In fact, integration by parts yields the following generalisation:
\begin{align}
\gamma &= \int \limits\_0^\infty (-\ln (x)) \mathrm{e}^{-x} \, \mathrm{d} x
= \int \limits\_0^\infty \frac{-\ln (x)}{x} x \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \int \limits\_0^\infty (-\ln (x))^2 \frac{1-x}{2} \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \int \limits\_0^\infty (-\ln (x))^3 \frac{x^2 - 3x +1}{6} \mathrm{e}^{-x} \, \mathrm{d} x \\
&= \dots \, \\
&= \int \limits\_0^\infty (-\ln (x))^{n+1} \frac{p\_n (x)}{(n+1)!} \mathrm{e}^{-x} \, \mathrm{d} x \, .
\end{align}
The polynomials $p\_n$ are defined recursively by $p\_0(x) = 1$ and
$$p\_n (x) = \mathrm{e}^{x} \frac{\mathrm{d}}{\mathrm{d}x} \left(x p\_{n-1} (x) \mathrm{e}^{-x}\right) \, , \, n \in \mathbb{N} \, ,$$
for $x \in \mathbb{R}$ . The exponential generating function
$$ \sum \limits\_{n=0}^\infty \frac{p\_n(x)}{n!} t^n = \mathrm{e}^{t+x(1-\mathrm{e}^t)}$$
can actually be computed from a PDE and it turns out that the polynomials are given by
$$p\_n(x) = \frac{B\_{n+1}(-x)}{-x} \, , \, x \in \mathbb{R} \, , \, n \in \mathbb{N}\_0 \, , $$
where $(B\_k)\_{k \in \mathbb{N}\_0}$ are the [Bell](http://mathworld.wolfram.com/BellPolynomial.html) or [Touchard](https://en.wikipedia.org/wiki/Touchard_polynomials) polynomials. | The form of the integral takes on the form of the product of a power function, $e^{-x}$, and an integer power of a logarithm. This allows us to consider the integral
$$ \int\_{0}^{\infty}x^{s-1+\epsilon}\,e^{-x}\,\mathrm{d}x = \int\_{0}^{\infty}x^{s-1}e^{\epsilon\ln x}\,e^{-x}\,\mathrm{d}x = \sum\_{n=0}^{\infty}\frac{\epsilon^{n}}{n!}\int\_{0}^{\infty}x^{s-1}\,e^{-x}\,\ln^{n}x\,\mathrm{d}x. $$
Using the gamma function, this integral is also
$$ \int\_{0}^{\infty}x^{s-1+\epsilon}\,e^{-x}\,\mathrm{d}x = \Gamma(s + \epsilon). $$
Using the recursion relation, we may write this in terms of $\Gamma(1+\epsilon)$, which we have a Taylor series expansion for. For example, with $x^{2}$ in the integrand, $s = 3$, so we get $\Gamma(3+\epsilon) = (2+\epsilon)(1+\epsilon)\Gamma(1+\epsilon)$.
We have rewritten our integral as a coefficient in a series expansion. Our integral needs the coefficient of $\epsilon^{3}$ to get the integral with $\ln^{3}x$. We therefore have to obtain the corresponding $\epsilon^{3}$ coefficient in the expansion of the gamma function $\Gamma(1+\epsilon)$.
The usual way of tackling this integral would be to consider the three terms separately and then keep the appropriate terms, but we can do better by evaluating the gamma function terms directly first, which contribute in the following manner:
$$\begin{align} x^{2} - 3x + 1 &\to \Gamma(3 + \epsilon) - 3\Gamma(2+\epsilon) + \Gamma(1+\epsilon) \\
&\to \left((2+\epsilon)(1+\epsilon) - 3(1+\epsilon) + 1\right)\Gamma(1+\epsilon) \\
&\to \epsilon^{2}\,\Gamma(1 + \epsilon). \end{align}$$
Since all that is left is an $\epsilon^{2}$ out in front, we only need keep terms up to first order in $\epsilon$ in the expansion of the gamma function (where $\gamma$ is the Euler-Mascheroni constant and $\zeta(s)$ is the Riemann zeta function)
$$\begin{align} \ln\Gamma(1 + \epsilon) &= -\gamma\epsilon + \sum\_{k=2}^{\infty}\frac{(-1)^{k}\zeta(k)}{k}\epsilon^{k} \\
\Gamma(1 + \epsilon) &\approx e^{-\gamma\epsilon} \approx 1 - \gamma\epsilon. \end{align}$$
Our coefficient is therefore $-\gamma$. Remembering to multiply by $3! = 6$ to account for the factorial in the original series expansion, our answer is
$$ \int\_{0}^{\infty}\left(x^{2} - 3x + 1\right)e^{-x}\ln^{3}x\,\mathrm{d}x = -6\gamma. $$ |
2,880,293 | $$I=\large \int\_{0}^{\infty}\left(x^2-3x+1\right)e^{-x}\ln^3(x)\mathrm dx$$
$$e^{-x}=\sum\_{n=0}^{\infty}\frac{(-x)^n}{n!}$$
$$I=\large \sum\_{n=0}^{\infty}\frac{(-1)^n}{n!}\int\_{0}^{\infty}\left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
$$J=\int \left(x^2-3x+1\right)x^n\ln^3(x)\mathrm dx$$
We can evaluate $J$ by integration by parts but problem, the limits does not work.
**How to evaluate integral $I?$** | 2018/08/12 | [
"https://math.stackexchange.com/questions/2880293",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | It is pretty straightforward to differentiate three times
$$ \int\_{0}^{+\infty}(x^2-3x+1)x^s e^{-x}\,dx = s^2\,\Gamma(s+1)$$
then consider the limit as $s\to 0^+$. The final outcome is $\color{red}{-6\,\gamma}=6\,\Gamma'(1)$ since $s^2\,\Gamma(s+1)$ clearly has a zero of order $2$ at the origin. | The form of the integral takes on the form of the product of a power function, $e^{-x}$, and an integer power of a logarithm. This allows us to consider the integral
$$ \int\_{0}^{\infty}x^{s-1+\epsilon}\,e^{-x}\,\mathrm{d}x = \int\_{0}^{\infty}x^{s-1}e^{\epsilon\ln x}\,e^{-x}\,\mathrm{d}x = \sum\_{n=0}^{\infty}\frac{\epsilon^{n}}{n!}\int\_{0}^{\infty}x^{s-1}\,e^{-x}\,\ln^{n}x\,\mathrm{d}x. $$
Using the gamma function, this integral is also
$$ \int\_{0}^{\infty}x^{s-1+\epsilon}\,e^{-x}\,\mathrm{d}x = \Gamma(s + \epsilon). $$
Using the recursion relation, we may write this in terms of $\Gamma(1+\epsilon)$, which we have a Taylor series expansion for. For example, with $x^{2}$ in the integrand, $s = 3$, so we get $\Gamma(3+\epsilon) = (2+\epsilon)(1+\epsilon)\Gamma(1+\epsilon)$.
We have rewritten our integral as a coefficient in a series expansion. Our integral needs the coefficient of $\epsilon^{3}$ to get the integral with $\ln^{3}x$. We therefore have to obtain the corresponding $\epsilon^{3}$ coefficient in the expansion of the gamma function $\Gamma(1+\epsilon)$.
The usual way of tackling this integral would be to consider the three terms separately and then keep the appropriate terms, but we can do better by evaluating the gamma function terms directly first, which contribute in the following manner:
$$\begin{align} x^{2} - 3x + 1 &\to \Gamma(3 + \epsilon) - 3\Gamma(2+\epsilon) + \Gamma(1+\epsilon) \\
&\to \left((2+\epsilon)(1+\epsilon) - 3(1+\epsilon) + 1\right)\Gamma(1+\epsilon) \\
&\to \epsilon^{2}\,\Gamma(1 + \epsilon). \end{align}$$
Since all that is left is an $\epsilon^{2}$ out in front, we only need keep terms up to first order in $\epsilon$ in the expansion of the gamma function (where $\gamma$ is the Euler-Mascheroni constant and $\zeta(s)$ is the Riemann zeta function)
$$\begin{align} \ln\Gamma(1 + \epsilon) &= -\gamma\epsilon + \sum\_{k=2}^{\infty}\frac{(-1)^{k}\zeta(k)}{k}\epsilon^{k} \\
\Gamma(1 + \epsilon) &\approx e^{-\gamma\epsilon} \approx 1 - \gamma\epsilon. \end{align}$$
Our coefficient is therefore $-\gamma$. Remembering to multiply by $3! = 6$ to account for the factorial in the original series expansion, our answer is
$$ \int\_{0}^{\infty}\left(x^{2} - 3x + 1\right)e^{-x}\ln^{3}x\,\mathrm{d}x = -6\gamma. $$ |
16,124,667 | Hi i am working in java and want to know how String objects are created in the String pool
and how they are managed.
So in the following example i am creating two Strings s and s1,so can anyone explain me how many Objects are created in LIne1?Also how many Objects are eligible for garbage collection in Line3?
```
String s = "x" + "y";//Line 1
String s1 = s;//Line 2
s = null;//Line 3
``` | 2013/04/20 | [
"https://Stackoverflow.com/questions/16124667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2303011/"
] | Only one object is created `"xy"` . compiler does it for optimization.
No object is eligible for garbage collection. | It would create one object `xy` in the String constant pool area. As `"x"+"y"` would be evaluated during compilation. Additionally, garbage collector cannot access String constant pool area.
Reference: <https://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5> |
19,423,030 | I am using c# MVC 4 and have embedded a Report Viewer aspx page to render reports from SSRS. I am using Sql Server 2008R2, Microsoft.ReportViewer.WebForms version 11.0.
Firstly the issue I am facing,
I am using session variables within the project to hold values relative to the site. These have nothing to do with SSRS, for example UserId.
In the web.config I have
Note: The timeout is set ridiculously high for this testing scenario.
Simarlarly I have updated ConfigurationInfo in the ReportServer database for the key SessionTimeout to 60 (again ridiculous value to test with).
My ReportViewer code is as follows to open the :
```
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ReportViewer1.Reset();
string Reportpath = Request["ReportName"];
string ServerUserName = ConfigurationManager.AppSettings["ReportServerUser"];
string ServerPassword = ConfigurationManager.AppSettings["ReportServerPwd"];
string ReportServerDomain = ConfigurationManager.AppSettings["ReportServerDomain"];
string ReportsPath = ConfigurationManager.AppSettings["ReportsPath"];
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
// Get report path from configuration file
ReportViewer1.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["ReportServer"]);
ReportViewer1.ServerReport.ReportPath = String.Format(ReportsPath + "/" + Reportpath);
IReportServerCredentials irsc = new CustomReportCredentials(ServerUserName, ServerPassword, ReportServerDomain);
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
ReportViewer1.ShowPrintButton = false;
#region Parameters for report
Microsoft.Reporting.WebForms.ReportParameter[] reportParameterCollection = new Microsoft.Reporting.WebForms.ReportParameter[1];
reportParameterCollection[0] = new Microsoft.Reporting.WebForms.ReportParameter();
reportParameterCollection[0].Name = "Example";
reportParameterCollection[0].Values.Add("Example");
ReportViewer1.ServerReport.SetParameters(reportParameterCollection);
#endregion Parameters for report
ReportViewer1.ServerReport.Refresh();
}
}
```
The issue I am facing
When I login, I have values set in the session.
When I open a report, the report executes fine in under a second and displays on the page.
Behind the scenes, I've noticed a row gets inserted in the Report Server Temp DB with an expiration date of 1 minute later (with my config).
A session key gets added to my
```
HttpContext.Current.Session.Keys
```
At this point all is fine and I even close the report page.
At this point I wait a minute which would mean that the session expires in the ReportServerTempDB.
I then navigate to a page whose action uses HttpContext.Current.Session for a value. Again, this action has nothing to do with reports. However when it tries to retrieve the key I get the following error
```
Microsoft.Reporting.WebForms.ReportServerException: The report execution <key> has expired or cannot be found. (rsExecutionNotFound)
```
I have been Googling this and have not found a working solution for my problem as most people seem to have had this with long running reports where the report session timed out before the execution was complete.
Any ideas?
Please comment if any more info is needed and I'll update the question.
Thanks in advance | 2013/10/17 | [
"https://Stackoverflow.com/questions/19423030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128756/"
] | I ran into the same issue. It appears that when the objects that the ReportViewer puts in Session are accessed, they try to ping the report server. If the report has expired, a ReportServerException gets thrown, which is expected behavior when a user is still viewing an expired report, but not when they're no longer on that page.
Unfortunately, these Session entries don't get cleaned up after the user leaves the page containing the ReportViewer. And for some reason, accessing the list of keys in the Session will trigger the report server to be pinged, thus raising this exception on completely unrelated pages.
While we can't get the list of keys, one thing we do have access to is the number of entries in Session. Using this information, we can walk through each item in Session and determine if it's one of those associated with the ReportViewer, and remove it.
```
[WebMethod]
public static void RemoveReportFromSession()
{
var i = HttpContext.Current.Session.Count - 1;
while (i >= 0)
{
try
{
var obj = HttpContext.Current.Session[i];
if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy")
HttpContext.Current.Session.RemoveAt(i);
}
catch (Exception)
{
HttpContext.Current.Session.RemoveAt(i);
}
i--;
}
}
```
The catch block helps to remove reports that have already expired (and thus throw an exception when accessed), while the type check in the if-statement will remove reports that have not yet expired.
I recommend calling this from the onunload event of the page that contains your ReportViewer. | On thing to consider with Patrick J. Brown`s answer: think twice before removing Session values in the try block, may belong to other browser window/tab. |
29,830,501 | I'm quite a newbie with SQL. I'm currently working on an **Oracle database** and I've created a report that pulls up data depending on the date range parameter.
**The code is as follows:**
```
SELECT
DISTINCT C.CUSTOMER_CODE
, MS.SALESMAN_NAME
, SUM(C.REVENUE_AMT) Rev_Amt
FROM
C_REVENUE_ANALYSIS C
, M_CUSTOMER_H MC
, M_SALESMAN MS
WHERE C.COMPANY_CODE = 'W1'
AND C.CUSTOMER_CODE = MC.CUSTOMER_CODE
AND MC.SALESMAN_CODE = MS.SALESMAN_CODE
AND trunc(C.REVENUE_DATE) between to_date(<STARTDATE>,'YYYYMMDD') and to_date(<ENDDATE>,'YYYYMMDD')
AND MS.COMPANY_CODE = '00'
GROUP BY C.CUSTOMER_CODE, MS.SALESMAN_NAME
ORDER BY C.CUSTOMER_CODE, MS.SALESMAN_NAME
```
**The resulting report for a date range from Jan 1st to April 30th is:**
```
+-----------+--------------+--------------+
|Customer |Salesman Name |Revenue Amount|
+-----------+--------------+--------------+
|Customer 1 |Salesman 1 | 5000.00|
+-----------+--------------+--------------+
|Customer 2 |Salesman 1 | 8000.00|
+-----------+--------------+--------------+
|Customer 3 |Salesman 2 | 300.00|
+-----------+--------------+--------------+
|Customer 4 |Salesman 3 | 600.00|
+-----------+--------------+--------------+
|Customer 5 |Salesman 3 | 5000.00|
+-----------+--------------+--------------+
|Customer 6 |Salesman 3 | 8000.00|
+-----------+--------------+--------------+
|Customer 7 |Salesman 4 | 9000.00|
+-----------+--------------+--------------+
|Customer 8 |Salesman 5 | 2000.00|
+-----------+--------------+--------------+
|Customer 9 |Salesman 6 | 1000.00|
+-----------+--------------+--------------+
|Customer10 |Salesman 6 | 5000.00|
+-----------+--------------+--------------+
|Customer11 |Salesman 7 | 6000.00|
+-----------+--------------+--------------+
|Customer12 |Salesman 8 | 8000.00|
+-----------+--------------+--------------+
```
Now here is where I need your help, please. I need to show a break up of revenues for each Salesman for each month between Jan to April.
**So I would like the result to look like this:**
```
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer |Salesman Name |Rev for Jan|Rev for Feb|Rev for Mar|Rev for Apr|Total Rev Amt|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer 1 |Salesman 1 | 1000.00| 1000.00| 1000.00| 2000.00| 5000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer 2 |Salesman 1 | 2000.00| 2000.00| 2000.00| 2000.00| 8000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer 3 |Salesman 2 | 100.00| 0.00| 100.00| 100.00| 300.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer 4 |Salesman 3 | 100.00| 200.00| 100.00| 200.00| 600.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer 5 |Salesman 3 | 1000.00| 2000.00| 1000.00| 1000.00| 5000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer 6 |Salesman 3 | 1000.00| 2000.00| 1000.00| 4000.00| 8000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer 7 |Salesman 4 | 2000.00| 2000.00| 3000.00| 2000.00| 9000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer 8 |Salesman 5 | 500.00| 400.00| 500.00| 600.00| 2000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer 9 |Salesman 6 | 200.00| 200.00| 200.00| 400.00| 1000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer10 |Salesman 6 | 1000.00| 1000.00| 2000.00| 1000.00| 5000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer11 |Salesman 7 | 2000.00| 2000.00| 1000.00| 1000.00| 6000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
|Customer12 |Salesman 8 | 2000.00| 2000.00| 2000.00| 2000.00| 8000.00|
+-----------+--------------+-----------+-----------+-----------+-----------+-------------+
```
Unfortunately, since I am a newbie, I don't have rights to create a Stored Procedure to regularly call this data. So I may have to write redundant code.
**But the question really is, what would the code be to be able to break down revenues per each month per salesman?**
Also, the number of columns varies depending on the Date Range. Eg; when Jan to April is selected, I get 4 columns for revenue plus 1 column for Total revenue. When Previous year's October to this year April is selected, I get 7 columns for revenue plus 1 column for Total revenue.
PLEASE can someone help a newbie eager to learn and prove himself? I would greatly appreciate your help. Thanks a lot in advance.
EDIT :
------
After a little persuasion, my manager has agreed to submit my stored procedure for approval and if approved, it will be created.
If I do get to create a stored procedure, what will be the code to get the desired result?
Thanks in advance. | 2015/04/23 | [
"https://Stackoverflow.com/questions/29830501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403824/"
] | Change `id` to `name` - after that you can access value of input field
```js
function myFunction(form, event) {
event.preventDefault();
alert(form.num_cluster.value);
}
```
```html
<form onsubmit="return myFunction(this, event)">
Num. Cluster: <input name="num_cluster" type="text">
<input type="submit">
</form>
```
As problem is little more interesting - we can extend our method **onsubmit**
```js
function s(form, event) {
event.preventDefault();
var values = Array.prototype.slice.call(form.elements) // as form elements are not an array
.filter(function(element) {
return element.type !== 'submit'; // I don't need submit button
})
.map(function(element) {
return (element.name + ': ' + element.value); // get name and value for rest form inputs and assign them to values variable
});
alert('values => ' + values.join(', ')) // finish
}
```
```html
<form onsubmit="return s(this, event)">
<p>Foo:
<input type="text" name='foo' />
</p>
<p>Bar:
<input type="text" name='bar' />
</p>
<p>Baz:
<select name='baz'>
<option value="lorem">lorem</option>
<option value="ipsum">ipsum</option>
</select>
</p>
<p>
<input type="submit" />
</p>
</form>
``` | ```
function myFunction(){
var value=document.getElementById("num_cluster").value;
/// value has the actual thing that you need
//... rest of your code
}
```
you can use this statement even in onsubmit event by directly writing java script there. |
37,014,685 | So I am trying to make a valid login for my web dev class' final project. Whenever I try to log in with the correct credentials, I always get redirected to the "something.php" page, and I never receive any of the output that I put in my code. This even happens when I input valid login credentials.I know this isn't a secure way to do a login, but this is for final project purposes only. I've attached all of my files below (minus pictures), even though you probably don't need all of them.
The something.php file (the php for the login)
```
<?php
$action = empty($_POST['action']) ? false : $_POST['action'];
/*var radio = document.getElementById('radio');*/
switch ($action) {
case 'login':
$username = empty($_POST['username']) ? '' : $_POST['username'];
$password = empty($_POST['password']) ? '' : $_POST['password'];
if ($username=='test' && $password=='pass') {
setcookie('userid', $username);
$response = 'Login: Sucess';
}
else {
$response = 'Login: Fail';
}
print $response;
break;
case 'get':
$userid = empty($_COOKIE['userid']) ? '' : $_COOKIE['userid'];
if ($userid=='test') {
$response = 'Todays special are organic Brazilian strawberries $1.75 a pound';
}
if ($username!='test' || $password!='pass'){
header('Location: XXX/something.php');
echo "username and password combo are not valid";
//radio.value = "logged out";
}
print $response;
break;
case 'logout':
setcookie('userid', '', 1);
print 'Logged out';
break;
}
?>
```
login.html page
```
<div class="group">
<div id="radio">
<form id="radio" action="">
<input type="radio" name="select" value="login"> Logged In<br>
<input type="radio" name="select" value="logout" checked> Logged Out<br>
</form>
</div>
<form id="content2" class="itemBlock">
<p> Don't have an account? Sign up here!</p>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname"><br>
E-mail: <br>
<input type="text" name="email"><br>
Password: <br>
<input type="text" name="password"><br>
<br>
<input type="button" value="Register" onclick="addToCartFxn()">
</form>
<div id="center">
<form id="content" class="itemBlock" action="something.php" method="post">
<br> <br>
E-mail: <br>
<input type="text" name="email"><br>
Password: <br>
<input type="password" name="password"><br>
<input type="submit" class="get" value="Login" id="login">
<input type="submit" value="Logout" id="logout">
</form>
</div>
</div>
```
final.php page
```
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Tabs - Content via Ajax</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<!--<link rel="stylesheet" href="/resources/demos/style.css">-->
<!--<script src="jquery-1.10.2.min.js"></script>-->
<script>
$(function() {
$( "#tabs" ).tabs({
beforeLoad: function( event, ui ) {
ui.jqXHR.fail(function() {
ui.panel.html(
"Couldn't load this tab. We'll try to fix this as soon as possible. ");
});
}
});
});
$(function(){
$('#login').click(function(){
$.post('something.php',
{
action: 'login',
username: $('#username').val(),
password: $('#password').val()
},
function(data){
$('#center').html(data);
});
});
$('#logout').click(function(){
$.post('something.php',
{
action: 'logout'
},
function(data){
$('#center').html(data);
});
});
$('.get').click(function(){
$.post('something.php',
{
action: 'get'
},
function(data){
$('#center').html(data);
});
});
});
function addToCartFxn() {
alert("This feature is coming soon!");
}
</script>
<style>
#floatright {
float:right;
}
#header{
background-image: url("tree rocks header.jpg");
width: 100%;
height: 200px;
padding-top: 1px;
text-align: center;
background-size: cover;
background-position-y: 3255px;
background-position-x: -2112px;
}
#headertext {
z-index: 100;
color: white;
font-size: 72px;
font-family: exo, arial, serif;
}
@font-face {
/* Declare the name of the font (we make this value up) */
font-family: exo;
/* And where it's located */
src: url("Exo-Medium.otf");
}
.addtocart{
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 7px 12px;
border-radius: 7px;
text-align: center;
text-decoration: none;
font-size: 5px;
margin-bottom: 3px;
}
#radio {
float: right;
}
#content {
font-family: exo, arial, serif;
text-align: center;
border-radius: 25px;
background-color:forestgreen;
align-content: center;
}
#content2 {
font-family: exo, arial, serif;
float:left;
}
#logout{
margin: 5px;
}
#login{
margin: 5px;
}
.itemBlock{
display:inline-block;
margin: 10px;
border: 2px black;
border-style: solid;
text-align: left;
padding-left: 5px;
padding-right: 5px;
}
@font-face {
/* Declare the name of the font (we make this value up) */
font-family: exo;
/* And where it's located */
src: url("Exo-Medium.otf");
}
#center{
margin-left: 42%;
}
body {
min-height: 100%;
height: auto! important;
}
.group:after {
content: "";
display: table;
clear: both;
}
</style>
</head>
<body>
<div id="header">
<p id="headertext"> Claw's Cache</p>
</div>
<div id="tabs">
<ul>
<li><a href="#tabs-1"> Our Products </a></li>
<li><a href="#tabs-2"> Available Produce </a></li>
<li id="floatright"> <a href="login.html"> Login</a></li><!--tabs-3's content is being put there by ajax-->
</ul>
<div id="tabs-1">
<p>Listed here are all the current vendors that are associated with us products.</p>
<?php
//Use glob function to get the files
//Note that we have used " * " inside this function. If you want to get only JPEG or PNG use
//below line and commnent $images variable currently in use
$images = glob("*.png");
$i=0;
//Display image using foreach loop
foreach($images as $image){
echo '<div class="itemBlock"> <a href="'.$image.'" target="_blank"><img src="'.$image.'" height="250" width="200" /></a> <br>';
echo '<button type="button" class="addtocart" onclick="addToCartFxn()"> add to cart</button> </div>';
}
?>
</div>
<div id="tabs-2">
<p>Our available produce page is being updated currently!
<br> <br> As a placeholder, we have attached a video that many of our customers recommend to every person interested in indoor gardening.</p><br>
<iframe width="560" height="315" src="https://www.youtube.com/embed/RWCIaydwM_w" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</body>
</html>
``` | 2016/05/03 | [
"https://Stackoverflow.com/questions/37014685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5948316/"
] | As other have suggested you should create the `Point` class:
```
public partial class Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
}
```
And, let's encapsulate the *functions* for computing distance and total cost :
```
public partial class Point
{
public static int CalculateDistance(Point p0, Point p1)
{
return Math.Max(
Math.Abs(p0.X - p1.X),
Math.Abs(p0.Y - p1.Y)
);
}
}
public static class PointExtensions
{
public static int GetTotalCost(this IEnumerable<Point> source)
{
return source
.Zip(source.Skip(1), Point.CalculateDistance)
.Sum();
}
}
```
Finally, you will need another extension method to create "all possible combination" :
```
public static class PermutationExtensions
{
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(this IEnumerable<T> source)
{
if (source == null || !source.Any())
throw new ArgumentNullException("source");
var array = source.ToArray();
return Permute(array, 0, array.Length - 1);
}
private static IEnumerable<IEnumerable<T>> Permute<T>(T[] array, int i, int n)
{
if (i == n)
yield return array.ToArray();
else
{
for (int j = i; j <= n; j++)
{
array.Swap(i, j);
foreach (var permutation in Permute(array, i + 1, n))
yield return permutation.ToArray();
array.Swap(i, j); //backtrack
}
}
}
private static void Swap<T>(this T[] array, int i, int j)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
```
*Source from [Listing all permutations of a string/integer](https://stackoverflow.com/questions/756055/listing-all-permutations-of-a-string-integer) adapted to be more LINQ-friendly*
---
Usage :
```
void Main()
{
var list = new List<Point>
{
new Point(1, 2),
new Point(1, 1),
new Point(1, 3),
};
// result: Point[] (3 items) : (1, 1), (1, 2), (1,3)
list.GetPermutations()
.OrderBy(x => x.GetTotalCost())
.First();
}
```
---
**EDIT** : As @EricLippert pointed out, `source.OrderBy(selector).First()` has some extra cost. This following extension method deals with this issue :
```
public static class EnumerableExtensions
{
public static T MinBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector, IComparer<TKey> comparer = null)
{
IEnumerator<T> etor = null;
if (source == null || !(etor = source.GetEnumerator()).MoveNext())
throw new ArgumentNullException("source");
if (keySelector == null)
throw new ArgumentNullException("keySelector");
var min = etor.Current;
var minKey = keySelector(min);
comparer = comparer ?? Comparer<TKey>.Default;
while (etor.MoveNext())
{
var key = keySelector(etor.Current);
if (comparer.Compare(key, minKey) < 0)
{
min = etor.Current;
minKey = key;
}
}
return min;
}
}
```
And, we can rewrite the above solution as :
```
list.GetPermutations().MinBy(x => x.GetTotalCost())
``` | You can change the for loop to Foreach to make it more readable and rather than using index to fetch values.
```
private static int CalculateMinimumTotalCost(List<Tuple<int, int>> tuples)
{
int minimumCost = 0;
Tuple<int, int> currentTuple = tuples.First();
foreach (Tuple<int, int> tuple in tuples)
{
minimumCost += Math.Max(Math.Abs(currentTuple.Item1 - tuple.Item1), Math.Abs(currentTuple.Item2 - tuple.Item2));
currentTuple = tuple;
}
return minimumCost;
}
``` |
5,605,181 | Is it possible to disable the execution of the logger during testing?
I have this class
```
public class UnitTestMe {
private final MockMe mockMe;
private final SomethingElse something;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getClass());
public UnitTestMe(MockMe mockMe, SomethingElse something) {
this..
}
public toTest() {
logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
mockMe.execute();
}
}
```
My Unit Test is failing with an NullPointerException because something.foo() is not a mocked object (i am using mockito with nicemock).
How can I test this class without removing the logger statement and without mocking irrelevant parts of the dependencies like `something`?
**Edit:** something is in this case a Customer Object, that is not used in the `toTest()` function but needed in other parts of this Class. I am using the Customer class in the logger statement to relate an action to an user.
**Edit 2:** Would it help to mock the logger object? I would assume that I will get an `NullPointerException` again, because the methods of the `something´ object are executed, too. | 2011/04/09 | [
"https://Stackoverflow.com/questions/5605181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | **Poor answer**: first decrease logging level to `WARN` or `ERROR` for this logger. Then, surround logging statement with `isInfoEnabled()`:
```
if(logger.isInfoEnabled())
logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
```
---
**Better one**: it looks a bit weird that you are using some object only for logging, so when you are testing a `toTest()` method, mocked dependency is used only for logging. I understand this is just an example, but looks like there is some design flaw. I would suggest mocking `SomethingElse` for the sake of simplicity as well. | You can use `try catch NullPointerException`.
If your test method want to test NullPointerException it will be better us expect NullPointerException
```
@expect(NullPointerException.class)
public void testMethod() {
//your test method logic
}
``` |
5,605,181 | Is it possible to disable the execution of the logger during testing?
I have this class
```
public class UnitTestMe {
private final MockMe mockMe;
private final SomethingElse something;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getClass());
public UnitTestMe(MockMe mockMe, SomethingElse something) {
this..
}
public toTest() {
logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
mockMe.execute();
}
}
```
My Unit Test is failing with an NullPointerException because something.foo() is not a mocked object (i am using mockito with nicemock).
How can I test this class without removing the logger statement and without mocking irrelevant parts of the dependencies like `something`?
**Edit:** something is in this case a Customer Object, that is not used in the `toTest()` function but needed in other parts of this Class. I am using the Customer class in the logger statement to relate an action to an user.
**Edit 2:** Would it help to mock the logger object? I would assume that I will get an `NullPointerException` again, because the methods of the `something´ object are executed, too. | 2011/04/09 | [
"https://Stackoverflow.com/questions/5605181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | **Poor answer**: first decrease logging level to `WARN` or `ERROR` for this logger. Then, surround logging statement with `isInfoEnabled()`:
```
if(logger.isInfoEnabled())
logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
```
---
**Better one**: it looks a bit weird that you are using some object only for logging, so when you are testing a `toTest()` method, mocked dependency is used only for logging. I understand this is just an example, but looks like there is some design flaw. I would suggest mocking `SomethingElse` for the sake of simplicity as well. | Your logging statement introduce an additional requirement for the mocking of `something`. You must make it give a non-null value returned for foo(), or rewrite your logging statements to avoid introducing these extra things. |
5,605,181 | Is it possible to disable the execution of the logger during testing?
I have this class
```
public class UnitTestMe {
private final MockMe mockMe;
private final SomethingElse something;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getClass());
public UnitTestMe(MockMe mockMe, SomethingElse something) {
this..
}
public toTest() {
logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
mockMe.execute();
}
}
```
My Unit Test is failing with an NullPointerException because something.foo() is not a mocked object (i am using mockito with nicemock).
How can I test this class without removing the logger statement and without mocking irrelevant parts of the dependencies like `something`?
**Edit:** something is in this case a Customer Object, that is not used in the `toTest()` function but needed in other parts of this Class. I am using the Customer class in the logger statement to relate an action to an user.
**Edit 2:** Would it help to mock the logger object? I would assume that I will get an `NullPointerException` again, because the methods of the `something´ object are executed, too. | 2011/04/09 | [
"https://Stackoverflow.com/questions/5605181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | **Poor answer**: first decrease logging level to `WARN` or `ERROR` for this logger. Then, surround logging statement with `isInfoEnabled()`:
```
if(logger.isInfoEnabled())
logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
```
---
**Better one**: it looks a bit weird that you are using some object only for logging, so when you are testing a `toTest()` method, mocked dependency is used only for logging. I understand this is just an example, but looks like there is some design flaw. I would suggest mocking `SomethingElse` for the sake of simplicity as well. | You can suppress the execution of logger
### usecase for PowerMockito:
```
// this is to suppress for logger.error(Exception e)
PowerMockito.doNothing().when(logger, "error", (Exception) any(Exception.class));
// this is to suppress for logger.debug(String message)
PowerMockito.doNothing().when(logger, "debug",anyString());
``` |
5,605,181 | Is it possible to disable the execution of the logger during testing?
I have this class
```
public class UnitTestMe {
private final MockMe mockMe;
private final SomethingElse something;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getClass());
public UnitTestMe(MockMe mockMe, SomethingElse something) {
this..
}
public toTest() {
logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
mockMe.execute();
}
}
```
My Unit Test is failing with an NullPointerException because something.foo() is not a mocked object (i am using mockito with nicemock).
How can I test this class without removing the logger statement and without mocking irrelevant parts of the dependencies like `something`?
**Edit:** something is in this case a Customer Object, that is not used in the `toTest()` function but needed in other parts of this Class. I am using the Customer class in the logger statement to relate an action to an user.
**Edit 2:** Would it help to mock the logger object? I would assume that I will get an `NullPointerException` again, because the methods of the `something´ object are executed, too. | 2011/04/09 | [
"https://Stackoverflow.com/questions/5605181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your logging statement introduce an additional requirement for the mocking of `something`. You must make it give a non-null value returned for foo(), or rewrite your logging statements to avoid introducing these extra things. | You can use `try catch NullPointerException`.
If your test method want to test NullPointerException it will be better us expect NullPointerException
```
@expect(NullPointerException.class)
public void testMethod() {
//your test method logic
}
``` |
5,605,181 | Is it possible to disable the execution of the logger during testing?
I have this class
```
public class UnitTestMe {
private final MockMe mockMe;
private final SomethingElse something;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getClass());
public UnitTestMe(MockMe mockMe, SomethingElse something) {
this..
}
public toTest() {
logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
mockMe.execute();
}
}
```
My Unit Test is failing with an NullPointerException because something.foo() is not a mocked object (i am using mockito with nicemock).
How can I test this class without removing the logger statement and without mocking irrelevant parts of the dependencies like `something`?
**Edit:** something is in this case a Customer Object, that is not used in the `toTest()` function but needed in other parts of this Class. I am using the Customer class in the logger statement to relate an action to an user.
**Edit 2:** Would it help to mock the logger object? I would assume that I will get an `NullPointerException` again, because the methods of the `something´ object are executed, too. | 2011/04/09 | [
"https://Stackoverflow.com/questions/5605181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can suppress the execution of logger
### usecase for PowerMockito:
```
// this is to suppress for logger.error(Exception e)
PowerMockito.doNothing().when(logger, "error", (Exception) any(Exception.class));
// this is to suppress for logger.debug(String message)
PowerMockito.doNothing().when(logger, "debug",anyString());
``` | You can use `try catch NullPointerException`.
If your test method want to test NullPointerException it will be better us expect NullPointerException
```
@expect(NullPointerException.class)
public void testMethod() {
//your test method logic
}
``` |
5,605,181 | Is it possible to disable the execution of the logger during testing?
I have this class
```
public class UnitTestMe {
private final MockMe mockMe;
private final SomethingElse something;
private final Logger logger = LoggerFactory.getLogger(this.getClass().getClass());
public UnitTestMe(MockMe mockMe, SomethingElse something) {
this..
}
public toTest() {
logger.info("Executing toTest. MockMe a: {}, Foo: b: {}", mockMe.toString(), something.foo().bar());
mockMe.execute();
}
}
```
My Unit Test is failing with an NullPointerException because something.foo() is not a mocked object (i am using mockito with nicemock).
How can I test this class without removing the logger statement and without mocking irrelevant parts of the dependencies like `something`?
**Edit:** something is in this case a Customer Object, that is not used in the `toTest()` function but needed in other parts of this Class. I am using the Customer class in the logger statement to relate an action to an user.
**Edit 2:** Would it help to mock the logger object? I would assume that I will get an `NullPointerException` again, because the methods of the `something´ object are executed, too. | 2011/04/09 | [
"https://Stackoverflow.com/questions/5605181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your logging statement introduce an additional requirement for the mocking of `something`. You must make it give a non-null value returned for foo(), or rewrite your logging statements to avoid introducing these extra things. | You can suppress the execution of logger
### usecase for PowerMockito:
```
// this is to suppress for logger.error(Exception e)
PowerMockito.doNothing().when(logger, "error", (Exception) any(Exception.class));
// this is to suppress for logger.debug(String message)
PowerMockito.doNothing().when(logger, "debug",anyString());
``` |
36,344,180 | I am working on filtering out a massive dataset that reads in as a list. I need to filter out special markings and am getting stuck on some of them. Here is what I currently have:
```
library(R.utils)
library(stringr)
gunzip("movies.list.gz") #open file
movies <- readLines("movies.list") #read lines in
movies <- gsub("[\t]", '', movies) #remove tabs (\t)
#movies <- gsub(, '', movies)
a <- movies[!grepl("\\{", movies)] # removed any line that contained special character {
b <- a[!grepl("\\(V)", a)] #remove porn?
c <- b[!grepl("\\(TV)", b)] #remove tv
d <- c[!grepl("\\(VG)", c)] #remove video games
e <- d[!grepl("\\(\\?\\?\\?\\?\\)", d)] #remove anyhting with unknown date ex (????)
f <- e[!grepl("\\#)", e)]
g <- e[!grepl("\\!)", f)]
i <- data.frame(g)
i <- i[-c(1:15),]
i <- data.frame(i)
i$Date <- lapply(strsplit(as.character(i$i), "\\(....\\)"), "[", 2)
i$Title <- lapply(strsplit(as.character(i$i), "\\(....\\)"), "[", 1)
```
I still need to clean it up a bit, and remove the original column (i) but from the output you can see that it is not removing the special characters ! or #
```
> head(i)
i Date Title
1 "!Next?" (1994)1994-1995 1994-1995 "!Next?"
2 "#1 Single" (2006)2006-???? 2006-???? "#1 Single"
3 "#1MinuteNightmare" (2014)2014-???? 2014-???? "#1MinuteNightmare"
4 "#30Nods" (2014)2014-2015 2014-2015 "#30Nods"
5 "#7DaysLater" (2013)2013-???? 2013-???? "#7DaysLater"
6 "#ATown" (2014)2014-???? 2014-???? "#ATown"
```
What I actually want to do is remove the entire rows containing those special characters. Everything I have tried has thrown errors. Any suggestions? | 2016/03/31 | [
"https://Stackoverflow.com/questions/36344180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5970435/"
] | out.print("\"");
This solution ended up being the one that worked. My editor kept telling me that it wasn't valid code, but it ran just fine. | print this instead:
```
out.print(""");
``` |
254,551 | If using Python on a Linux machine, which of the following would be faster? Why?
1. Creating a file at the very beginning of the program, writing very large amounts of data (text), closing it, then splitting the large file up into many smaller files at the very end of the program.
2. Throughout the program's span, many smaller files will be created, written to and closed.
Specifically, the program in question is one which needs to record the state of a very large array at each of many time-steps. The state of the array at each time-step needs to be recorded in independent files.
I've worked with C on Linux and know that opening/creating and closing files is quite time-expensive, and fewer open/create operations means faster programs. Is the same true if writing in Python? Would changing the language even matter if still using the same OS?
I'm also interested in RAM's role in this context. For example -- correct me if I'm wrong -- I'm assuming that parts of a file being written to will be placed in RAM. If the file gets too big, will it bloat RAM and cause problems in speed or other areas? If an answer could incorporate RAM that would be great. | 2014/08/27 | [
"https://softwareengineering.stackexchange.com/questions/254551",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/143527/"
] | To answer your question, you really should benchmark (i.e. measure the execution time of several variants of your program). I guess it might depend on how many small files you need (10 thousand files is not the same as 10 billion files), and what file system you are using. You could use `tmpfs` file systems. It also obviously depends on the hardware (SSD disks are faster).
I would also suggest to avoid putting a big lot of files in the same directory. So prefer `dir01/file001.txt` ... `dir01/file999.txt` `dir02/file001.txt` ... to `file00001.txt` ... `file99999.txt` ie have directories with e.g. at most a thousand files.
I would also advise to avoid having a big lot of tiny files (e.g. files with less than a hundred bytes of data each): they make a lot of filesystems unhappy (since a file needs at least its [inode](http://en.wikipedia.org/wiki/Inode)).
However, you should perhaps consider other alternatives, like using a database (which might be as simple as [Sqlite](http://sqlite.org) ...) or using some indexed file (like [`gdbm`](http://www.gnu.org.ua/software/gdbm/) ...)
Regarding RAM, the kernel tries quite hard to keep file data in RAM. See e.g. [linuxatemyram.com](http://www.linuxatemyram.com/); read about [posix\_fadvise(2)](http://man7.org/linux/man-pages/man2/posix_fadvise.2.html), [fsync(2)](http://man7.org/linux/man-pages/man2/fsync.2.html), [readahead(2)](http://man7.org/linux/man-pages/man2/readahead.2.html), ...
BTW, Python code will ultimately call C code and use the same (kernel provided) [syscalls(2)](http://man7.org/linux/man-pages/man2/syscalls.2.html). Most file system related processing happens *inside* the [Linux kernel](http://en.wikipedia.org/wiki/Linux_kernel). So it won't be faster (unless Python adds it own user-space buffering to e.g. [read(2)](http://man7.org/linux/man-pages/man2/read.2.html) data in megabyte chunks, hence lowering the number of executed syscalls).
Notice that every Linux system is able to deal with a lot of disk data, either with a single huge file (much bigger than available RAM: you could have a 50Gbyte file on your laptop, and a terabyte file on your desktop!) or in many files. | I think it doesn't so much depend on the programming language, but on how Linux (and other systems) handle files: For each file that's created, an inode is created that contains meta information about the file. Therefore it is faster creating one large file than a myriad of smaller ones.
Regarding RAM, the OS should take care of it anyway. If too many pages get occupied, the OS writes them to the hard drive. If you want to handle it on your own, there's a flush function in python as well: <http://www.tutorialspoint.com/python/file_flush.htm> |
24,893,236 | [Material design](http://www.google.com/design/spec/material-design/introduction.html#introduction-principles) makes a huge emphasis on the metaphor of "sheets of paper". To make these, shadows are essential. Since Material design is a philosophy and **not an API** (despite it being built into L), this should be done anywhere (Windows Forms, HTML/CSS, etc.). **How do I do this in Android API 14 to 20?**
Note that premade PNGs won't really be that practical for circular and other non-square shapes. | 2014/07/22 | [
"https://Stackoverflow.com/questions/24893236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453435/"
] | here is just a rough sample ...
```
<?xml version="1.0" encoding="utf-8"?>
```
```
<!-- Drop Shadow Stack -->
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#00CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#10CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#20CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#30CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#50CCCCCC"/>
</shape>
</item>
<!-- Background -->
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
</shape>
</item>
```
In your layout file you may use it ...
```
<Button
android:id="@+id/add_btn"
android:text="+"
android:textColor="#FFFDFC"
android:textSize="44sp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="50dp"
android:layout_marginBottom="40dp"
android:layout_width="64dp"
android:layout_height="64dp"
android:clickable="true"
android:enabled="true"
android:singleLine="false"
android:layout_alignParentTop="false"
android:background="@drawable/round_button"/>
``` | The floating action button (with shadow) can be emulated on old platforms with a simple java class.
I'm using Faiz Malkani's version here: <https://github.com/FaizMalkani/FloatingActionButton>
[Note, that to get it compatible back to Gingerbread you'll need to put some SDK version checks around the animations and transparency calls in his code.] |
24,893,236 | [Material design](http://www.google.com/design/spec/material-design/introduction.html#introduction-principles) makes a huge emphasis on the metaphor of "sheets of paper". To make these, shadows are essential. Since Material design is a philosophy and **not an API** (despite it being built into L), this should be done anywhere (Windows Forms, HTML/CSS, etc.). **How do I do this in Android API 14 to 20?**
Note that premade PNGs won't really be that practical for circular and other non-square shapes. | 2014/07/22 | [
"https://Stackoverflow.com/questions/24893236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453435/"
] | Rendering shadows on pre-Lollipop is not easy, but possible. The trick is that a shadow is simply a black, blured shape of a view. You can do that by yourself.
1. Draw your shadow-casting view to a bitmap with LightingColorFilter(0,0) set
2. Blur it using ScriptIntrisincBlur
3. Draw the shape
4. Draw the view on top of the shape
Sounds lika a lot of code to write, but it works for all cases, so you can easily cover all your views. | The floating action button (with shadow) can be emulated on old platforms with a simple java class.
I'm using Faiz Malkani's version here: <https://github.com/FaizMalkani/FloatingActionButton>
[Note, that to get it compatible back to Gingerbread you'll need to put some SDK version checks around the animations and transparency calls in his code.] |
24,893,236 | [Material design](http://www.google.com/design/spec/material-design/introduction.html#introduction-principles) makes a huge emphasis on the metaphor of "sheets of paper". To make these, shadows are essential. Since Material design is a philosophy and **not an API** (despite it being built into L), this should be done anywhere (Windows Forms, HTML/CSS, etc.). **How do I do this in Android API 14 to 20?**
Note that premade PNGs won't really be that practical for circular and other non-square shapes. | 2014/07/22 | [
"https://Stackoverflow.com/questions/24893236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453435/"
] | If you're not worried about backwards compatibility past Lollipop, you can set the elevation Attribute directly in the XML
```
android:elevation="10dp"
```
Otherwise you have to set it in Java using the support.v4.ViewCompat library.
```
ViewCompat.setElevation(myView, 10);
```
and add this to your build.gradle
```
compile 'com.android.support:support-v4:21.+'
```
<http://developer.android.com/reference/android/support/v4/view/ViewCompat.html#setElevation(android.view.View,%20float)> | The floating action button (with shadow) can be emulated on old platforms with a simple java class.
I'm using Faiz Malkani's version here: <https://github.com/FaizMalkani/FloatingActionButton>
[Note, that to get it compatible back to Gingerbread you'll need to put some SDK version checks around the animations and transparency calls in his code.] |
24,893,236 | [Material design](http://www.google.com/design/spec/material-design/introduction.html#introduction-principles) makes a huge emphasis on the metaphor of "sheets of paper". To make these, shadows are essential. Since Material design is a philosophy and **not an API** (despite it being built into L), this should be done anywhere (Windows Forms, HTML/CSS, etc.). **How do I do this in Android API 14 to 20?**
Note that premade PNGs won't really be that practical for circular and other non-square shapes. | 2014/07/22 | [
"https://Stackoverflow.com/questions/24893236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453435/"
] | here is just a rough sample ...
```
<?xml version="1.0" encoding="utf-8"?>
```
```
<!-- Drop Shadow Stack -->
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#00CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#10CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#20CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#30CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#50CCCCCC"/>
</shape>
</item>
<!-- Background -->
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
</shape>
</item>
```
In your layout file you may use it ...
```
<Button
android:id="@+id/add_btn"
android:text="+"
android:textColor="#FFFDFC"
android:textSize="44sp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="50dp"
android:layout_marginBottom="40dp"
android:layout_width="64dp"
android:layout_height="64dp"
android:clickable="true"
android:enabled="true"
android:singleLine="false"
android:layout_alignParentTop="false"
android:background="@drawable/round_button"/>
``` | You can use android.support.v7.widget.CardView.
Maybe is not the perfect solution but for me is working on what I want. So, for example this is the trick I use on my app ... on an rectangular shape and I am pleased of the result.
```
private View.OnTouchListener touch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final android.support.v7.widget.CardView card_view = (android.support.v7.widget.CardView) ((View) v.getParent()).findViewById(R.id.card_view);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
card_view.setCardElevation(6);
card_view.setScaleX(1.007f);
card_view.setScaleY(1.007f);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
card_view.setCardElevation(3);
card_view.setScaleX(1f);
card_view.setScaleY(1f);
break;
}
return false;
}
};
```
In xml file I use:
```
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="2dp"
card_view:cardMaxElevation="6dp"
card_view:cardElevation="3dp">
``` |
24,893,236 | [Material design](http://www.google.com/design/spec/material-design/introduction.html#introduction-principles) makes a huge emphasis on the metaphor of "sheets of paper". To make these, shadows are essential. Since Material design is a philosophy and **not an API** (despite it being built into L), this should be done anywhere (Windows Forms, HTML/CSS, etc.). **How do I do this in Android API 14 to 20?**
Note that premade PNGs won't really be that practical for circular and other non-square shapes. | 2014/07/22 | [
"https://Stackoverflow.com/questions/24893236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453435/"
] | If you're not worried about backwards compatibility past Lollipop, you can set the elevation Attribute directly in the XML
```
android:elevation="10dp"
```
Otherwise you have to set it in Java using the support.v4.ViewCompat library.
```
ViewCompat.setElevation(myView, 10);
```
and add this to your build.gradle
```
compile 'com.android.support:support-v4:21.+'
```
<http://developer.android.com/reference/android/support/v4/view/ViewCompat.html#setElevation(android.view.View,%20float)> | here is just a rough sample ...
```
<?xml version="1.0" encoding="utf-8"?>
```
```
<!-- Drop Shadow Stack -->
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#00CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#10CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#20CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#30CCCCCC"/>
</shape>
</item>
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
<padding
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
android:left="1dp"/>
<solid android:color="#50CCCCCC"/>
</shape>
</item>
<!-- Background -->
<item>
<shape android:shape="oval">
<corners android:radius="64dp"/>
<solid android:color="#009A3D"/>
<size
android:width="64dp"
android:height="64dp"/>
</shape>
</item>
```
In your layout file you may use it ...
```
<Button
android:id="@+id/add_btn"
android:text="+"
android:textColor="#FFFDFC"
android:textSize="44sp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginRight="50dp"
android:layout_marginBottom="40dp"
android:layout_width="64dp"
android:layout_height="64dp"
android:clickable="true"
android:enabled="true"
android:singleLine="false"
android:layout_alignParentTop="false"
android:background="@drawable/round_button"/>
``` |
24,893,236 | [Material design](http://www.google.com/design/spec/material-design/introduction.html#introduction-principles) makes a huge emphasis on the metaphor of "sheets of paper". To make these, shadows are essential. Since Material design is a philosophy and **not an API** (despite it being built into L), this should be done anywhere (Windows Forms, HTML/CSS, etc.). **How do I do this in Android API 14 to 20?**
Note that premade PNGs won't really be that practical for circular and other non-square shapes. | 2014/07/22 | [
"https://Stackoverflow.com/questions/24893236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453435/"
] | Rendering shadows on pre-Lollipop is not easy, but possible. The trick is that a shadow is simply a black, blured shape of a view. You can do that by yourself.
1. Draw your shadow-casting view to a bitmap with LightingColorFilter(0,0) set
2. Blur it using ScriptIntrisincBlur
3. Draw the shape
4. Draw the view on top of the shape
Sounds lika a lot of code to write, but it works for all cases, so you can easily cover all your views. | You can use android.support.v7.widget.CardView.
Maybe is not the perfect solution but for me is working on what I want. So, for example this is the trick I use on my app ... on an rectangular shape and I am pleased of the result.
```
private View.OnTouchListener touch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final android.support.v7.widget.CardView card_view = (android.support.v7.widget.CardView) ((View) v.getParent()).findViewById(R.id.card_view);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
card_view.setCardElevation(6);
card_view.setScaleX(1.007f);
card_view.setScaleY(1.007f);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
card_view.setCardElevation(3);
card_view.setScaleX(1f);
card_view.setScaleY(1f);
break;
}
return false;
}
};
```
In xml file I use:
```
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="2dp"
card_view:cardMaxElevation="6dp"
card_view:cardElevation="3dp">
``` |
24,893,236 | [Material design](http://www.google.com/design/spec/material-design/introduction.html#introduction-principles) makes a huge emphasis on the metaphor of "sheets of paper". To make these, shadows are essential. Since Material design is a philosophy and **not an API** (despite it being built into L), this should be done anywhere (Windows Forms, HTML/CSS, etc.). **How do I do this in Android API 14 to 20?**
Note that premade PNGs won't really be that practical for circular and other non-square shapes. | 2014/07/22 | [
"https://Stackoverflow.com/questions/24893236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453435/"
] | If you're not worried about backwards compatibility past Lollipop, you can set the elevation Attribute directly in the XML
```
android:elevation="10dp"
```
Otherwise you have to set it in Java using the support.v4.ViewCompat library.
```
ViewCompat.setElevation(myView, 10);
```
and add this to your build.gradle
```
compile 'com.android.support:support-v4:21.+'
```
<http://developer.android.com/reference/android/support/v4/view/ViewCompat.html#setElevation(android.view.View,%20float)> | Rendering shadows on pre-Lollipop is not easy, but possible. The trick is that a shadow is simply a black, blured shape of a view. You can do that by yourself.
1. Draw your shadow-casting view to a bitmap with LightingColorFilter(0,0) set
2. Blur it using ScriptIntrisincBlur
3. Draw the shape
4. Draw the view on top of the shape
Sounds lika a lot of code to write, but it works for all cases, so you can easily cover all your views. |
24,893,236 | [Material design](http://www.google.com/design/spec/material-design/introduction.html#introduction-principles) makes a huge emphasis on the metaphor of "sheets of paper". To make these, shadows are essential. Since Material design is a philosophy and **not an API** (despite it being built into L), this should be done anywhere (Windows Forms, HTML/CSS, etc.). **How do I do this in Android API 14 to 20?**
Note that premade PNGs won't really be that practical for circular and other non-square shapes. | 2014/07/22 | [
"https://Stackoverflow.com/questions/24893236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453435/"
] | If you're not worried about backwards compatibility past Lollipop, you can set the elevation Attribute directly in the XML
```
android:elevation="10dp"
```
Otherwise you have to set it in Java using the support.v4.ViewCompat library.
```
ViewCompat.setElevation(myView, 10);
```
and add this to your build.gradle
```
compile 'com.android.support:support-v4:21.+'
```
<http://developer.android.com/reference/android/support/v4/view/ViewCompat.html#setElevation(android.view.View,%20float)> | You can use android.support.v7.widget.CardView.
Maybe is not the perfect solution but for me is working on what I want. So, for example this is the trick I use on my app ... on an rectangular shape and I am pleased of the result.
```
private View.OnTouchListener touch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final android.support.v7.widget.CardView card_view = (android.support.v7.widget.CardView) ((View) v.getParent()).findViewById(R.id.card_view);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
card_view.setCardElevation(6);
card_view.setScaleX(1.007f);
card_view.setScaleY(1.007f);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
card_view.setCardElevation(3);
card_view.setScaleX(1f);
card_view.setScaleY(1f);
break;
}
return false;
}
};
```
In xml file I use:
```
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="2dp"
card_view:cardMaxElevation="6dp"
card_view:cardElevation="3dp">
``` |
98,945 | I have got a shortcode that displays a custom post type, via a `foreach`. The shortcode has been used in the standard post type. I have used `the_title();` in the shortcode. `the_title();` outputs the post\_title of the standard post type (which the shortcode is in), rather than `the_title();` of the custom post type. My code:
```
function faq_register_shortcode() {
add_shortcode( 'display_faqs', 'mp_faq_shortcode' );
}
function mp_faq_shortcode() {
$args = array( 'post_type' => 'faq_type_mp', 'numberposts' => 3, 'post_status' => 'any', 'post_parent' => null );
$attachments = get_posts( $args );
if ($attachments) {
foreach ( $attachments as $post ) {
the_title();
the_content();
}
}
}
```
So for example, if the standard post type (which the shortcode is in), had a `post_title` of 'this is the standard post type', this is what is outputted in the shortcode. I want to display the `post_title` which belongs to the custom post type, NOT the standard post (which the shortcode is in).
What have I done wrong please? | 2013/05/09 | [
"https://wordpress.stackexchange.com/questions/98945",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | You need to add `setup_postdata($post);` inside your loop:
```
foreach ( $attachments as $post ) {
setup_postdata($post);
the_title();
the_content();
}
``` | My guess is that you'll need to use `setup_postdata($post);` inside of your foreach loop. <https://codex.wordpress.org/Function_Reference/setup_postdata> |
98,945 | I have got a shortcode that displays a custom post type, via a `foreach`. The shortcode has been used in the standard post type. I have used `the_title();` in the shortcode. `the_title();` outputs the post\_title of the standard post type (which the shortcode is in), rather than `the_title();` of the custom post type. My code:
```
function faq_register_shortcode() {
add_shortcode( 'display_faqs', 'mp_faq_shortcode' );
}
function mp_faq_shortcode() {
$args = array( 'post_type' => 'faq_type_mp', 'numberposts' => 3, 'post_status' => 'any', 'post_parent' => null );
$attachments = get_posts( $args );
if ($attachments) {
foreach ( $attachments as $post ) {
the_title();
the_content();
}
}
}
```
So for example, if the standard post type (which the shortcode is in), had a `post_title` of 'this is the standard post type', this is what is outputted in the shortcode. I want to display the `post_title` which belongs to the custom post type, NOT the standard post (which the shortcode is in).
What have I done wrong please? | 2013/05/09 | [
"https://wordpress.stackexchange.com/questions/98945",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | You need to add `setup_postdata($post);` inside your loop:
```
foreach ( $attachments as $post ) {
setup_postdata($post);
the_title();
the_content();
}
``` | Both [`the_title`](http://codex.wordpress.org/Function_Reference/the_title) and [`the_content`](http://codex.wordpress.org/Function_Reference/the_content) are template tags and the operate inside the Loop based on the `global` variable `$post` which is setup by [`setup_postdata`](http://codex.wordpress.org/Function_Reference/setup_postdata) or by [`the_post`](http://codex.wordpress.org/Function_Reference/the_post) ([which runs `setup_postdata`](http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/query.php#L2846)). What is happening is that those tags are using whatever values were last shoved into the `global $post` variable. You can run [`setup_postdata`](http://codex.wordpress.org/Function_Reference/setup_postdata) in your function as already suggested or do something like:
```
foreach ( $attachments as $post ) {
echo apply_filters('the_title',$post->post_title));
echo apply_filters('the_content',$post->post_content));
}
``` |
98,945 | I have got a shortcode that displays a custom post type, via a `foreach`. The shortcode has been used in the standard post type. I have used `the_title();` in the shortcode. `the_title();` outputs the post\_title of the standard post type (which the shortcode is in), rather than `the_title();` of the custom post type. My code:
```
function faq_register_shortcode() {
add_shortcode( 'display_faqs', 'mp_faq_shortcode' );
}
function mp_faq_shortcode() {
$args = array( 'post_type' => 'faq_type_mp', 'numberposts' => 3, 'post_status' => 'any', 'post_parent' => null );
$attachments = get_posts( $args );
if ($attachments) {
foreach ( $attachments as $post ) {
the_title();
the_content();
}
}
}
```
So for example, if the standard post type (which the shortcode is in), had a `post_title` of 'this is the standard post type', this is what is outputted in the shortcode. I want to display the `post_title` which belongs to the custom post type, NOT the standard post (which the shortcode is in).
What have I done wrong please? | 2013/05/09 | [
"https://wordpress.stackexchange.com/questions/98945",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | You need to add `setup_postdata($post);` inside your loop:
```
foreach ( $attachments as $post ) {
setup_postdata($post);
the_title();
the_content();
}
``` | **THE ANSWER**
This is the working code
```
function faq_register_shortcode() {
/* register the [display_faqs] shortcode */
add_shortcode( 'display_faqs', 'mp_faq_shortcode' );
}
function mp_faq_shortcode() {
global $post;
$args = array( 'post_type' => 'faq_type_mp', 'numberposts' => 3, 'post_status' => 'any', 'post_parent' => null );
$attachments = get_posts( $args );
if ($attachments) {
foreach ( $attachments as $post ) {
setup_postdata($post);
the_title();
the_content();
}
}
}
```
Based on this codex page (someone linked to) <https://codex.wordpress.org/Function_Reference/setup_postdata> . Sorry I can't explain it further, because I don't currently understand why it works. |
263,238 | I have a prediction model tested with four methods as you can see in the boxplot figure below. The attribute that the model predicts is in range of 0-8.
You may notice that there is **one upper-bound outlier** and **three lower-bound outliers** indicated by all methods. I wonder if it is appropriate to remove these instances from the data? Or is this a sort of cheating to improve the prediction model?
[](https://i.stack.imgur.com/dFVsJ.png) | 2017/02/21 | [
"https://stats.stackexchange.com/questions/263238",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/91142/"
] | It is **almost always** a cheating to remove observations **to improve** a regression model. You should drop observations only when you truly think that these are in fact outliers.
For instance, you have time series from the heart rate monitor connected to your smart watch. If you take a look at the series, it's easy to see that there would be erroneous observations with readings like 300bps. These should be removed, but not because you want to improve the model (whatever it means). They're errors in reading which have nothing to do with your heart rate.
One thing to be careful though is the correlation of errors with the data. In my example it could be argued that you have errors when the heart rate monitor is displaced during exercises such as running o jumping. Which will make these errors correlated with the hart rate. In this case, care must be taken in removal of these outliers and errors, because they are not [at random](http://missingdata.lshtm.ac.uk/index.php?option=com_content&view=article&id=76:missing-at-random-mar&catid=40:missingness-mechanisms&Itemid=96)
I'll give you a made up example of when to not remove **outliers**. Let's say you're measuring the movement of a weight on a spring. If the weight is *small relative to the strength* of the weight, then you'll notice that [Hooke's law](https://en.wikipedia.org/wiki/Hooke's_law) works very well: $$F=-k\Delta x,$$ where $F$ is force, $k$ - tension coefficient and $\Delta x$ is the position of the weight.
Now if you put a very heavy weight or displace the weight too much, you'll start seeing deviations: at large enough displacements $\Delta x$ the motion will seem to deviate from the linear model. So, you might be tempted to remove the *outliers* to improve the linear model. This would not be a good idea, because the model is not working very well since Hooke's law is only approximately right.
UPDATE
In your case I would suggest pulling those data points and looking at them closer. Could it be lab instrument failure? External interference? Sample defect? etc.
Next try to identify whether the presnece of these outliers could be correlated with what you measure like in the example I gave. If there's correlation then there's no simple way to go about it. If there's no correlation then you can remove the outliers | There are pros and cons to removing outliers and build model for "normal pattern" only.
* Pros: the model performance is better. The intuition is that, it is very hard to use ONE model to capture both "normal pattern" and "outlier pattern". So we remove outliers and say, we only build a model for "normal pattern".
* Cons: we will not be able to predict for outliers. In other words, suppose we put our model in production, there would be some missing predictions from the model
I would suggest to remove outliers and build the model, and if possible try to build a separate model for outlier only.
For the word "cheating", if you are writing paper and explicitly list how do you define and remove outliers, and the mention improved performance is on the clean data only. It is not cheating. |
263,238 | I have a prediction model tested with four methods as you can see in the boxplot figure below. The attribute that the model predicts is in range of 0-8.
You may notice that there is **one upper-bound outlier** and **three lower-bound outliers** indicated by all methods. I wonder if it is appropriate to remove these instances from the data? Or is this a sort of cheating to improve the prediction model?
[](https://i.stack.imgur.com/dFVsJ.png) | 2017/02/21 | [
"https://stats.stackexchange.com/questions/263238",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/91142/"
] | It is **almost always** a cheating to remove observations **to improve** a regression model. You should drop observations only when you truly think that these are in fact outliers.
For instance, you have time series from the heart rate monitor connected to your smart watch. If you take a look at the series, it's easy to see that there would be erroneous observations with readings like 300bps. These should be removed, but not because you want to improve the model (whatever it means). They're errors in reading which have nothing to do with your heart rate.
One thing to be careful though is the correlation of errors with the data. In my example it could be argued that you have errors when the heart rate monitor is displaced during exercises such as running o jumping. Which will make these errors correlated with the hart rate. In this case, care must be taken in removal of these outliers and errors, because they are not [at random](http://missingdata.lshtm.ac.uk/index.php?option=com_content&view=article&id=76:missing-at-random-mar&catid=40:missingness-mechanisms&Itemid=96)
I'll give you a made up example of when to not remove **outliers**. Let's say you're measuring the movement of a weight on a spring. If the weight is *small relative to the strength* of the weight, then you'll notice that [Hooke's law](https://en.wikipedia.org/wiki/Hooke's_law) works very well: $$F=-k\Delta x,$$ where $F$ is force, $k$ - tension coefficient and $\Delta x$ is the position of the weight.
Now if you put a very heavy weight or displace the weight too much, you'll start seeing deviations: at large enough displacements $\Delta x$ the motion will seem to deviate from the linear model. So, you might be tempted to remove the *outliers* to improve the linear model. This would not be a good idea, because the model is not working very well since Hooke's law is only approximately right.
UPDATE
In your case I would suggest pulling those data points and looking at them closer. Could it be lab instrument failure? External interference? Sample defect? etc.
Next try to identify whether the presnece of these outliers could be correlated with what you measure like in the example I gave. If there's correlation then there's no simple way to go about it. If there's no correlation then you can remove the outliers | I originally wanted to post this as a comment to another answer, but it got too long to fit.
When I look at your model, it doesn't necessarily contain one large group and some outliers. In my opinion, it contains 1 medium-sized group (1 to -1) and then 6 smaller groups, each found between 2 whole numbers. You can pretty clearly see that when reaching a whole number, there are fewer observations at those frequencies. The only special point is 0, where there isn't really a discernable drop in observations.
In my opinion, it's worth addressing why this distribution is spread like this:
* Why does the distribution have these observation count drops at whole numbers?
* why does this observation count drop not happen at 0?
* What is so special about these outliers that they're outliers?
When measuring discrete human actions, you're always going to have outliers. It can be interesting to see why those outliers don't fit your model, and how they can be used to improve future iterations of your model. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.