How to programatically create an address field

Question: I would like to use the address field module in my module.  How do I create an address field and an instance for that field.  I haven't found any code in the module that defines what the array structure should look like.
I found this code in the commerce module (under modules/customer/commerce_customer.module):
if (empty($field)) {
  $field = array(
    'field_name' => $field_name,
    'type' => 'addressfield',
    'cardinality' => 1,
    'entity_types' => array('commerce_customer_profile'),
    'translatable' => FALSE,
  );

  $field = field_create_field($field);
}

if (empty($instance)) {
  $instance = array(
    'field_name' => $field_name,
    'entity_type' => 'commerce_customer_profile',
    'bundle' => $profile_type['type'],
    'label' => t('Address'),
    'required' => TRUE,
    'widget' => array(
      'type' => 'addressfield_standard',
      'weight' => -10,
      'settings' => array(
        'format_handlers' => array('address', 'name-oneline'),
      ),
    ),
    'display' => array(),
  );

I can modify that to meet my needs, if someone is familiar with this module and could point out some attributes that may be missing, I'll accept their response as an answer to this question.
Update The address that I'm importing may contain up to 6 lines for the street address (all for one location) as defined by RETS.  Is it possible to store a street address this long in an address field?  If not I can concatenate the extra addresses into the second address line.
Comment: Those arriving here may also be interested in this question: http://drupal.stackexchange.com/q/45905/10645
Answer: I had a similar question these days, and I tried to see if the Features module could help. Features worked to me.
You can create the field by the UI and then export a feature with the address field already created.
After that you can move the inc files for your custom module and add an include on your .module file:
include_once('[your_module].features.inc');

Then, you will need to add the some lines on your .info from the info file of the exported feature.
Your info file will need something like this:
dependencies[] = "features"
dependencies[] = "text"

features[field][] = "node-article-field_address"

This question may help you too: Develop a module that adds a new content type with custom fields.
Comment: Don't have time to test atm but I'll accept your answer because it sounds legit
Answer: This is also a useful link for creating just address field form values: http://drupal.org/node/970048


Convergence in probability and $L_2$ for normal random variables

Question: In an answer here: Convergence of identically distributed normal random variables, the following lemma is mentioned:

Lemma: Let $X_1, X_2, \ldots$ be a sequence of zero-mean normal random
  variables defined on the same space with variances $\sigma^2_n$. Then,
  $X_n \to X_\infty$ both in probability and in $L_2$ (and hence also in
  distribution) if and only if $\sigma^2_n \to \sigma^2 < \infty$. In
  this case, the limit $X_\infty$ is also normally distributed with mean
  zero and variance $\sigma^2$.

I'd like to find out more about this lemma. Does it have a name?
Comment: I like it because it makes no assumption on the dependence between the variables in the sequence. It also provides a nice clean basis for thinking about things like Riemann sums of normal random variables (Think: Integrals of Brownian motion), allowing one to conclude the distribution is normal without having to think very hard or carefully about anything strange that could be happening in the limit.
Comment: Would you like to see a proof, is that it? No, it really doesn't have a name.
Comment: It is the only case I saw that convergence in probability may imply convergence in L2, but no source I found says anything about it. What are the tools used in this direction?
Comment: Uniform integrability. Are you familiar with that?
Comment: I claim no particular novelty, especially since the proof is not hard. But, this is simply a little fact I thought about several years ago and condensed down into this statement.
Comment: Yes, I am familiar with Uniform Integrability, thanks for the direction. It indeed seems to be a very powerful result.
Comment: I've updated the answer in the other question as well to reflect the fact that the previous statement had an error.
Answer: Unfortunately, the quoted statement in the question is a muddled version of the one I originally intended. Thank you for catching this. I've also updated the statement in the original question. A counterexample to the former is given at the end of this answer.
Here is the intended statement:
Lemma: Let $X_1,X_2,\ldots$ be a sequence of zero-mean normal random variables defined on the same space with variances $\sigma_n^2$. Then, $X_n \to X_\infty$ in probability if and only if $X_n \xrightarrow{\,L_2\,} X_\infty$, in which case $X_\infty \sim \mathcal N(0,\sigma^2)$ where $\sigma^2 = \lim_{n\to\infty} \sigma_n^2$.
Remark: The main points here are that (a) we can "upgrade" convergence in probability to $L_2$ convergence in the case of sequences of normals, (b) we are guaranteed that the distribution of the limit is normal (which is not otherwise obvious) and (c) we get both of the above without specifying anything about the joint distributions of the elements in the sequence.
Proof (sketch):
One direction is easy: Convergence in $L_2$ always implies convergence in probability. To prove to the other direction: If $X_n \to X$ in probability, then
$$\varphi_n(t) = \mathbb E e^{it X_n} \to \mathbb E e^{it X_{\infty}}$$ by dominated convergence. But, $\varphi_n(t) = e^{t^2 \sigma_n^2 / 2}$, and $e^{t^2 \sigma_n^2 / 2}$ converges for each $t$ as $n \to \infty$ if and only if $\sigma_n^2 \to \sigma^2$. This is enough to imply that $\sup_n \sigma_n^2 < \infty$, and hence the collection $\{X_n^2\}$ is uniformly integrable. Thus, $X_n \xrightarrow{\,L_2\,} X_\infty$. This further shows the limit $X_\infty$ must be normal since then $\mathbb E e^{it X_\infty} = e^{t^2 \sigma^2 / 2}$, which is the characteristic function of a normally distribution random variable.
Notes
The convergence of the sequence $\sigma_n^2$ and the fact that the limiting distribution $X_\infty$ is normally distributed are part of the conclusion. By the same exact argument, we can also replace $L_2$ convergence with the more general $L_p$ convergence by recognizing that the variance determines the distribution in this case and all moments are finite, so $\{X_n^p\}$ is also uniformly integrable.
From this it is clear that we have the following weaker result on convergence in distribution, which is well-known and given as an exercise in some probability textbooks.
Lemma: Let $X_1,X_2,\ldots$ be a sequence of normal random variables. Then, $X_n \to X_\infty$ in distribution if and only if $\mu_n \to \mu$ and $\sigma_n^2 \to \sigma^2$, in which case $X_\infty \sim \mathcal N(\mu,\sigma^2)$.
A nice application of the second lemma is to consider the marginal distribution of the Riemann integral of Brownian motion,
$$
I_t = \int_0^t B_s \, \mathrm{d} s \> .
$$
By considering the Riemann sums and using the second lemma, we see that $I_t \sim \mathcal N(0, t^3/3)$.

A counterexample to the quoted statement in the question can be found by considering $X_\infty \sim \mathcal N(0,1)$ and $X_n = (-1)^n X_\infty$. Here, $\sigma_n^2 = 1$ for all $n$ so $\sigma_n^2 \to 1$, but $X_n$ does not converge to $X_\infty$ in probability or $L_2$.
Comment: I would prefer to write that as a comment, but I'm not allowed to, at the moment. So this is basically a question regarding cardinal's answer: Why is $\sup_{n}\sigma_{n}^{2}<\infty$ impying uniform integrability of $\lbrace X_{n}^{2}\rbrace$ ?
Cheers
Comment: Thanks for the answer and the clarification. Would it be possible to elaborate a little on the uniform integrability and the sequence of the variances?
Comment: Hi @Aarkham. I've added a few details. Let me know if there is anything I can clarify. Cheers.


Solving an exponential recurrence relation

Question: Let $f(t)$ be a sequence s.t. $e^{f(t)}\geq e^{\frac{2}{n}\log n}+e^{\frac{2}{n}f(t-1)}$ where $f(0)=e^{\frac{2}{n}\log n}, t\in \mathbb{N}, t\geq 1$. I am trying to find a lower bound on $f(t)$ as a function of $n,t$. So I was trying to think of this as a recurrence inequality but am not sure how to solve an exponential recurrence relation because I'm used to linear recurrence relations. Any ideas?
If we look at a few terms, it looks as follows:
\begin{align*}
e^{f(t)} &\geq e^{\frac{2}{n}\log n} + e^{\frac{2}{n}f(t-1)} \\
&= e^{\frac{2}{n}\log n} + \left( e^{f(t-1)} \right)^\frac{2}{n} \\
&\geq e^{\frac{2}{n}\log n} + \left( e^{\frac{2}{n}\log n} + e^{\frac{2}{n}f(t-2)} \right)^{\frac{2}{n}}\\
&\geq \cdots
\end{align*}
Answer: For any $t$, the exponential being positive on $\mathbb{R}$,
$$ e^{f(t)} \geq e^{\frac{2}{n}\ln(n)} + e^{\frac{2}{n}f(t-1)} \geq e^{\frac{2}{n}\ln(n)} $$
and taking the logarithm of the last inequality we have
$$ f(t) \geq \frac{2}{n}\ln(n). $$
Comment: Looking for a better bound than that because that's trivial.
Comment: Have you got any extra information about $f$ like continuity or existence of limit as $|t| \longrightarrow + \infty$ ?
Comment: Added details now. $t\in \mathbb{N}, t\geq 1$. So I am thinking of $f(t)$ as a sequence as $t$ changes and not as a continuous function.
Answer: First, there is some confusion from using $n$ and $t\in \mathbb{N}.$ So, let $n^{2/n} = c.$ Now, let $g(t) = \exp(f(t)),$ so we have:
$$g(t) \geq c + g(t-1)^{2/n}\geq c + (c+ g(t-2)^{2/n})^{2/n}\sim c + c^{2/n} (1+ \frac2n \frac{g(t-2)^{2/n}}{c}) $$ for $n$ large. This shows that the trivial bound given by blamethelag is close to sharp.
Comment: I see, may I know why $(1+g(t-2)^{2/n})^{2/n} \sim (1+\frac{2}{n}g(t-2)^{2/n})$ for large $n$?


Using external shared library in R

Question: I have written a few c++ function for integration into an R package by Rcpp, and these functions reply on the boost filesystem library. I have specified these in src/Makevar:
PKG_LIBS = -lboost_system -lboost_filesystem

And the package compiles ok:
==> R CMD INSTALL --preclean --no-multiarch --with-keep.source txtutils2
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c RcppExports.cpp -o RcppExports.o
* installing to library '/Library/Frameworks/R.framework/Versions/3.1/Resources/library'
* installing *source* package 'txtutils2' ...
** libs
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c bedcollc.cpp -o bedcollc.o
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c bedcollr.cpp -o bedcollr.o
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c countlines.cpp -o countlines.o
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c fileSize.cpp -o fileSize.o
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c ncols.cpp -o ncols.o
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c printlines.cpp -o printlines.o
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c readbed.cpp -o readbed.o
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c readcol.cpp -o readcol.o
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG  -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/RcppArmadillo/include"   -fPIC  -std=c++11 -c readcols.cpp -o readcols.o
clang++ -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/usr/local/lib -o txtutils2.so RcppExports.o bedcollc.o bedcollr.o countlines.o fileSize.o ncols.o printlines.o readbed.o readcol.o readcols.o -lboost_system -lboost_filesystem -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
installing to /Library/Frameworks/R.framework/Versions/3.1/Resources/library/txtutils2/libs
** R
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
* DONE (txtutils2)

But when I try to load it, something goes wrong:
> library(txtutils2)
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  unable to load shared object '/Library/Frameworks/R.framework/Versions/3.1/Resources/library/txtutils2/libs/txtutils2.so':
  dlopen(/Library/Frameworks/R.framework/Versions/3.1/Resources/library/txtutils2/libs/txtutils2.so, 6): Library not loaded: libboost_system.dylib
  Referenced from: /Library/Frameworks/R.framework/Versions/3.1/Resources/library/txtutils2/libs/txtutils2.so
  Reason: image not found
Error: package or namespace load failed for 'txtutils2'

I am on osx 10.10, if that matters.
General instructions on usage of external shared libs in R is also most welcome.
Comment: Can you please clarify whether your problem is a) linking against a Boost library (which we just answered this week), or b) linking against a set of your files (which should work by default), or c) something else I not understanding.
Answer: As far as I know, what you have met is not the problem of Rcpp even not the problem of R. It may be about linking on OSX.
I don't use Mac, so I just give you some advice. Try
otool -L yourpackagename.so

You should see a link to the boost library you use. You need to check whether the path is right.

Using external shared library in R


Html5 Math Applets. Interactive free online

Question: I was an aficionado at collecting links from websites with math java applets that allowed interaction to learn mathematical concepts visually and interactively. My favorite was Manipula Math.
But since Java is running out of support in the current internet browsers and has been replaced by HTML5 my links do not work anymore.
Therefore, I have proposed to list in the answers to this question a collection of websites that contain applets in HTML5 format that explain mathematical concepts interactively.
Answer: To start this list I indicate the sites:
https://www.mathwarehouse.com/interactive/html5-applets/
https://www.geogebra.org/t/functions
https://www.geogebra.org/t/algebra
https://www.geogebra.org/m/aHUtYYRK
https://www.geogebra.org/t/calculus


Which test to use: Chi-squared, Fisher's exact or some other?

Question: I asked 200 survey participants the same sequence of eight multiple-choice questions with four answer options (A, B, C and D). Here are the results:

All A's: 58
All B's: 1
All C's: 2
All D's: 0
Mixtures of A's, B's, C's and D's: 139

I want to work out whether these results are statistically significant, which I take to mean whether the probability that they occurred randomly is less than 0.001. I understand the expected value for each combination of answers – all A's, all B's, all C's, all D's, and each mixture of A's, B's, C's and D's – to be 200/(4^8), which is 0.003051758.
So here's the problem. I've read that a Chi-squared test requires all of the expected values to be greater than five, and in this case none of them is greater than five. I've also read that none of the observed values can be zero, and in this case one of them is zero. I've seen something about artificially combining categories to bring all the expected and observed values above five and zero respectively, but I don't understand how this can be done without artificially affecting the p-value. Finally, I've read a few things about Fisher's exact test, but all of them seem to suggest that I'd be allowed only a few rows of values, whereas in this case I have 65,536 (i.e. 4^8).
What is the most appropriate method in this circumstance?
Comment: By your comment on Fisher's exact test are you referring to the 'norm' of limiting it to 2x2 tables? Otherwise, please provide a link to the reference in question.
Comment: You've caught me out there. What I'm alluding to is the inability of any free online calculators or Excel functions I've found to handle more than six rows. Suffice it to say I haven't the mathematical ability to do the calculations manually.
Answer: With your concern about using Fisher's exact test, as I understand it the test can be applied to tables larger than 2x2, but the reason for this norm is that it is computationally expensive otherwise.
The greater concern related to Fisher's exact test would be the assumption of fixed totals. An example of this is given here. Quoted:

An example [of fixed totals] would be putting 12 female hermit crabs and 9 male hermit crabs in an aquarium with 7 red snail shells and 14 blue snail shells, then counting how many crabs of each sex chose each color (you know that each hermit crab will pick one shell to live in)

Your study design does not meet this condition.
Other options are:

A G-test (likelihood ratio $\chi^2$). Some recommend using this when the sample is low. In R you can use the likelihood.test function in the Deducer package
Exact multinomial test. Recommended here and elsewhere. The function 'xmulti' of the R package XNomial. Read the vignette.

Now that you've reached the limits of excel, give another software package a go.
Comment: Conditioning on marginal totals has always been controversial. I don't really see it as an issue. Because the exact test has to look at calculating multinomial probabilities for all table as extreme or more extreme than the given table it can be computer intensive even by today's standards.
Comment: I looked at the reference you (Simon) link about the chi square test. It contains a lot of good information and references but I did not see anything about the asymptotic nature of it.
Comment: @Michael, I see that I have my own homework to do digesting [this](http://sites.stat.psu.edu/~dhunter/asymp/fall2002/lectures/ln11.pdf) among other material.
Comment: Putting aside any judgment about the links you provide I liked your answer and gave an upvote. If you want to invest time in studying the asymptotic properties of Pearson's chi square by all means go for it.
Comment: Thanks for your replies. I'll have a look at those links. In the meantime, can you please confirm whether my calculation of expected values is correct?


Add cutom body class when view is not return any results

Question: I know how to add additional class by preprocess function but I need to combine it with the view. So the new custom class should be added if my view returns 0 results. It looks like I can't use hook_views_pre_build because there's no vars for page elements. Any thoughts how to achieve it?
Comment: I'm almost positive you'd have to build the view manually using the views API in your pre-process function, check the results array, and if empty, add your class.
Comment: have you tried no result behaviour and adding class from their?
Comment: Target a views hook that is post execution and contains the result count. Throw the result in a drupal_static and then read that static from the preprocess. Perhaps a bit dirty but if not overused in hard to solve situations like these perhaps an option.
Comment: @J. Reynolds this sounds like a good approach, even if I need to read the variable in different function.
Answer: Might be a little over-kill, but it's the first thing that comes to mind without having to build a custom view in code (which is cleaner imo). I am referencing Views 2 only, might be different in 3.

Create an empty view page, strip it of everything if you'd like, it just needs to exist.
In the view you are using, for the no results behavior, choose to include the empty view.
Using the Context module, add the condition that if the empty view is shown on the page to execute. In the reactions area, add Theme HTML which will allow you to enter in your custom css class to the body tag.


Octaver + Phaser in Boss ME-70?

Question: Is there a way to achieve both phaser and octaver in Boss ME-70? They appear to be under the same pedal, is there any trick for it?
Thanks
Comment: Use octaver on expression pedal
Comment: @jeremy this will give you the modified note only, not both.
Answer: The manual seems to indicate that, in memory mode, you can assign an effect to arbitrary patch (pedal) position using write mode. This suggests to me that you can assign any effect to a different patch pedal than the one you'd normally be forced to use in manual mode.
See Boss ME-70 User Manual (page 10)
Comment: Can you elaborate because I haven't figured out how to do it, I want to create a patch and store it as a User Preset, so that it has both the effects Octaver AND Phaser enabled, whilst they both are under the same pedal number. I'm not sure you fully understood my question.
Answer: After reading the manual and trying out several ways, apparently it's impossible to achieve this with this multi-FX.
I hope someone beats my answer and proves me wrong, please comment on.
Comment: I have no experience with this particular pedal but have a Boss ME-50B which functions in a similar way to this unit. I'm not aware of any tricks, you can only select one effect from each category. However if you want octave+phaser you can use the pedal effect for the octave though it might sound different than the pedal effect and I don't think you can mix the direct signal with the pedal effect.

Octaver + Phaser in Boss ME-70?


Do you find it easier nowadays to practice and learn music that what it used to be years ago?

Question: Judging from my own experience, I believe that nowadays is much easier to find good teachers and material to practice and become really good.
For example, I am middle aged and was a fan of Queensryche back in the '90s. Once I listened to them, I wanted to learn to play guitar so I got a number of music books, took some lessons from a guitar teacher, bought queensryche's books containing their transcribed songs and started practicing. It took me a lot of time to understand certain concepts and whenever I was stuck I would ring up the teacher or go through the books. Those were the times. No internet and no mp3s.
Now, besides having a good teacher, you can find a video on youtube explaining in multiple ways e.g the myxolydian scale, create your own studio using https://www.reaper.fm/, create your own backing tracks and practice your scales along with the tracks.
So my question is: Can someone become a much better musician nowadays with all this information available than years ago?
Comment: This will be measured by what actually determines the term 'musician'. And it also will elicit opinionated answers, so will maybe suffer from being closed. However, it's a point worth pondering upon...
Comment: Better? No. Does it make music more accessible to more people? Without question.
Comment: I guess that would balance out with the decrease in funding for orchestras, opera companies, etc.
Answer:
Can someone become a much better musician nowadays with all this information available than years ago?

IMO, it depends. Here is a story about the Beatles:

Together, they figured out guitar chords as if they were ancient runes. When Paul and George heard that someone across town knew the fingering for the B7 chord they got on a bus to meet the guy and learn it.
(source)

Would the Beatles be better musicians if they didn't have to travel across town to learn the fingering for B7? That's not clear at all. Maybe they would know a bit more theory. Maybe they would be somewhat better in some respects, but not reach the same level of fame since they faced more competition from a larger number of their peers who had access to the same knowledge. Hopefully they wouldn't succumb to "analysis paralysis" and spend all their time watching music theory on Youtube rather than practicing and experimenting. Many maybes, few clear answers.
There is more information available today, with less effort, for a larger number of people. Getting to professional level or beyond still takes a lot of dedicated effort over a long period of time, I'm not convinced that the availability of more information reduces the total time from first-timer to professional by all that much.
But there may an improvement for hobbyists and bedroom musicians (who are the most likely to be hampered by a lack of knowledge), it may make music accessible to a larger number of people, and "the best of the best" may be better in the future simply because it's selecting from a larger total pool of musicians.
Answer:
Can someone become a much better musician nowadays with all this information available than years ago?

Yes. The key to improvement is doing the required practice, which is inevitable Any good musician will have many hours of practice. Guided practice is also key and there have always been plenty of teachers to provide the guidance. The difference now though, is that not only do we have teachers available but there is a wealth of knowledge at our fingertips. So yes, the potential to improve is greater because the barriers to additional knowledge have been reduced.
Answer:
Can someone become a much better musician nowadays with all this information available than years ago?

The short answer is "No" because the key to improvement is not having more information it is doing the required practice. Guided practice is the key and there have always been plenty of teachers to provide the guidance. And, no, YouTube and Zoom are not substitutes for a real live human teacher in the same room as you.


Useful tuning for 7 or 8 string guitars

Question: So, I'm looking to add an Ibanez 7 or 8 string to my guitar zoo, but although I have looked into various standard tunings I am trying to figure out practical tunings so I can rapidly add the new string(s) into my existing songs without spending ages practicing (don't have enough time between gigs, and as guitars with more than 6 strings aren't standard I guess I can tune them how I like:-)
I tend to run a drop-D tuning on my main gigging guitars (we have a heavy rock sound) so was thinking about just adding a low A for the 7 string, which will make general riffing very straightforward but does anyone have experience of tunings which work better?
Comment: Ended up with a 7 string Ibanez RF Prestige, and have been trying AEADGBE,  ADADGBE and DEADGBE. Still not sure which works best but will report back once I settle on one.
Comment: B-E-A-D-G-B-E-A...............This gives you a high A on top and a low B on the bottom.
Comment: @Ken I've heard there's also a variation with G at the top, used by IIRC John Pizzarelli.
Comment: Does this answer your question? [Problems with 8 string guitar tuning?](https://music.stackexchange.com/questions/16133/problems-with-8-string-guitar-tuning)
Answer: Adding a low A on standard (AEADGBE) is very fun. it's possible to get a very fat metal sound out of it. I have also seen (EAEADGBE) for 8-string guitars. Since the options you are going to consider for the low strings are very close to each other (a whole step apart), you should also be able to toggle between them easily to figure out what you like best.
Comment: Just to note - B gives you the forth, but dropping it to an A has the same effect as dropping your E to D on a 6 string (one finger power chords, easy 9ths etc).
Comment: Yeah, the repeat of the EAEA on the lower strings is really powerful for chords because it lets you barre and get an extended power chord. It's also useful for soloing and improvisation because you are adding two strings that you should already be familiar with (strings 7 and 8 mirror 5 and 6 as A and E).
Comment: Have been gigging using ADADGBE, and this setup seems to work very well. Seriously considering taking the drop D back up to an E now I don't need it any more, but I'll then need to put in the effort to change round the songs we do in drop D tuning :-)
Answer: This seems to be highly connected to what you want to do with it.
Harp guitars have many bass strings, where you hold down the low end with big bass strings but the melody occurs on the high strings, and it strikes me that drop-D-influenced 7-and-8-string tunings go like that, where you're just going to be doing simple chord shapes on the 6, 7 and 8th strings.
If it was me, though, I'd likely use the low strings as a way to play higher on the neck where my reach is better, so, given an 8-string, I'd probably want F#BEADGBE, maybe dropped to EADGCFAE but maybe not. I might even drop the minor third between the 2nd and 3rd string and go F#BEADGCF.
Comment: Yeah - I tend to use it entirely as a normal guitar, just with some extra low reach, and the tuning I currently use (ADADGBE) lets me pack some low powerchords in there as needed. I do think I may take the bottom two back up to BE though and just tweak my current drop-D style to fit. In the long run I think it will help me avoid losing my muscle memory on a normal E-tuned 6 string
Answer: I've played 8-string classical guitar for close to forty years (mine was built by John Gilbert*), using it for my own compositions and for lute music. Since the 7th string of lutes was often tuned to a low B, and the low B continues standard fingering (including barring) into the low notes, that seemed natural. I dropped it to a low A for some pieces in that key as well, for great effect. And since you've got electrics here, and are not finger-picking, I'd think that a low B would go well with standard bar chords there as well.
So what about the 8th string, then? Anything lower than the low B I found overbalanced the guitar on the bass side (even though the Gilbert has incredible trebles). But after seeing the Brazilian guitarist Egberto Gismonti play an 8th string with the 8th tuned to a treble note (getting a "fine-string banjo" effect, with a high note under the thumb) I settled on tuning the 8th to a C just above the B of the second string. This gave me some incredible effects in the key of C when I dropped the 6th string to C as well, so I got some good music out of that. The only hitch was that I couldn't be sloppy with my thumb on the low strings - if I missed the 7th string and got the 8th, I got a wrong note way out of register.
All this is more or less in the past, since I play mostly flamenco now (my luthier just built a 7-string flamenco guitar, however - hmmm...). As for Gismonti, he went on to a ten-string guitar, oh well.
Have fun, and good luck with your experiments!
(Here's John Gilbert, who built a number of 8-string classicals - http://www.guitarfoundation.org/blogpost/754189/139600/Remembering-John-Gilbert)
Answer: I recently added an 8 string to my collection, and I've been using standard 8 string tuning. You can still use bar chords or power chords, such as F# B EADGBE.
Answer: I can't speak for 7 string guitars, but I've always tuned my 8 string classical guitars to 7=D and 8=A. (ADEADGBE) If I had an 8 string electric, I'd tune it this way too.
Answer: The Traditional Russian 7-string guitar is tuned D-G-B-D-G-B-D.
While it doesn't extend the range in either direction, it offers many more possibilities for chord voicings.
Answer: The most useful tuning for a 7 string guitar is simply to tune to G string down a half-step.
This makes it so that all your regular shapes work from the low B string. Making it so your instrument a B to B instrument with a high E string added.
So now your basic E major chord works but it is transformed a fourth down. Making it a B Major chord. Everything works you just have to remember it is all transposed a 4th down.
Comment: I tried that and it wasn't useful to me - mainly as it didn't give me anything "new" so tonally it would have been a waste of money. So I went ADADGBE for a couple of them - gives me new shapes, esp with partial barre with my thumb :-)

Useful tuning for 7 or 8 string guitars


Estimating the radius of the Earth from a plane trip

Question: My friend had an interview at Cambridge. He was asked the following question, and was stumped:

I fly to Chicago. The plane trip is $8$ hours. I look at the time and then set my watch back $6$ hours. Knowing that the Earth rotates $360^\circ$ in $24$ hours, what is the radius of the Earth?
Comment: So the question assumes that the subject _**needs to be told**_ that the earth rotates 360° in 24 hours, but _**just knows already**_ what the latitudes of Cambridge and Chicago are and how fast the unspecified plane flies?
Comment: _Which_ Cambridge, though? The one in Massachusetts is quite a bit closer to Chigaco than the one in England (and neither has an airport of its own).
Comment: Incidentally, the interviewer was probably testing you on your problem-solving skills, but not your mathematical problem-solving skills. You could have asked what the distance is between Cambridge and Chicago, as this is likely information the interviewer had, and problem-solving includes figuring out where to obtain information.
Comment: Without knowing the speed of the plane, that $8$ hours seem to be a useless information
Comment: Can you clarify what you mean by this "my watch back 6 hours"?
Comment: But it's only an estimation. You may just take an approximate number of the plane speed.
Comment: @Edward I guess it means that the person traversed 6 time zones?
Comment: Edward - I mean take the original time (in England) and take 6 hours off. For example 18:00 - 12:00 because of a 6 hour time difference
Comment: So the question is really "flying from Cambridge to Chicago"? @Hiraphor
Comment: Essentially, John, but I don't think the location matters in this case, only the time difference
Comment: No, the Latitude of the cities (and the speed) seems to be relevant here @Hiraphor
Comment: Henning - Cambridge, England
Comment: John Ma, in an interview  I don't think they're expected to know the latitudes of the cities. This can be worked out using the information given, apparently.
Comment: Please check with your friend again, you might miss some information.
Comment: John, this isn't a case of missed information, this question was written down in the interview and is pretty much word for word.
Comment: Henning - either the Cambridge interviewers don't know what they're doing or there is a method of working this out without knowing already knowing the speeds, latitudes and longitudes.
Comment: They might know what they are doing. They want the applicants to smell something wrong.
Comment: "Half its diameter", of course.
Answer: There is not enough information in the question to get anywhere near an estimate of the earth's radius.
Even if we assume that "setting your watch back 6 hours" means that the difference in longitude between the two points is exactly 90°, the question still doesn't specify the latitude of the two cities. And, of course, to get from a question where all the givens are time to an answer with the dimension of length, we would need to know the (ground) speed of the plane too.
To see concretely how there is too little information, Some other possible scenarios with a plane that flies with the same ground speed (and on the same earth) would be:

You fly from Frankfurt am Main to Santiago de Chile. It takes 15 hours, and when you arrive you set your watch back 6 hours.

or

You fly from Stockholm to Lagos. It takes 8 hours, and when you arrive you set your watch back 1 hour.

or even

You fly from Nuuk to Comodoro Rivadavia. It takes 15 hours, and when you arrive you set your watch back 1 hour.

If the problem was solvable with the given information, there would need to be a method that gave the same radius of the earth when given the inputs $(8,6)$ as for $(15,6)$ and $(8,1)$ and $(15,1)$.
Distance sources.
Comment: I think this answers it, he got as far as setting it to 90 degrees but was lost after. Perhaps you had to determine the question wasn't possible and they just wanted to see the thinking process, but thanks for clarifying that.
Answer: To me the most straightforward way of seeing that this is unsolvable without further information is to analyse the units/dimensions (see dimensional analysis).
None of the given information contained a unit of distance. Hence, it must be impossible to calculate a distance from it.
Sometimes a distance is "hidden" in a compound unit (e.g. a speed in km/h or a fuel economy in miles per gallon) that can be "broken out" by using a second piece of information (in the previous examples, a time in hours or fuel consumption in gallons). But there's none of that here.
Since there's no information about scale here whatsoever, one can imagine in a galaxy far away, on a world the size of a pearl, the Microuniversity of Minicambridge asking the same question.
Comment: Dimensional analysis is taught as a high school topic in the United Kingdom and has a reputation as a regular source of university interview questions in science, so my guess would be this being the angle the examiners were taking. I'd be surprised if the question was asked in this form *verbatim* - Oxford and Cambridge in recent decades have tried to make the interview process less intimidating to applicants from non-traditional or underprivileged backgrounds, and their publicity material frequently avows there will be "no trick questions".
Answer: My guess is that the interviewer was not expecting to get an exact answer, but was looking to see how confident your friend was at making their own approximations and working using those. For example, here are two guestimates that, if correct, would provide the information that is needed as previous answers have pointed out:

Chicago and England have similar climates so there's probably not too much difference in latitude. They aren't close to the equator and aren't close to the pole, so let's guess about halfway between. i.e. latitude of 45 degrees.
I know that military jets go supersonic, but you're probably talking about a commercial jet here and they don't. Let's guess about half the speed of sound: i.e. about 150m/s

Note that these estimates are incredibly crude, but they're reasoned and would have given your friend something to do that the interviewer could have judged.
p.s. A good source to emulate for this sort of crude estimation is the xkcd What If? articles, which use guesses like these to insight into situations much further from normal human experience.
Comment: Commercial jets fly at about 80% of the speed of sound, but an 8-hour trip would be mostly at a high altitude where speed of sound is much less than at sea level. About 450 to 480 knots might be a reasonable guess. Knowing that 1 knot = 1 nautical mile/hour = 1852 m/hour (yes, I repeated all of this from memory) you could convert that to km/hour, which is useful if you want the radius in km rather than nautical miles.
Answer: Estimate plan flies at 500knts.  Fly for 8 hours = 4000miles.  Clock back 6 hours, so I'm 1/4 of the way round the earth.  Therefore circumference of earth is 4x = 16,000miles at this lattitude.  London is 53' so call it 45' for argument sake, using pythag/trig this means circumference is 0.7 (approx) of that at equator.  Therefore 16000/0.7 = 23,000 (approx.)  (actual is around 21,600 Nautical miles so not bad for an estimate)
Comment: The plane will fly a great-circle route, not just follow a line of latitude (even if the latitudes were the same). But given the many other sources of error due to guesswork, this particular source of error isn't especially large. Good enough for an order-of-magnitude estimate, anyway.
Answer: The goal of this interview question wasn't a mathematics answer.  It is really a question that is suppose to trigger you to ask more question.
The issues with which Cambridge was important, as with all sorts of pseudo distance units being thrown at you.  The interviewee is suppose to be asking all sorts of questions to clarify and request more data.  This is very typical in standard business interactions, where clients always think they want something, but actually rarely does, and really has no idea what they want.


Powershell - filtering output of command

Question: I'm quite new to powershell, but I've done a lot of batch scripting (yay for moving into the 'now!'). I'm trying to re-write my largest accomplishment in batch scripting into powershell, and right off the bat I'm hitting a bit of a wall.
What my original batch script did was install drivers for all of the detected system hardware. It did this by running devcon.exe and doing a search on the output, looking for VEN_ &DEV_ and trying to match it up with a comparison. This took a bit of time on slower computers (i3/Atom/slow AMD).
I stumbled across this command in powershell:
    get-wmiobject -class CIM_VideoController PNPDeviceID
It spits out a list which contains just a few bits of info on the display adapter. The line in particular I'd like is the PNPDeviceID. I so far haven't had much luck in finding a way to manupulate the output to list just the VEN_ numbers.
Here's what I'd like to do: Run the command above, manipulate it so I get just the vendor number into one variable and the device number into another variable.
I tried doing this:
get-wmiobject -class CIM_VideoController PNPDeviceID | Select-String -Pattern "PNPDeviceID" -SimpleMatch

The problem I'm having is, it spits out nothing at all. I also have no clue on how to manipulate the output of that line further giving me only the 4 digit identifier of the 'VEN_' or the 'DEV_'.
Would anyone know how to do this?
Answer: You can just do this:
$deviceID = (get-wmiobject -class CIM_VideoController).PNPDeviceID

the output of such objects are allways stored in a property which you can access by dot notation
Comment: That works great! What I'd like to do with that output is to put only the 4 digits listed after the 'VEN_' into a variable. How can I do that?
Comment: use it´s `.substring()` method or a regex like in TheMadTechnician´s answer
Answer: I mean no disrespect, but this is pretty basic stuff. Have you considered finding a book (even an online one) and reading up on PowerShell? I've heard good things about Learning PowerShell In A Month Of Lunches.
As for your request, to get the four digit ID you could pipe that property's value to a regex match, and then output that match. It could be done like this:
$VidCardID = get-wmiobject -class CIM_VideoController PNPDeviceID | Where{$_.PNPDeviceID -match "VEN_(\d{4})"} | ForEach{$Matches[1]}

That will set $VidCardID to the 4 digit ID for the video card.
Comment: Perfect!!! As you were typing this, I stumbled upon the regular expression website (regular-expression.info) and was trying to figure it out. What you've put up here will help me figure it out even faster. Thank you so much for you help!


Criar e editar dados de uma tabela com relacionamento Laravel

Question: Tenho uma tabela chamada agenda, dentre os campos desse agenda é possível adicionar vários responsáveis por ela, que são os usuários cadastrados no sistema, para isso existe um campo do tipo multiple select, que permite selecionar vários IDs de usuários, e para guardar esses vários "responsáveis", criei uma tabela chamada agenda_responsaveis, que salva o id da agenda (agenda_id) e o id de cada usuário (user_id).
Atualmente, ao criar a agenda, para salvar os responsaveis, eu percorre os dados do select com um foreach e insiro os dados na tabela agenda_responsaveis
Ex:
$create = Agenda::create($data);

        foreach ($request->responsavel_id as $key => $id) {

            AgendaResponsavel::create(array(
                'agenda_id' => $create->
                'user_id' => $id
            ));
        }

E na parte da edição da agenda, eu procuro todos os registros com o agenda_id, faço a exclusão dos dados antigos e insiro novamente os novos dados que vem do select. Faço dessa forma porque não possuo o id de cada registro da tabela agenda_responsaveis.
Ex:
AgendaResponsavel::where('agenda_id', $agenda_id)->delete();

foreach ($request->responsavel_id as $key => $id) {

            AgendaResponsavel::create(array(
                'agenda_id' => $agenda_id,
                'user_id' => $id
            ));
        }

gostaria de saber se existe uma forma mais eficiente de se fazer isso? sem parecer uma "gambiarra"
Answer: Como o amigo Jedson Melo disse você pode usar o Eloquent que auxilia no processo de criação dos relacionamentos nas bases de dados.
Conforme a documentação os models podem se relacionar com outros abstraindo a relação de fato.
Como identificado se trata de um relacionamento N*N, ou muitos para muitos, o que gera uma tabela pivô.
No laravel eu posso representar esse relacionamento de maneira mais simples. Dentro do seu model Agenda você deve criar uma função (geralmente nesse utiliza-se o nome do outro model do relacionamento no plural). Ficaria assim:
public function responsaveis(){
return $this->belongsToMany('App\User', 'agenda_responsaveis', 'agenda_id', 'user_id');
}

O primeiro argumento é o caminho do outro model do relacionamento, o segundo(opcional) é o nome da tabela, ele é opcional pois caso você utilize o padrão laravel não é necessário passa-lo pois o laravel já identifica. Os dois outros também são opcionais e só remetem ao nome dos campos. Como seu caso os nomes se diferem um pouco do padrão, é bom passar.
Ai para inserir na tabela pivô há duas possibilidades:

Usando o método attach
Ou usando o método sync

O attach simplesmente associa na base. Que no caso é sua primeira necessidade.
Já o sync serve para o seu segundo problema. O que ele faz, toda vez que é chamado, é excluir os relacionamentos anteriores e mantém os mais atuais que você mandou. É algo como uma sincronização.
Então aproveitando o exemplo do amigo, você poderia utilizar o attach no momento de inserção:
//caso os ids estejam num array, você pode envia-los todos de uma vez
$agenda = Agenda::create($data);
$agenda->responsaveis()->attach($array_de_ids_responsaveis);

Ai para a edição você faria a busca e depois utilizaria o sync:
$agenda = Agenda::find($id_agenda);
$agenda->responsaveis()->sync($novos_ids);

Acho que é isso, qualquer dúvida consulte a documentação.
Comment: Precisa ter o relacionamento na App\User também?
Comment: Não é necessário. Mas caso você queira  retornar as agendas ou inserir na tabela pivô a partir do model User ai você cria. Digamos que queira pegar as agendas de um responsável:
`$user = User:find($id);
$agendas = $user->agendas;
`. Enfim, caso não necessite para você manipular os dados através do outro model, você não precisa criar.
Answer: Utilizando os relacionamentos que o Eloquent ORM que o laravel proporciona. No seu caso você tem um relacionamento de Many to Many para entre agenda e responsável, então basta configurar as models seguindo a Documentação e você poderá utilizar algo assim:
$agenda = Agenda::create($data);
$agenda->responsaveis()->attach($request->responsavel_id);


Transmissão com certificado digital c#

Question: Estou desenvolvendo uma rotina de transmissão de nota fiscal eletrônica de serviços em c#.
Já assinei as TAGS de acordo com o manual da prefeitura mas quando tento fazer a transmissão retorna este erro.
<MensagemRetorno>
      <Codigo>E504</Codigo>
      <Mensagem>O certificado digital do prestador de serviços é obrigatório.</Mensagem>
      <Correcao>Envie junto a requisição do serviço o certificado digital do prestador de serviços.</Correcao>
</MensagemRetorno>

Answer: Apenas para ajudar quem estiver com o mesmo problema consegui enviar o certificado com o seguinte código
WsTeste.consulta ws = new WsTeste.consulta();
ws.Url = @"https://wsserver/securemath/math.asmx";
ws.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certPath));
Retorno = ws.consultarLote("teste", XMLAssinado.OuterXml);

Para maiores detalhe vejam este link
Answer: O problema deve estar na string que você está enviando, que deve estar mal formatada, tente fazer o seguinte, primeiro formate sua string seguindo a documentação da prefeitura, fica mais ou menos como está abaixo, e cuidado, IISRetido tem que estar com S ou N e não 0 ou 1, se atente na documentação para tipo de Rps, etc.:
char pad = '0';
string strDeAssinatura = tpRPS.ChaveRPS.InscricaoPrestador.ToString().PadLeft(8, pad) +
                tpRPS.ChaveRPS.SerieRPS.PadRight(5, ' ') +
                tpRPS.ChaveRPS.NumeroRPS.ToString().PadLeft(12, pad) +
                tpRPS.DataEmissao.ToString("yyyyMMdd").PadLeft(8, pad) +
                tpRPS.TributacaoRPS.ToString() +
                tpRPS.StatusRPS.ToString() +
                iisRetido +
                tpRPS.ValorServicos.ToString("N2", _enUS).Replace(".", "").ToString().PadLeft(15, pad) +
                tpRPS.ValorDeducoes.ToString("N2", _enUS).Replace(".", "").ToString().PadLeft(15, pad) +
                tpRPS.CodigoServico.ToString().PadLeft(5, pad) +
                tomadorTipo +
                tpRPS.CPFCNPJTomador.Item.PadLeft(14, pad);

Depois assine apenas essa string, você pode usar a função abaixo para isso:
Depois jogue o valor em tpRPS.Assinatura e pronto.
Boa sorte.
private byte[] Assinatura(string strDeAssinatura)
{
    KeyInfo keyInfo = new KeyInfo();
    KeyInfoX509Data keyInfoData = new KeyInfoX509Data(_cert);
    RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)_cert.PublicKey.Key;
    keyInfo.AddClause(keyInfoData);
    RSACryptoServiceProvider rsaKey = _cert.PrivateKey as RSACryptoServiceProvider;
    RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(rsaKey);
    RSAFormatter.SetHashAlgorithm("SHA1");
    SHA1Managed SHhash = new SHA1Managed();
    byte[] SignedHashValue = RSAFormatter.CreateSignature(SHhash.ComputeHash(new ASCIIEncoding().GetBytes(strDeAssinatura)));
    return SignedHashValue;
}

Transmissão com certificado digital c#


VBA: Set permission to read Excel file to whole organization

Question: So, I've run into a VBA problem. Due to IT policies I can't control read/write access to my Excel files on folder level, but have to do it for each individual file. I have a folder with 15 files, that everyone having access to the folder can access and write in. On a certain date I want to lock these files down, so that only a specific group can write, but the rest can still read.
I'm aware it's realtively easy to do this manually (File->Info->Protect Workbook->Restrict Access), but since I already run a macro for other reasons when we want the files locked down, I'd like for it to do this part too. This is where I run into my problem:
I've figured out how to set the permission for a specific user, using this code
<code>Sub set_access()

Dim UserPerm As Office.UserPermission

Workbooks("workbook name").Activate
   Set UserPerm = ActiveWorkbook.Permission.Add("name@company", msoPermissionFullControl)
</code>
I can loop through this for each person I want to have writing/full access, no problem. There's like fifteen of us and I know who we are.
The thing is I also want everyone in my organization to retain their reading rights. This has it's own button if I do it manually (in the Permission menu that is accessed as mentioned above), but I can't understand how to trigger that setting via vba. I've tried to record a macro of me doing it manually, to see the code, but nothing is recorded. I've also read just about everthing I could find online like four or five times, and what I need simply doesn't seem to be covered.
Does anyone know if this is poosible? Or if it isn't; can I reach the same results some other way?

tldr: I can set permission by individual, but in addition to this I want to give a general read-only access to my Excel files for anyone in my organization. Can this be done with vba? If so; how?
Comment: Try changing `msoPermissionFullControl` to `msoPermissionRead` for the people who you want to have read only
Comment: Hi Glenn,
As I wrote in my post the problem is I want everyone in the company to have access to read the file. I simply cannot keep a correct and updated list of that many users. In the menus there is a button to give everone reading accesss, and I'm looking for a simular vba-driven solution.
Comment: I've just had a good look at the options in that dialog and it looks like your best option would be to have your IT department setup two user groups for you.  One user group would be read only access and the other group would be the read/write access.  then have them by default add people to the read only group and then you can specify who gets added to the read/write group.  Then in the `Read` field for the file, you list the read only group and in the `Change` field you list the read/write group
Comment: There's two problems with this. 1) I'd have to involve IT and 2) I'm still stuck setting the permissions manually in each file. Also, the option to give everyone in the organization reading rights is already a default Excel option, so IT won't be needed in the first place. If it can't be done with vba I already know the way to do it manually.
Answer: I had the same problem and was looking into it. After all, by using "Everyone" instead of an email address, I was able to set permissions for everyone in my organization. try it.
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/31423727)
Comment: @Taku I'm finally back at work, and this worked perfectly, it was the "" that was needed.


StringTemplate - How to iterate through list inside list?

Question: Let's say i've list of objects that i want to iterate in stringTemplate. the object look like that:
public class a1 {
private String name;
private String value;
private List<a2> a2list;
 public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getValue() {
    return value;
}
public void setValue(String value) {
    this.value = value;
}
 public List<a2> geta2list() {
    return a2;
}

}
public class a2 {
private String name;
private String value;
 public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getValue() {
    return value;
}
public void setValue(String value) {
    this.value = value;
}

}
imagine something like a conversation. a1 is the creator and a2 is answers.
i did that:
$a1:{

$it.value$

   $a2:{

$it.name$

$it.value$

      }$

}$

and i'm getting "action parse error;"
any ideas?
Thanks!
Koby
Comment: Please let me know if what you had asked had worked. I am trying to so a similar task, and not able to iterate through a List within a List. Please Help !!!
Answer: What's the syntax error?  Perhaps you need <...> not $...$


How do I use FAQ module views with accordion effect?

Question: I want to use a setup similar to the hard-coded faq-page, having the questions grouped by category, but having the answers hide/show with the accordion effect. I would like to add a jump menu attachment at the top of the page, but this requires setting up anchor links in the original view. I have tried using the various Views displays provided by the module, but these don't have the accordion effect. Is there a magic combination that I'm missing?
Thanks!
Answer: If the FAQ module uses views to display the answers, then you can install the Views Accordion module, which creates a new plugin in views to render each result.
Views Accordion:

Views Accordion provides a display style plugin for the Views module.
It will take the results and display them as a JQuery accordion, using the first field as the header for the accordion rows.
For Drupal 7 the module integrates the jQuery UI Accordion plugin as a views style plugin. You can configure the options provided by the jQuery UI plugin.
For Drupal 6 the module used it's own jQuery code, so a different set of features is available for D6.


How to programmatically send an action in an iOS extension, since `sharedApplication` is unavailable?

Question: I'm implementing an iOS action extension, using code shared with the main app. Some of it uses [[UIApplication sharedApplication] sendAction:to:from:event] to send actions to the first responder.
Since sharedApplication is unavailable in an extension, this code won't compile.
I've tred one workaround, which is instanciating a UIControl, and sending an action from it using -[UIControl sendAction:to:forEvent:]. This works but has a big drawback (in addition to feeling very hacky): it's not possible to control the sender (this will be the UIControl instance), which in my case is necessary.
Another workaround I'm considering is retrieving the UIApplication object wrapping the extension by observing UIApplication notifications and getting the object property from them (I've confirmed that some of these notifications are still sent in the extension.) But even if this did work would it have any chance to be approved by Apple, since it would just be cheating the sharedApplication limitation? Has anybody experienced with this technique in a live app?
Thanks!
Comment: I am interested in the same functionality. Did you found right way hot to implement it?
Comment: Not in a way I'm happy with. I instanciate a fake UIControl subclass instance as described in the second paragraph, where I set the nextResponder to the actual sender I'm interested in.
Answer: It looks like there isn't a direct way to do this.  Looking at a disassembled UIKit, there are surprisingly few methods that call -[UIApplication sendAction:to:from:forEvent:], and all of those explicitly provide a sender.
The good news is that -[UIControl sendAction:to:forEvent:] is just a thin wrapper around -[UIApplication sendAction:to:from:forEvent:]:
void -[UIControl sendAction:to:forEvent:](void * self, void * _cmd, void * arg2, void * arg3, void * arg4) {
    rbx = [arg3 retain];
    [*_UIApp sendAction:arg2 toTarget:rbx fromSender:self forEvent:arg4];
    rdi = rbx;
    [rdi release];
    return;
}

If you're willing to risk that Apple might change the fundamental behavior of control interactions to completely do away with UIApplication in extensions, it would probably be relatively safe to call sendAction:to:from:forEvent: on a found application instance.  The way I would retrieve it is view.window.nextResponder, since this is always a UIApplication if the window is not nil:
[(id)view.window.nextResponder sendAction:@selector(foo:) to:nil from:nil event:nil]

Apple shouldn't reject this since you aren't using disallowed API's and you aren't doing anything UIControl isn't already doing.
If you don't want to take the risk, what you're doing is probably the best approach, creating a dummy control (if needed) and using it to send the action.
Comment: narrator's voice: he didn't
Comment: Interesting insight, thanks. I did not check the implementation of `UIControl` but the disassembly you provided comforts me in using my current approach. I'd rather stay away from `UIApplication` to do this since with the advent of extensions I don't expect it to remain accessible. I did not yet check if there is any hope for a clean implementation with iOS 10 but I will, and post my findings here if any.


How to find location of a point for a rectangle

Question: I have a circle with a line that is drawn through it at two points. I have the coordinate for the center of the circle, the two coordinates where it intersects the circle and the radius as well. I want to put the two rectangles around the two pieces from the circle, as shown by the green marking. My question is how can I get the coordinates of the rectangle? Any help would be appreciated
One of the things i considered using was the midpoint formula to find the middle coordinate between the intercepting points and then I can find the distance.
Answer: Assuming the center to be the origin, compute $r-\Big\Vert \frac{A+B}2 \Big\Vert$. This is the amount of offset needed. The direction is given by $\frac{A+B}2$, so the complete formula is
$$O = \frac{r-\left\Vert\frac{A+B}2\right\Vert}{\left\Vert\frac{A+B}2\right\Vert} \frac{A+B}2 = \frac{2r - \Vert A+B\Vert}{2\Vert A+B\Vert} (A+B)$$
Comment: are A and B those intersecting points?  I can calculate the distance apart for those little pieces in between the circle to the point of the rectangle, but I'm not sure about the coordinates because the cut can be made at an angle
Comment: $A$ and $B$ are the coordinates of the two intersection points. The other points of the rectangle are given by $A' = A+O$ and $B'=B+O$, all the points are two-coordinate vectors and $\Vert P \Vert = \sqrt{P_1^2+P_2^2}$. The Angle of $\overline{AB}$ is irrelevant to the question.
Comment: so A' and B' would be the two co-ordinates on the blue line correct from my understanding?
Comment: @Masterminder No, $A'$ and $B'$ will be the corners of the rectangle _not_ on the circle (Green). $A$ and $B$ are the red-circled points in your sketch.
Comment: Yes but they will lie on the blue line correct? The line divides the circle and those rectangles start where the blue line is. Do you know what I mean?
Comment: @Masterminder No. $A$ and $B$ form the blue side of the rectangle and $A'$ and $B'$ form the opposite, green, side.
Answer: Hint : find the angular coefficient of the line between the points $A$ and $B$ $\left( m = \frac{A_y-B_y}{A_x-B_x}\right)$ and $q$ (where the line crosses the y-axis), and solve the system of the equation of the circle and the line, letting $\Delta = 0$. Let $(C_x,C_y)$ be the centre of the circle, and $r$ its radius...
\begin{cases}
(x-C_x)^2+(y-C_y)^2=r^2 \\
y=mx+q \\
\end{cases}
Let $\Delta = 0$, because if $\Delta \gt 0$ there are 2 solutions $\to$ there are 2 common points between the line and the circle, otherwise $\Delta \lt 0$ there are no intersections.
Answer: Find equation of the blue line and that of the circle(shift origin here or it will get a bit nasty) and add an arbitrary constant to it and put in equation of circle retaining only x terms.
You will get a quadratic equation. Set discriminant to be 0 as you want only 1 point of contact with circle(tangent)
Knowing this point, You can find its equation and equation of other lines as you know their slopes/points. You will get 2 values of arbitrary constants up there corresponding to 2 rectangles.


Magento 2 : block function call from another block function

Question: If I want to call any function from a block file in another block file, then how that is possible?
~Thank you in advance!
Answer: if you need to call a function declared in another block file you have to extend the block
<code>class YourBlockClass extends OtherBlock
</code>
But if you need to call the function without extending the block you have to put the function in a helper that is made to have functions that are called in many places.
Comment: but there for block class, there is a need to extend the /View/Element/Template class if the __construct is used. so how to fix that?


Inequivalent norms (given by different inner products) on infinite dimensional Hilbert space.

Question: I have this question in reviewing for my exam.
Let $H$ be an infinite dimensional Hilbert space. Write down an inner product on $H$ that gives a norm inequivalent with the original norm. Is $H$ complete under the norm determined by the new inner product?
In my understanding, as the norm of a Hilbert space is induced by the inner product it equipped, there are different inner products, all satisfy linearity, conjugate symmetry, positive-definiteness, hence different norms. My confusion is, why the question is asking "original norm"?  Is a Hilbert space uniquely determined by the inner product it uses? For example, the collection of square integrable functions on $R^d$ is a Hilbert space and equipped with a inner product of integral form. Finite-dimensional complex Euclidean space with dot product. Or, there is a space can be equipped with different inner product (to define its norm) to form the same Hilbert space? For example, the Euclidean space?
BTW, how is this question related to the fact that.

All infinite-dimensional (separable) Hilbert spaces are $l^2$$(Z)$ in
  disguise

Due to my poor understanding of functional analysis, I am not sure how is this question trying to motivate my thinking. Any help would be appreciated!
Thanks in advance!
Comment: Regarding the "original norm": If someone writes "let $H$ be a Hilbert space", they are usually assuming that some **fixed** scalar product on $H$ is given. Hence you are supposed to find a new inner product on $H$ such that the induced norm is not equivalent (in the sense of $\Vert \cdot \Vert_1 \leq C_1 \Vert \cdot \Vert_2 \leq C_2 \Vert \cdot \Vert_1$) to the norm induced by the original inner product. The hint tells you (more or less) to first consider the case $H =\ell^2$ (with the usual inner product). After that, try to deduce the general case from that.
Answer: Even in finite dimensions you can easily change the inner product. Let $\{ e_{n} \}$ be an orthonormal basis of $\mathbb{C}^{N}$ and define the new inner product
$$
                 (x,y)_{\mbox{new}}=\sum_{n=1}^{N}\lambda_{n}(x,e_{n})(e_{n},y).
$$
where $\lambda_{n} > 0$ for all $n$.
All the norms are equivalent on $\mathbb{C}^{N}$. This can be written as
$$
                      (x,y)_{\mbox{new}}=(Ax,y)_{\mbox{old}}
$$
where $A$ is a positive definite selfadjoint matrix. In finite dimensions, this describes every possible inner-product. The inner products are in one-to-one correspondence with positive definite matrices. Because selfadjoint $A$ can be diagonalized by an orthonormal basis of eigenvectors, $(Ax,y) = \sum_{n}\lambda_{n}x_{n}y_{n}^{\star}$ always looks like a weighted inner product when viewed with respect to a correctly chosen orthonormal basis.
If $X$ is an infinite dimensional linear space on which two topologically equivalent Hilbert inner products are defined, say $(\cdot,\cdot)$ and $(\cdot,\cdot)_{1}$, then the same thing happens. There exists a unique positive bounded selfadjoint $A$ such that
$$
              (x,y)_{1}=(Ax,y),\;\;\; x,y\in X.
$$
But it also goes the other way: $(x,y)=(Bx,y)_{1}$ where $B$ is positive. You end up with $(x,y)=(Bx,y)_{1}=(ABx,y)$ which gives $AB=I$. Similarly $BA=I$. The existence of such $A$ and $B$ comes from the Lax-Milgram Theorem, which is proved using the Riesz Representation Theorem for bounded linear functionals on a Hilbert Space.
But there are bounded positive linear operators $A$ on a Hilbert space $X$ which are not positive definite. Such an $A$ gives rise to $(x,y)_{1}=(Ax,y)$ with $\|x\|_{1} \le C\|x\|$ for a constant $C$, but the reverse inequality need not hold, which can lead to an incomplete $X$ under $\|\cdot\|_{1}$. For example, let $X=L^{2}[0,1]$ with the usual inner product. Define a new inner product by $(f,g)_{1}=\int_{0}^{1}xf(x)g(x)\,dx$. This is achieved as $(Af,g)$ where $Af=xf(x)$. This space is not complete because $1/\sqrt{x}$ is in the completion of $L^{2}$ under the norm $\|\cdot\|_{1}$. The completion of $(X,\|\cdot\|_{1})$ consists of $\frac{1}{\sqrt{x}}L^{2}[0,1]$. However, if you instead define $\|f\|_{1}^{2}=\int_{0}^{1}(x+\epsilon)|f(x)|^{2}\,dx$ for some $\epsilon > 0$, then you end up with an equivalent norm on $X$.
Comment: yes, I came across this before, thank you for the reminders and further remarks.
Comment: Thanks for answering. While $l^2$(Z) is complete and separable, how to show all infinite-dimensional (separable) Hilbert spaces are $l^2$(Z) in disguise?
Comment: @Bob : They're not. You can let $S$ be any set, and define $l^{2}(S)$ as the set of complex functions $f$ on $S$ for which $f$ is zero except for a finite or countable number of points, and such that $\sum_{s\in S}|f(s)|^{2} < \infty$. This is a general Hilbert space. Such a Hilbert is $l^{2}(\mathbb{Z})$ iff $S$ is countable. The correspondence comes by finding a complete orthonormal basis $\{ e_{s}\}_{s\in S}$ for the Hilbert space $\mathcal{H}$. Then $\mathcal{H}\simeq l^{2}(S)$ comes from the correspondence $x\in\mathcal{H} \sim f_{x} \in l^{2}(S)$ given by $f_{x}(s)=(x,e_{s})$
Comment: thanks. I do mean some countable $Z$, I was looking at p163 of S&S real analysis. Thank you.
Comment: @Bob : The cardinality of an orthonormal basis for a Hilbert space $\mathcal{H}$ is unique. That is, if you have two different orthonormal bases, then the bases have the same cardinality. Then, through the $l^{2}(S)$ correspondence, you find that Hilbert spaces with the same cardinality orthonormal bases are equivalent. So all Hilbert spaces are isometrically isomorphic to $l^{2}(S)$ where the cardinality of $S$ is uniquely determined to be the cardinality of a complete orthonormal basis. So dimension becomes cardinality and the spaces are isomorphic iff they have the same dimension.
Comment: @T.A.E. Why $1/sqrt{x}$ is in the closure of $L^2$ under the new inner product you defined.
Comment: @user156460 : $(Af,f)=\int x|f|^{2}\,dx = \|\sqrt{x}f\|^{2}$ closes to $\sqrt{x}f \in L^{2}$ or $f \in \frac{1}{\sqrt{x}}L^{2}$.


How does one grep the Help from admin templatates in Powershell?

Question: If I open my Local Group Policy Editor in Windows and go to Local Computer Policy -> Administrative Templates -> Control Panel -> Personalization for example, and then I click on one of the many settings listed, is there a way to grep all of the policy descriptions (listed as Help:) to find the particular policy I want to look at without reading through all of them, using PowerShell or some other tool?
Answer: In the group policy editor, click on "Administrative Templates" (either in Computer Configuration or User Configuration), then:
"Action" -> "Filter Options" -> select "Any" in "Managed", "Configured" and "Commented" to match all the group policies.
Then, you can "Enable keyword filters" and create your filter. The view will be filtered until you uncheck "Action" -> "Filter On".

(you'll need to check "Help text" unlike the screenshot above)


Como traduzir "rows selected" no datatables js

Question: Esse é o código da minha página HTML, está 90% traduzido a tabela, mas quando seleciono algum item, não traduz, e nem sei como traduzir.
<?php
session_start();
$pagTitle = "Clientes";
require_once ("../tools/conexao.php");
include_once ("../tools/head.php");
$clientes = "active";
$openClient = "open";
?>

<?php
include_once ("../tools/header.php");
include_once ("../tools/slidebar.php");
?>

<button type="button" data-positionX="right"data-positionY="top"data-effect="fadeInUp"data-message="Well done! You successfully read this important alert message."data-type="success" class="btn pmd-ripple-effect btn-success pmd-z-depth pmd-alert-toggle">Alert Success</button>
    <?php if(isset($_SESSION['msg'])){echo $_SESSION['msg'];unset($_SESSION['msg']);}?>

<a href="<?php echo $baseUrl;?>app/">Dashboard

Clientes

         Adicionar

                                #
                                ID
                                Nome
                                CPF
                                Telefone
                                Email
                                Estado
                                Cidade
                                Endereço
                                CEP
                                Sexo
                                Status

                            <?php
                            /*Pegar dados no bd*/
                            $sql = "SELECT * FROM clientes";
                            $dados = mysqli_query($conn, $sql);
                            $count =  mysqli_num_rows($dados);
                            while($rows = mysqli_fetch_assoc($dados)) {
                        ?>
                        <?php
                            if ($rows['ativo'] == "Desativado") {echo "";}
                        ?>

                                <?php echo $rows['idCliente']; ?>
                                <?php echo $rows['nome']; ?>
                                <?php echo $rows['cpf']; ?>
                                <?php echo $rows['telefone']; ?>
                                <?php echo $rows['email']; ?>
                                <?php echo $rows['estado']; ?>
                                <?php echo $rows['cidade']; ?>
                                <?php echo $rows['endereco']; ?>
                                <?php echo $rows['cep']; ?>
                                <?php echo $rows['sexo']; ?>
                                <?php echo $rows['ativo']; ?>

                        <?php } ?>

                    <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>

Adicionar Cliente

                    <form autocomplete="false" method="post" action="addCliente.php" class="form-horizontal">

                            Nome
                            <input type="text" class="mat-input form-control" name="nome" id="nome" value="">

                            CPF
                            <input type="text" class="mat-input form-control" name="cpf" id="cpf" value="">

                            Telefone
                            <input type="text" class="mat-input form-control" name="telefone" id="telefone" value="">

                            Email
                            <input type="text" class="mat-input form-control" name="email" id="email" value="">

                            Estado
                            <input type="text" class="mat-input form-control" name="estado" id="estado" value="">

                            Cidade
                            <input type="text" class="mat-input form-control" name="cidade" id="cidade" value="">

                            Endereço
                            <input type="text" class="mat-input form-control" name="endereco" id="endereco" value="">

                            CEP
                            <input type="text" class="mat-input form-control" name="cep" id="cep" value="">

                                        Sexo
                                        <select name="sexo" class="select-simple form-control pmd-select2">
                                            <option>Masculino</option>
                                            <option>Feminino</option>
                                            <option>Outro</option>
                                        </select>

                                        Status
                                        <select name="ativo" class="select-simple form-control pmd-select2">
                                            <option>Ativo</option>
                                            <option>Desativado</option>
                                        </select>

                            <button  class="rounded btn pmd-ripple-effect btn-success" type="submit">Cadastrar</button>
                            <button data-dismiss="modal"  class="rounded btn pmd-ripple-effect btn-danger" type="button">Fechar</button>

                    </form>

<?php include_once("../tools/footer.php"); ?>


Objective C: Own controls for a blog

Question: i want to make an app for a little blog. (Looks little bit like the facebook timeline)
There is already a website for it. I know that i can make a HTML document to an app, but i want a native version.The website looks like that:

The scructure is very simple: Title, image, title.
Now: I solve it like that:
I have in my mainview a UIScrollView. And add the control:

And add the controls in a foreach where i grab the data:
MangoListItem *myLabel = [[MangoListItem alloc]initWithFrame:CGRectMake(0, 0, 200, 40)];
[myLabel setBackgroundColor:[UIColor redColor]];
[scrollView addSubview:myLabel]

First: Is this a good solution?
Second: How can i associate the .xib File with the .h File?
Thank you for your help!
Answer: NSString * nibName = @"MyCustomView";
[[[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil] firstObject];

Comment: Thanks for the answer. Where do i have to put that code?
Comment: put that in the viewdidload.  You could also simply instantiate your UIViewController using initWithNibName: from the start, that will save you some time, and be easier for you.  Take a look here for a tutorial: http://www.idev101.com/learn/view_controllers.html
Comment: Thank you for your help. I try to solve it in combination with this post: http://stackoverflow.com/questions/14144672/custom-xib-based-ui-control

Objective C: Own controls for a blog


Windows 2008 server hosting in Europe

Question: I'm searching for a Windows 2008 server in Europe, preferably in Germany or UK or anything with good routing to Denmark (as its where the primary traffic will be generated from).
The server will be used as web server (asp.net mvc, php), mail server and database server. We are running a few sites with around 200 concurrent users, which isn't much, but we intend to expand in the near future and the server should be easy to scale in form of adding more RAM and HDD space - if its possible.
I think a virtual server may be the best choice - hyper-v or virtuozzo? - considering cost vs specs - but i'm open to suggestions.
The max budget is in the range of $1000-1200/year.
You guys have any suggestions? Let me know if you need further info.
Answer: Take a look at this: http://english.keyweb.de/

Windows 2008 server hosting in Europe


Better approach to optimize PHP Cron Job

Question: I can't get into too many specifics as this is a project for work, but anyways..
I'm in the process of writing a SOAP client in PHP that pushes all responses to a MySQL database. My main script makes an initial soap request that retrieves a large set of items (approximately ~4000 at the moment, but the list is expected to grow into hundreds of thousands at some point).
Once this list of 4000 items is returned, I use exec("/usr/bin/php path/to/my/historyScript.php &") that sends a history request for each item. The web service api supports up to 30 requests / sec. Below is some pseudo code for what I am currently doing:
<code>$count = 0;

foreach( $items as $item )
{
    if ( $count == 30 )
    {
      sleep(1); // Sleep for one second before calling the next 30 requests
      $count = 0;
    }

    exec('/usr/bin/php path/to/history/script.php &');
    $count++;
}
</code>
The problem I'm running into is that I am unsure when the processes finish and my development server is starting to crash. Since data is expected to grow, I know this is a very poor solution to my problem.
Might there be a better approach I should consider using for a task like this? I just feel that this is more of a 'hack'
Comment: You can try counting how much time it took you to handle the 30 requests and then sleep for 1-that time and that would make it slightly faster.
Answer: I am not sure, but i feel that the reason for your application crash, you are keeping large set of data in PHP variable. Look into this, based on RAM size this(data size) will leads to system crash. And my suggestion is try to limit incoming data from external service per request, instead number of request to the service.
Comment: Thank you for the feedback! I have the script optimized now! I'm making sure to disconnect from the database right after the query finishes and I'm sleeping for 2 seconds, not 1. This allows the API to process my requests.


osTicket, auto assignation by account

Question: I am evaluating osTicket for a company who repair printers.
When company's customers need support, they have to log in osTicket to open a issue.
First, they have to be able to select one device id (or serial number) of their broken printer. For this, I will need to populate the relation id_device-account in somewhere. Then they will select the kind of issue and will apport other datas.
After the issue was saved, the system have to assig that ticket to a technician (for this I will need to populate a second list with the relation between staff-memebers and accounts).
Where can I define these lists with relations (device-account and staff-member-account) and how can I performed these automations?
Thanks in advance and regards,
Gonzalo
Answer: This is built into osTicket. Or at least it is for the latest version.
You will need to set up a custom form: Admin -> Manage -> Forms and then add your printer values into the main support form.
Then you need to go to Manage -> Ticket Filter. In there, you can assign filters  based on the custom form's field for each printer type (or multiple printer types if you want) and have them sent to specific agents or to agent teams or departments under the action tab.
Comment: @Josua Walcher thank for your help. I will try that you said. It would be fantastic if it was possible to use my custom form like company's ticket form. Is it possible?
Comment: That's how I'm using it on another project - the custom form integrates with the default form, @Gonzalo, and then the tickets get shipped off to the various support staff based on the options chosen by the end user. It should work well for your use case.
Comment: Thankyou again @Josua-walcher. I tried that you said but I found only one way to include my custom form... I have to include it in a help topic (I don't want to  do that). What I doing wrong? Regards.
Answer: @Gonzalo, Following the answer from @Joshua Walcher all you need to do is add your form under the Ticket Details under Manage > Forms > Ticket Details. Once there just create your custom entry and define it as you need, you can even choose the order in which it's displayed on the Client Page and assign variables to that field. Once there it should appear in all of the tickets they create. I use this for information we need to pull and made it mandatory, If you need to assign based on value just use the Tickets Filter as previously mentioned by @Joshua. Hope this helps!

osTicket, auto assignation by account


invalid target element for this operation ngTable

Question: It's a known issue for ngTable that it can't create a header element for tables in IE 9 (and below). It creates the error
invalid target element for this operation

I just wanted to give anyone who gets this error a solution. Go to your angular.js file. Find the line that says
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];

and replace it with
tmp.append(wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2]);

I couldn't find an answer to this anywhere so I hope it can help someone.
Answer: This issue is being tracked in github. At this point there is no resolution and the suggested workaround is to use jQuery instead of angular's jqlite.
Comment: @011001000110000101110110011010 what can you do more than referencing the issue in this case ? specially if there's no resolution at this time, unfortunately SO cannot yet refresh on github issue
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes.
Comment: This perfectly answers the question. It is a known bug and there is no solution, period.


Generating "surrogate data" to calculate error on estimators

Question: We have a dataset in the form of a time series $Y_n$.
We assume it follows an underlying parametric distribution $f(n,\beta)$, $\beta$ being the parameters.
From the observed dataset, we get an estimator $\tilde{\beta}$ for the parameters (say from an MLE). I am interested in the uncertainty of this estimator. Of course, there could be a variety of methods, but I am interested in the use of surrogate data as done in this paper: https://www.sciencedirect.com/science/article/pii/S0048733315001699
Basically, the idea is simple: we generate a bunch of artificial data using the distribution $f$ with parameters $\tilde{\beta}$ (we do a Monte Carlo simulation for those who like complicated words to describe simple things). Those generated data will differ from the original: we then apply our MLE to each of these new surrogate data to obtain new estimations. We obtain this way a distribution of estimated parameters, which can be summarized with whatever suitable metric (e.g. std dev)
Sounds great to me, makes intuitive sense. The only problem is, I can't really find documentation to back up the validity of this method. When searching, I can't get out of a loophole because it seems that all I can find when looking for surrogate data tests are specific tests for the linearity of a system. I could not find a reference that uses surrogate data in this way to calculate uncertainties on estimators.
Question: Is this surrogate data procedure valid for calculating errors on estimators, and could you point me to sources that discuss/prove it?
Comment: Sounds like a parametric bootstrap to me.
Comment: @utobi Oh wow, I take it back, apparently parametric bootstrap is just the keyword I was missing. That does seem to be exactly what I'm looking for, and I should have what I need to do further research on my own. Well, that was a swift answer, that makes me feel a little silly for asking, but thanks a lot
Comment: glad to read it helped :-). For completeness, I expanded on an answer.
Answer: As per my comment, what you described seems to be matching with the parametric bootstrap. Very quickly, the bootstrap method comes in two flavours:
(a) parametric
(b) nonparametric.
Very informally, in (b), new data are generated by sampling with replacement from the original data, samples of the same size as the original dataset. On the other hand, in (a) we sample from the parametric model assumed for the data at hand, with the parameter value fixed at the estimate obtained from the original data.
For a complete treatment of the bootstrap, why it works, and when it doesn't work please check Davison and Hinkley's book Bootstrap Methods and Applications.


htaccess won't work for directory

Question: hello I am facing a problem with my htacess i have two php files that are used for URL rewriting first one is video.php and second one is channel.php. on homepage when I click any video its properly works for rewriting the url e.g.

mysite.com/video.php?url=1234

changes to that works properly for me

mysite.com/1234-video-custom-slug

but when I click for any channel it loads the same video.php but with rewriting urls of channel like:

mysite.com/channel/1-channel-slug

instead of rewriting urls from channel.php?id=1
I don't know what i am doing wrong here is my htaccess file code
RewriteEngine On

RewriteRule ^([a-zA-Z0-9-/]+)$ video.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+)/$ video.php?url=$1
RewriteRule ^channel/([a-zA-Z0-9-/]+)$ channel.php?id=$1
RewriteRule ^channel/([a-zA-Z0-9-/]+)/$ channel.php?id=$1

Comment: change the order of the rewriterule. Put channel.php rewrite followed by video.php rewrite.
Answer: Change the order like this
RewriteEngine On

RewriteRule ^channel/([a-zA-Z0-9-/]+)$ channel.php?id=$1
RewriteRule ^channel/([a-zA-Z0-9-/]+)/$ channel.php?id=$1
RewriteRule ^([a-zA-Z0-9-/]+)$ video.php?url=$1
RewriteRule ^([a-zA-Z0-9-/]+)/$ video.php?url=$1

htaccess won't work for directory


Continuous Dimensional Spaces

Question: I was wondering, is there such a thing as a 'continuous dimensional space' in mathematics?
For instance, consider $\mathbb{R}^2$. If this can be thought of as two $\mathbb{R}$'s, does there exist something of the form $\mathbb{R}^\mathbb{R}$ ? But not for a single superscript real number, but rather the whole set at once.
What does such a space mean for real numbers?
I'm having a hard time trying to express my thoughts in words. That might be because I'm saying something ridiculous (very likely). Anyways, could someone please explain?
Answer: In set theory, the notation $A^B$ (where $A,B$ are sets) stands for the set of all functions from $A$ to $B$. We are used to think of $\mathbb{R}^2$ as consisting of tuples $(a,b)$ of real numbers but we might as well think of $\mathbb{R}^2$ as the set $\mathbb{R}^{\{ 1, 2\}}$. The latter set consists of functions $f \colon \{ 1,2 \} \rightarrow \mathbb{R}$ from a set $\{ 1, 2 \}$ with two elements (whose members I decided to conveniently call $1,2$ but specific elements don't really matter) to $\mathbb{R}$. The translation between tuples and functions goes like this:
$$ f \mapsto (f(1),f(2)), \\ (a,b) \mapsto f(x) = \begin{cases} a & x = 1, \\
b & x = 2. \end{cases} $$
so we can think of $f(1)$ as giving us the "first coordinate" of a tuple and of $f(2)$ as giving us the second coordinate.
This might look a bit strange in the beginning but it allows you to interpret $\mathbb{R}^\mathbb{R}$ as the set of functions from $\mathbb{R}$ to $\mathbb{R}$. To specify a point in $\mathbb{R}^7$ we need to give seven real numbers or a function from a set with seven elements to $\mathbb{R}$ and to specify a point in $\mathbb{R}^{\mathbb{R}}$ we need to give "$\mathbb{R}$ real numbers" or, in other words, a function from $\mathbb{R}$ to $\mathbb{R}$. This space has the structure of a vector space which is not finite dimensional although I wouldn't call it a "continuous dimensional space".
Answer: Yes. In fact, in set theory, $A^B$ means "the set of functions from $B$ to $A$". This aligns nicely with the idea of the space $\mathbb{R}^n$: it's the set of functions from an $n$-element set (say $\{1,2,\dotsc,n\}$) to $\mathbb{R}$. This is the same as saying that the elements are $n$-tuples $(r_1,r_2,\dotsc,r_n)$.
There's no difficulty in extending the abstract definition to, say, $\mathbb{N}$: now you have a countable set, and so the elements are tuples of the form $(r_1,r_2,\dotsc)$, where the list doesn't terminate. You may recognise this: it's a sequence.
To come to your question, $\mathbb{R}^{\mathbb{R}}$ can therefore be thought of as "functions from $\mathbb{R}$ to $\mathbb{R}$", i.e. the set of $f:\mathbb{R} \to \mathbb{R}$.
When $V$ is a vector space, $V^n$ is also a vector space by making operations act componentwise (i.e. $(x+y)_k = x_k+y_k$ for each $1 \leqslant k \leqslant n$ and so on). This still works if we take $V^{\mathbb{R}}$, except we say that addition and scalar multiplication act pointwise: in particular, you might know already that "functions from $\mathbb{R}$ to $\mathbb{R}$" is a vector space when we set $(f+g)(x) = f(x)+g(x)$ and $(\lambda f)(x) = \lambda \cdot f(x)$.

Continuous Dimensional Spaces


Where does Drupal store information after creating a rule?

Question: I'm wondering where Drupal stores information in the database when one creates a rule with an event A node has been flagged and an action Grant user points to a user.
Can you help me?
Answer: Rules are stored in the rules_rules table in D7. The table contains the rows of name (a machine readable name) and data (a data blob).

^ this is from D6, D7 has rules stored in rules_config, with rules_trigger holding the triggers and the ID of the rule and the trigger matching to each other.
Comment: I can't find a rules_rules table in my database... Did you mean rules_config?
Comment: No, rules_rules. You should have a rules_config, rules_dependencies, rules_rules, rules_sets, rules_tags and rules_trigger tables.
Comment: I don't have the rules_rules and rules_sets tables. Is that abnormal?
Comment: Are you able to create rules and save them?
Comment: Yes, I am able to do so.
Comment: Actually, I was looking at rules 1.x from D6. My bad.

Looking at the schema for D7 in the rules.install file (good place to look at how a module is setting up it's database tables) there should be a rules_config, rules_trigger, rules_tags and rules_dependancies.

The trigger, ie "after a node has been flagged" or published, or what have you, will be in rules_trigger, it's ID matches the id of a rule in rules_config.

Sorry about the mixup.


How to call non static method from web method

Question: In my code, previously I save data when a button click, here hdnDisplayOrderSaveData is ASP hidden filed
    protected void btnSaveDisplayOrder_Click(object sender, EventArgs e)
        string data = hdnDisplayOrderSaveData.Value;
        Service service = new Service();
        if (IsSaveStringValid(data))
        {
            bool result = service.SaveServicesDisplayOrder(data);
            if (result)
            {
                ClientScript.RegisterStartupScript(typeof(Page), "script", "showMessage(1);", true);
            }
            else
            {
                ClientScript.RegisterStartupScript(typeof(Page), "script", "showMessage(2);", true);
            }
        }
        LoadDisplayOrder();
    }

Then I need to move above functionality to web method, So my code as follows,
public partial class ProductAdminSortOrder : BasePage
    {
        private List<int> serviceIds = new List<int>();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                CheckSession();
                CheckPagePermissions(Permissions.ServicesAdministrator);
                LoadDisplayOrder();
            }
            catch (Exception ex)
            {
                Logger.LogErrorEvent(ex);
                throw;
            }
        }

        ///
        /// Loads the display order.
        ///
        private void LoadDisplayOrder()
        {

        }

        [WebMethod]
        public static void SaveOrder()
        {

            string data = hdnDisplayOrderSaveData.Value;
            Service service = new Service();
            if (IsSaveStringValid(data))
            {
                bool result = service.SaveServicesDisplayOrder(data);
                if (result)
                {
                    ClientScript.RegisterStartupScript(typeof(Page), "script", "showMessage(1);", true);
                }
                else
                {
                    ClientScript.RegisterStartupScript(typeof(Page), "script", "showMessage(2);", true);
                }
            }
            LoadDisplayOrder();
        }

        //protected void btnSaveDisplayOrder_Click(object sender, EventArgs e)

        //}

        private bool IsSaveStringValid(string data)
        {
            data = Regex.Replace(data, @"\s+", "");

            string[] items = data.Split('#');

            if (!IsDataValid(item))
            {
                return false;
            }
        }

        private bool IsDataValid(string[] item)
        {
            if (item.Length != 2)
            {
                return false;
            }
            else
            {
                return serviceIds.Any(id => id == Convert.ToInt32(item[0], CultureInfo.InvariantCulture));
            }
        }

    }

after that, I'm getting following errors,
An object reference is required for the non-static field, method, or property 'ServicesAdminSortOrder.hdnDisplayOrderSaveData'
An object reference is required for the non-static field, method, or property 'ServicesAdminSortOrder.LoadDisplayOrder()'
An object reference is required for the non-static field, method, or property 'Page.ClientScript'

I have two questions, is the web method should be static
How can I avoid these errors?

Updated:
how I call web method,
function DeleteKartItems() {
     $.ajax({
     type: "POST",
     url: 'ProductAdminSortOrder.aspx/SaveOrder',
     data: "",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (msg) {
         console.log('success');
     },
     error: function (e) {
         console.log('failed');
     }
     });
}

Comment: You won't be able to access the non-static hidden field.  You can send it as a part of the request to the `WebMethod` using ajax or an ASP Update Panel.
Comment: The method `SaveOrder()` should not be static
Comment: @Slugart But once I removed static part, Web method not calling
Comment: @Slugart this web method is in aspx.cs not in a web service. so the problem is I cant call nonstatic method using Ajax.
Comment: The other methods are not accessible because they are not static. They are part of the main page, the variables etc do not exist in the context of the webmethod, which is a totally separate request to the server. So even if you could access them they would not be populated as you expect. If you need a specific value during your web method execution you need to either need to pass it in the request parameters or fetch it from somewhere on the server such as the database or session
Answer: You will need to send the data that was previously stored in the hidden field as a part of the request to the WebMethod using ajax or an ASP Update Panel.  An example: https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Comment: You are not (and never will be) able to call the non-static method from a static method.
Comment: this web method is in aspx.cs not in a web service. so the problem is I can't call the nonstatic method using Ajax.