How do I convert a PCRE to EBNF?

Question: I'm writing a spec thingamajig and I don't know EBNF. I have the following PCRE:
^(?:\$(?:\$|{\d+})|[^$])*$

Where, in the input:

$$ is an escaped $.
${num} is an argument number.
Everything else (that is not a $) is a literal.
A $ not followed by $ or {num} is an error.

And I need to convert it to EBNF. How do I convert this PCRE to EBNF?
(I noticed there are many questions about going from EBNF to PCRE, but I haven't seen any about going the other way around)
Comment: Do you intend to let the `.` in that regex match a `$`? (So that the string `$a$42` is acceptable?) (Because if so, that is *lexically* equivalent to `.*`)
Comment: @rici I could do that, or I could error. For this specific use-case, `.` should be `.`, not `[^$]`.
Comment: If you really mean `.`, then the syntax (but not the semantic structure) is precisely described by `.*` , which in EBNF would be something like `{ any character }`. But you probably actually want to describe the semantic parsing, in which case you will need to jump through some hoops to create an unambiguous grammar. Or you could just reject loose dollar signs as errors :)
Comment: @rici EBNF can be used to describe ASTs, which's what I'm after. `$$` is escaped `$`, `${number}` is argument number, everything else is literal.
Comment: Yes, sort of. Technically, you would need an unambiguous grammar, but it is easier to use an EBNF comment to indicate that `any character` would include only those instances of `$` which are not followed by `$` or `{`. Iirc there is formal way of inserting contextual predicates in EBNF but I'll check the standard before answering. Which means I'll need to be at my computer, so it's not going to be immediate.
Comment: @rici I see. Thanks. Perhaps I should indeed consider it an error.
Answer: Two things make answering this apparently simple question complicated:

The term "EBNF" has a large variety of manifestations. There is ISO standard ISO/IEC 14977:1996 for "Extended BNF" but as far as I know, it is rarely used in practice. (Note: There is a free download link on that page; purchase is not necessary.) Many internet protocols use "Augmented BNF" as defined by RFC 5234, which is probably a better fit for your particular problem. And there are lots of parser generators which extend BNF in various ways, generally by adding regular-expression-like repetition and optionality operators, without being standardized in any way. (In fact, it was this chaos of possible definitions that motivated the ISO to produce a standard, but as is often the case with ISO standards, the lack of free text access -- until a decade after its release -- and freely-available tools hindered adoption.)

Regular expressions do not necessarily produce unambiguous grammars, and the regular expression you provide is ambiguous, since $ is allowed to be used as an ordinary character. The implication (and, I'm certain, the intention) is that a $ may not be treated as a regular character if it is followed by another $ or a number surrounded by braces, but the regular expression itself does not (and does not need to) make that distinction. Less obvious is what the intention might be for a string like:
 ${42 looks like an error to me but it would be accepted by the regex.

Anyway, here is an ISO EBNF for something similar to your language. Note that it does not accept the above string.
(* EBNF does not have wildcard characters and there is no way to
   enumerate all possible characters, so I use the exception mechanism
   to describe the set
 *)
any character
  = ? Any character representable by the source character encoding ? ;
decimal digit
  = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
literal sequence
  = {any character} -
      ({any character}, ('$$' | '${'), {any character}) ;
escaped dollar
  = '$$' ;
parameter
  = '${', decimal digit, {decimal digit}, '}';
thingamajig
  = {literal sequence | escaped dollar | parameter}

On the whole, since you provide a mechanism for escaping dollar signs, it would probably be simpler to just ban the use of loose dollar signs. That makes both the specification and the parser simpler, and avoids the problem of non-canonical representations. (Non-canonical representations can be a security problem because round-tripping a string into an internal representation and back could then fail fingerprint validation, and because they allow for information leaking. Those may not be significant in this case, but in general best practice for data exchange protocols is to avoid non-canonical representations when possible.)

How do I convert a PCRE to EBNF?


What is the meaning of group extension?

Question: I frequently see the notation
$1\to N\to G\to Q\to 1$.
Wikipedia explains that this is the notation to describe situation where there is an injective map from $N$ to $G$ called $i$ and $G/i(N)\cong Q$. It says that if $N\subset Z(G)$ then it is called central extension and if $N$ is cyclic, then this is called successive cyclic extension.
Why is there $1$ on the end in this notation and why is this notation important? I was just learning about supersolvable group and nilpotent group, and this notation seems out of context. Can you explain a little bit of context with simple terms without using Galois extension?
Comment: The key word here is "short exact sequence".
Comment: The context is that it happens frequently that $G$ is very complicated but there is a (non-complicated) normal subgroup $N$ such that $Q=G/N$ is affordable. So the question is what does $N$ and $G/N$ tell us about $G$, and can we construct all the possible $G$, which leads to the cohomology stuffs. The two simplest cases are when $N$ is in the center and when $Q$ is isomorphic to subgroup $Q'\le G$ such that $Q'\cap N= \{1\}$.
Comment: @reuns: I am quite sure that by "$Q=G/N$ is affordable", you just mean "$Q$ is not too complicated to consider"; but given the sheer number of adjectives that can apply to groups, I wouldn't be surprised if there was a serious technical answer to the question, "what is an affordable group?".
Answer: Short exact sequences
That's what's called a "short exact sequence", and the notation only really makes sense in light of exact sequences more generally. We say a sequence of groups and homomorphisms between them like
$$ \dots \to G_{-1} \to G_{0} \to G_{1} \to G_{2} \to \dots $$
is exact if the kernel of the map from $G_k$ to $G_{k+1}$ is the image of the map from $G_{k-1}$ to $G_k$ for each $k$. This turns out to be a useful concept, but explaining why it's useful is, I think, out of scope.
A special case of this is an exact sequence like the one in your question
$$ 1 \to N \xrightarrow{f} G \xrightarrow {g} Q \to 1.$$
The claim that this sequence is exact tells you three things:
(1) The image of the map $1 \to N$ is the kernel of the map $N \xrightarrow{f} G$. Since the image is trivial that means $f$ is injective.
(2) The image of the map $N \xrightarrow{f} G$ is the kernel of the map $G \xrightarrow {g} Q.$ That is, $\operatorname{im} f$ (which is a copy of $N$ in $G$) inside $G$ is $\ker g$.
(3) The image of the map $G \xrightarrow {g} Q$ is the kernel of the map $Q \to 1$. Since the kernel is all of $Q$, that means $g$ is surjective.
So this can be summarized as follows: The sequence
$$ 1 \to N \xrightarrow{f} G \xrightarrow {g} Q \to 1.$$
is said to be a short exact sequence if $f$ is injective, $g$ is surjective, and $\operatorname{im} f = \ker g$. The only special role that the $1$'s play in this is that they are convenient ways to indicate that $f$ is injective and that $g$ is surjective, given that we are talking in terms of exact sequences anyway. The fact that these claims fit nicely into the framework of exact sequences is part of what makes the framework useful, but it's not useful in an obvious way until you've worked with it a bit, especially if you're only touching short exact sequences.
Special examples of this:

If $g:G \to H$ is any surjective map, then $1 \to \ker g \xrightarrow{f} G \xrightarrow {g} H \to 1$ is a short exact sequence, where $f: \ker g \to G$ is the inclusion map.

If $N$ is a normal subgroup of $G$, then $1 \to N \xrightarrow{f} G \xrightarrow {g} G/N \to 1$ is a short exact sequence, where $f$ is the inclusion map and $g$ is the obvious projection map.

But you don't have to use short exact sequences to talk about group extensions.
Group extensions
A group extension of a group $H$ is a group $G$ together with a surjective map $\pi: G \to H$. The extension is said to be central if $\ker \pi \subseteq Z(G)$. It's said to be cyclic if $\ker \pi$ is cyclic, etc.
The basic idea is that elements of $G$ are elements of $H$, but "with some extra information attached". If you started with $G$, you could reconstruct $H$ as a quotient: $H \cong G/\ker \pi.$
The nature of the extra information is, of course, related to what information you forget when you map elements of $G$ down to elements of $H$, i.e. information about the kernel $\ker \pi$. That's why a lot of data about the extension is stated in terms of the kernel: roughly the messier the kernel (and its relationship to $G$), the messier the information you're attaching. The simpler the kernel (and its relationship to $G$), the simpler the information you're attaching.
Group extensions are a basic way of building more complicated groups out of simpler ones. In that sense they're a bit like products of groups, but messier and richer.
Answer: The first $1$ indicates that the map $i:N\to G$ is injective.  The last that the map from $G$ to $Q$ is surjective.  This is because the sequence is exact.  That's the kernel of each map is the image of the previous one.
The sequence is called a short exact sequence, and an extension is a super-group, or a group that contains another as a subgroup.
We get $G/i(N)\cong Q$ by the first isomorphism theorem.

What is the meaning of group extension?


How to implement jquery ajax call client->server method in mvc3?

Question: Q1:  Can somebody provide code example for jquery ajax to server method call in mvc3?
Q1a: Does the server return have to be a Json result returned from server side?  What are my options with the returned data from the server side method (json, just return a string, etc,)?
-- Something like this...
-- script called from razor view:
$("#textbox1).change(function()
{
$.ajax(
    {url: '/controller/action',
    data: { val1: $("#textbox1").val(), val12: ("#textbox2").val()},
    success: function(data){
             $("#SumResult").val(data);
           }})
});

-- Server method within same controller:
public ActionResult <or> String (int val1, int val2)
{
    return (i != null && j != null) ? (i + j).ToString() : "";

 }

Answer: Below article should give you an idea :
http://tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views

Q1a: Does the server return have to be a Json result returned from
  server side?

No, you can pretty much return anything from server (in ASP.NET MVC world, from controller method). If you return JSON, it is pretty much convenient for you to work with it inside your JavaScript code.

What are my options with the returned data from the server side method
  (json, just return a string, etc,)?

Some of them are :

XML
JSON
Html

Assuming that your controller supposed to return ActionResult, some of that you can return are as follows :

Content
Json


Generators of the product group $G \times H$ given two finite groups?

Question: Was wondering about the generators of $G\times H$ given two finite groups $G, H$ and supposing you knew their generators (abstractly).  In particular $G, H$ are both $p$-groups for different $p$.
Does $S \times T$ generate $G \times H$ whenever $S$ generates $G$ and $T$ generates $H$?
Comment: Not necessarily. If $G$ and $H$ are both cyclic, then you can take $S$ and $T$ singletons, in which case $S\times T$ is a singleton. But then for $S\times T$ to generate $G\times H$ it would be necessary that $G\times H$ be cyclic, and the product of two cyclic groups is cyclic if and only if their orders are coprime. So that lets you generate lots and lots of counterexamples to $S\times T$ generating $G\times H$.
Answer: You don't even need all of $S\times T$; Since the two components of $G\times H$ don't "speak" with each other (meaning, the product is determined individually for each component), you can simply use the sets ${(g_i,e_h)}, {(e_g,h_i)}$ where $h_i\in T, g_i\in S$.
Take some member of $G \times H - (a,b)$. We know that each component can be expressed as the product of generators of its respective group - $(a,b)=(g_1g_2...g_n,h_1h_2...h_k)$. This means that: $$(a,b)=(g_1,e_h)...(g_n,e_h)(e_g,h_1)...(e_g,h_k)$$
And so each element may be expressed as a product of elements from our given set. As an exercise, show that the given set cannot be reduced - if we take away any generator from the set, then there will be some element in $G\times H$ which will not be generated by our set.
Comment: That makes sense.  Except, can't you take away a member if $T, S$ were not minimal?  Also your first hyphenation appears that you're removing $(a,b)$ from the group.
Comment: What if $S$ and $T$ don't contain the identity elements, though?  Indeed, in general $S\times T$ may not generate $G\times H$ if $S$ generates $G$ and $T$ generates $H$ (consider when $G$ and $H$ are cyclic of the same order and $S$ and $T$ are singletons, for instance).  In the particular case of the question where $G$ and $H$ are $p$-groups for different primes you can show this can't happen but it takes a bit of work.
Comment: You're correct, I assumed you meant T and S to be minimal. If they are not, you are able to take out elements.
Comment: S and T don't have to contain the identity element - we choose a set of the form described above and get it for free - the identity of each group is also a product of the elements of T or S respectively, and so we can generate it using the generating set described above, am I wrong? The set contains the identity in each component, without assuming it belings to S or T
Comment: You're right that the set you described generates $G\times H$, but it doesn't answer OP's question of whether $S\times T$ generates $G\times H$.
Comment: I now see that I misunderstood what OP was asking - thanks.


Likert scale 0-4 or 1-5

Question: I am conducting a study with Likert scale questions and my thesis advisor advised me to rescale the answers from 1-5 (strongly agree-strongly disagree) to 0-4. She says this will help in the regression analyses. I am researching the effect of a supportive manager on motivation of a employee (which are both Likert scale questions).
I do not understand the advantage of rescaling the model to 0-4. Does anyone know why this would be better?
Comment: Regression of one ordered  (ordinal) scale on another is a dubious idea any way. If you are proposing literally a regression of $y$ against $x$ subtracting 1 from the response just affects the intercept. it can't make interpretation easier. You need to widen the advice you're getting.
Answer: I don't understand it, either.
If you plot motivation (vertically) against manager supportiveness (horizontally), then rescaling only results in a relabeling of the axes: every 1 becomes a 0, every 2 a 1, and so on. (Incidentally, if you plot raw scores, you will have overplotting. Look into jittering your data to reduce this, or into sunflowerplots.)
If you regress motivation ($y$) on supportiveness ($x$), then the original regression equation might be
$$ y=\beta_0+\beta_1x +\epsilon, $$
whereas the equation after rescaling would be
$$ y'=\beta_0'+\beta_1'x'+\epsilon. $$
Now, $y'=y-1$ and $x'=x-1$, so the second equation becomes
$$ y-1=\beta_0'+\beta_1'(x-1) + \epsilon,$$
or
$$ y=1+\beta_0'-\beta_1'+\beta_1'x +\epsilon. $$
Comparing coefficients gives us
$$1+\beta_0'-\beta_1' = \beta_0\text{ and }\beta_1'=\beta_1. $$
Thus, the intercept changes, but the regression coefficient stays the same. (So will their $t$ and $p$ values.) The information content is precisely the same.
The only advantage I see is that the rescaled intercept coefficient is slightly easier to interpret, as motivation when supportiveness is zero - which is a valid value after rescaling, but not before. So it's not that the regression will be easier, but interpretation may be so, slightly.
You may want to ask your supervisor what they mean. Be prepared to tactfully change the subject if they start stuttering. Not everyone is (or needs to be) an expert in statistics.

Likert scale 0-4 or 1-5


How to find an interval over which f is increasing/decreasing at an increasing/decreasing rate?

Question: I'm in Calculus 1, and I'm asked the following questions:
Given the graph of the function $f(x)=5x^3-3x^5$:
Using the EXACT values for zeros of $f'(x)$ and $f''(x)$ identify intervals in the domain where:
$f$ is increasing at an increasing rate over: (EDIT: I think the answer is $(0,\frac{1}{\sqrt{2}})$)
$f$ is increasing at a decreasing rate over: (EDIT: I think the answer is $(-\frac{1}{\sqrt{2}},0)$)
$f$ is decreasing at an increasing rate over: (EDIT: I think the answer is $(-infinity,-\frac{1}{\sqrt{2}})$)
$f$ is decreasing at a decreasing rate over: (EDIT: I think the answer is $(\frac{1}{\sqrt{2}},infinity)$)
I'm also asked to find local extrema, but I'll cross that bridge when I get there.
I've already determined $f'(x)=15x^2-15x^4$ and $f''(x)=30x-60x^3$, that's easy, and the zeros of the first derivative are $x=-1, x=0, x=1$; and the zeros of the second derivative are $x=-\frac{1}{\sqrt{2}}, x=0, x=\frac{1}{\sqrt{2}}$
I've also determined the inflection points to be $(-\frac{1}{\sqrt{2}},-\frac{7}{4\sqrt{2}}), (0,0), and (\frac{1}{\sqrt{2}},\frac{7}{4\sqrt{2}})$ by substituting the zeros of the second derivative into the original $f(x)$ function.
I'm stuck on the "increasing at an increasing rate" and subsequent other ones as well. Any tips would be appreciated! Thank you!
EDIT: I've tried my hand at the answers but I'm not sure if they're correct.
Comment: Any interval where (for example) the first and second derivative are both positive represents an interval where the function is strictly increasing, at a strictly increasing rate.
Comment: Increasing/decreasing: derivative, increasing rate/decreasing rate: second derivative.
Answer: The key here is that $\ f\ $ is increasing over intervals where $\ f'\ge0\ $ and decreasing  over intervals where $\ f'\le0\ $, and $\ f'\ $ is increasing over intervals where $\ f''\ge0\ $ and decreasing  over intervals where $\ f''\le0\ $.  Combining these observations we have:

Over intervals where $\ f'\ge0\ $ and $\ f''\ge0\ $, $\ f\ $ will be increasing at an increasing rate;
Over intervals where $\ f'\ge0\ $ and $\ f''\le 0\ $, $\ f\ $ will be increasing at a decreasing rate;
Over intervals where $\ f'\le0\ $ and $\ f''\ge0\ $, $\ f\ $ will be decreasing at a decreasing rate;
Over intervals where $\ f'\le0\ $ and $\ f''\le0\ $, $\ f\ $ will be decreasing at an increasing rate;

Since condition $1$ holds over the interval $\ \left(0,\frac{1}{\sqrt{2}}\right)\ $, you're correct that $\ f\ $ is increasing at an increasing rate there (you could also include the end points in the interval if you wish).  However you've missed the fact that this condition also holds over the interval $\ \left(-1,-\frac{1}{\sqrt{2}}\right)\ $, so $\ f\ $ is also increasing at an increasing rate over that interval rather than decreasing at an increasing rate as you state in your third answer.
Since condition 3 holds over the interval $\ \left(-\frac{1}{\sqrt{2}},0\right)\ $ and nowhere else other than the interval $\ \left[-\frac{1}{\sqrt{2}},0\,\right]\ $, your second answer, that $\ f\ $ is decreasing at a decreasing rate over that interval is also correct.
Your remaining answers aren't correct.  To fix them, simply determine the signs of $\ f'\ $ and $\ f''\ $ over the remaining intervals $\ (-\infty,-1\,]\ $, $\ \left[\frac{1}{\sqrt{2}},1\,\right]\ $ and $\ [\,1,\infty)\ $ with limits at the zeroes of $\ f'\ $ and $\ f''\ $  and look up the answer in the list given above.


How do I create a static local variable in Java?

Question: I've read Java does not support static local variables unlike C/C++. Now if I want to code a function with a local variable, whose value should persist between function calls, how do I do that?
Should I resort to using instance variables?
Comment: he wanted static locals (in a C sense) to maintain state through multiple function calls.  In other words having locals exist after the function returns.  This is one use of closures.
Comment: TL;DR answer: you can't. Make a static member variable of the containing class.
Comment: this is why Java needs closures (kidding).
Comment: @darren : What do closures have to do with static locals?
Comment: Part of the confusion on this thread is that the "static" keyword works differently in C and Java.  In C, if used inside a function, the state of that variable is preserved from one call to the next, but only has scope inside that function.  Java doesn't have an equivalent keyword, but some answers correctly describe how you can use an object to emulate this behavior.
Answer: You can have a static class variable, which will be preserved across all instances of the class. If that's what you want. If not, use an instance variable, which will only be preserved across method calls on this object.
public class Foo {
   static int bar;
   //set bar somewhere

   public int baz() {
      return 3 * bar;
   }
}

Comment: I think in most of the cases *instance variables* should be just fine, if what @gameover want is something to replace method static local variables.
Comment: @EllieP. `return lastID++;`
Comment: I agree. It's pretty rare to want a non-final static variable. Assigning ID numbers to objects is an example, though--store the last used ID number as a static variable. assignID() returns lastID+1
Comment: To prevent confusion, you may want to restrict yourself to using static variables for static methods, and instance variables for instance methods.  For instance methods with static functionality, encapsulate that functionality in a static method which is called from the instance method.
Comment: it gives error in ideone `error: illegal start of expression`
Answer: If you want to reuse variable value between function calls and isolate this variable from other methods, you should encapsulate it in an object. First, define a class with only the "static-like" variables and the function you need:
class MyFunctionWithState {
    private int myVar = 0;
    public int call() {
      myVar++;
      return myVar;
    }
 }

Then, from your client code:
class Foo {
    private MyFunctionWithState func = new MyFunctionWithState();
    public int bar() {
      return func.call();
    }
 }

Now if func relies on the internal state of Foo you can either pass the relevant data through call() or pass an instance of Foo and let the function call the appropriate getters:
class MyFunctionWithState {
    private int myVar = 0;
    public int call( Foo f ) {
      myVar += f.getBaz();
      return myVar;
    }
 }

class Foo {
    private MyFunctionWithState func = new MyFunctionWithState();
    public int bar() {
      return func.call( this );
    }
    public int getBaz() {  /*...*/  }
 }

Comment: Why does it have to be so complicated?  Does placing static int myVar in a member function conflict with some part of the java language or feature?  I do not agree that it's rare to want something of this type either.  Maybe I need some function to keep to the state of a variable and I don't want all other functions within the class to have access to that variable.  It's much better to have the variable closer to where it is used.  I guess I could place the variable right above the function, but that still allows causes confusion when other functions might be using the same variable name.
Comment: When I said " Does placing static int myVar in a member function conflict with some part of the java language or feature?", I meant "would it possible to add this language feature in a future java version?"
Answer: Local Variables are variables inside a method. Only method gets to access these variables. you cannot have a static local variable , but you can use instance variables or class variables.
If you have your method as static which by default creates a copy of this method to all the objects and cant be broken down any further as local variables limit their access only to the method in which they reside.
Answer:
Should I resort to using instance
  variables?

yes - after all, that is what instance variables are for. They store the state between invocations of the methods of the object. Having static class variables can sort of achieve the same result, but can make your program more coupled and harder to test/mock/maintain.
Answer: Disclaimer: Just because you can, doesn't mean you should
Although Java doesn't support static local variables, it's fairly easy to emulate in recent versions of Java. From Java 16 onwards, it is possible to create a local class with a mutable static field in a method. Subsequently, you mutate the local class's static field just like you would in C/C++.
public class Main {

    public void foo() {
        class Local {
            static int count = 0;
        }
        Local.count++;
    }

}

Before Java 16, local classes may only contain static constants.
Answer: In the following example count behaves like a static local variable, that you might use in C:
public class Foo {

   private int count = 0;

   public int getCount() {
       return count++;
   }
}

There are no static local variables like other languages support. Since java is very "class"-oriented, it tries to bring it to that context. If you want to simulate that behavior, you use an instance variable, which is only used by this method. So this is static for different method calls, not for the class itself.
Comment: Static for a single instance does not sound very static to me. The main point of static is A) global value in the class. Does no depend on the instance. B) Avoid creating a variable for every instance :)
Comment: @borjab: True, but since the OP wrote: `Now if I want to code a function with a local variable, whose value should persist between function calls, how do I do that?` ... it seemed right to respond with the obvious. Static depends somewhat on the context: For the function within this instance it would be `static` ... on the other hand regular `static` classes aren't very static amongst different instances of the program or even different devices ;-)
Answer: Either you marked an answer correct that wasn't, or you actually wanted static class variables - but the right answer is basically Levit's, or technically a mixture of all the answers.
For people from a C background like me, truly wanting static function-local variables purely for the scope advantage over globals, it seems the answer is you can't in Java.  Not without doing something like @paradigmatic is going for with an instance of a class with a static global and getter() unique to the instance of the class you are running your function in.
If, as I suspect, you're running the class as a Singleton, or completely statically like the inately procedural programmer we all started as, @Ellie P's or @user2626445's answer would work fine since no other instance is going to screw up your global.  But to achieve what I think it is you want it should actually be just an instance variable, which is a global in C.  They persist across function calls but allow your function to be used in an OO way, so multiple instances can keep their own persistent variables for this particular function.
Personally, I get around this in jave the same way I get around Hi-Tech C not allowing function bit variables, by declaring the global in the file just above the function declaration.  That way me when I hack the code later is less likely to think it's a global and be tempted to mess with it - isn't that why we encapsulate things?
Answer: final int intVar = 1; // Will be inited only once. Behaves as C++ static local var in the method.
Comment: This is a misleading answer, since the only reason `intVar` behaves like a C++ static local variable in this example is because it's assigned a constant.  e.g. in `void method(int arg) { final int intVar = arg; ... }`, `intVar` will not behave like a C++ static local variable.
Comment: you can't increment or decrement final variables


SQLite sendo acessado remotamente

Question: Seria possível de criar uma conexão do App no Android com o serviço do SQLite com PC Local? Não falo de um banco de dados dentro do próprio Android, mas sim comunicando-se com PC mesmo.
Comment: O que é um PC local?
Answer: Sim, é possível, mas não recomendável.
Qualquer acesso direto ao arquivo é problemático, o sistema operacional tem dificuldade de lidar com acessos remotos concorrentes diretos. Além disso não é tão simples cuidar da segurança ao acesso a esse arquivo e tem chance de acabar expondo o computador onde está o arquivo do SQLite.
Obviamente que estou considerando que o computador pode ser facilmente localizado na rede. Tem uma série de preocupações a serem observadas que dependeria de um estudo mais profundo do assunto. Não dá para seguir receita de bolo, e acho que nem tem uma, por bons motivos.
O que é mais recomendável é o acesso ser feito através de uma aplicação intermediária no computador onde está localizado o arquivo SQLite e essa aplicação é que faz o acesso ao DB.

Existe a possibilidade de criar uma aplicação própria para isso e usar um protocolo de comunicação próprio entre a aplicação servidora e o cliente no Android:
Só é recomendado para programadores experientes ou que tenha bom domínio da computação. Se não souber fazer tem vários pontos para dar errado.

Ou pode usar um servidor web padrão e criar apenas a aplicação que faz o acesso ao SQLite de forma simples e entregar para o servidor HTTP cuidar da comunicação com o Android:

há riscos de fazer errado, mas não é tão complicado;
tem receitas de bolo (para serem seguidas cegamente e a solução não ficar tão boa, a começar porque está sendo escolhida porque é fácil e não porque é a melhor);
e quase todo mundo pode ajudar porque isso é uma solução padrão adotada;
mas pode não ser a melhor performance se não precisa do acesso via HTTP.

Coloquei no GitHub para referência futura.
Comment: Aí você tem que fazer uma nova pergunta.
Comment: Como não reconheço serviço com SQLite gratuito tivesse essa ideia tola de fazer isso. Obrigado
Comment: Poderia ensinar a realizar a conexão do Android (Virtual) com o PostgreSQL na máquina local? Obrigado!
Comment: Link: http://pt.stackoverflow.com/questions/155435/android-como-conectar-android-virtual-com-postgresql-na-m%c3%a1quina-local

SQLite sendo acessado remotamente


json_encode function not return Braces {} when array is empty in php

Question: I have this code
$status = array(
                "message"=>"error",
                "club_id"=>$_club_id,
                "status"=>"1",
                "membership_info"=>array(),
                );

echo json_encode($status);
This function return json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}
But I need json like this:
{"message":"error","club_id":275,"status":"1","membership_info":{}}
Comment: @jogesh_pi The issue is that it generates inconsistent json (array when empty and object when not). Other parsers have issues with this: https://stackoverflow.com/questions/26725138/force-conversion-of-empty-json-array-to-dictionary-type
Comment: that is how json represents an array. [] stands for an array in Json
Comment: The first three comments here are not correct.
Comment: What is the problem with the current format?
Comment: This is the correct json format. Arrays are enclosed in Braces - "[ ]".
Answer: use the JSON_FORCE_OBJECT option of json_encode:
json_encode($status, JSON_FORCE_OBJECT);

Documentation

JSON_FORCE_OBJECT (integer)
  Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.

Or, if you want to preserve your "other" arrays inside your object, don't use the previous answer, just use this:
$status = array(
                "message"=>"error",
                "club_id"=>$_club_id,
                "status"=>"1",
                "membership_info"=> new stdClass()
                );

Comment: yeah the problem is that arrays like `["one"]` are then transformed into an object two, which is wrong.
Comment: Bottom line: DO NOT use JSON_FORCE_OBJECT (unless you want your normal arrays mangled/curly-bracified). And in your JSON tree you must validate each object node for being empty and manually cast it to object or replace with `new StdClass()` ...
Comment: The answer here answers the OP's question. You need to look at other answers to partially preserve arrays inside objects.
Answer: $status = array(
                "message"=>"error",
                "club_id"=>$_club_id,
                "status"=>"1",
                "membership_info"=>(object) array(),
                );

By casting the array into an object, json_encode will always use braces instead of brackets for the value (even when empty).
This is useful when can't use JSON_FORCE_OBJECT and when you can't (or don't want) to use an actual object for the value.
Answer: There's no difference in PHP between an array and an "object" (in the JSON sense of the word). If you want to force all arrays to be encoded as JSON objects, set the JSON_FORCE_OBJECT flag, available since PHP 5.3. See http://php.net/json_encode. Note that this will apply to all arrays.
Alternatively you could actually use objects in your PHP code instead of arrays:
$data = new stdClass;
$data->foo = 'bar';
...

Maybe it's simpler to handle the edge case of empty arrays client-side.
Answer: I know this is an old question, but it's among the first hits on Google, so I thought I should share an alternative solution.
Rather than using standard PHP arrays, in PHP 7+ you can instead use Map() as part of the Data Structure extension. Documentation.
A Map object has practically identical performance as arrays and also implements ArrayAccess so it can be accessed as a regular array. Contrary to a standard array, however, it will always be associative and works as expected with json_encode. It also has some other minor benefits like object keys and better memory handling.
Some example usage:
use Ds\Map;

$status = new Map([
            "message"=>"error",
            "club_id"=>$_club_id,
            "status"=>"1",
            "membership_info"=>array(),
          ]);

$map = new Map();
print json_encode($map); // {}

$map = new Map();
$map["foo"] = "bar";
print json_encode($map); // {"foo":"bar"}
print $map["foo"]; // bar

$map = new Map();
$map[1] = "foo";
$map[2] = "bar";
$map[3] = "baz";
print json_encode($map); // {"1":"foo","2":"bar","3":"baz"}

Comment: it's a good solution but worth noticing that Data Structures is not a built-in PHP extension.

It needs to be installed before use. The [installation instructions](https://www.php.net/manual/en/ds.installation.php) are available on php.net.
Answer: While this may not be considered elegant, a simple string replace can effectively address this.
str_replace("[]", "{}", json_encode($data));

This mitigates the issue of JSON_FORCE_OBJECT converting a normal array into an object.
Comment: This won't work if there's `[]` inside a string: `str_replace('[]', '{}', json_encode(['key' => '[]']))` --> `{"key":"{}"}`


Analytic subvariety in complex manifold

Question: I am trying to figure out a statement in a textbook
"If $M$ is any complex manifold of a projective space $\mathbb{P}^{n}$, $V\subseteq M$ an analytic subvariety of dimension $k$, then we can find a linear subspace $\mathbb{P}^{n-k}$ of $\mathbb{P}^{n}$ meeting $V$ in isolated points."
Why should this be true?
Thanks!
Answer: I don't know your background. $V$ will be algebraic (Chow's Theorem) of some degree $d$, and so the generic $\Bbb P^{n-k}$ will intersect $V$ transversely (Bertini's Theorem) in $d$ points. (You can deduce this by applying transversality theory to deduce that the generic $\Bbb P^{n-k}$ is transverse to all the smooth strata of $V$.)
Comment: I am just starting on the Principles of Algebraic Geometry by Philip Griffiths and it is only in the start of this book that he mentioned this result without any reference to Chow's Theorem or Bertini's theorem. Is there any other elementary proof of this result?
Comment: @enoughsaid05: Griffiths and Harris deal with this sort of question numerous times in Chapter 1. Where exactly are you?
Comment: I am in page 64 where it shows that the even Betti numbers of a complex submanifold of a projective space are positive.
Comment: This follows from their discussion on earlier pages — see pp. 49-61. The right background for this, which they more or less assume, is the basics of transversality theory. You might want to take a look at Guillemin and Pollack to get the intuition for this. The basic fact needed for your question is easier: If you vary the linear spaces $\Bbb P^{n-k}$ in $H_{2n-2k}(\Bbb P^n,\Bbb Z)$, the generic one is transverse to any given submanifold of $\Bbb P^n$.

Analytic subvariety in complex manifold


how to count items/boolean after if-statements (python)

Question: I have a csv where I need to count the total number for each category:
New_Cell[2]                            Category I need to count

1                                            [A01]
1                                            [A01]
0                                            [A01]
1                                            [A01]
0                                            [A02]
1                                            [A02]
1                                            [A02]
2                                            [A02]
1                                            [A02]

I need it to count each occurrence of TRUE for the if-condition so that it will look like:
[A01] : 3

instead of:
 1 1 1

I currently have:
A01 = "[A01] Officials"

data_out = open("mentees_all_attributes.csv", "rU")
reader = csv.reader(data_out)
next(reader,None)
for line in reader:
    cells = line
    new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[10] # name, # of participation, primary occupation/industry, secondary occupation/industry
    if int(new_cell[1]) > 0: #Isolate all the participants with more than 0
        primary = new_cell[2]
        if primary == A01:
            if True:
                counts =+ 1
                print counts
data_out.close()

Comment: I think you mean `counts += 1`. And the `if True` can be omitted, of course.
Comment: `counts =+ 1` means `counts = (+1)` which means `counts = 1`. Try `counts += 1`.
Answer: Initialize counts before the loop begins, increment it when your condition succeeds, and only print it after the loop ends.
counts = 0
for line in reader:
    cells = line
    new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[10] # name, # of participation, primary occupation/industry, secondary occupation/industry
    if int(new_cell[1]) > 0: #Isolate all the participants with more than 0
        primary = new_cell[2]
        if primary == A01:
            counts += 1
print counts

Note that counts =+ 1 and counts += 1 do very different things. The first means "assign positive one to counts" and the second one means "increment count's value by one"
Comment: It outputs 1 2 3 instead, can I sum it up so it can just output 3 or able to print as A01: 3 ?
Comment: Did you put the `print` outside the loop? If you have exactly one print statement and it's at the global scope not inside any loops, then exactly one object should be printed.
Comment: Thank you that's it. I just have one more question, if I have to count multiple categories, do I have to have multiple count global variables?
Comment: In that case I'd recommend using a single [collections.Counter](https://docs.python.org/2/library/collections.html#collections.Counter), which is designed exactly for the purpose of counting multiple things.
Answer: To add on to Kevin's answer, you can also use a dictionary to increment the counts for multiple categories.
categories = {}
counts = 0
for line in reader:
    cells = line
    new_cell = cells[0], cells[6], cells[7], cells[8], cells[9], cells[10]
    if int(new_cell[1]):
        primary = new_cell[2]
        if primary:
            if primary not in categories.keys():
                categories[primary] = 0
            categories[primary] += 1

for k,v in categories.items():
    print k, v


How do we find weight and b value of SVM classifier for XNOR operation by hand?

Question: Problem statement

Show that the Boolean function (x1 ∧ x2) ∨ (¬x1 ∧ ¬x2) is not linearly separable (i.e. there is no linear classifier sign(w1 x1 + w2 x2 + b) that classifies all 4 possible input points correctly). Assume that "true" is represented by 1 and "false" is represented by −1. Show that there is a linear separator for this Boolean function when we use the kernel K(x, y) = (x · y)2 (x.y denotes the ordinary inner product) . Give the weights and the value of b for one such separator

I was trying to solve the above problem in SVM by hand. The input dataset is XNOR truth table (here -1 is used as false value)

x1
x2
x1 XNOR x2

-1
-1
1

-1
1
-1

1
-1
-1

1
1
1

It was given to prove that this can not be classified using any linear classifier. Which I already did. Now the second part of the problem is to use the kernel function
$K(X,Y) = (X.Y)^{2}$
and prove that there is linear separator for this data when this kernel function is applied.
I proved it following way:
Applying transformation using that kernel, I could see
$\phi(X) = [x_1^{2}  ,\sqrt{2}x_1x_2,x_2^{2}]$
And I transformed entire dataset to this
$$\begin{bmatrix}
&1&\sqrt{2}&1\\
&1&-\sqrt{2}&1\\
&1&-\sqrt{2}&1\\
&1&\sqrt{2}&1\\
\end{bmatrix}
$$
Which can be easily separable.
But the problem wants me to find the weight and value of b variable.
This is so far I have done, but I'm really stuck thinking around
I know
$\alpha_i(y_i(W.X+b)-1)=0 $
and for non support vectors $\alpha_i$ is zero
But how can I know which data points are support vectors? I know these are points lying closer to "gutter" or hyperplane. But how can I know it mathematically? as this can't separated using a linear classifier and therefore I can't know which points lies closer to the imaginative plane. Also how will I find $\alpha_i$ for these support vectors? Don't I need weight and b value for it? But I want to find $\alpha_i$ first inorder to find weight and b value.
This question probably is a naïve one, which came up due to not having deeper understanding of SVM. But I would appreciate giving me some pointers to correct my thinking and guide me to solve this problem.
Edit: added my original problem statement, in case my explanation wasn't that clear.
Answer: Separable case
If you want to get the weights for the separable case, look at the transformed dataset:
\begin{bmatrix}
&1&\sqrt{2}&1\\
&1&-\sqrt{2}&1\\
&1&-\sqrt{2}&1\\
&1&\sqrt{2}&1\\
\end{bmatrix}
and your y values are basically $[1, -1, -1, 1]$.
You have to apply the SVM method in the transformed space, i.e., your equation would be: $$\alpha_i(y_i(W.\phi(x_i)+b)-1)=0.$$
Notice that if you take the second coordinate of the $\phi(x_i),$ you can have a direct relationship with the y values. So take W to be $(0, 1, 0)$ which picks the second coordinate. Now your $W.\phi(x_i)$ values are $\sqrt{2}\ [1,-1,-1,1].$
If you if you scale the $W$ to be $(0, 1/\sqrt{2}, 0).$ and look carefully, the $y_i * (W.\phi(x_i))$ values are all $1.$
Hence, $b=0$ and any real values of $\alpha_i>0$ would work in this case.
Non-Separable case
Now you are in two-dimensional space, and your quadrant 1 and 3 basically have 1's, and the rest have -1's. First, take any line visually and check that it can not divide them. If the first and the fourth points are on the same side, at least one other point would be in the same side too.
Mathematically, why?
Take any line in the form $f(x_1,x_2)=x_2 - m x_1 - c = 0.$ Now if a point $(x,y)$ satisfies $f(x,y)>0,$ it will lie on one side, and if the value is $<0,$ it will lie on the other side. The values of $f$ for your four points are, respectively: $-1+m-c, 1+m-c, -1-m-c, 1-m-c.$
If $-1+m-c<0,$ and $1-m-c<0,$ both happen (i.e., first and fourth points are on the same side), then $1-c<m<c+1.$ If $c>0,$ the point $(1,-1)$ will be less than 0 too, i.e., that is on the same side of $(1,1) (-1,-1).$ If $c<0,$ the other point will be on the same side of them. Similarly, you can show that if $-1+m-c>0,$ and $1-m-c>0,$ both happen, one of the other points will be on the same side.
Also, note that the y-axis can not separate them.
You can translate this whole argument in the form of hyperplanes too.
Comment: Hey thanks for answering. One doubt regarding the answer, are we taking all the points as support vectors here? If so how can we know all of them are support vectors?
Comment: You can check that the distance of hyperplanes and all the points are the same. Hence all four can be treated as support vectors. Or you can take two from each side as support vectors. (I'm not sure about the usual convention here.)
Now suppose you have another additional point (2, 2). That would not be a support vector here.


Log4j RollingFileAppender every minute

Question: I'm testing Log4j RollingFileAppender with log4j 2.6.2.
I want to rotate the logs every minute and so I have a log4j2.xml very similar to one example of here https://logging.apache.org/log4j/2.x/manual/appenders.html#RollingFileAppender.
This is my log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="testlog4j2" packages="">
  <Properties>
    <Property name="baseDir">C:/tmp/testlog4</Property>
  </Properties>
  <Appenders>
    <RollingFile name="RollingFile" fileName="${baseDir}/app.log"
          filePattern="${baseDir}/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH-mm}.log.gz">
      <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
      <CronTriggeringPolicy schedule="0 0/1 * * * ?"/>
      <DefaultRolloverStrategy>
        <Delete basePath="${baseDir}" maxDepth="2">
          <IfFileName glob="*/app-*.log.gz" />
          <IfLastModified age="60d" />
        </Delete>
      </DefaultRolloverStrategy>
    </RollingFile>
  </Appenders>
  <Loggers>
    <Root level="ALL">
      <AppenderRef ref="RollingFile"/>
    </Root>
  </Loggers>
</Configuration>

And this is an app where I write a log every second.
package testlog4j2;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class TestLog4j {

    private final static Logger logger = LogManager.getLogger(TestLog4j.class);

    public static void main(String[] args) {
        try {
            for (int i=1; i<=240; i++) {
                logger.info("Hello");
                Thread.sleep(1*1000);
            }
        } catch (Exception e) {
            //e.printStackTrace();
            logger.error("Excepcion general", e);
        }
    }
}

What happens is:

once the system rotates the log at the first minute appears continuously errors like this
2016-07-28 15:10:02,015 Log4j2-Log4j2Scheduled-1 ERROR Unable to move file C:\tmp\testlog4\2016-07\app-2016-07-28-15-10.log.gz to C:\tmp\testlog4\2016-07\app-2016-07-28-15-10.log.gz: java.nio.file.NoSuchFileException C:\tmp\testlog4\2016-07\app-2016-07-28-15-10.log.gz -> C:\tmp\testlog4\2016-07\app-2016-07-28-15-10.log.gz
There isn't a gz for every minute
The result gz don't have a log with 60 lines. Instead they have 1, 2 or three lines of log.
The main log C:\tmp\testlog4\app.log has no content

What I'm I doing wrong?
Thanks
Answer: You may have found a bug. Please raise a bug report on the Jira issue tracker with all the details you describe here.
Answer: By now It seems to work with TimeBasedTriggeringPolicy instead of CronTriggeringPolicy.
My conf looks now like this
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="testlog4j2" packages="">
  <Properties>
    <Property name="baseDir">C:/tmp/testlog4</Property>
  </Properties>
  <Appenders>
    <RollingFile name="RollingFile" fileName="${baseDir}/app.log"
          filePattern="${baseDir}/app-%d{yyyy-MM-dd-HH-mm}.log">
      <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />

      <TimeBasedTriggeringPolicy interval="1"/>
      <DefaultRolloverStrategy>
        <Delete basePath="${baseDir}" maxDepth="0">
          <IfFileName glob="*/app-*.log" />
          <IfLastModified age="2M" />
        </Delete>
      </DefaultRolloverStrategy>
    </RollingFile>
  </Appenders>
  <Loggers>
    <Root level="ALL">
      <AppenderRef ref="RollingFile"/>
    </Root>
  </Loggers>
</Configuration>

The delete is not working by now but that's another story I will investigate next.
Best regards
Comment: The delete works now with this

Log4j RollingFileAppender every minute


How to stop all scripts from loading for IE 9 and less users

Question: I added a this code to the header to redirect IE user using IE 10 or less

The problem is that my page is loading some scripts causing internet explorer to crash, my question is, is there any way to stop all the scripts from loading for those users and automatically redirect them to the update you browser page?
Thanks in advance for any help!
Comment: possible duplicate of [How to target IE9 with new HTML5 Boilerplate?](http://stackoverflow.com/questions/9233468/how-to-target-ie9-with-new-html5-boilerplate)
Comment: try linking to different stylesheets - such as  instead of putting it in the html
Comment: Try fixing your scripts. Not everyone can update their browser, and it is unlikely that someone will be so deperate to visit your page that they will upgrade, even if they can.
Answer: That will cover the effect you want by redirecting them before the scripts run, but I'm with RobG on the fact that those scripts should be prioritized and fixed. This should be put ahead of any of the scripts you load in the page so that the redirect is prioritized.


Show full query for anonymous user

Question: I'm currently troubleshooting an issue where anonymous users and certain roles see a different set of results from a view than administrators and roles with more permissions do. The view is supposed to have two node results, but for anonymous and others, there is only one.
I am trying to get the full SQL of the final query that's creating the anonymous pages. I'm using hook_views_query_alter(), and I can get the full query using dpq($view->query->query()); when I'm logged in as an administrator.
However, when I'm an anonymous user, or one of the other roles encountering the bug, I get SQL like this: ((taxonomy_index.status = :db_condition_placeholder_7) AND (node_field_data.type IN (:db_condition_placeholder_8))).
I tried getting the placeholder values from a technique I used in drupal 7, using the arguments() method, but apparently that doesn't exist in Drupal 8.
But moreover, I would like to avoid matching up the string db_condition_placeholder manually, because I could make a mistake, and misdiagnose what the source of the problem is. I want the full query string that drupal sends to the database, so that I can debug it directly with the MySQL server.
I tried other techniques listed here, such as ->addTag('debug'), which apparently did nothing, and kint($view->query->query());, which only returns output for administrator users.
How can I get the full query string from a view executed for anonymous users?
Comment: Maybe try turning off SQL Rewriting? I dislike that it's the default as I usually am using views to get around access restrictions anyway. You can still place  query based filtering to do _simple_ access anyway.
Comment: If `kint($view->query->query())` works, then take `$view->query->query()` and simply try to `echo` it (maybe with one of the methods listed in the output `kint($view->query->query())` gave you).
Comment: To display the query using kint($view->query->query()), go to the permission page for devel and enable kint for anon users.
Comment: @mradcliffe Disabling SQL rewriting worked. Could you please post that as an answer? I'd like to accept it : )
Comment: Sure, I didn't think it was exactly an answer to the specific question, but it probably makes sense to add it, @user1359. Thank you.
Answer: Note: This does not answer the question of "trying to get the full SQL of the final query that's creating the anonymous pages", but answers the underlying issue.
tl;dr Checking the Advanced Settings > Query > Disable SQL Rewriting option will allow views to return consistent results.
Explanation
The views module (contrib and core) configures views with restrictive entity access enabled by default. This sends the query object through hook_db_rewrite_sql (6), hook_query_TAG_alter (7, 8). Nodes for instance will add in joins to the node_access table, which can be prohibitively expensive on queries.
This is important for sites that use complex entity access where one node may be hidden from view based on node grants/access rights.
However query results will be different when querying entities (such as nodes) depending on if you are logged in. This can be frustrating when building a view as a site builder - what you see is not what you get.
It may not necessary to use SQL rewriting because a view has other access restrictions. Checking the Advanced Settings > Query > Disable SQL Rewriting option will allow views to return consistent results.
This is usually the first thing I do when creating a view unless I specifically need the extra access checks because

It improves performance significantly.
I create selective and filtered views that naturally restrict data using filters, contextual filters and view access restrictions.

Update 2019.06
Note that the views module changed the label for this setting from "Disable SQL Rewriting" to "Disable Access Checks".
Comment: The option `Disable SQL Rewriting` is unchecked by default. Did you mean to word that `Checking the Advanced Settings > Query > Disable SQL Rewriting option`?
Comment: Yes, thank you, @prkos.

Show full query for anonymous user


getAttribute('href') always returning '#' regardless of actual href attribute on mobile browsers

Question: I have an anchor element
Markers

and its event listener
$('a').on('click', function(e){
    alert($(e.target).attr('href'));
    alert(e.target.getAttribute('href'));
    e.preventDefault();
});

both return ./LayerFilter.html on the desktop, but # on the android browsers (tried 2.3 and 3.x)
if I add data-href='./LayerFilter.html' to the anchor element and use $(e.target).attr('data-href'), Android suddenly gets the correct value.
What's the deal with this?
Is there a way to not have to add a new attribute to anchor and just use the href?
Comment: How about e.target.href? In theory, it should always give the full URI.
Answer: Apparently this was due to jquery mobile "enhancing" the page
I was on 1.1.0, upgrading to 1.1.1 solved the problem.


Notes between chords

Question: I am just a beginner playing the piano and been studying the scales, progressions, triads. Just the basic theory. So when i play a song i can play the chords but i don't know how to find notes to play between them so that the melody doesn't sound like a hammer with different sounds.
Can you point me in the proper direction about what should i study for this?
thank you very much to read this newbie question
Comment: Can you explain the problem a bit more, maybe an example of what you mean by the hammer thing? Are you making up your own melodies or playing existing song melodies? Is this accompaniment for a singer, or solo piano or what?
Answer: This seems to be a question about chord-scale theory. This theory states that each chord has a scale that it belongs to. If the song is relevively simple, all of the chords will belong to the same key, mealing that if you play any notes from that scale, the melody will sound "good".
Looking deeper, if we assign each note in a scale a number or degree we can learn more about chord progressions. For example, the scale degrees of C major would be:
C  D  E  F  G  A  B  C.
1  2  3  4  5  6  7  8  1
 Each chord from a chord progression is build off of a scale degree.
For example, for a song in the key of C major, a C major triad would be made from the 1st, 3rd, and 5rd degrees of the C major scale: C, E, G. If, in the same song, the progression calls for the IV chord, or F major, the chord will be build from the 4th scale degree(4th, 6th, 1st) - F, A, C. Through the whole chord progression, any notes from C major will suit.
Hope this helps
Answer: A song is in a certain key.  There is a scale of that key.  If the key is C major, the scale is C, D, E, F, G, A, B, C.    We can form chords from those notes.  The most common ones are triads - the ones fingered 1, 3, 5.
That's C major - C, E, G.
D minor - D, F, A.
E minor - E, G, B etc.
For 'in-between' notes stick to the notes of the basic scale.
But be warned.  Those 'rules' might help you to string together notes that don't sound WRONG.  But you'll find an awful lot of songs that go beyond that basic framework.  Just about all of them in fact!
For a start, as 'rules' they tell you the blues is wrong.  Chromatic chords are wrong.  (Songs in C major frequently use C7, F7, F minor, B♭ major chords and many more, without ever departing from a C major framework.)
So don't treat them as rules.  Just as a description of the most basic framework of a musical key.
PLEASE don't try to work outward from 'theory'.  Look at real music and ask 'what's happening here?'   If it breaks a 'rule' - well, we're not in black-and-white any more.  We've left Kansas, the 'Summer Holiday' bus is on the road.  Glorious Technicolor! And  remember the vast majority of movies ARE in colour. Film students might sometimes choose to work in monochrome as an exercise, but they aren't expected to do so for years before graduating to colour.  (Actually, this analogy is going a bit wrong, maybe they should...)
Answer: If you're talking about left hand notes in between playing the chords, there are a couple of things you can try:
1) Arpeggiate the chords as you play them--play the notes of the chords in various order in a faster rhythm than the melody rather than playing them all at once.
2) As long as you stay in the same key, going up or down the scale stepwise from one chord tone to the next can also work to fill in. For example, instead of just playing the chord tones above, you could play C/D/E/G successively or C/E/F/G successively and it would still sound fine.

Notes between chords


Criar um programa em C que leia um numero inteiro e determine a soma dos seus divisores

Question: Estou aprendendo C e estou com díficuldade em resolver esse exercício de estudo sobre ponteiros. É pedido para que o programa seja respondido em 2 funções (uma com a matemática e a outra com os printfs), justamente para fazer o uso dos ponteiros.
O código que eu tentei desenvolver, porém não consigo entender o porquê funcionou é esse:
#include <stdio.h>

///Construa um programa emC que leia umnúmero inteiro não
///negativo e determine a soma dos seus divisores. A soma dever ser
///efetuada através de uma função somadiv e o resultado impresso no
///programa principal. O protótipo da função é:void somadiv(int x, int *y);
void somadiv(int *numero, int *soma)
{
    int divisor;

    for(divisor=1; divisor<0; divisor++)
    {
        if ((*numero)%divisor == 0) /// a divisão nn tem resto.
        {
            *soma = *soma + divisor;
            printf("\n\t valores do if: %i\n",*numero);
            printf("\n \t\tTeste com o soma:%i\n", soma);
        }
    }

}

int main()
{
    int numero;
    int numconta;
    int soma;

    printf("Digite um numero: ");
    scanf("%i",&numero);

    numconta = numero;
    somadiv(&numero, soma);

    printf("\nO valor escrito e: %i\n",numconta);
    printf("\n A soma dos valores e: %i\n",numero);
}

Desde já eu agradeço pela ajuda.
Comment: Fala Canarin, bem vindo ao site. Do jeito que está, achei difícil entender qual a sua dúvida exatamente. Você disse que quer "entender o porquê funcionou", mas pelo que entendi, esse código não está funcionando. Foi um erro de digitação? Seria legal também explicar exatamente qual é a dúvida, de forma mais específica. Só perguntando porque funciona ou não fica difícil saber qual parte explicar. Olhando o código, algumas partes não parecem fazer muito sentido também. Se puder editar sua pergunta pra adicionar esses pontos, ajudaria bastante a obter uma resposta.
Comment: `for(divisor=1; divisor<0; divisor++)` esse comando nunca vai ser executado, se divisor começa em "1" e a condição é "menor que zero (<0)" então nunca vai entrar ai, comece olhando isso
Comment: A função que declarou não é a que descreveu no comentário e está invertendo onde é um ponteiro e onde é um endereço. Se acostume a mostrar esses valores na tela enquanto está testando seu programa. Vai ter surpresas.
Comment: E você mesmo escreveu que o resultado deveria ser impresso no programa principal. Mas deixou 2 `printf()` na função...
Answer:
O código que eu tentei desenvolver, porém não consigo entender o porquê funcionou

Também não entendo como possa ter funcionado. Do modo como escreveu deve simplesmente retornar sem fazer nada.
    int divisor;

    for(divisor=1; divisor<0; divisor++)

conforme dito nos comentários não vai entrar nesse loop nunca e na falta de um return explícito vai retornar porque chega ao fim do código da função.
De seu código:
//programa principal. O protótipo da função é:void somadiv(int x, int *y);
void somadiv(int *numero, int *soma)

Você acabou de dizer no comentário que o primeiro parâmetro é um int mas declara ao invés disso um int*. Está errado o comentário ou a declaração?
A função como escrita
void somadiv(int *numero, int *soma)
{
    int divisor;   for(divisor=1; divisor<0; divisor++)
    {
        if ((*numero)%divisor == 0) /// a divisão nn tem resto.
        {
            *soma = *soma + divisor;
            printf("\n\t valores do if: %i\n",*numero);
            printf("\n \t\tTeste com o soma:%i\n", soma);
        }
    }

}

ao entrar no loop e usando % para encontrar um divisor pode não ser a melhor opção: Se b divide x então existe a de modo de x = a * b, e assim você encontra os divisores aos pares, certo? Então usar módulo é um provável desperdício. E claro que à medida em que aumenta um fator o outro diminui, de modo que não deve ir além da raiz quadrada do número.
Por outro lado todo número é divisível por 1 e por ele mesmo.
 printf("\n \t\tTeste com o soma:%i\n", soma);

Esse printf() está errado. soma é int* e deve escrever *soma
    scanf("%i",&numero);

    numconta = numero;
    somadiv(&numero, soma);

Isso também está errado: deve passar numero para a função, o valor lido, e não o endereço dele. E o endereço de soma, porque é onde vai retornar o valor somado pela função. Devia usar
    scanf("%i",&numero);
    numconta = numero;
    somadiv(numero, &soma);

E teste sempre o retorno de scanf(): não há sentido em chamar a função se não ler nada.
Considere esse exemplo:
void somadiv(int numero, int* soma)
{  // se ab = x a e b sao divisores de x
    // todo numero e divisivel por 1 e por si mesmo
    *soma = 1; // sempre
    if (numero < 2) return;
    *soma += numero;  // o minimo se > 1
    if (numero == 2) return;
    for (int a = 2;; a += 1)
    {
        int b = numero / a;
        if (b * a == numero)
        {
            if (a == b)
            {
                *soma += a; // nao pode ter outros
                return; // depois desse
            }
            *soma += a + b;
        }
        if ((a * a) >= numero) return; // fim da linha
    }
    return;
}

Trata os casos especiais: 0 1 e 2... E daí pra diante encontra os divisores aos pares e para na hora certa.
um programa de teste
int main(void)
{
    int teste[] = {0, 1, 2, 3, 4, 17, 32, 25, 9, 8, 1024};
    int N       = sizeof(teste) / sizeof(teste[0]);
    for (int i = 0, soma = 0; i < N; i += 1)
    {
        somadiv(teste[i], &soma);
        printf(
            "A soma dos divisores de %d: %d\n\n", teste[i],
            soma);
    }
    return 0;
}

Esse programa simplesmente chama a função para os valores na tabela teste. Eis a saída
A soma dos divisores de 0: 1

A soma dos divisores de 1: 1

A soma dos divisores de 2: 3

A soma dos divisores de 3: 4

A soma dos divisores de 4: 7

A soma dos divisores de 17: 18

A soma dos divisores de 32: 63

A soma dos divisores de 25: 31

A soma dos divisores de 9: 13

A soma dos divisores de 8: 15

A soma dos divisores de 1024: 2047

uma versão mais verbosa
Com uns printf() de teste fica mais clara a lógica:
void somadiv(int numero, int* soma)
{  // se ab = x a e b sao divisores de x
    // todo numero e divisivel por 1 e por si mesmo
    printf(
        "\nsomadiv(%d)\n    %d e %d\n", numero, 1, numero);
    *soma = 1;
    if (numero < 2) return;
    *soma += numero;  // o minimo se > 1
    if (numero == 2) return;
    for (int a = 2;; a += 1)
    {
        int b = numero / a;
        if (b * a == numero)
        {
            if (a == b)
            {
                *soma += a;
                printf("    divisor: %d\n", b);
                return;
            }
            *soma += a + b;
            printf("    divisores: %d e %d\n", a, b);
        }
        if ((a * a) >= numero) return;
    }
    return;
}

A saída para essa versão

somadiv(0)
    1 e 0
A soma dos divisores de 0: 1

somadiv(1)
    1 e 1
A soma dos divisores de 1: 1

somadiv(2)
    1 e 2
A soma dos divisores de 2: 3

somadiv(3)
    1 e 3
A soma dos divisores de 3: 4

somadiv(4)
    1 e 4
    divisor: 2
A soma dos divisores de 4: 7

somadiv(17)
    1 e 17
A soma dos divisores de 17: 18

somadiv(32)
    1 e 32
    divisores: 2 e 16
    divisores: 4 e 8
A soma dos divisores de 32: 63

somadiv(25)
    1 e 25
    divisor: 5
A soma dos divisores de 25: 31

somadiv(9)
    1 e 9
    divisor: 3
A soma dos divisores de 9: 13

somadiv(8)
    1 e 8
    divisores: 2 e 4
A soma dos divisores de 8: 15

somadiv(1024)
    1 e 1024
    divisores: 2 e 512
    divisores: 4 e 256
    divisores: 8 e 128
    divisores: 16 e 64
    divisor: 32
A soma dos divisores de 1024: 2047

Comment: :) E dessa vez levou mais de 1 hora para uma resposta minha ser marcada como inútil! Mas é bom pra eu lembrar que preciso melhorar!


How do I redirect a specific page on my drupal site to an external site?

Question: I have a shop on my drupal website which we have replaced with an updated squarespace page.  I need the drupal page to automatically redirect to the new shop and I can only find a help page from circa '07 which says redirects are in the works...
Thanks
Comment: Which version of Drupal you are using?
Comment: You could do it at the server level or use hook_init(), check the URL and use drupal_goto(). Doing it with nginx or Apache would be best in terms of performance.
Answer: You can use drupal_goto("external-path");
Answer: There are different ways to redirect automatically,
1) Web Server, Apache or nginx: in Apache, you can write rewrite rules() this link will help in .htaccess file which you can place in your document root. In nginx you can follow this link
2) Drupal hooks: hook_init or hook_boot, check the page URL using drupal_get_path_alias(current_path()) and use drupal_goto
3) javascript or jquery -> Add js to the respective page which you needs to redirect
Using Jquery: $(location).attr('href',url);
Using javascript: window.location.href="url";


After calling drupal_flush_all_caches, menu items with access callback TRUE are giving access denied error

Question: I was building a custom module that affected the front page and I found myself having to go clear the caches for it to take effect. So as part of the code, I put in drupal_flush_all_caches().
After I ran the page, my website had all sorts of issues. It seems like any menu item with 'access callback' => TRUE, is getting access denied errors for any user. These items were working fine before the cache clearing.
Current versions (yes I know I need to upgrade)
Drupal: 6.38
PHP version: 5.6.38
Server: Red Hat Enterprise Linux Server 7.5 x86_64

PHP ini values:
session.cookie_httponly Off
session.use_only_cookies    On
session.cookie_secure   Off
session.hash_function   0
session.cookie_domain   .example.com

Things I have done:

Checked users table for uid of 0 - exists with status of 1, has role of anonymous user, has permission of access content
Repaired database tables
Clear browser cache
Clear drupal cache (/devel/cache/clear)
Rebuild menu (/devel/menu/reset)
Clear db sessions table

Please let me know if you need additional information. Thank you.
Comment: Are you using Apache? if yes, Is `a2enmod rewrite` enabled?
Answer: The answer lies in some custom code I wrote to understand why some unrelated things were issuing an error. I discovered it was this when I was copying the code to my test site and then putting in this new code which resulted in the same issue on the test site. So that is how I was able to narrow it down. Going forward, I am going to have 3 sites, one for new development, one that mirrors the live site, and the actual live site. The issue comes from being in the middle of upgrading modules on the test site and so I couldn't really use it reliably to test new code, so I would code it on the live site (a big NO-NO and I really shouldn't have done this). The only reason I didn't my custom code was an issue was because I hadn't cleared the cache in a while, so the menu items were still available.
Maybe this will help someone in there processes to not be dumb like I was.


dimension of intersection of subspaces, one of which of dimension $n-1$

Question: Let $H$ be a linear subspace of dimension $n-1$ of a linear space $V$ of dimension $n$.
Let $W$ be some subspace of $V$.
Show one of the following holds:

$W \subseteq H$ or
$\dim(W \cap H) = \dim(W) - 1$

This makes a lot of sense to me, as if there is some element in w that isn't in a largest subspace of V, then one of its dimensions can't be spanned by any of the vectors in the basis of $H$, thus its dimension is at most $\dim(W) - 1$.
It is intuitive, but I can't come up with a proof...
please help
Answer: Hint: use the Grassman formula for dimension of $H + W$
$$\dim (H+W)+\dim (H\cap W)=\dim (W) + \dim (H)$$
If $W \subset H$ then $H + W=H$, otherwise it is all the ambient space $V$.
Edit: suppose $H+W=V$, then $\dim (H+W)=n$ and by Grassman formula:
$$n + \dim (H\cap W)=\dim (W) + \dim (H)=\dim (W) + n-1$$
Comment: sorry, I don't see how $H+W$ helps me here... could you explain please?
Comment: Is it more clear, now?


Evaluating $\iint_R\big(x^2+y^2\big)\,dA$

Question:
Evaluate the following double integral:
  $$\iint_R\big(x^2+y^2\big)\,dA,$$
  where $R$ is the region given by plane $x^2+y^2\leq a^2$.

My attempts:
\begin{align}
\iint_{R}\big(x^2+y^2\big)\,dA
&=\int_{-a}^{a}\int_{-\sqrt{a^2-x^2}}^{\sqrt{a^2-x^2}}\big(x^2+y^2\big)\,dy\,dx\\
&=\int_{-a}^{a}\left(x^2y+\dfrac{y^3}{3}\right)_{-\sqrt{a^2-x^2}}^{\sqrt{a^2-x^2}}\,dx\\
&=\dfrac{2}{3}\int_{-a}^{a}\sqrt{a^2-x^2}\cdot\left(2x^2+a^2\right)dx.
\end{align}
I can't go further from here, please help.
Comment: Try converting to polar coordinates.
Comment: @BobaFret yah, but I was interested in calculating $\dfrac{2}{3}\int_{-a}^{a}\sqrt{a^2-x^2}\cdot(2x^2+a^2)dx$
Comment: @mnulb I guess the same idea correct there.
Comment: A shortcut to keep in mind for multivariable calculus that is extremely useful here: $\int_a^b \sin^2 t dt = \int_a^b \cos^2 t dt = \frac{b-a}{2}$ if $b$ and $a$ are integer multiples of $\frac{\pi}{2}$
Answer: As has been hinted, polar coordinates are the way to go. But if you really need to continue, the first thing I would note is that your integrand is an even function of $x$ over a symmetric integral. Therefore, you can simplify a tad to
$$\dfrac{4}{3}\int_{0}^{a}\sqrt{a^2-x^2}\cdot\left(2x^2+a^2\right)dx. $$
Now, whenever I see something like $\sqrt{a^2-x^2},$ I think trig substitution. In this case, you draw a triangle with $a$ as the hypotenuse, and one of the other sides as $x$. The third side will be $\sqrt{a^2-x^2}.$ I'll just put $\theta$ as the angle opposite $x,$ so that we have the following:
\begin{align*}
\frac{x}{a}&=\sin(\theta)\\
x&=a\sin(\theta)\\
dx&=a\cos(\theta)\,d\theta\\
\frac{\sqrt{a^2-x^2}}{a}&=\cos(\theta).
\end{align*}
For $x$ going from $0$ to $a,$ we can write that $0\le\theta\le\pi/2.$ Our integral becomes
\begin{align*}
\dfrac{4}{3}\int_{0}^{a}\sqrt{a^2-x^2}\cdot\left(2x^2+a^2\right)dx
&=\dfrac{4}{3}\int_{0}^{\pi/2}a\cos(\theta)\cdot\left(2a^2\sin^2(\theta)+a^2\right)a\cos(\theta)\,d\theta\\
&=\frac{4a^4}{3}\int_0^{\pi/2}\cos^2(\theta)\left(2\sin^2(\theta)+1\right)d\theta.
\end{align*}
This integral breaks up into two pieces, each of which succumbs to the usual methods for integrating products of $\sin(\theta)$ and $\cos(\theta).$ Can you take it from here? The result should be
$$\frac{4a^4}{3}\cdot\frac{3\pi}{8}=\frac{\pi a^4}{2}.$$
Check with polar version:
\begin{align*}
\iint_R\big(x^2+y^2\big)\,dA
&=\int_0^{2\pi}\int_0^a r^2\cdot r\,dr\,d\theta\\
&=2\pi\,\frac{r^4}{4}\bigg|_0^a\\
&=\frac{\pi a^4}{2},
\end{align*}
as required.
Answer: Hint: Try $x=a\sin(t)$, but really polar coordinates would be the move here.
Answer: Whenever you have $\sqrt{a^2-x^2}$ in an integral, use the substitution $x=a \sin(\theta )$.
For information :
In case of having  $\sqrt{x^2-a^2}$  use the substitution $x=a \sec(\theta )$.
In case of having  $\sqrt{x^2+a^2}$  use the substitution $x=a \tan(\theta )$
Answer: $$\iint_R x^2+y^2 dA=\int_0^{2\pi}\int_0^a r^3drd\theta=2\pi\int_0^a r^3 dr$$


Can we load core css files from custom theme with yml lib?

Question: Is there a way to provide f.e normalize.css within my custom template using a *.libraries.yml config file? Tried the following, didnt work out.
I was just wondering if this would be possbile, for it seems to be nice, while the file comes with drupal8 installation.
global-styling:
  css:
    theme:
      css/style.css: {}
    core:
      normalize-css/normalize.css: {}
  js:
    dependencies:
      - core/modernizr

Answer: The first attempt to load the single file normalize.css is not correct. If you want to do it this way, you have to use the full path to this file.
But this is not the preferred way to do this. You don't know if in future the position of this file will change. Better use the library already defined in core, as you have done in the second attempt to load modernizr. This will work, if you put the key dependencies on the first level of the array, for example see the core library date:
drupal.date:
  version: VERSION
  js:
    misc/date.js: {}
  dependencies:
    - core/drupal
    - core/modernizr
    - core/jquery.once
    - core/jquery.ui.datepicker

If you look for normalize.css, this is defined in core:
normalize:
  remote: https://github.com/necolas/normalize.css
  version: "3.0.3"
  license:
    name: MIT
    url: https://github.com/necolas/normalize.css/blob/master/LICENSE.md
    gpl-compatible: true
  css:
    base:
      assets/vendor/normalize-css/normalize.css: { weight: -20 }

And you can use it as dependency in *.libraries.yml:
  dependencies:
    - core/normalize

Or as library in the theme.info.yml file:
libraries:
  - core/normalize

If you use a core library, you don't have to put it in your own library, you can choose the direct way to use it.
Comment: Thanks for the hint.Especially for the core.libraries file which is in drupal core folder!


Derivation of fourier series equation

Question: No matter where I search, every time if there's an article about Fourier series derivation, the first step made by author is to present the following formula:
$$f(x) = \frac{a_0}{2}+\sum_{n=1}^\infty \left(a_n \cos(\frac{2\pi}{T}nx) + b_n \sin(\frac{2\pi}{T}nx)\right)$$
Then, given that formula, the coefficients $a_n$ and $b_n$ are derived. My question is, how did Fourier come up with this main equation? Was it just a lucky guess? It could have been, because there are various proofs showing that the formula is true.
Here the main equation just appears there without justification, just like formulas for even and odd cases below. It's really hard to call the article a derivation in my opinion.
Comment: This follows from general Hilbert space theory, see for example https://www.math.ucdavis.edu/~hunter/book/ch6.pdf Theorem 6.26 (just a random google hit). The equation is an application of that theorem with the Hilbert Space being $L^{2}(\mathbb{T})$ and the functions $ \{\sin(nx): n \in \mathbb{N}\} \cup \{\cos(nx): n \in \mathbb{N}\}$ being the orthogonal basis. Note that the convergence is generally not pointwise, but meant in terms of the norm of the respective Hilbert Space.
Comment: This answer may help: http://math.stackexchange.com/questions/364304/fourier-analysis/364371#364371
Answer: This answer is mostly for students who used an algebra approach. I don't know if Fourier himself thought up the series this way, but it is common today. I left a lot of steps out and mainly showed ideas that I struggled with when I first tried to motivate the Fourier Series.
I'll start off by observing a trigonometric polynomial:
$T(x) = c_0 + c_1 \cos(x) + c_2 \cos(2x)+...+c_n \cos(n x) + d_1 \sin(x) + ... + d_n \sin(n x)$
where $c_n$ and $d_n$ are some non-zero value.
The goal is write the orthogonal basis, from there I can find the coefficients.
So, I need declare the inner product:
$<\textbf{f},\textbf{g}> = \int_0^{2\pi} f(x)g(x)dx$
Before I can obtain a orthogonal basis, I should first get the orthonormal basis by using the Gram–Schmidt process. Where $\|\textbf{g}_0\| = \|\textbf{g}_1\| =\|\textbf{g}_2\| = ... =\|\textbf{g}_n\| = 1$.
$\|\textbf{f}\|^2 = <\textbf{f}><\textbf{f}> = 2\pi$
Thus, $\|\textbf{f}\| = \sqrt{2\pi}$
and
$e_0 = \frac{\textbf{f}}{\|\textbf{f}\|}$
$\textbf{g}_0 = e_0 = \frac{1}{\sqrt{2\pi}}$
$\textbf{g}_1 = e_1 = \frac{1}{\sqrt{\pi}}\cos(x)$
...
$\textbf{g}_n = e_n = \frac{1}{\sqrt{\pi}}\cos(nx)$...
$\textbf{g}_{n+1} = e_{n+1} = \frac{1}{\sqrt{\pi}}\sin((n+1)x)$...
$\textbf{g}_{2n} = e_{2n} = \frac{1}{\sqrt{\pi}}\sin(nx)$
The orthogonal basis yields:
$a_0 = \frac{2}{\sqrt{2\pi}}<\textbf{f},\textbf{g}_0>$   (Use 2 because it makes generalizing the coefficients possible.)
$a_1 = \frac{1}{\sqrt{\pi}}<\textbf{f},\textbf{g}_1>$...
$a_n = \frac{1}{\sqrt{\pi}}<\textbf{f},\textbf{g}_n>$...
$b_n = \frac{1}{\sqrt{\pi}}<\textbf{f},\textbf{g}_{2n}>$
Now that everything is divided into sines and cosines I can get the coefficients:
$a_n = \frac{1}{\pi}\int_0^{2\pi} f(x)\cos(nx)dx $
and
$b_n = \frac{1}{\pi}\int_0^{2\pi} f(x)\sin(nx)dx $
Answer: You will agree that the functions
$$x\mapsto\cos(\lambda x),\qquad \lambda>0,$$
and their translates are the "purest", "simplest", "most beautiful", etc., periodic functions you can think of. They are the solutions of the "super simple" ODE $$y''+\lambda^2\>y=0$$ for given $\lambda>0$.
Among all these functions solely the functions
$$x\mapsto\cos\left({2n\pi \over T}x\right)$$
and their translates have the prescribed period $T$. It follows that the most general functions that can be built linearly from such pure periodic functions of period $T$ are the functions specified in your question.
Herewith the following grand problem arises: Can every $T$-periodic function $g$ be written in this form, or will after the best conceivable approximation of $g$ by series of this type remain some "nonharmonic remainder"? That the latter is not the case is the essential content of the theory of Fourier series.

Derivation of fourier series equation


add file browser button to ckeditor

Question: I have installed ckeditor 3.5.2 with Wysiwyg profiles and every thing works great.
but in admin user  page i can see file browser link . how to add this link like button to ckeditor? i checked buttons like image and imce a but it doesn't add file browser to ckeditor.
at now i have upload files in admin user page and link them with ckeditor.
Anyone have this filebrwoser button (for uploading zip ,...) on ckeditor?
Answer: I'm not 100% sure but I think you need the IMCE Wysiwyg Bridge module.
Comment: i have installed this module.that would need special setting? You have file browser on your ckeditor? Could u put a pic from that?
Comment: Personally I'm not a big fan of IMCE, so I don't have a screenshot for you. If I recall correctly, after enabling the bridge module, there should be an IMCE button in the popup you get when you click the wysiwyg image button.
Comment: i have image button and a file browser if i click image button but what if i would like to upload zip file?
Comment: I don't know, sorry.
Answer: How to enable the file browser feature with Ckeditor in Drupal 8?

Install Embed Module.
Install Entity Embed module.
Install File Browser module.
It requires following contributed modules -
Entity Browser
Entity Embed
Embed
dropzonejs
DropzoneJS entity browser widget
To configure the "Entity Browser" Module, you will need ctools module.
At this page - https://example.com/admin/config/content/formats/manage/full_html
Drag the "File Browser" icon from Available Buttons to Ac
Enable the checkbox -  "Display embedded entities"

Thats all.

add file browser button to ckeditor


Reverse DNS for two ADs in the same subnet

Question: I currently have two separate AD forests that exist within the same subnet. The two forests have independent copies of the reverse lookup zone for that subnet.
Example:
Domain A DC1: 10.1.1.1/24
Domain A DC2: 10.1.1.2/24
Domain A AppServer1:10.1.1.3/24
Domain B DC1: 10.1.1.11/24
Domain B DC2: 10.1.1.12/24
Domain B Appserver1:10.1.1.13/24
What I'm after, is a configuration that allows this reverse zone to be shared between them so that both sets of DNS servers can make updates to the zone.
This kind of thing is a little far from my everday work, so a kick in the right direction is a welcome suggestion as well. Decoupling one AD into new segments is a possibility I'm open to but would like to avoid if possible. If there is a DNS related solution I'd prefer that.
Comment: Just to clarify this in my mind: Why do you want a single rDNS zone that can be updated and queried by clients in both AD domains? The copy of each rDNS zone is only relevant to clients that use each of the respective DNS servers. I run multiple AD domains at home on the same subnet and the DNS server for each AD domain hosts it's own rDNS zone for the subnet, which is relevant to that DNS server's clients only. Do you have a need to "share" the RDNS zone so that clients using one DNS server can resolve PTR records for hosts that reside in the other rDNS zone? I'm not seeing the need you have.
Comment: So my question is, how important are authenticated updates to you?  Have you tried permitting un-authenticated updates, and temporarily adjusting the DNS client settings to point at the other set of DNS servers?  Are you willing to have that reverse zone be handled by a server separate from both domains perhaps?
Comment: That's my thinking as well, it's not as important. Basically one AD is an actively changing corporate environment, and one is more of a service environment. I suppose one really only needs/reverse entries for its relevant resources.
Answer: I don't think there's a way for two DNS servers in different forests to do multi-master two-way sync... but maybe there's another way:
This may reduce security but what if you setup one forest as a primary rDNS zone, and the other forest as the secondary rDNS zone.  I don't think secondary could be stored in AD so you'd need to setup secondary on each DNS server in second forest.
Then configure both forests' rDNS zone to allow zone transfers and enable notify.  Limit to DNS server IP's for security sake.
The snag is what will a client on second forest do? It updates DDNS in it's forest but I'm not sure if client or DNS Service is what updates the rDNS zone. And since I think secondary zone for the rDNS is read-only, then somehow a referral needs to be made to the primary rDNS in first forest.  If that actually happened, then I would imagine first forest rDNS would need to be changed from secure updates only to nonsecure and secure.  Not as big a deal for rDNS zones, but still.
This is a rare scenario but curious myself if it can be done.  Let us know how it goes.  I could be totally wrong in my thinking here.
Comment: This will have to do for now, becuase one environment is fairly static, I'll simply have to add my entries over there and that should be alright. Perhaps next go round we'll use a master forest with two child domains instead but this was kind of a work in progress/design as you go and now we have to live with it.
Answer: this is impossilbe. you cannot have 2 rDNS Zones for the same subnet on one server. it would be the same if you wan't to create 2 Forward Zones with the same Domain Name
Comment: Impossible is a bit strong wouldn't you say?  Though it doesn't apply in this case, I can easily have two zones for the same subnet on Bind using views.  But that doesn't really matter, since it doesn't sound like he wants two zones, he wants a single zone that, clients from both domains can submit updates to.
Comment: yes i was wrong on the goal


How do Organic groups and virtual sites relate to each other?

Question: I just want to know that a site which is built in Openscholar, a LMS for Drupal.
Therefore, how organic group is tied up with virtual sites? Also I want to know the the Views module's role in such circumstances.
Comment: What's 'vsite'? There's no mention of such a thing on google in relation to Drupal
Comment: oh ho..i am metioned it above its in Drupal's lms "Openscolar"  . It creates a sperate site for a user under main site,a kind of subsite
Comment: does it mean virtual site?
Comment: yeah vsite means virtual site...
Answer: I am not sure about openscholar but what organic modules can do about virtual sites-

With help of organic group you can declare an entity as a "group" or call it context, an example could be a sports site with group as "cricket"
With help of og you have permission granularity in context to group, so a user can have access to all post which comes under a "group" in our example "cricket" being totally unaware of other groups, can say "hockey"
With in group you can have group specific roles, a user who can admin cricket group but still can not do anything on hockey group.

So each group can be seen as fully functional site in itself - virtual site
Note: Domains have nothing to do with og, it's just a matter of context switching
Comment: yeah...exactly...
Comment: does that answer your question?
Comment: yeah lots of it is the answer...but i want to find out how organic groups are related to vsite(virtual site). I want to know the basic architecture of organic group and vsite.
Answer: As a variation of what's explained in the prior answer, you could also use the Group module for this (instead of the Organic groups module). Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. So each group can be seen as fully functional site in itself, i.e. a virtual site.
It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. So since Group is entirely entity based, it has out-of-the-box integrations (= no extra modules needed) with other great modules such as Rules, the Views, etc.
For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".
Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Comment: Seems that it will work  !! let me implement first.
Comment: defiantly m experimenting something ! Once done i will let u kw whole idea .
Comment: @RajenderRajan : merci for feedback ... and yes I think you will like what you will discover ... looking forward to your evaluation later on ...!
Comment: @RajenderRajan Did you make any progress in your experimenting?
Comment: Openscholar by default provides a vsite for a particular user..M just wanted to use Rules module, organic module and Views to customize  the work flow of Openscholar. Till nothing much has been results, i have tried different approaches but just fail to get desired result.


Call Event on Controller after State Change

Question: I'm using UI-Router for AngularJs. Here's a code snippet:
mc.Controller('usersControllerActions', function ($rootScope, $scope, $state) {
    $scope.editedUser = null;    // This is set in my code (so it's not null)

    $scope.edit = function ($event) {
        $event.stopPropagation();
        $state.go('users.edit');
        $rootScope.$broadcast('setUser', $scope.editedUser);
    }
});

mc.controller('usersControllerManager', function ($rootScope, $scope, $state, global) {
    $scope.user = {};

    $scope.$on('setUser', function (event, user) {
        $scope.user = user;
    }
}

Part of my routes:
    .state('users.edit', {
        views: {
            'manager@': {
                templateUrl: '/areas/users/manage',
                controller: 'usersControllerManager',
            }
        }
    })

My issue is the first time my route is called and the view is initialized, the setUser event is not called.  However, every subsequent time it runs fine.  It's almost like when the state changes the first time, the event hasn't had time to register itself.
I'm simply trying to pass a selected user to an edit form.
How do I get this to work?
Comment: Is `$scope.editedUser` set asynchronously?
Comment: no, it is set in another method in my controller.
Comment: Could you include more of the code so we can see what is going on? It sounds like if the user is selected in a different view you could use $stateParams?
Answer: If you are passing users across multiple controllers, it might be better to create a service that handles which user is currently selected/being edited. This way you avoid the issue of running into cases where the next controller hasn't been instantiated yet. Services are singletons, so they will not have this race condition.
So, instead of using $rootScope.broadcast(), you could use:
// do stuff
myUserService.setEditedUser(editedUser);
$state.go()

----
// set user in other controller
$scope.user = myUserService.getEditedUser();

Comment: that's what i ended up doing, but my concern is that in large applications creating a bunch of singletons could create a potential memory leak of sorts.
Comment: This is the way I've seen it done for most angular applications when it comes to handling users and updates, so I wouldn't be too concerned.
Comment: Singletons.... memory leak... you realize memory leaks come from creating and destroying instances of objects and the computer not giving all the memory back on destroy. Sooo that's just backwords to begin with, and also JS's garbage collection is impeccable and never dirty unless you personally muck it up with streams in NodeJS...


Calculating when significance will be reached in A/B test ($\chi^2$ test of the difference between two proportions)

Question: I'm a marketer trying to understand the math involved in A/B testing. I've come across a tool that estimates how many more samples are required to reach significance for a test that's already begun. When you enter your test results thus far, it tells you how many more samples are required to reach the 90% confidence level.
If I enter the following data into the form:
           Visitors    Goals
Group A:        200       25
Group B:        190       26

The tool tells me that I need an estimated 8405 more samples to reach significance at the 90% confidence level.
So far I've:

Read through the explanation of sample size in a couple of different statistics books.
Manipulation of power analysis equations on paper.
Experimenting with power.prop.test() in R.

I'm just not seeing how to calculate this. Can someone help?
Answer: I can't reproduce the exact numbers produced by this calculator but the output seems quite close to the result you might get from power.prop.test() for a power of 50% in a two-sided test, using the sample estimates for the two proportions, e.g.
power.prop.test(p1=26/190, p2=25/200, power=.5, sig.level=.1)

(The result is 4390 per group, so 8780 total or 8390 visitors more than you already have, the 15-observation difference could easily be accounted for by a rounding error somewhere – including on the website – or some other computational detail.)
If this is really what it is, it seems that there is a fundamental flaw in the approach, as it implicitly assumes that the proportions you got from your sample are indeed the true proportions, which seems to defeat the whole point of doing an experiment in the first place. In fact, there is no telling if the difference will "reach" significance, as you could very well discover that the results are very different after you have collected more data (perhaps the difference will be smaller or even go in the other direction).
Intuitively, this should be easy to realize if you consider that the recommended sample size is more than 20 times the size of the sample you already have. The data you have will be dwarfed by these new data and you will in effect have a completely new experiment that could go either way (especially since it's already clear that the effect is not very strong and the data you already have are not conclusive – otherwise, you could already reject the null hypothesis).
For a similar idea, expressed more carefully in a completely different context, you might refer to Kraemer H.C., Mintz J., Noda A., Tinklenberg J., & Yesavage J.A. (2006). Caution regarding the use of pilot studies to guide power calculations for study proposals. Archives of General Psychiatry, 63 (5), 484-489.
The information provided on the calculator's page is in any case very thin and insufficient to serve as a basis for a proper power analysis. Even if you were willing to disregard the point I just discussed, you would at the very least need the desired level of power (together with the effect size and error level) to compute a sample size and it does not seem to be mentioned anywhere.
Comment: @Lenwood If you absolutely must adjust the sample size as you go, it might be better to consider [accuracy in parameter estimation](http://stats.stackexchange.com/questions/16985/how-to-report-general-precision-in-estimating-correlations-within-a-context-of-j#30287) rather than power and repeated tests, [which can be very misleading if done improperly](http://allendowney.blogspot.nl/2011/10/repeated-tests-how-bad-can-it-be.html).
Comment: That's a great tip on `power.prop.test()`, I'll take another look there. Thanks also for the article, I think that's exactly what I was looking for. Regarding your comment about the fundamental flaw, my understanding is that the right way to do this is to calculate the required sample size prior to the test beginning. In my experience most marketers either don't understand this or ignore it. So however incorrect, calculating significance as you go is the standard practice. That's no comment on the website I linked to, just my experience with marketers that run A/B tests.
Answer: I just stumbled upon the equation that R is using in the power.prop.test() function.
$$
n=\dfrac{2(\bar{p})(1-\bar{p})(Z_{\beta}+Z_{\alpha/2})^{2}}{(p_{1}-p_{2})^{2}}
$$
Note that the power & confidence intervals are expressed as Z-scores. I'm using a power of 80%, which is $Z_{\beta}=0.84$, and a confidence interval of 95%, which is $Z_{\alpha/2}=1.96$. These values give me the same answers as I'm getting from R. I won't mark this as the answer, but wanted to include it in case anyone lands here looking for an exact solution.

EDIT: I should correct my statement. This isn't the exact equation that R uses in their power.prop.test() function, but it does yield the same results. Their equation is more complex than this. I've tried them head to head dozens of times now, and the results are consistently +/- 2 of each other.