Error while installing node modules in reactjs

Question: Getting the below shown error I tried to install node modules using npm i command for my react js project
D:\Rev>npm i

> email@example.com install D:\Rev\node_modules\node-sass
> node scripts/install.js

Cached binary found at C:\Users\admin\AppData\Roaming\npm-cache\node-sass\4.12.0\win32-x64-64_binding.node

> firstname.lastname@example.com postinstall D:\Rev\node_modules\node-sass
> node scripts/build.js

Binary found at D:\Rev\node_modules\node-sass\vendor\win32-x64-64\binding.node
Testing binary
Binary is fine

> firstname.lastname@example.com postinstall D:\Rev\node_modules\react-vertical-timeline-component
> node lib/post_install.js

> firstname.lastname@example.com postinstall D:\Rev
> set NODE_ENV=production && npm run build-prod

> firstname.lastname@example.com build-prod D:\Rev
> webpack --mode production --config webpack/webpack.production.config.js --progress --colors

D:\Rev\node_modules\webpack-cli\bin\config-yargs.js:89
                                describe: optionsSchema.definitions.output.properties.path.description,
                                                                           ^

TypeError: Cannot read property 'properties' of undefined
    at module.exports (D:\Rev\node_modules\webpack-cli\bin\config-yargs.js:89:48)
    at D:\Rev\node_modules\webpack-cli\bin\webpack.js:60:27
    at Object.<anonymous> (D:\Rev\node_modules\webpack-cli\bin\webpack.js:515:3)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! firstname.lastname@example.com build-prod: `webpack --mode production --config webpack/webpack.production.config.js --progress --colors`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com build-prod script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\admin\AppData\Roaming\npm-cache\_logs\2019-09-27T08_52_21_812Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! firstname.lastname@example.com postinstall: `set NODE_ENV=production && npm run build-prod`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the email@example.com postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\admin\AppData\Roaming\npm-cache\_logs\2019-09-27T08_52_21_942Z-debug.log

The package.json is as follows:
{
  "name": "example-project",
  "version": "1.0.0",
  "description": "",
  "main": "bundle.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev-server": "set NODE_ENV=development && webpack-dev-server --mode development --config webpack/webpack.config.js --progress --colors",
    "build": "set NODE_ENV=development && webpack --config webpack/webpack.production.config.js --progress --colors",
    "build-prod": "webpack --mode production --config webpack/webpack.production.config.js --progress --colors",
    "postinstall": "set NODE_ENV=production && npm run build-prod"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-eslint": "^8.2.3",
    "babel-loader": "^7.1.4",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "css-loader": "^0.28.11",
    "eslint": "^4.19.1",
    "eslint-loader": "^2.0.0",
    "eslint-plugin-react": "^7.8.2",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "node-sass": "^4.9.0",
    "react-collapsible": "^2.2.0",
    "sass-loader": "^7.0.1",
    "style-loader": "^0.21.0",
    "webpack": "^4.8.3",
    "webpack-cli": "^2.1.5",
    "webpack-dev-server": "^3.1.4",
    "webpack-merge": "^4.1.2"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-react": "^6.24.1",
    "classnames": "^2.2.5",
    "dnd-core": "^3.0.2",
    "file-loader": "^1.1.11",
    "file-system": "^2.2.2",
    "foundation-sites": "^6.4.3",
    "gatsby-plugin-glamor": "^1.6.13",
    "glamor": "^2.20.40",
    "history": "^4.7.2",
    "jquery": "^3.3.1",
    "lodash": "^4.17.10",
    "moment": "^2.22.1",
    "qs": "^6.5.2",
    "raf": "^3.4.1",
    "rc-tree": "^1.11.4",
    "react": "^16.3.2",
    "react-autocomplete": "^1.8.1",
    "react-column-resizer": "^1.1.8",
    "react-datepicker": "^1.5.0",
    "react-dialog": "^1.0.2",
    "react-dnd": "^3.0.2",
    "react-dnd-html5-backend": "^2.6.0",
    "react-dom": "^16.3.2",
    "react-dropzone": "^4.2.9",
    "react-html-table-to-excel": "^2.0.0",
    "react-idle-timer": "^3.0.0",
    "react-js-pagination": "^3.0.2",
    "react-redux": "^5.0.7",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-router-redux": "^5.0.0-alpha.9",
    "react-simple-dropdown": "^3.2.0",
    "react-sortable-hoc": "^0.8.4",
    "react-toastify": "^4.0.1",
    "react-tooltip": "^3.10.0",
    "react-transition-group": "^2.3.1",
    "react-vertical-timeline-component": "^2.0.6",
    "react-widgets": "^4.2.6",
    "redux": "^3.7.2",
    "redux-form": "^7.3.0",
    "redux-thunk": "^2.2.0",
    "uglifyjs-webpack-plugin": "^1.2.5",
    "universal-cookie": "^2.1.2",
    "url-loader": "^1.0.1"
  }
}

How can I solve this issue?
Answer: Can you try to remove totally local node_modules
Then call
 npm cache verify

or
npm cache clean

https://docs.npmjs.com/cli/cache.html
Then try to npm i again


When (in the context of 'non-independent tests') does Bonferroni correction *not* yield the appropriate FWER?

Question: I have a question about the oft-heard suggestion that a Bonferroni correction is appropriate in the context of posing multiple independent hypotheses and inappropriate elsewhere, in contrast to statements like:

One of the most widespread of these misunderstandings is that the method would be based on an assumption of independence between p-values. This misunderstanding comes from a frequently used, but deficient motivation for Bonferroni, saying that the probability of making a false rejection if all $m_0$ p-values of true hypotheses are independent, and we perform each test at level... By this reasoning, Bonferroni seems like a method that only provides approximate FWER control and that requires an assumption of independence for its validity. In fact, the method of Bonferroni provides exact FWER control under any dependence structure of the p-values.

To explore this question numerically, I wrote a small R script where I simulated multivariate normal data according to some correlation matrix (sampled from a flat LKJ), estimated sample correlations among that data, and computed the corresponding p-values. I then estimated regression coefficients between these samples $x$ and independently generated data (i.e. from $y = a + 0 \cdot x + e$), and then computed the corresponding p-values. After Bonferroni correction, the FWER for both was at the desired value, $\alpha$. This should also apply if the correlation structure / non-independence were in $y$, given the symmetry between $y \sim x$ and $x \ sim y$.
So is this whole 'non-independence between tests' thing actually a thing w/ the Bonferroni? I'm aware there are other motivations for disfavoring the correction, e.g. it only bounding the FWER from above, and with sufficiently many tests over finite data you get ever higher false-negative rates as the significance threshold goes to 0. If the dependence structure between tests is irrelevant to Bonferroni correction, where did this advised requirement of "multiple independent hypotheses" come from?
(sorry if this question is ill-posed -- maybe I'm misunderstanding the term 'independence' here. I usually just fit hierarchical models, cite Gelman, Hill, & Yajima '12, and call it a day, but am working more in a NHST world lately and am trying to wrap my head around different multiple comparisons strategies)
Answer: Assuming that the marginal tests all are valid (i.e., $P_{0i}(p_i \le \alpha) \le \alpha$, for all $\alpha \in (0,1)$), then the Bonferroni correction guarantees that the FWER is $\le \alpha$ as well, for all dependence structures.  In other words $P_0(\min p_i \le \alpha/m_0) \le \alpha$.  Here, $P_0$ refers to the complete null model, but the result also applies for partial null models, when the minimum is taking over the p-values for hypotheses that are in the subset of true nulls.
Since there is a "$\le \alpha$" in the result, it hardly sounds like one could call this result "exact."  "Valid" would be a better term.
On the other hand, you can get exact results, ones that replace "$\le \alpha$" with "$= \alpha$," by exactly exploiting correlation structures, e.g., as in Tukey's method. Such methods reduce the inherent conservatism of the Bonferroni method. You can also make the results approximately (asymptotically) $= \alpha$, rather than $\le \alpha$, again reducing the conservatism, by approximately exploiting correlation structures (e.g., using the bootstrap).
Here is a reference.
Answer: Neither of the positions in the quote is correct: the Bonferroni method does not assume independence of the p-values, but it is also not an exact method.  The Bonferroni correction is actually a highly conservative (non-exact) correction and so it is usually the case that the true family-wise error rate is substantially below the desired value $\alpha$ under this procedure.  In fact, the only time the Bonferroni method will give you the exact family-wise error rate you stipulate is when the events that the individual hypothesis are rejected are mutually exclusive, which never happens in actual statistical practice.
You say that you did a simulation and it gave you a family-wise error rate at the desired level $\alpha$.  Presumably what you mean is that the actual family-wise error rate was bounded by the desired level $\alpha$ --- it would be highly unusual (and indicative of a mistake) if it was at that exact value.

Let me illustrate how the Bonferroni method works, and what it relies on mathematically.  To do this, suppose we are conducting $m$ comparisons.  Let $p_i$ denote the p-value for comparison $i$ and let $\mathbf{H}_0$ denote the null hypothesis for all the comparisons.  Under the Bonferroni method we reject the null hypothesis if $p_i \leqslant \alpha/m$.  Consequently, under this method, the error rate for the $i$th comparison is the probability of Type I error, which is:
$$\text{ER}_i \equiv \mathbb{P} \Big( p_i \leqslant \frac{\alpha}{m} \Big| \mathbf{H}_0 \Big) = \frac{\alpha}{m},$$
and the family-wise error rate for the set of all $m$ comparisons is the probability of Type I error for at least one of those comparisons, which is:
$$\text{FWER}_m \equiv \mathbb{P} \Big( \min (p_1,...,p_m) \leqslant \frac{\alpha}{m} \Big| \mathbf{H}_0 \Big).$$
Without any assumption of independence, you can apply Boole's inequality to get:
$$\begin{align}
\text{FWER}_m
&= \mathbb{P} \Big( \min (p_1,...,p_m) \leqslant \frac{\alpha}{m} \Big| \mathbf{H}_0 \Big) \\[6pt]
&= \mathbb{P} \Big( p_1 \leqslant \frac{\alpha}{m}, \cdots , p_m \leqslant \frac{\alpha}{m} \Big| \mathbf{H}_0 \Big) \\[6pt]
&\leqslant \sum_{i=1}^m \mathbb{P} \Big( p_i \leqslant \frac{\alpha}{m} \Big| \mathbf{H}_0 \Big) \\[6pt]
&= \sum_{i=1}^m \frac{\alpha}{m} \\[6pt]
&= \alpha. \\[6pt]
\end{align}$$
As you can see, the use of Boole's inequality gives this result a highly conservative character.  The only time you will get $\text{FWER}_m = \alpha$ exactly is when the events for rejection of the null hypothesis are mutually exclusive, which never really happens in practice.  Depending on the dependency (or independence) between the p-values for the comparisons, the exact family-wise error rate will usually be substantially less than the desired level $\alpha$.
Comment: Correlation does not have that much effect unless they are extremely large.  The effect of correlation on FWER is definitely not linear in the correlations. Distributional characteristics (e.g., discreteness) can have great effects though.  See https://www.jstor.org/stable/2684683


P value calculation

Question: I have three groups of experiments. For each experiment I am looking for the percentage of occurrence of case x.
In the first group I have 15 experiments. The case x was seen 10.191% of the total time for 15 experiments.
In the second group I have 6 experiments. The percentage of x is 1.564%.
In the third group I have 3 experiments. The percentage of x is 0%.
I want to show that occurrence of case x  significantly decreased from group one to two and to three. Thus I want to calculate the p-values.  Can anyone tell me how to do it?
Edit:
The number of measurements for the first group is 22568 and 10.191% of these measurements are case x.
The second group has 1854 measurements (1.564% are x) and the third group has 1164 measurements (0% x)
Comment: Could you please explain how it would be possible for a percentage of *anything* in a group of size $n=6$ to be any value other than $0, 100/6, 200/6, \ldots, 500/6,$ and $100$?  In particular, how do you arrive at $1.5667\%$?
Comment: You can add an official answer to your own questions, but in this case your answer might be wrong. It completely ignores the fact that there are 15 experiments in group 1, and that outcomes within an experiment might not be independent.
Comment: That doesn't really answer the question, it just raises more questions. If you have N = 6, @whuber is correct. If you have something else, please describe what you have. See [how to ask a statistics question](http://www.statisticalanalysisconsulting.com/how-to-ask-a-statistics-question/).
Comment: I think you are using incorrect terminology: you have _rates_, not _percentages_. So in the first group, you have the event occurring at an (average) rate of 0.1 / minute, for example. Is that correct?
Comment: The question asks about differences between groups of experiments, so on one count that would address @Aniko's concern.  Then again, in doing such tests we attempt to compare obtained results to the sort that would occur by chance under a null hypothesis.  Does it make sense to characterize any null hypothesis at the level of "group of experiments?"
Comment: @whuber The data-sets i have are time dependent. In the second group, the case x was seen 1.5667% of the total time.
Comment: @PeterFlom Please see the edit. I hope now my question is more clear
Comment: You may need to explicit a little bit better what you did because (at least to me) it is still unclear. Something on the line of: "In each experiment I measured 5000 events and counted how many were of type x", or whatever you did...
Comment: @nico you are right i should have written before. Please see the edit
Comment: After the correction from @nico , here is the solution:

https://onlinecourses.science.psu.edu/stat414/node/268. Thank you so much to everyone
Answer: Since numbers are available (obtained from percentages), chi-square gives following result (in R code):
<code>> M
      [,1] [,2]
[1,] 22568 2300
[2,]  1854   29
[3,]  1164    0
>
> chisq.test(M)

        Pearson's Chi-squared test

data:  M
X-squared = 246.59, df = 2, p-value < 0.00000000000000022
</code>
Edit: I should probably take no_x and x counts rather than total_N and x counts:
<code>> M
      [,1] [,2]
[1,] 20268 2300
[2,]  1825   29
[3,]  1164    0
>
> chisq.test(M)

        Pearson's Chi-squared test

data:  M
X-squared = 276.24, df = 2, p-value < 0.00000000000000022
</code>
Answer: You can use a Wald approximation for confidence intervals for the first set of experiments, and probably the second.  For the third, you can't calculate confidence intervals at all, but you can test whether any of the other experiments were significantly different from zero.
Wikipedia has a formula for the Wald and other approximations and this paper: Interval Estimation for a Binomial Proportion, describes the various approximations in more detail.
You should probably test for differences between the samples in each experiment group (which is what I assume Aniko is implying.  If there are big differences between the 15 experiments in the first group for instance, it would call into question these simple confidence intervals, and you might want to consider an effects model of some sort.
Comment: The Wald approximation can be wildly inaccurate where the proportions are close to zero or one, as they seem to be in this case, and is not a recommended method in the paper that you link. It should probably never be used. See this: http://stats.stackexchange.com/questions/15567/putting-a-confidence-interval-on-the-mean-of-a-very-rare-event/15568#15568

P value calculation


no permission to connect to the WMI provider - after sql server installation

Question: I am the administrator of a windows server 2016.
After installing sql server, I want to use the sql server configuration manager to have a look at what ports and accounts are there, check if all is ok.
however I get the error message - cannot connect to WMI provider.

it is a virtual box, but not sure how much it could be related to this.
how can I find who is the WMI provider and get this permission to connect to that?
Answer: It seems you have installed SQL Server 2005 components or you are installing them. Please very verify that on Control Panel -> Programs and Features. SQL Server 2005 is not supported on Windows Server 2016. Please read this official document to know which versions of SQL Server are supported on Windows Server 2016.
Based on that documentation, the lowest version of SQL Server supported on Windows Server 2016 is SQL Server 2012 with Service Pack 2.
If you have confirmed that you are installing only SQL Server 2012 or later versions of SQL Server then workaround the problem by opening a command prompt, type the following command, and then press ENTER:
mofcomp "%programfiles(x86)%\Microsoft SQL Server\number\Shared\sqlmgmproviderxpsp2up.mof"

Note For this command to succeed, the Sqlmgmproviderxpsp2up.mof file must be present in the %programfiles(x86)%\Microsoft SQL Server\number\Shared folder.
For more details about this workaround, please read this support article.
Answer: running the following command as suggested by Alberto Morillo sorted out the problem
and now the sql server configuration manager works as you can see on the picture below.
mofcomp "%programfiles(x86)%\Microsoft SQL Server\140\Shared\sqlmgmproviderxpsp2up.mof"

however, the running under 64 bits os was set to no, and now I have changed it to yes and restarted the services.


Why no mutable sorted map in Scala

Question: I have been looking for options to implement a mutable sorted map in scala. I know I can store my data in a mutable map and then transformed into a sorted map if is needed or wrap the TreeMap from Java. However, Does anyone know why this is not implemented in scala? Is against any functional programming style?
Regards
Comment: The 2 keys concepts of functionnal programming are 'function are objects' and 'immutability'
Comment: then, the best implementation should be to have a mutable map and then transform this map to a new one by sorting it. ?
Comment: However, @Jasper-M scala has mutable collections mutable.Map, etc.
Comment: Looks like it's implemented in 2.12: https://github.com/scala/scala/blob/v2.12.0-M4/src/library/scala/collection/mutable/TreeMap.scala
Answer: There is no reason but the omission of writing one. In fact, a mutable sorted map was added to Scala 2.12.x.
Answer: There's some discussion in this old answer about possible reasons there isn't an implementation.
With regards to your second question, there are other mutable collections in Scala so I don't see any hard reason there couldn't be a mutable sorted map (see the older question as well). In a more general sense, functional programming can be taken to imply that mutable data is not used, and in this case a mutable sorted map would be avoided. However mutable collections may well be used "behind the scenes" in a library to improve performance, as long as they won't be visible to users of the library.

Why no mutable sorted map in Scala


Decomposing $\mathbb{N}$

Question: Let the Symbol $|\ |$ denote cardinality of an set. Is it possible to construct a family $N_i\subset\mathbb{N}$, $i\in\mathbb{N}$, such that:
1- $|N_i|=\infty$,
2- $\mathbb{N}=\bigcup_{i=1}^\infty N_i$,
3- $|N_1\cap N_i|=i$, $\forall i\geq 2$.
Thanks
Edit: I changed 3.
Comment: Yes it is (replacing *for all $i\in\mathbb N$* in 3. by *for all $i\geqslant2$*). Now, what did you try?
Comment: You guys are right, its is for $i\geq 2$. I will edit it.
Comment: Hint: split $\mathbb{N}$ into two infinite disjoint sets, one of which will be all of $N_1$, the other which will contain most of the elements of each $N_i$, $i\geq 2$...
Answer: You obviously can't have $N_1$ infinite and $|N_1\cap N_1|=1$, but if you just want $|N_1\cap N_k|=k$ for $k>1$, the answer is yes.
Let $\{M_k:k\ge 2\}$ be any partition of the odd positive integers into infinite sets, and let $N_1$ be the set of even positive integers. Now let
$$\begin{align*}
N_2&=M_2\cup\{2,4\}\\
N_3&=M_3\cup\{6,8,10\}\\
N_4&=M_4\cup\{12,14,16,18\}\;,
\end{align*}$$
and so on.
Answer: No. Condition 3 implies that $N_1$ has exactly one element ($|N_1\cap N_1|=1$); so $|N_1\cap N_i|\leq1$ for all $i$.

Decomposing $\mathbb{N}$


Linux, timing out on subprocess

Question: Ok, I need to write a code that calls a script, and if the operation in script hangs, terminates the process.
The preferred language is Python, but I'm also looking through C and bash script documentation too.
Seems like an easy problem, but I can't decide on the best solution.
From research so far:

Python: Has some weird threading model where the virtual machine uses
one thread at a time, won't work?
C: The preferred solution so far seems to use SIGALARM + fork +
execl. But SIGALARM is not heap safe, so it can trash everything?
Bash: timeout program? Not standard on all distros?

Since I'm a newbie to Linux, I'm probably unaware of 500 different gotchas with those functions, so can anyone tell me what's the safest and cleanest way?
Answer: Avoid SIGALRM because there is not much safe stuff to do inside the signal handler.
Considering the system calls that you should use, in C, after doing the fork-exec to start the subprocess, you can periodically call waitpid(2) with the WNOHANG option to inspect whether the subprocess is still running. If waitpid returns 0 (process is still running) and the desired timeout has passed, you can kill(2) the subprocess.
Answer: In bash you can do something similar to this:

start the script/program in background with &
get the process id of the background process
sleep for some time
and then kill the process (if it is finished you cannot kill it) or you can check if the process is still live and then to kill it.

Example:
sh long_time_script.sh &
pid=$!
sleep 30s
kill $pid

you can even try to use trap 'script_stopped $pid' SIGCHLD - see the bash man for more info.
UPDATE: I found other command timeout. It does exactly what you need - runs a command with a time limit. Example:
timeout 10s sleep 15s

will kill the sleep after 10 seconds.
Answer: There is a collection of Python code that has features to do exactly this, and without too much difficulty if you know the APIs.
The Pycopia collection has the scheduler module for timing out functions, and the proctools module for spawning subprocesses and sending signals to it. The kill method can be used in this case.

Linux, timing out on subprocess


$.getJSON won't get JSON

Question: I am trying to get my script to load in a JSON file which is located in the root of my website:
$.getJSON( "slides.json", function(json) {
    var slides = json;
    console.log(slides);
}

However, on loading the website I get the following error:
Failed to load resource: the server responded with a status of 404 (Not Found)

So I tried surfing to http://mywebsite/slides.json, and also got a 404. So I tried to change my file extension to slides.txt, and that worked just fine with the surfing, as well as the script reading.
Can somebody explain why my IIS won't distrubute the JSON file as it would a text file?
Thanks :)
Comment: Did you try to take a look to this link? Unfortunately I think that the issue should be with IIS not JS, so you may think to add also IIS as tag at your question https://stackoverflow.com/questions/332988/get-iis6-to-serve-json-files-inc-post-get
Comment: Unfortunately by default IIS doesn't serve JSON. Try these steps:
- Open IIS Manager
- Right click on `MIME` and choose `open feature`
- Add a new action (top right with `Add...`)
- Enter `JSON` for the extension and `application/json` for the MIME type.

Hope this helps!
Comment: you changed the extension *on the server* or just in your javascript?
Comment: Thanks guys, indeed the question was already answered. I just didn't know what to look for. :)
Answer: Unfortunately by default IIS doesn't serve JSON. Try these steps:
- Open IIS Manager
- Right click on MIME and choose open feature
- Add a new action (top right with Add...)
- Enter JSON for the extension and application/json for the MIME type.
Hope this helps!
Comment: Glad I could help :)
Comment: Excellent, this did it! Thanks man.

$.getJSON won't get JSON


Make middle column take all the remaining space

Question: I've made a usercontrol where my rootcontainer is a grid.
The grid has 3 columns, and I want to make the first and last column a fixed size of 30.
The middle column should take all the remaining space.
But my code is not working..
Here is my code:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:ee="http://schemas.microsoft.com/expression/2010/effects"
mc:Ignorable="d"
x:Class="UserControlSolution.UserControlButton"
x:Name="UserControl"
Height="50" Background="{DynamicResource DarkGrey}">

        <ei:GoToStateAction TargetObject="{Binding ElementName=UserControl}" StateName="Expand"/>

        <ei:GoToStateAction TargetObject="{Binding ElementName=UserControl}" StateName="Collapse"/>

        <ei:GoToStateAction TargetObject="{Binding ElementName=UserControl}" StateName="CenterUserName"/>

<Grid x:Name="LayoutRoot" Height="50" RenderTransformOrigin="0.5,0.5" VerticalAlignment="Top" HorizontalAlignment="Left">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="30"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="30"/>
    </Grid.ColumnDefinitions>
    <VisualStateManager.CustomVisualStateManager>
        <ei:ExtendedVisualStateManager/>
    </VisualStateManager.CustomVisualStateManager>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="VisualStateGroup">
            <VisualStateGroup.Transitions>
                <VisualTransition GeneratedDuration="0:0:0.3" To="Expand"/>
                <VisualTransition GeneratedDuration="0:0:0.1" To="Collapse"/>
            </VisualStateGroup.Transitions>
            <VisualState x:Name="Expand">
                <Storyboard>
                    <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Height)" Storyboard.TargetName="UserControl">
                        <EasingDoubleKeyFrame KeyTime="0" Value="90"/>
                    </DoubleAnimationUsingKeyFrames>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.VerticalAlignment)" Storyboard.TargetName="UserCallAlarmPanel">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static VerticalAlignment.Top}"/>
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>
            </VisualState>
            <VisualState x:Name="Collapse"/>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <StackPanel x:Name="UserCallAlarmPanel" Grid.Column="0" Background="{DynamicResource DarkGrey}" Margin="0,0,2,0" HorizontalAlignment="Left" VerticalAlignment="Center">
        <Viewbox Height="25">
            <ContentControl Content="{DynamicResource calls_icon}" />
        </Viewbox>
        <Viewbox Height="25">
            <ContentControl Content="{DynamicResource alarm_icon}"/>
        </Viewbox>
    </StackPanel>

    <StackPanel x:Name="UserContainer" Orientation="Vertical" VerticalAlignment="Center" Grid.Column="1" Background="{DynamicResource Red}" >
        <TextBlock x:Name="NameLabel" FontSize="16" Foreground="#FFE5E5E5" Text="Onthaal Telefoon" VerticalAlignment="Top" FontFamily="Segoe UI Semibold" RenderTransformOrigin="0.5,0.5" Margin="0,0,0,2"/>
        <TextBlock x:Name="UserStatusLabel" TextWrapping="Wrap" VerticalAlignment="Top" Foreground="#FFE5E5E5"><Run Language="nl-nl" Text="Demeestere advocaten"/></TextBlock>
    </StackPanel>

    <Viewbox x:Name="StatusIconContainer" VerticalAlignment="Center" Grid.Column="2" OpacityMask="Black">
        <ContentControl x:Name="StatusIcon" Content="{DynamicResource appbar_check_orange}" VerticalAlignment="Top" />
    </Viewbox>
</Grid>
</UserControl>

I've set the width of the middle column to '*' but that doesn't work apparently.
This is what it looks like when I set the middle column background to blue:
Answer: Either you have to give some width that should be greater than 60 (30+30) or you have to set HorizontalAlignment="Stretch" in order to take grid the full space. After grid stretches to fill its parent the middle column will take the rest of the space left after 30 and 30 of first and last column
Comment: Yes, that was it. I had to set the HorizontalAlignment of the main grid to Stretch. Thanks!
Answer: Just don't define a width for your middle ColumnDefinition and it will fill up all the available space.
 <Grid.ColumnDefinitions>
        <ColumnDefinition Width="30"/>
        <ColumnDefinition />
        <ColumnDefinition Width="30"/>
    </Grid.ColumnDefinitions>

Comment: The asterisk the OP used is the default value, so your code is equivalent to what he already has.


How should a custom configuration entity define a dependency on other configuration?

Question: In a custom module I am defining a defaults Configuration entity that references a role.
I would like to define a dependency on the role. This is my first attempt.
public function calculateDependencies() {
  $this->dependencies = parent::calculateDependencies();
  $this->addDependency('module', 'user');
  if (isset($this->role_id)) {
    $this->addDependency('config', "user.role.{$this->role_id}");
  }
  return $this; // Also tried return $this->dependencies;
}

The Drupal documentation on dependencies references the Block configuration class that looks very similar:
  public function calculateDependencies() {
    parent::calculateDependencies();
    $this->addDependency('theme', $this->theme);
    return $this;
  }

However I am seeing an error shown below when trying to save the entity.The backtrace indicates it is coming from the attempt to add a dependency on the user module. I chose to add that dependency by taking an example from system.action.user_add_role_action.administrator.

PHP Error:  Cannot use object of type Drupal/my_module/Entity/MyAccessDefaults as array in /app/web/core/lib/Drupal/Core/Entity/DependencyTrait.php on line 32

For example I am trying to test with this code:
$values = [
  'id' => 'administrator', 'label' => 'Administrator role grants',
  'grant_type' => 'role', 'role_id' => "administrator",
  'grants' => ['grant_view' => 1]
];
$default_admin_config = \Drupal::entityTypeManager()->getStorage('my_entity')->create($values);
$default_admin_config->save();

Answer: ConfigEntityInterface::calculateDependencies returns $this, so this line:
$this->dependencies = parent::calculateDependencies();

Is causing problems (replacing the dependencies array with the instance of the current class, which is presumably a MyAccessDefaults).
Looking at the code, and other core classes which implement ConfigEntityInterface, your code should be:
public function calculateDependencies() {
  parent::calculateDependencies();
  $this->addDependency('module', 'user');
  if (isset($this->role_id)) {
    $this->addDependency('config', "user.role.{$this->role_id}");
  }
  return $this;
}

Comment: Yes, that was the issue. I had just got it working when you answered with the same change. I think I copied that part from a sample somewhere.


baixar pdf que está fora da aplicação jsf java

Question: preciso colocar pra download alguns pdf que estão fora da minha aplicação, estão na pasta c:\tmp\
como poderia fazer utilizando o primefaces para disponibilizar estes arquivos pra download?
eu pensei em salvar na pasta
C:\jboss-as-7.1.1.Final\standalone\deployments\app.war\WEB-INF
mas cada vez que eu fizer o deploy este arquivo é eliminado
Answer: Tente isso:
Declare um atributo do tipo DefaultStreamedContent no seu bean:
Exemplo:
private DefaultStreamedContent download;

Faça os Get e sets:
public DefaultStreamedContent getDownload() {
        return download;
    }

public void setDownload(DefaultStreamedContent download) {
        this.download = download;
}

Em seguida :
    //Método que faz o download do anexo
    public void prepDownload() throws Exception {
        File file = new File("c:/tmp/arquivo.pdf");

        InputStream input = new FileInputStream(file);
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        setDownload(new DefaultStreamedContent(input, externalContext.getMimeType(file.getName()), file.getName()));
    }

Depois no seu botão;


If $\alpha$ is a root of $x^{p^n}-x+1$, then show that $\mathbb{F}_{p^n}\subset\mathbb{F}_p(\alpha)$

Question: Question
Let $\mathbb{F}_p$ be the field with $p$ elements, where $p$ is a prime. Let $f_{n,p}(x)=x^{p^n}-x+1$, and suppose that $f_{n,p}(x)$ is irreducible in $\mathbb{F}_p[x]$. Let $\alpha$ be a root of $f_{n,p}(x)$. Show that $\mathbb{F}_{p^n}\subset\mathbb{F}_p(\alpha)$ and $[\mathbb{F}_p(\alpha):\mathbb{F}_{p^n}]=p$.
Answer
I know that $\mathbb{F}_{p^n}$ consists of the roots of the polynomial $x^{p^n}-x$. Thus, if we can find a root, say $\gamma$, of this polynomial in $\mathbb{F}_p(\alpha)$, except $0$, in terms of $\alpha^i$'s, we are done as the other roots follow by $\gamma,\gamma+1,\dots,\gamma+p-1$. However, I couldn't find such a root. Is there any way I can follow to find it or do I need another approach to solve this question? Thanks in advance...
Comment: As usual in fields extensions, we can identify $\;\alpha=x/\langle f_{n,p}(x)\rangle\in\Bbb F_{p^n}[x]/\langle f_{n,p}(x)\rangle=\;$ the quotient ring of $\;\Bbb F_{p^n}[x]\;$ by the ideal $\;\langle f_{n,p}(x)\rangle\;$ , which is a field since this ideal is maximal as the polynomial which generates it is irreducible, and then we usually write $\;\Bbb F_{p^n}[x]/\langle f_{n,p}(x)\rangle=\Bbb F(\alpha)\;$
Comment: @ancientmathematician The given polynomial is not irreducible over the prime field. See for example [this old answer of mine](https://math.stackexchange.com/a/581159/11619) for more about its factorization in $\Bbb{F}_p[x]$.
Comment: @ancientmathematician The exception to that is the case $p=n=2$.
Comment: So that means the field $\mathbb{F}_p(\alpha)$ has degree $p^n$ over $\mathbb{F}_p$ and so has order $p^{p^n}$. If what they ask you to prove is true then the field $\mathbb{F}_p(\alpha)$ has degree $p$ over $\mathbb{F}_{p^n}$ and so has order $(p^n)^p$. It doesn't stack up, does it? With my proposed amendment it would.
Comment: And, like yesterday, **you absolutely should link to [the question](https://math.stackexchange.com/q/122274/11619) you are asking about**
Comment: I did not understand how showing this would help to solve the question (also I couldn't show what you wrote either). And actually the question you linked is the second part of this question and it easily follows after proving these ones.
Comment: Ok I see that but why is it true that $\alpha^{p^n}=\alpha+1$ and where should we use this information to show that $\mathbb{F}_{p^n}\subset\mathbb{F}(\alpha)$?
Comment: @JyrkiLahtonen Is my worry about the order of the field just nonsense?
Comment: @JyrkiLahtonen Thanks, that was my conclusion, that for the hypotheses of the OP's question to hold we need $n=1$.
Answer: I need to apologize. I just noticed that even though we have handled non-irreducibility of this polynomial as well as its factorization over the prime field somewhat adequately, this time the question in the title is markedly different. I only saw what I expected to see, and failed to read closely.

As stated, the claim in the title is actually false!
For a counterexample consider the case $p=2$, $n=3$. In the ring $\Bbb{F}_2[x]$ have the factorization into irreducibles
$$x^8-x+1=(x^2+x+1)(x^6+x^5+x^3+x^2+1).$$
And if $\alpha$ is a root of the quadratic factor $x^2+x+1$, then $\Bbb{F}_2(\alpha)=\Bbb{F}_4$, which is not a subfield of $\Bbb{F}_{2^n}=\Bbb{F}_8$.

What I was keen on proving in the comments is that the splitting field of the polynomial $f(x)=x^{p^n}-x+1$ over the prime field $\Bbb{F}_{p}$ is
$$
K=\Bbb{F}_{p^{pn}},
$$
that is, the unique extension of degree $pn$.
To see this we need to first show that if $\alpha$ is a zero of $f(x)$ from some extension field of $\Bbb{F}_p$, then $\alpha^{p^{pn}}=\alpha$, implying that $\alpha\in K$. While doing that we also observe that $\alpha^{p^n}=\alpha-1$, implying that we NEVER have $\alpha\in\Bbb{F}_{p^n}$. However, if $\alpha$ is any root of $f(x)$ and $z\in\Bbb{F}_{p^n}$ is arbitrary, we easily see that $\alpha+z$ is also a root of $f(x)$. Hence $z$ must be an element of the splitting field. Consequently $L=\Bbb{F}_{p^n}\subseteq K$.
As $[K:L]=p$ is a prime, there are no intermediate fields between $L$ and $K$. Hence $K$ must be the splitting field.

We can also show that while we don't have the title claim for each and every root of $f(x)$, for a bit more carefully chosen root $\alpha$ of $f(x)$ we do have $K=\Bbb{F}_p(\alpha)$. This part of my answer requires familiarity with the properties of the trace map.
In the field $L$ there exists $p^{n-1}$ elements of trace $-1\in\Bbb{F}_p$. Among them we can find an element $z$ such that $L=\Bbb{F}_p(z)$. Reusing the calculation in the linked old answer of mine we see that $m_z(x)=x^p-x-z$ is a factor of $f(x)$ in the ring $L[x]$. So if $\alpha$ is a zero $m_z(x)$, then also $f(\alpha)=0$. Furthermore:

$z=\alpha^p-\alpha\in \Bbb{F}_p(\alpha)$, and hence $L=\Bbb{F}_p(z)\subset \Bbb{F}_p(\alpha)$, but
$\alpha\notin L$ because otherwise $z=\alpha^p-\alpha$ would have trace zero.

The case $p=n=2$ is exceptional for the purposes of irreducibility of $f(x)$ simply because in that case $pn=4=p^n$.
Comment: @confused There was a sign error there. If $\alpha$ is a zero of $x^{p^n}-x+1$, then $\alpha^{p^n}-\alpha+1=0$. Solving from this we get the corrected claim
$$\alpha^{p^n}=\alpha-1.$$ From this it follows by induction on $k$ that
$$\alpha^{p^{kn}}=\alpha-k$$ for all $k=1,2,\ldots,p-1$, and then finally
$$\alpha^{p^{pn}}=\alpha-p=\alpha.$$
Comment: I again want to ask: How did you find that $\alpha^{p^n}=\alpha+1$? Also, I didn't understand something. You choose $\alpha$ specificly at the last part of your answer but in my question $\alpha$ was chosen arbitrarily just as a root of $f_{n,p}$.
Comment: And the first counterexample shows that your claim is not necessarily true for all choices of $\alpha$. Therefore some care is needed.
Comment: Actually, I don't understand why you gave this counterexample. The title and the question are in fact a little different because I want to keep it short on the title. In the question it is said that "**suppose** $f_{n,p}$ is irreducible". After making such a supposition, we shouldn't choose $\alpha$ specificly, in my opinion.


Setting up a date field to require an end date

Question: I'm attempting to create a custom content type for a module via hook_install. When I create a date type (from Date module), I want it to require an end date (there's a checkbox when you're setting up the field via the gui). This is the settings array for the field:
<code>'settings' => array(
    'enddate_get' => 1,
    'enddate_required' => 1,
),
</code>
This isn't working (the widget is still only asking for one date), so I'm guess that I have the wrong settings. Does anyone know how to properly set this up?
Comment: Is that D6 or D7?
Comment: Looks tagged as D7 to me.
Comment: Sorry, I tagged it after this comment was posted. I thought I replied also.... must not have
Answer: I believe you would need to setup the requirement on the form you are building for the custom content type so you would add this to the date_end form entry:
<code>$form['CUSTOM_CONTENT_TYPE']['DATE_END'] = array(
...
  '#required' => TRUE,
...
),
</code>


Uniform convergence $\sum _{n=1}^{\infty }\:e^{-nx}$ on $D=[0.1,\infty)$

Question:
Uniform convergence $\sum _{n=1}^{\infty }\:e^{-nx}$ on $D=[0.1,\infty)$

$$\sum _{n=1}^{\infty }\:e^{-nx}=\sum _{n=1}^{\infty }\:(e^{-x})^n$$
so its geometric series then $$\sum _{n=1}^{\infty }\:(e^{-x})^n=\frac{e^{-x}}{1-e^{-x}}$$
now we need to find $S(x)$
$$S(x)=\lim _{n\to \infty}S_n(x)=\lim _{n\to \infty}\frac{e^{-x}}{1-e^{-x}}$$
so how can i find this and check uniform convergence?
thanks a lot
Answer: One has, as $N \to \infty$,
$$
\sup_{x \in D}\left|S(x)-S_N(x) \right|=\sup_{x \in D}\left|\frac{e^{-(N+1)x}}{1-e^{-x}}\right|\le \frac{e^{-(N+1)0.1}}{1-e^{-0.1}}\to 0
$$giving the desired conclusion.
Comment: oh okey i got it thanks a lot
Comment: i still didn't get how is $S(x)=\frac{e^{-x}}{1-e^{-x}}$?
Comment: It comes from $$S_N(x)=\frac{e^{-x}-e^{-(N+1)x}}{1-e^{-x}}$$ and $$ S(x)=\lim _{N\to \infty}S_N(x).$$
Comment: if we choose $N \to \infty$ so we get $S_N(x)=\sum _{n=1}^{N} e^{-xn}$ ? Is that correct ?
Comment: @J.Doe Yes, by definition we have here $S_N(x):=\sum _{n=1}^N\:e^{-nx}$.
Answer: We know that $f(t)=\sum_{n\geq 1}t^n$, a power series, converges uniformly on $[0,1-\epsilon]$ for all $\epsilon >0$, as its radius of converges is $1$.
So, the series $f(e^{-x})$ converges uniformly on $[\epsilon, \infty)$, choosing $\epsilon =0.1$ concludes the problem.
Answer: Actually,$$S_n(x)=\sum_{k=1}^n(e^{-x})^k=\frac{e^{-x}-(e^{-x})^{n+1}}{1-e^{-x}}$$and, since $e^{-x}<1$ (for each $x\in[0.1,+\infty)$),$$\lim_{n\to\infty}S_n(x)=\frac{e^{-x}}{1-e^{-x}}.$$The convergence is uniform because, for each $x\in[0.1,+\infty)$, and each $n\in\mathbb N$, $(e^{-x})^n\leqslant(e^{-0.1})^n$ and the series $\sum_{n=1}^\infty(e^{-0.1})^n$ converges. So, all it takes is to apply the Weierstrass $M$-test.


Simple order cancellation in Drupal Commerce, with 24 hour time limit?

Question: I want to create a way for customers to log in and edit their completed orders (the orders are registrations to classes). Compared to the standard order-edit page I want to remove all options except 'change order status to cancelled'. Preferably a simple page stating the content of the order, then some cancellation 'rules', and then a button saying 'cancel this order'.
Cancellation should then also check whether date/time of the booked class is less than 24 hours away from the moment of cancellation. If <24 hours, it should either refuse cancellation, or allow cancellation (nice for those on the waiting list), but not refund the cost of the class (paid for using a voucher - using the giftcard module)
Background: the site sells two products: one is a set of vouchers. These vouchers can then be used to buy product 2, which is a registration to a class at a specific date and time. When customers have booked a class, they now get an email with link to their order page. Their they find a button 'edit order', click that and you go to the standard order edit page which shows line-items, billing and shipping etc, and allows all existing changes to the order status. As this page is not made trough either a template or a view, I have no clue how to change what customers get to see and do with their completed order.
Also rules does not allow me to compare the time of the status change with the time/date field of the booked class, so I can't control the 24 hour limit either..
Suggestions are to build a custom module doing the above, but I have no idea how to kick that off..
All/any help massively appreciated
Answer: I haven't tested any of this, but you might some of the following useful:
Entity Operations allows you to take a Rule and turn it into a menu tab. This would be one way of getting that onto the order view page.
Something I've really been wanting to try is the Entity action links sandbox:

Allows actions and rules components to be executed via AJAX links on entity view.

Just note the patches discuss in the Sandbox README.
If you wanted to do the Rules route, these would be probably your best option, because you can use conditions and components to provide some sort of response or action system based on the order status and time.
Otherwise, you'd need to create a custom module with a custom access callback that does the appropriate checks and then executes the action if allowed. (For a developer, I think this would actually be an easier route.) But the rules stuff is intriguing.
Comment: Hello Nick, first of all many thanks for giving me some suggestions on how to tackle this.

However, I am now victim to the wonderful feeling of being a complete novice and am back here begging you (or anyone else knowledgeable) for more help.. What goes wrong for me (I fully accept the likelihood it is my stupidity and nothing else that prevents success)
Comment: - Entity Operations: Installed this module and its subs, and then basically nothing much happens. I now have a new content type called 'Entity Operations Test Node Type' which has one non-standard field only, called 'Test entities'. Under admin/structure/example_entity I can create a test entity (but it has no fields whatsoever) that I can then select when creating the content type.. and nothing else happens.
Comment: I also have a new View called 'Entity Operations Views Tab', which has a master display and one called 'entity tab', where the last on selection gives an empty page. In the read-me texts that come with the module there is a part about implementation that says "Operations are declared with hook_entity_operation_info()." Now that is where I am lost, where do I find that hook, or where do I create it (and how)? Then it says: "You also need the following Entity API properties in your hook_entity_info():" 'module' => 'my module',  'entity class' => 'Entity', // or a subclass of Entity". Help..
Comment: - Entity action links sandbox: I can see the page, but nothing I can install or use, under version control I find"Setting up this repository locally for the first time

git clone --branch 7.x-1.x http://git.drupal.org/sandbox/davereid/1883906.git entity_action_links
cd entity_action_links"

I'm pretty much a github virgin (shame on me), been there to get module tweaks for drupal modules, but this address gives me 'The requested URL /sandbox/davereid/1883906.git was not found on this server'. Again: help! (please..)
Comment: @xax Look carefully and copy&paste the [exact command](https://www.drupal.org/project/1883906/git-instructions): `git clone --branch 7.x-1.x http://git.drupal.org/sandbox/davereid/1883906.git`. This one which you posted doesn't make sense and has some mistakes. If you've other question, you need to post another one (comments are not for resolving different issues). If it's git one, ask at [SU](https://superuser.com/).


Vmware server 2.x remote console on firefox fails when VM does not come up

Question: The Vmware server 2.x remote console on firefox fails when a VM does not come up.
But this is when I need it to see what happens. The client that does not come up is windwos server 2003.

The same situation, but another firefox windwo active (the msgbox popup is still the same):
Comment: have you tried it under IE8?
Comment: good idea. next time this happens I will.
Answer: you don't state the version of Firefox used to connect. I ran into an issue where my FF was too new. i.e. 3.6.x is actually broken, and I had to install an older version so I could connect to VM console on VMware Server.
one other person said - "I downloaded the 3.5 Version again. Then installed aon the computer. No more problems :-) Don't updrade to 3.6 if you want to use vmware-server plugin."
more info at this link:
http://support.mozilla.com/nl/forum/1/564314
the older FF version (3.5.x) made everything work for me.
Comment: I too have had problems with VMWare Server V2.x's management interface under recent Firefox versions, and have just moved to using IE for such access (as most of the places I run VMWare are where I'm running Windows) What options you have if you are running something else as your current desktop environment I'm not sure - it might be worth trying Chromium before rolling FF back to 3.5.x
Comment: qcurtiscu thank you, this should solve it, will install an additional portable 3.5 soon :-)


Finding the Automorphism and Image

Question: Let $f: G \to G$.  Let $G$ be contained in $\text{GL}_2(\mathbb{R})$ and let $G$ be the Matrix
$$
\begin{pmatrix}
\pm 1 & 0\\
0 & \pm 1
\end{pmatrix}
$$
The question asked to check that $G$ is a group and then determine automorphism of $G$ and the Image of $f$. I understand how to show that $G$ is a group, but would appreciate any help on showing the Automorphism of G and the Image of $f$. Thank you
Comment: LaTeX tutorial: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: What are the generators of the group?
That is the first question you need to answer.

Here's the second half of the question
Assume $\phi : G \to G$ is an automorphism
Then $\phi $ is an isomorphism which is onto. So for any $y \in G $ there exists $x \in G $ s.t. $\phi (x) = y $
This shows $\phi (G) = G $
Now you just need to show that your function is an automorphism.
Comment: It seems clear to me that this answer is a valid hint to find the automorphisms of the group G. Thus it should not be downvoted or closed. It could have been made more clear, however.
Comment: Excuse me I keep forgetting comments and answers are distinct. Is it possible to move this to comment status?
Comment: There I answered half the question. Hopefully that cleans this up.
Answer: Of course the identity is an autpmorphism. You also have the automorphism $$A \mapsto -A$$  (check $-A$ belongs to G). The image of both is the whole G group.

Finding the Automorphism and Image


howto check iptables status with normal user?

Question: How could check if iptables is running ok in a machine ,using a restricted permission user ?
i need to monitor this...
BR
Thanks for the great Site !!!
Comment: UPDATE :

Since im tring to do this with a script ,
im getting ---->>>> sudo:: sorry, you must have a tty to run sudo

Any ideaS?
Comment: update: what about a dummy iptable rule ?   :)          i could set up a dummy rule and then any user/script could test with a ping or telnet   ...what do you think ?
Answer: iptables needs to be run as root. You can solve this by using sudo and restricting a particular user to a particular command line. Run visudo and add the following line
<code>restricteduser    ALL = NOPASSWD: /sbin/iptables
</code>
and now your restricted user can run:
<code>$ sudo /sbin/iptables -L -v
</code>
They will be able to modify your firewall configuration if you enable them to run iptables.
Comment: Note that other arguments can be forbidden by using ! But this is greatly explained in thé sudoers man page.
Comment: You can also restrict argument allowed for the command by adding them after /sbin/iptable like "restricteduser    ALL = NOPASSWD: /sbin/iptables -L -v" (but I don't know enough iptable to tell if when you put -L it prevent to use others switch that could change the config)
Comment: Greatly explained, but not clearly explained. :) The sudoers manpage is not the best written document in the world. But +1 for the comment.
Comment: I've wrapped this kind of thing in a C program that checks a couple things then runs the command.  Depending on the platform and local policies the program gets run under sudo or is installed setuid. The program can be written in languages other than C; a lot of people would use perl or python for this kind of task.
Comment: You could also replace ALL with the actual hostname


Least writes sort for a linked list python

Question: I have a linked list: 1 3 7 4 5 0 2 6. I wish to sort it in the least number of moves/writes.
I can only move elements of that list using a function insertBetween(element, after, before) which simply inserts element in between the after and before elements.
For example, the first run might want to move 1 after 0 and before 2:
insertBetween(1, 0, 2)
The list will now be 3 7 4 5 0 1 2 6.
Now it might want to move 7 to the end: insertBetween(7, 6, None)
The list will now be 3 4 5 0 1 2 6 7.
Now it might want to move 0 to the start: insertBetween(0, None, 3)
The list will now be 0 3 4 5 1 2 6 7.
The only priority for this sorting algorithm is the least number of uses of the function insertBetween(element, after, before), since using it is extremely expensive. I wish to implement it in Python.
Comment: It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, stack traces, compiler errors - whatever is applicable). The more detail you provide, the more answers you are likely to receive.
Comment: How could it be very expensive? Sorting will be linear at least, if comparison-based *n log(n)*. So copy the items to a list, sort them there, then copy them back. Since it's Python, placing stuff in a list is really not expensive. It's more like copying pointers.
Comment: @Martijn_Pieters I'm not specifically looking for someone to write code, more of a name or further information of an algorithm if it exists.
Comment: @Ami Tavory The linked list data isn't stored in python, just the function I am using is.
Comment: @Tom321 I don't see why it matters. Make a list of proxy objects, sort that, then set the real list. I really don't see why the moves are important at all.
Comment: @Ami Tavory The problem I have is that there is no way of assigning the initial list to the sorted list. The only method of interaction with the data is using the function `insertBetween(element, after, before)`
Answer: Don't focus on the elements you move. They can be moved anywhere and are not the problem. Instead, focus on the elements you don't move. Those need to be already sorted. So if you have N elements and a longest sorted subsequence with length L, you just need N-L moves to move the N-L elements not in that subsequence, and you can't do better. Finding the longest sorted subsequence is a standard problem, but look here if you don't know how to do it.
Comment: I wasn't thinking of it like this, thanks. I can see that a max number of moves would be N-L, but if there are multiple sorted subsequences that occur whilst sorting, there must be an optimal way of sorting them. I'll have to create some toy examples.
Comment: *"occur whilst sorting"*? Not sure what you mean. I'd just first find a longest sorted subsequence, and then afterwards move all other elements appropriately.


Image of a strip under the map $e^z$

Question: Please help me in finding the image of the strip $\lbrace (x,y) \in\mathbb{C} : mx-\pi<y<mx+\pi,-\infty<x<\infty\rbrace $ under the mapping $w=e^z $ ?
Where $m$ is any real number.
Comment: What's $m$ supposed to be?
Comment: $m$ is any real number, edited
Answer: $${\mathbb C}\setminus \{0\}$$
as for any complex $(a,b)\neq0$, you can find $\rho>0$ and $\theta\in[-\pi,\pi]$ such that
$(a,b)=\rho e^{i\theta}=e(\ln(\rho)+i\theta)$.
So take $x=\ln(\rho)$ and $y$ can be found in $[mx-\pi,mx+\pi]$ such that $y-\theta=2k\pi$ ($k\in\mathbb Z$)
Hence, $(x,y)$ is in your strip and $e^{(x+iy)}=(a,b)$
EDIT : except that your strip doesn't contain $y=mx\pm\pi$. So you will not have all points $\rho.e^{i.(m\rho+\pi)}$ that is some kind of spiral :
$${\mathbb C}\setminus \{\rho.e^{i(m\rho+\pi)}\;|\;\rho\ge0\}$$

Image of a strip under the map $e^z$


How to use @FindBy annotation in Selenium WebDriver

Question: I want to know what wrong with my code, because when I try to test my code, I didn´t get anything.
public class SeleniumTest {

private WebDriver driver;
private String nome;
private String idade;

@FindBy(id = "j_idt5:nome")
private WebElement inputNome;

@FindBy(id = "j_idt5:idade")
private WebElement inputIdade;

@BeforeClass
public void criarDriver() throws InterruptedException {

    driver = new FirefoxDriver();
    driver.get("http://localhost:8080/SeleniumWeb/index.xhtml");
    PageFactory.initElements(driver, this);

}

@Test(priority = 0)
public void digitarTexto() {

    inputNome.sendKeys("Diego");
    inputIdade.sendKeys("29");

}

@Test(priority = 1)
public void verificaPreenchimento() {

    nome = inputNome.getAttribute("value");
    assertTrue(nome.length() > 0);

    idade = inputIdade.getAttribute("value");
    assertTrue(idade.length() > 0);
}

@AfterClass
public void fecharDriver() {

    driver.close();

}

}
I´m using Selenium WebDriver and TestNG, and I tried to test some entries in JSF page.
Comment: what is the output you got?
Comment: The code is ok, it works for me as expected. Are you sure your `http://localhost:8080/SeleniumWeb/index.xhtml` is ok?
Answer: There's a difinition for @BeforeClass :
@BeforeClass
Run before all the tests in a class

And @FindBy is "executed" each time that you'll call the class.
Actually your @FindBy is called before the @BeforeClass so it won't work.
What i can suggest to you is to keep the @FindBy but let's start to use the PageObject pattern.
You keep your test's page and you create another class for your objects like :
public class PageObject{
  @FindBy(id = "j_idt5:nome")
  private WebElement inputNome;

  @FindBy(id = "j_idt5:idade")
  private WebElement inputIdade;

  // getters
  public WebElement getInputNome(){
    return inputNome;
  }

  public WebElement getInputIdade(){
    return inputIdade;
  }

  // add some tools for your objects like wait etc
}

Your SeleniumTest'll looks like that :
@Page
PageObject testpage;

@Test(priority = 0)
public void digitarTexto() {

  WebElement inputNome = testpage.getInputNome();
  WebElement inputIdade = testpage.getInputIdade();

  inputNome.sendKeys("Diego");
  inputIdade.sendKeys("29");
}
// etc

If you're going to use this tell me what's up.


How do I avoid behaviors are invoked after an AJAX call?

Question: I have a search result page, with the first set of data being fetched during the page load, and we add a Load More button. Clicking on this button fires an AJAX call, using the ajax_links_api module. After the AJAX call is completed, we append more search results to the current set.
I have a behavior where I read the URL parameter; if it exists, I open a Colorbox.
If the colorbox opens on page load, we close it, and then click on Load More (which fires AJAX); then the Colorbox JavaScript is fired again, and we see the popup in action again.
I don't want to fire the Colorbox JavaScript after AJAX is completed/fired.
I tried jQuery Once, but it didn't work.
How can I achieve this? Can I detect when an AJAX call happens?
The following is the code I am using.
<code>Drupal.behaviors.openColorbox = {
  attach: function (context, settings) {
    if ($('body', context).hasClass('page-search-site')) {
      var nid = url('?node');
      if (nid != undefined) {
        if (nid.trim()) {
          $('div.search-result')
            .find('.node-' + nid)
            .once('colorbox-clicked')
            .click();
        }
      }
    }
  }
};
</code>
Answer: You are using .once in the wrong spot
<code>(function($, Drupal) {

  "use strict";

  function openColorbox(context) {
    $(context).find("div.search-result").once("openColorbox").each(function () {
      if ($('body', context).hasClass('page-search-site')) {
        var nid = url('?node');
        if (nid != undefined) {
          if (nid.trim()) {
            $('div.search-result')
              .find('.node-' + nid)
              .click();
          }
        }
      }
    }
  }

  Drupal.behaviors.openColorbox = {
    attach: function (context) {
      openColorbox(context);
    }
  };

}(jQuery, Drupal));
</code>
Note that this is D8 style. If you are using D7, the above will not work as it is done differently, and you didn't tell us which Drupal version you are using.
Comment: Well, my original post was edited. I am using drupal 7.
I tried the above code, and it wont work.
Reason - I have this class "'.node-' + nid" multiple times...
Comment: So what are the conditions that it should execute under?
Comment: As soon as the DOM is ready, the JS should execute, and not even once after that. I have multiple AJAX calls on the page, some automated, some on some events. The JS should not fire, post the AJAX events.
Comment: Have you got more than one div.search-result on the page?
Comment: Yes, each search result div has this class.
Comment: Ok then, what is parent of those divs that has a unique ID?
Comment: Jaypan, I solved by adding the JS in a module, inline. that is, I took the JS out of Drupal Behaviour.


Why is normalizing seasonal adjustment factors done additively?

Question: One of the methods for dealing with seasonal influence is to establish a multiplicative factor for each season within a "year". For example, this happens with exponential smoothing models of type $(*,*,M)$. These adjustment factors need to be normalized - if there are $m$ seasons in a "year", then the seasonality normally represents only $m-1$ degrees of freedom.
The standard normalization requirement for adjustment factors $f_1, \dotsc, f_m$ seems to be to require that $\sum_{i=1}^m f_i = m$ - that is, the arithmetic mean of the factors is $1$. This is certainly the case in Hyndman et al., "Forecasting wtih Exponential Smoothing" (section 8.2).
I would have expected the requirement that the geometric mean be $1$, i.e., $\prod_{i=1}^m f_i = 1$. This because the standard for additive seasonal adjustment is that $\sum_{i=1}^m f_i = 0$; these two are equivalent under taking logarithms. Is there a good mathematical reason for the choice, or is it just a convention?
Answer: It doesn't make much difference in practice. But your suggested multiplicative adjustment is more consistent with the way the seasonal factors are used in ETS(*,*,M) models.
Comment: I know this is old but I didn't find any other question on this matter. If we have an estimate of the trend. Wouldn't multiplicative (product=1) seasonal normalization be more appropriate only if the trend estimate is centered on the geometric mean of the data (ie. if the log(trend) is centered on the arithmetic mean of the log transformed data)? And would additive (mean=1) normalization be more appropriate if the trend estimate is centered on the arithmetic mean of the data?
Answer: It may depend on the context.
Suppose you are seasonally adjusting something like quarterly GDP.  This makes sense multiplicatively because all the figures now are roughly a multiplicative factor higher (based on inflation and growth) than they were some years ago.
But if you want the seasonally adjusted figures for the four quarters to add up to the actual annual total (to avoid having to explain what a different "seasonally adjusted annual total figure" might mean) then you may need need to normalise the seasonal adjustments additively.


How to find correlation among dependent variables?

Question: If I want to find how strongly a dependent variable is related to another dependent variables in a study, do I make use of multiple regression?
The reason I am asking is because the book mentions that for instance to conduct a standard regression, I will need to input all the independent variables and the corresponding dependent variable into SPSS. Not sure the procedure if I need to find a relationship between two or more dependent variables.
Kindly clarify. Thanks
Answer: If you want the simple bivariate correlation(s), just leave out the other variables (the ones you're treating as independent presently) and calculate the correlation(s) between the variables you're interested in. It doesn't necessarily matter that they're dependent variables for your other analyses (unless you want to take those predictive models into account). Bivariate correlations don't require designation of in/dependent variables.
If you want to remove the variance that's explained by the independent variables from your dependent variables, you can use partial (or semipartial, depending on what you're really after) correlations, structural equation modeling, and probably several other methods. It sounds like you're looking for something in that family of analyses, but in case you're actually looking to predict multiple dependent variables from your independent variables, multivariate-regression is the variation on multiple regression that handles that. Structural equation modeling also works for that purpose (I think the SEM gurus would say it subsumes these analyses, technically), and canonical correlation is similar too.
Comment: @user39531: was there anything else you wanted to know here, or is my answer [acceptable](http://meta.stackexchange.com/a/5235/246931)?
Comment: Sure thing. If you know which approach you want to take, consider looking around for other questions about the specific method if you want any further help, and feel welcome to ask another if you can't find the right question already.


External anchor link or map for attached images

Question: I'm looking to wrap the attached images (part of the content type) in an anchor. Typically we are putting together pages that are cross promotions so they go out to other non-Drupal sites
For now we are putting the images in via HTML with the a and img tags on the ones we need external links for. Now we are using views to have a grid page, block, views slideshow but these manually input images are not visually promoted in these new views.
Some had suggested having the link below the image in text (using the link module) but that solution is confusing users who see our standard 'click here to book' and 'book now' phrases on the image.
Simply how can I wrap the image with a link? (with or without the link module, which doesn't wrap)
Answer: You can copy the templates views uses to your theme and modify them so that a field returned in the view is used to theme another.  Views has this built in in its latest versions, but only allows divs, spans, etc, and you want an anchor.  Check out Exposing Individual Fields on Output for Styling here for an example of what I am talking about.  There they wanted to just wrap an in a div to set the color, but you could use the same concept to wrap it in an anchor.


Why can Gibbs sampling outputs be used in Rao-Blackwellization?

Question: I'm currently learning Chib (1995)'s method to calculate the marginal likelihood of a Bayesian model using Gibbs sampling outputs. I'm stuck in the Rao-Blackwellization step.
Suppose $\mu$ and $\phi$ are the model parameters, and y is the data. The key step is to calculate $p(\mu,\phi|y)$, which can be written as $p(\mu |\phi,y)*p(\phi |y)$. The first part is the full conditional and known. The second part can be further written as $p(\phi |y)=\int p(\phi | \mu, y)*p(\mu|y) d\mu$. Based on Rao-Blackwell theorem,
$$p(\phi^* |y) \approx \dfrac{1}{N} \sum_{i=1}^{N} p(\phi^* | \mu^i, y)$$
As far as I understand, this is an average of the full conditional $p(\phi^* | \mu, y)$, over the posterior marginal distribution of $\mu$.  So, we need to supply a set of realizations of $\mu$ from the posterior marginal distribution of $\mu$, i.e., $p(\mu|y)$.
However, Chib suggests that we can insert the Gibbs sampling outputs of $\mu$ into the summation. But aren't the outputs obtained from Gibbs about the joint posterior $p(\mu,\phi|y)$? Why suddenly can we use the results from joint distribution to replace the marginal distribution?
Some discussions about Gibbs and Rao-Blackwellization are here. But my question is not covered by the answers. Is this a misunderstanding about Gibbs sampling?
Comment: You question about marginal and joint has been answered here:https://stats.stackexchange.com/questions/213052/sampling-from-marginal-distribution-using-conditional-distribution/213057?noredirect=1#comment641484_213057
Answer: Note: This issue has already been discussed on X Validated, but I cannot trace the items.Like this one.
This is a standard misunderstanding of multivariate simulation, a Monte Carlo version of the Law of the Unconscious Statistician: when creating a sample $\{(\mu_i,\phi_i),\,i=1,...,I\}$ from a joint posterior distribution $p(\mu,\phi|y)$ the subsamples $\{\mu_i,\,i=1,...,I\}$ and $\{\phi_i,\,i=1,...,I\}$are automatically distributed from the marginal posterior distribution $p(\mu|y)$ and $p(\phi|y)$, respectively. Hence, assuming the Gibbs sampler has reached its stationary regime, using the output of the sampler into
$$\dfrac{1}{N} \sum_{i=1}^{N} p(\phi^* | \mu^i, y)$$
is valid since
$$
\underbrace{\mathbb{E}^{\mu^i}[p(\phi^* | \mu^i, y)]}_{\text{expectation in }\mu^i}=\int p(\phi^* | \mu, y) p(\mu,\phi|y)\text{d}\mu\text{d}\phi = \int p(\phi^* | \mu, y) p(\mu|y)\text{d}\mu
$$


Extract a row from table

Question: I am trying to extract a specific row of data from a table in a live webpage using the following code.
requestCrossDomain('https://email@example.com&p=grid_id&p=T10M&p=DLYRANGE&step=2&lon=16', function(results) {
    $('#loadedContent').css("display","").html(results);

    //alert($($('#loadedContent table')[4]).text());
//The above line parses the table i need and displays the content in an alert box.

//But when I try the same line of code to display a specific row, it doesnt display anything

    alert($($('#loadedContent table tr:eq(2)')[4]).text());

 });

Note that the Website does not assign a name or id to the tables in its page. so I try to extract the table using the position. I am quite successful until this. But when i try to extract a specific row of data from the table. I could not. What should I do to extract a row of data from the table.
P.S: there are multiple tables in the page and none of it is assigned a name or id
Comment: `alert($('#loadedContent table:eq(4) tr:eq(2)').text());`
Comment: wow. dat was great. thank u :)
Answer: You can use :eq() selector here
alert($('#loadedContent table:eq(4) tr:eq(2)').text());

This will select 3rd tr inside 5th table

Extract a row from table


Warning: POST Content-Length of 11394639 bytes exceeds the limit of 8388608 bytes

Question: I have gone through all the solutions that I could find including these
ones but couldn't resolve my problem.
I have made following changes to both php.ini production & development version;
post_max_size = 5000M
upload_max_filesize = 5000M

However it doesn't make any difference. If I am trying to upload image files of large value, I am receiving
below response error in my console-log;

Warning:  POST Content-Length of 11394639 bytes exceeds the limit of
8388608 bytes in Unknown  on line 0
 []

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

var data = JSON.parse(this.responseText);

I am hoping to have clarified my issue. Thanks for looking into it in advance !
Comment: Do this - do `phpinfo();` on the page, and see where is `php.ini` located. Make sure you edit the right file, and restart the server?
Comment: I have php production and development version and I have changed both but still doesn't help...!!
Answer:
I have made following changes to both php.ini production & development version;
post_max_size = 5000M
upload_max_filesize = 5000M

I did have the same issue, but after changing the php.ini file and rebooting apache this worked for me.

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I can see that you have some issue there. Check the file against any dodgy characters as it seems to be causing an issue. Sometimes when you want to upload a file, its name could have illegal characters for the database or js. Make sure that every character in the file name you try to upload does not have any illegal character, or it is encoded/decoded accordingly.
I hope I helped - this is my first post.
Let me know how did it go!
Best wishes,
mateekk
Answer: I had the same problem in my ubuntu 16.04.
After the upgrading of php, I have several php.ini and at the begining I was mixed up.
Under
/etc/php,
I have the folders php5.5, php5.6, php7.0, php7.1, so be sure to correct the right one (because ,due to legacy, I was used to work in /etc/php5).


Network share as USB connected device

Question: I have a situation where I am having to work around a medical vendor who has for security reasons limited the connectivity to a system.
The only connection I have available to the system is USB and I need to (somehow) have this USB port connect to a network share of a remote server but appear to the machine as a hard drive / flash drive and work with out installing any drivers or making networking changes on the computer. When the drive is selected it should show the contents of the shared folder etc.
I am unable to modify the medical system in any way but it is a Windows OS running with a skin.
Many thanks!
Comment: If the machine has no existing network connection to the share and you are not allowed to make network changes (including DHCP or static assigning IP), then this is functionally impossible.  If the machine can already see the network share or you would be allowed to modify TCP/IP settings then there is a variety of ways to accomplish what you want (Good news, you probably wouldn't need to even use the usb slot if it already has a network connection).
Comment: And that's how you leak medical data. If vendor went through all the troubles of blocking network access, don't go around it.
Answer: Do you really mean the "only" connectivity? eg No wired network or WiFi or anything?
If so, then what you describe is impossible. USB and network are totally different. You can get USB to network adapters but they will probably require drivers.
If the machine IS locked down, then they will have disabled DHCP by default so you will have no way of configuring the adapter. If they haven't disabled DHCP then you can probably use DHCP to give it an IP address/DNS server etc. and then, assuming you have a network share with files, do the suggestion above.
However, that won't in any way appear to be a USB drive. Depending on the application, it may refuse to see a mapped device as a USB disk.
If it is a medical device, I'd prefer it if you tried not to hack it yourself. I imagine the vendors have locked it down for a reason. I for one, would not like to be in hospital with my life depending on a device that had been hacked with advice from serverfault, by people with literally no idea what the device does or is. We could very easily suggest things that may fatally compromise the functionality of the device.
Answer: If you have enough permissions on the systems, it is possible to do something you want using these two commands:
MKLINK /D C:\Share \\Server\Share
SUBST S: C:\Share

It would result into a new drive (S:\), which would open contents of \\Server\Share.
Another option, using USB, can be taking a NTFS formatted USB flash and running the following command on it:
MKLINK /D Share \\Server\Share

Then, when you would see a Share folder inside the USB, and entering that folder would get you to the share.

Network share as USB connected device


How to connect to multiple Schema in Oracle RDS

Question: I am creating a CI/CD pipeline to run my application, In my application it has multiple databases like database1, database2 ..... previously I was using AWS aurora Postgres , now I want to check the compatibility of the application with oracle RDS. Well, I don't know much about the oracle. I got to know that we can create multiple schemas
My application has 7 databases with a different names and in CI/CD pipeline I am using SQL plus to connect to the database and created all schemas, but I don't  know how can I connect to a particular schema
I was able to connect to a database that I specified when creating Orcale RDS using:-
sqlplus  firstname.lastname@example.com:1521/demo

I have used the following command to create the schema:-
CREATE BIGFILE TABLESPACE  database1 DATAFILE SIZE 128M AUTOEXTEND ON NEXT 1M
MAXSIZE unlimited LOGGING EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO;

create user  database1 identified by database1 profile default default tablespace
database1 TEMPORARY TABLESPACE TEMP ACCOUNT UNLOCK;

GRANT create trigger, CONNECT, RESOURCE, create table, create view, create
procedure, create sequence TO  database1;

after that, I am running SQL plus command to connect to database1and it is not working
sqlplus  email@example.com:1521/database1

Just wanted to is there any way to connect to a  particular schema as my application is using jdbc:oracle:thin   to connect to the database
Answer: In Oracle, schema = user ("create user database1 ..."), so what you're looking for is this:
sqlplus email@example.com:1521/demo

'demo' is actually the network service name, which will be the same for all users/schemas within the physical database instance.


How to include "children" content types on a content type page?

Question: Let's say I override the way a content type page looks. My content type is Parent. So I create a page named: node--parent.tpl.php
But how about when you want to use nested content types?
Let's say:

Content Type Parent
Content Type Child

I use node--parent.tpl.php, but how do I display the children that belong to the parent? (linked using Contextual Filters).
For example in node--parent.tpl.php have a way to display:
Parent Name: Joe
Children: Sue, Phil, Mary and Jim
Answer: Contextual filters are part of Views, they can't be used to link content types together. If you're simulating a relationship between the two types using a contextual filter, it will only exist in the very narrow context of that View.
The standard way to link content types together is with the Entity Reference module. Something similar to the following should get you what you're looking for:

Add a multiple cardinality entity reference field to the Parent content type, referencing the Child type.
Optionally install Inline Entity Form, if creating the Child content while inside the Parent edit form makes sense for your use case. It provides a widget for the entity reference field type. I won't go into details, if you choose that widget and visit the edit form for a Parent node, you'll see what it does.
Use either the autocomplete or inline entity widget to relate the Child nodes to the relevant Parent nodes.
Visit the display options for the Parent content type, choose "Rendered Entity" for the display format of your entity reference field, and in the settings choose an appropriate view mode.

That will render the Child nodes inside the Parent node without the need to alter the template file at all.


Hide android soft keyboard when click on navigation drawer in fragment

Question: I want to hide soft keyboard when click on hamburger Icon in FragmentDrawer.I am using ActionBarDrawerToggle in Fragment. When I use Input Method Manager in onDrawerOpened and onDrawerClosed , it show error getSystemService and getCurrentFocus method cannot resolve.
Comment: Possible duplicate of [Close/hide the Android Soft Keyboard](http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard)
Comment: show your code.
Comment: Possible Duplicate http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard
Answer: Set the "Id" of the Main Layout. and in the "OnClickListener" call the method pasted below.
<code>public static void hideKeyboard(Activity activity) {
        if (activity != null) {
            if (activity.getCurrentFocus() != null) {
                InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity
                        .INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
                        .getWindowToken(), 0);
            }
        }
    }
</code>
Answer: Use Activity to getCurrentFocus
<code>      @Override
      public void onDrawerStateChanged(int newState) {
        InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
        InputMethodManager.HIDE_NOT_ALWAYS);
        }
</code>


Can the Django admin GUI filter on whether a text field is blank?

Question: I have a Django model containing a text field. In the admin GUI, I'd like to be able to filter just those records containing text in this field. Is it possible?
Code something like this will filter on the contents of textfield, but shows filters on 'All' and each distinct entry in the filter. I'd like to filter 'All' or 'Contains something'.
class MyModel(models.Model):
    # ...
    textfield = models.CharField(max_length=100)
    # ...

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('...', 'textfield', '...')
    list_filter = ('...', 'textfield', '...')

Comment: Possible duplicate of [Filtering Django Admin by Null/Is Not Null](http://stackoverflow.com/questions/7691890/filtering-django-admin-by-null-is-not-null)
Answer: Yes, but it's not documented. Look at django\contrib\admin\filterspecs.py to see how the default filterspecs are created and how you can create your own. This feature is planned for version 1.1, and there's already a patch if you want to try the feature now on the latest HEAD revision: http://code.djangoproject.com/ticket/5833
Also not documented is the fact that you can put arbitrary GET parameters on the URL of your change_list page to filter the results. For example /admin/app/model/?field1__lte=5&field2__gte=10 Unfortunately ?field__isnull=True won't work, but you can easily experiment to see if you could find a filter that would work in your case.
Answer: Yes, you can extend SimpleListFilter and easily do this since django 1.4.   See:
See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
Answer: No.  See http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-filter

Set list_filter to activate filters in
  the right sidebar of the change list
  page of the admin. This should be a
  list of field names, and each
  specified field should be either a
  BooleanField, CharField, DateField,
  DateTimeField, IntegerField or
  ForeignKey.

But...
Two things.

Be sure to allow blank for your text field.
class MyModel(models.Model):
    # ...
    textfield = models.CharField(max_length=100,blank=True)
    # ...
Add a is_blank method to help with processing.  It doesn't filter, but it's helpful.
def is_blank(self):
    return len(self.textfield) == 0


Impossível conectar-se ao servidor remoto - Ao consumir webservice C#

Question: Eu tenho uma aplicação desenvolvida em C# que consome um webservice também em C#.
Em alguns casos (não é sempre e não é em todos os lugares/clientes) na hora de consumir o webservice eu recebo o seguinte erro:

Impossível conectar-se ao servidor remoto
    Uma tentativa de conexão falhou porque o componente conectado não respondeu
    corretamente após um período de tempo ou a conexão estabelecida falhou
    porque o host conectado não respondeu meuip:80

Eu já tive problemas com um outro erro (que estourava na mesma linha) que era:

Descrição do erro: O nome remoto não pôde ser resolvido: 'webservices.meusite.com.br'

Mas consegui solucionar apenas repetindo a tentativa caso houvesse erro.
O stacktrace mostra o seguinte:

<code>em System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   em System.Net.HttpWebRequest.GetRequestStream()
   em System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
   em Updater.WebServ.Servico.Metodo(Int32 Id)
   em Updater.TelaPrincipal.btTeste_click(Object sender, EventArgs e)
</code>

O mais intrigante de tudo é que não importa quantas vezes eu tente aqui, nunca dá erro. O problema é apenas em alguns lugares.
O que pode estar causando isso?
Comment: Qual é o StatusCode retornado no response? O StatusCode indica se o problema é no cliente ou no servidor.
Comment: acredito que seja problema no Timeout da operação, já verificou a conexão dos seus clientes?
Comment: @TobyMosque A conexão dos que eu testei é praticamente a mesma coisa da minha aqui.
Comment: @RenattoMachado Desculpa a ignorância, mas onde eu vejo o StatusCode?
Comment: @JéfersonTavares aqui tenho uma aplicação que também faz alguns acessos via web, e tenho problemas quando a conexão é 3G tendo que reconectar o modem para que possa funcionar o serviço. Não é esse o caso? A conexão via web de seus clientes é feita de que forma?
Comment: @AndrewAlex ADSL, os dois que eu testei hoje de manhã tinham conexões boas. Mas isso pode ter sido causado por instabilidades ou algo assim então.
Comment: O StatusCode é uma das propriedades do seu response. Você está usando HttpClient para fazer a requisição?
Comment: @JéfersonTavares Isso depende muito dos tipos de operações existentes no seu WebService e da tecnologia aplicada no WebService, voce utiliza WebServices mesmo ou WCF? no seu contrato existe alguma transferência de metadados? a quantidade de dados transmitidos em seus métodos é grande? Ao que parece pode ser um problema de Timeout ou mesmo um limite de cota no tamanho da mensagem.
Comment: @JulioBorges, deve ser timeout então, porque as informações que eu recebo são pequenas strings. Pra constar, eu utilizo webservices, não WCF. E, como eu citei acima, a quantidade de dados transmitida é bem pequena.
Comment: já que após algumas tentativas você obtêm sucesso, o problema está na conexão de internet de seus clientes que não é de boa qualidade. Um software que responde adequadamente em várias máquinas não pode ser o causador da falta de resposta em outras.
Answer: O problema deve ser Timeout, tente configurar as chaves de Timeout na chave bindings do arquivo de configuração do software cliente.
<code>     <basicHttpBinding>
        <binding name="WebServiceSoap"
                 closeTimeout="00:30:00"
                 openTimeout="00:30:00"
                 receiveTimeout="00:30:00"
                 sendTimeout="00:30:00"
                 allowCookies="false"
                 bypassProxyOnLocal="false"
                 hostNameComparisonMode="StrongWildcard"
                 maxBufferSize="655360"
                 maxBufferPoolSize="524288"
                 maxReceivedMessageSize="655360"
                 messageEncoding="Text"
                 textEncoding="utf-8"
                 transferMode="Buffered"
                 useDefaultWebProxy="true">
          <readerQuotas maxDepth="32"
                        maxStringContentLength="8192"
                        maxArrayLength="1638400"
                        maxBytesPerRead="40960"
                        maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None" realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
</code>


basic_string UTF16 encoding to NSString

Question: What is the best method to convert from a C++ basic_string<wchar_t> object with UTF16 encoding to an Objective-C NSString object?
Can I cast from wchar_t* to char* like so and still have stringWithCString use the string correctly?
[NSString stringWithCString:(char*)wideCharBasicString.c_str() encoding:NSUTF16StringEncoding];

Thank you,
Shane
Comment: To be very general, if you guarantee that your original string is UTF-16 (not just UCS-2), you could copy it into a `uint16_t[]`, then use `iconv` to create the desired encoding (if it differs from UTF-16) and then construct your NSString from there.
Comment: A `wchar_t` on iOS is 32-bit wide IIRC.
Comment: I just verified it is indeed 32-bit. How would I go about the same method with UTF32 encoding?
Comment: So NSString *myNSString = [NSString stringWithFormat:@"%S",wideCharBasicString.c_str()]; seems to do the trick. stringWIthCString was only giving me an empty NSString.

Also if anyone needs to use this like I did, the flag -fshort-wchar turns wchar_t to 16-bit on iOS.
Answer: If the buffer is UTF-16 encoded, you could do this:
    NSData* data = [[[NSData alloc] initWithBytesNoCopy:buffer
                                                 length:length
                                           freeWhenDone:NO] autorelease];
    NSString* result = [[NSString alloc] initWithData:data
                                             encoding:NSUTF16LittleEndianStringEncoding];

stringWithCString looks like it barfs on multi-byte character buffers, stopping at the first NULL byte it finds.
[UPDATE]
I filed a bug with apple, and this is the expected behaviour, apparently. stringWithCString only supports 8-bit encodings and will stop at the first zero byte.
Comment: Okay it's old but I was in the same case : I confirm stringWithCString won't work with UTF16 in IOS 5.1
Answer: I used the following to do the converison:
NSString *myNSString = [NSString stringWithFormat:@"%S",wideCharBasicString.c_str()];

Also if anyone needs to use this like I did, the flag -fshort-wchar turns wchar_t to 16-bit on iOS.
Answer: This is the least ugly way to do it (utf16):
NSString* nsstr = [NSString stringWithCharacters:str.c_str() length:str.length()];

basic_string UTF16 encoding to NSString


Does $\exists f'(x_0)$ imply that $f$ is defined on $N(x_0, \epsilon)$ for some $\epsilon>0$?

Question: We define the derivative at $x_0$ as,

For $f : (a,b) \to \mathbb{R}$, and $x_0 \in (a,b)$
$$f'(x_0) \overset{def}{=} \lim_{h\to 0} \frac{f(x_0 + h) - f(x_0)}{h}$$

Question
So, we often use the expression $\exists f'(x_0)$, then
does it imply that $f$ is defined on $N(x_0, \epsilon)$ for some $\epsilon>0$?
Or is there any counterexample for this claim?
Comment: Yes, it does imply that.
Answer: If a function is differentiable  at some point $x_0$  then not only it is defined on some neighborhood of $x_0$, but the function is also continuous at that point.
The existence of
$$f'(x_0){=} \lim \frac{f(x_0 + h) - f(x_0)}{h}$$ implies that $$\lim _{x\to x_0} f(x) =  f(x_0)$$
Answer: Actually I have seen in most calculus books that they assume this condition of $x_0$ being in the interior of your domain. So, technically we can only say that a function is differentiable if this function is defined in an open domain.
But in general, one can define (extend the definition of) a function to be differentiable in a set $K\subset \mathbb{R}^n$ even if the set $K$ is not open. We say that a function $f:K\to \mathbb{R}^m$ is differentiable if there exists an open set $U$ containing $K$ and a (usual) differentiable function $F:U\to \mathbb{R}^m$ such that $F|_K=f$.


How to limit number of points that user can add through Geofield widget to Openlayers maps?

Question: Im using the modules stuck very similar to one described here (
Need a simple Google Maps solution; lost in the labyrinth of modules).
Geofield, Openlayers, Drupal 7

The difference is that I dont use Address field for auto detecting the lat/lang from address. The Geofield field widget type is set to "Openlayers map" so the points can be manually added by user to the map when the node is being edited.
Is there any way to limit the maximum number of points that user can mark on map? (to 1)
Answer:
In the settings of the GeoField you'd like to limit the entry for, set Storage Options to 'Store each simple feature as a separate field.'
Then in Location field settings, you can set the limit to one.

Number 1 is important, as it will make sure that clicking on the map a second time, moves the point around, instead of creating new points.
Comment: Strange, let's dig into this. The map settings of the map you're using to do the input (under admin/structure/openlayers/maps) might be important. I've noticed that enabling some options messes up the experiences here and there. These are the settings I used under the 'Behavoirs' section of the map I'm using: http://i.stack.imgur.com/LwUaz.jpg,
http://i.stack.imgur.com/wP9fL.jpg. Does that have any effect?
Comment: I tried it as you describes but it still possible to add more points, even with the limit to 1.
Comment: Didn't work for me, with the behaviors as you described, the user can still select multiple points. Maybe what you mean in "Location field settings" is something different than the "Number of values" ?
Answer: Try the 7.x-2.x-dev version of geofield. It fix this bug.
Answer: If you go to your content type > manage fields and click edit next to your Geofield, then scroll to the bottom of the page you should have options for Multi-value input handling and Number of values either/both if these should give you the control you want.
Answer: If you go to your content type > manage fields and click edit next to your Geofield, then scroll to the bottom of the page you should have options for set Storage Options to 'Store each simple feature as a separate field. check thisn as it is a radio button


Bitbucket Pipeline - Fails to build Quarkus native image (Out of Memory)

Question: I am trying to setup a Bitbucket Pipeline for building a native Quarkus image of my app, but the build fails with

Caused by: java.lang.RuntimeException: Image generation failed. Exit code was 137 which indicates an out of memory error. Consider increasing the Xmx value for native image generation by setting the "quarkus.native.native-image-xmx" property

I have increased the size of the pipeline touse double amount of memory (8 GB instead of 4 GB) and tried to give docker more memory, but without any success. I have changed the database layer from mongodb to postgres. After that change the build fails with mentioned error. My bitbucket-pipelines.yml:
pipelines:
  branches:
    develop:
      - step:
          name: Build Native Image
          image: quay.io/quarkus/ubi-quarkus-native-image:21.2-java11
          services:
            - docker
          size: 2x
          caches:
            - maven
          script:
            - ./mvnw package -Pnative
          artifacts:
            - target/*-runner

definitions:
  service:
    docker:
      memory: 7128

Can I set other parameters to assign more memory to the build?
Comment: Can you try setting `-Dquarkus.native.native-image-xmx=5GB`?
Answer: Graalvm will grab as much memory as it can get access to and sometimes that his the outer limit. Thus even if you give it more it will keep failing.
Thus it might be a question of actually constraining the JVM so graalvm will start garbage collecting sooner.
You do that setting -Dquarkus.native.native-image-xmx=5GB as suggested by the error message and @geoand.