I have to create a web tracking pixel like facebook pixel, glami pixel etc

Question: I need to create a web tracking pixel like Facebook pixel, glami pixel, etc
Tried cross-domain connection and worked:

laravel domain1: header('Access-Control-Allow-Origin', '*')
laravel fake shop: js XMLHttpRequest

So far I have:

And I want something like:

Also is this link helpful?: https://github.com/dockwa/openpixel
Answer: Solved my own problem:
    /**
     * @test track('PageView', {foo: 'bar'});
     */
    !function(a, u, d, i, o, t, e, k) {t='PixelTrack';o=[];
        a['track']=(...f)=>{o.push(f)};e=u.createElement('script');
        e.async=true;e.src = d;u.getElementsByTagName('head')[0].appendChild(e);
        e.onload=()=>{a[t](i);o.forEach((item)=>{a[t](item)})};
    }(window, document, 'http://www.domain.cr/js/pixel.js', 'INSERT_YOUR_API_KEY_HERE');

//    (function(a, u, d, i, o, t, e, k) {
//        e = 'PixelTrack';
//        t = [];
//        a['track'] = function(...f){
//            t.push(f);
//        };
//
//        k = document.createElement(d);
//        k.async = true;
//        k.src = i;
//
//        k.onload = function() {
//            a[e](o);
//            t.forEach((item) => {
//                a[e](item)
//            })
//        };
//
//        u.getElementsByTagName("head")[0].appendChild(k);
//
//    })(window, document, 'script', 'http://www.domain.cr/js/pixel.js', 'INSERT_YOUR_API_KEY_HERE');

And in pixel.js is laravel mix of something like:
window.PixelTrack = function(params){ console.log('do stuff') }


A conjecture for the golden ration via continued fraction $\phi=\frac{1+\sqrt{5}}{2}$

Question: Playing with my own question Got a factored version of the Taylor's series?  I found that :
Define :
$$f(x)=\frac{1}{\sqrt{x-2/x}}$$
Then it seems we have :
$$\phi=f(f(\cdots f(\phi)\cdots))$$
Numerical checking is agree so some question :
edit :
I'm really interested by an generalization the next polynomial are :
$$x^4-2x^3+2x,x^5-3x^3+2x,...$$
How to (dis)prove it ? How fast is the convergence if true ? Is there a generalization if true ?
Comment: We just have $f(\phi)=\phi$ , not really exciting. Applying $f$ gives a constant sequence.
Comment: What exactly is your conjecture? As mentioned above, $\phi=f(f(\cdots f(\phi)\cdots))$ is trivially true because $f(\phi)=\phi$. What generalizations are you thinking of? What are the polynomials $x^4-2x^3+2x,x^5-3x^3+2x$ and what would be the next one? What exactly do you want prove or disprove?
Comment: Why did you delete your  previous question ? It was an interesting problem.
Comment: @ClaudeLeibovici reopen and see the edit
Comment: @Peter so have you an idea to generalize ?
Answer: Let $f(x)=(x-2/x)^{-1/2}$, define $f_0=f$ and $f_n=f\circ f_{n-1}$.
Note that we do have $f_n(\phi)\to\phi$ simply because $f(\phi)=\phi$, i.e. $f_n(\phi)$ is a constant sequence. The more interesting question would be
$$\text{does $f_n(x)\to\phi$ for $x\neq\phi$ ?}$$
A simple find is $\psi=1-\sqrt5$ since $f(\psi)=\phi$. For all other $x\neq\phi$ or $\psi$, either $f_n$ diverges or $f_n$ is not well-defined. To see this, note that if $x\geq0$, then $f_2(x)$ will not be well-defined for $x\leq\sqrt2$ or $x\geq\sqrt3$, hence we shall only focus on $x\in(\sqrt2,\sqrt3)$. On this range, define the difference
$$g(x)=|f(x)-\phi|-|x-\phi|=\big(2\phi-f(x)-x\big)\text{sgn}(x-\phi).$$
It is not hard to verify $g(x)>0$ for all $x\in(\sqrt2,\sqrt3)$ with $x\neq\phi$. This means every time we apply $f$, the distance to $\phi$ becomes larger and thus $f_n$ will diverge. To summarise, for positive $x\neq\phi$ either $f_n$ diverges or $f_n$ is not well-defined. As for all negative $x\neq1-\sqrt5$, we have $f(x)\geq0$ and $f(x)\neq\phi$, therefore the same argument for positive $x$ applies.
In addition, note that $\phi$ is the only possible limit point for $f_n$, since a limit point $x$ must satisfy $f(x)=x$ which yields only one solution $x=\phi$.
Answer: $$\begin{align}
f(\phi)&=\frac1{\sqrt{\phi-\frac2\phi}}\\
&=\frac{\sqrt\phi}{\sqrt{\phi^2-2}}\\
&=\frac{\sqrt\phi}{\sqrt{\phi+1-2}}\\
&=\frac{\sqrt\phi}{\sqrt{\phi-1}}\\
&=\frac{\sqrt\phi}{\sqrt{\phi^{-1}}}\\
&=\phi
\end{align}$$
So that means continued fraction is just $\phi+\underline{0}?$


Trouble while adding south to existing app

Question: I am following the djano-rest-framework tutorial. I am trying to add south for db migration. This is what my pip freeze looks like:
Django==1.8.1
djangorestframework==3.1.2
MySQL-python==1.2.5
Pygments==2.0.2
South==1.0.2

My settings.py for the tutorial project looks like this:
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'snippets',
    'south'
)
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'snippets',
        'HOST': 'localhost',
        'PORT': 3306,
        'USER': 'abcd',
        'PASSWORD': ''
    }
 }

SOUTH_DATABASE_ADAPTERS = {
    'default': 'south.db.mysql'
}

I am getting the following error on running ./manage.py syncdb:
/home/superq/learn-django/env/lib/python2.7/site-packages/south/db/generic.py:9: RemovedInDjango19Warning: The django.db.backends.util module has been renamed. Use django.db.backends.utils instead.
  from django.db.backends.util import truncate_name

There is no South database module 'south.db.mysql' for your database. Please either choose a supported database, check for SOUTH_DATABASE_ADAPTER[S] settings, or remove South from INSTALLED_APPS.

I have already installed and uninstalled south multiple times. Any ideas?
Answer: You are using Django 1.8. There is no reason to add South: versions of Django since 1.7 have included built-in migrations. In fact, the South docs explicitly state that it is not compatible with 1.7+.
Comment: I opened the shell and tried to do 'import south'. It says no such module available.
Comment: Yes. Why would you do that? I just said, South is not necessary or compatible with 1.8.
Comment: I was trying because neither schemamigration or startmigration commands are available for manage.py
Comment: No, because Django 1.7/1.8 have their own migration commands, which are [fully explained in the documentation](https://docs.djangoproject.com/en/1.8/topics/migrations/).
Comment: My bad. Will look at it thouroughly now. Any other example resources would also be appreciated. Thanks!


How can I deal with outdated versions of jQuery on a client site?

Question: I've already run into clients running 1.3 code, when my work relied on 1.4's much improved features.
Yet these clients don't have the resources to update their old code ...
Example: The client refers to jQuery 1.3 in their site's template, but I'd really rather use 1.4 for my code and not have to try and use the older version.
Any thoughts on how to deal with this problem?
Edit: The ideal solution would be totally JS ... no server-side code as the client prefers it that way.
Comment: @Justin then find a way to embed the right jQuery dynamically as discussed below, and check against your `dir` for 1.4 and you should be good.
Comment: what exactly is your question? Can't you update the versions?
Comment: No, I cannot update the version. The client has code on their site which won't work with 1.4 --- Code I cannot edit and is not in the scope of my project --- The client doesn't the resources to fix their old page either.
Comment: @Justin then you are giving insufficient information for anybody to answer your question - the obvious answer is use 1.4 on your pages, and 1.3 on theirs. For tips how to achieve that you'll have to explain about your client's setup, what server side languages there are, what the templates look like, etc. etc.
Comment: @Pekka The problem is their "template" applies to all the pages on their site (and they use 1.3) It's not so much a server side issue, basically my pages need to work WITHIN their "template" ... but need to use 1.4 (and NOT break their existing pages.)

If that's not really possible that's fine, just looking for suggestions.
Comment: @Justin see my comments below, this is probably solvable somehow. The nicest I can think of if your pages were all in the same directory - you could parse the URL for that, and include 1.4 in that case.
Comment: @Pekka BTW, not all the pages in the site are in the dir ... but all MY pages are (and will always be) as I'm using cowboy's BBQ plugin http://benalman.com/projects/jquery-bbq-plugin/ to use hash's like http://something.com/dir/#/home/ & http://something.com/dir/#/newpage etc ...
Comment: I am in the same situation. My client uses 1.11 and I have made a script using 3.4.1 :(
Answer: Try and make the clients aware that the "resources" needed are typically pretty light.  Converting to a new version is usually a very quick process, unless they had a lot of erroneous code that was allowed before, but incorrect.
Have them take a look at the release notes for 1.4, and for that matter 1.4.1 and 1.4.2, the benefits of the upgrade far outweigh the time it takes to upgrade in every case I've come across.  The only caveat to this is in the 1.4 upgrade specifically, the added JSON strictness.  From the 1.4 release notes:

jQuery 1.3 and earlier used JavaScript's eval to evaluate incoming JSON. jQuery 1.4 uses the native JSON parser if available. It also validates incoming JSON for validity, so malformed JSON (for instance {foo: "bar"}) will be rejected by jQuery in jQuery.getJSON and when specifying "json" as the dataType of an Ajax request.

This means JSON operations are much faster, but old/invalid JSON won't cut it.  If they have to go fixing web-services because the JSON has to be absolutely valid in 1.4+, this could be a show-stopper on an upgrade for a large project...and I'm not sure what to tell you on that one.
As for plugins...every major/popular plugin supports new releases very quickly, if not they're pretty quick to fix yourself...and many just don't need any editing at all, because they weren't broken by the upgrade (still, check for new versions of a plugin, they may get performance boosts from a new version of core).
Comment: Thank you resource, and for the vote of confidence in 1.4 ... I too believe it would be worth the upgrade and that helps a lot.
Comment: FWIW, you could monkey-patch the jQuery.parseJSON(json) function to use the old eval() way if you really need support for broken JSON.
Comment: @Nick Craver This is true ... "strictly" speaking but actually a lot of custom code & plugins don't work as expected. It's not jQuery's fault really ... 1.3 is what, 1 1/2 years old?
Comment: @Justin - It is...but the time doesn't matter, it's how many changes in the release, and there weren't that many breaking changes from 1.3 to 1.4, can you give a few examples of breaks it creates?  I might be able to answer a bit narrower if I had some examples :)
Comment: @Nick Crave it seems to be mostly their (uhm not so great) custom code and some plugins that don't work ... and that's not really my problem it's theirs. Thanks for the offer tho.
Answer: If you're asking whether two versions of jQuery can be embedded into the same document at the same time, the answer is no.
Your client would have to upgrade, which should be relatively easy to do - if they're lucky, without any work at all: See @Nick's excellent overview.
Alternatively, if you need to use jQuery 1.4 on some pages, and 1.3 on others, you would certainly be able to set up some server-side shenanigans to serve the correct version. (It would probably even be possible using JavaScript.) but to do that, you'd have to give us more info about the setup.
Comment: @Justin nope, once the `
Comment: @Justin I thought about that as well, it should be possible. You could parse `location.href` or check your custom variable you specified before (`jquery_version = "1.4";`). It's only that `document.write()` doesn't work in the `head` AFAIK, so you'd have to create the script object using `createElement`. Probably possible - maybe worth a separate question.
Comment: I can modify the template: So, I guess it might be possible to put something on each page ... which could "notify" the *template* that it needs 1.4 (and tell it to **not** include 1.3) ... not sure about the performance repercussion of that however?
Comment: @Justin any server-side languages available? PHP? ASP?
Comment: @Justin can you write something into the `head` section of each file *before* jQuery is included, or can that be done only centrally in the template?
Comment: @Justin are *your* pages in their own directory?
Comment: @Pekka I could write something with jQuery 1.3 to the head AFTER 1.3 is included ... would that work? :) The client really doesn't want to use anything server side (more their issue then mine.) ASP.net (with PHP available) but they are weary of any server side stuff (I know wack.)
Comment: Hum since I can edit the template ... what if I wrapped the
Comment: @Pekka I will look into this, and see if that's the way to go. If so, I think you qualify as the "answer" anyhow & I will mark it as so. Thanks for the help.
Answer: I am not sure I understand you question. Do you have a website that uses JQuery? Surely if you put the JQuery javascript files in a folder in your web app and reference them in your script tags then the users' browers will download the new libraries.
Can you please explain what you mean when you say

the clients don't have the resource to
  update their old code.
Comment: In other words ... The client has many, many pages on their site that would break if upgraded to 1.4 (mostly due to bad code ...) so the entire template can't be upgraded as it would break said pages. However those pages have nothing to do with the newer project.
Comment: If it has nothing to do with the new project you are working on.. why worry about the pages using 1.3? work on your project with 1.4 as you are comfortable with it and follow Nick's advice on making the clients aware
Comment: 1.3 does have to do with my project in that 1.3 is included in the site wide template (which my pages need) ... and I need 1.4 on my page, and NOT 1.3


cross partition proof

Question: I have been having troubles in how to proof the cross partition. For what I know a partition must hold two properties:

The elements of the subsets that form the partition should be
equal to U, where U is the universe set. b)
The subsets that form
the partition should be disjoint or their intersection should be the
empty set.

I have seen the following exercise related to cross partition in a book:

I can assume that I have two, or more partitions, of S that holds properties 1 and 2. So if I make a new set of partitions in Ai and Bj then these will be also partitions because I am not adding any new element to any of these subsets. From this point I make the cartesian product between Ai and Bj considering only those subsets that are common, comparing the partitions that I made before of Ai and Bj or that their intersections are not the empty set. These are also partitions because I am not adding any new element that could generate any intersection on the partitions that I have formed.
Is this proof correct?
Comment: I don't know what you mean by "cross-product", but if you mean "Cartesian product", then your proof is definitely wrong.
Comment: sorry @AlexM. I have corrected it.
Answer: I suspect that you have the right general idea, but your explanation is too vague and imprecise for me to be sure. Let me show you how to write up a proper proof of the result. In fact, since it's no harder, I'll prove the corresponding result for arbitrary partitions, not just finite ones.

Proposition. Let $\mathscr{P}$ and $\mathscr{Q}$ be partitions of a set $S$. Let
$$\mathscr{R}=\{P\cap Q:P\in\mathscr{P}\text{ and }Q\in\mathscr{Q}\}\setminus\{\varnothing\}\;;$$
that is, $\mathscr{R}$ is the family of all non-empty sets of the form $P\cap Q$ with $P\in\mathscr{P}$ and $Q\in\mathscr{Q}$. Then $\mathscr{R}$ is a partition of $S$.

To prove the proposition, we need to verify that $\mathscr{R}$ satisfies the conditions defining what it means to be a partition of $S$. Specifically, we need to prove two things:

We need to show that $\bigcup\mathscr{R}=S$, i.e., that for each $x\in S$ there are a $P\in\mathscr{P}$ and a $Q\in\mathscr{Q}$ such that $x\in P\cap Q\in\mathscr{R}$.
We need to show that the family $\mathscr{R}$ is pairwise disjoint, i.e., that if $R_0$ and $R_1$ are distinct members of $\mathscr{R}$, then $R_0\cap R_1=\varnothing$.

To prove that $\bigcup\mathscr{R}=S$, let $x\in S$ be arbitrary. $\mathscr{P}$ is a partition of $S$, so there is a $P\in\mathscr{P}$ such that $x\in P$. And $\mathscr{Q}$ is also a partition of $S$, so there is a $Q\in\mathscr{Q}$ such that $x\in Q$. Clearly $x\in P\cap Q$, so $P\cap Q\ne\varnothing$, and therefore we have $x\in P\cap Q\in\mathscr{R}$, as desired.
To prove that $\mathscr{R}$ is pairwise disjoint, suppose that $R_0,R_1\in\mathscr{R}$. Then there are $P_0,P_1\in\mathscr{P}$ and $Q_0,Q_1\in\mathscr{Q}$ such that $R_0=P_0\cap Q_0\ne\varnothing$, and $R_1=P_1\cap Q_1\ne\varnothing$. Suppose that $R_0\cap R_1\ne\varnothing$. Then there is some $x\in S$ such that
$$x\in R_0\cap R_1=(P_0\cap Q_0)\cap(P_1\cap Q_1)=(P_0\cap P_1)\cap(Q_0\cap Q_1)\;.$$
In particular, this means that $x\in P_0\cap P_1$ and hence that $P_0\cap P_1\ne\varnothing$, i.e., that $P_0$ and $P_1$ are not disjoint. But $\mathscr{P}$ is a partition of $S$, so its members are pairwise disjoint. Thus, $P_0$ and $P_1$ cannot be distinct members of $\mathscr{P}$: it must be the case that $P_0=P_1$. An exactly similar argument shows that $Q_0=Q_1$, and it follows immediately that $R_0=R_1$. We've now shown that if two members of $\mathscr{R}$ are not disjoint, then they are in fact equal, and hence that distinct members of $\mathscr{R}$ must be disjoint, exactly as we wanted.
This concludes the proof that $\mathscr{R}$ is a partition of $S$.
Added: For a direct proof that $\mathscr{R}$ is pairwise disjoint, suppose that $R_0,R_1\in\mathscr{R}$, and $R_0\ne R_1$. Let $P_0,P_1,Q_0$, and $Q_1$ be as above. Without loss of generality we may assume that there is some $x\in R_0\setminus R_1$. Thus, $x\in P_0\cap Q_0$, and $x\notin P_1\cap Q_1$. Since $x\notin P_1\cap Q_1$, either $x\notin P_1$, or $x\notin Q_1$ (or both). Suppose that $x\notin P_1$. Then $x\in P_0\setminus P_1$, so $P_0\ne P_1$, and since $\mathscr{P}$ is a partition, it follows that $P_0\cap P_1=\varnothing$ and hence that
$$R_0\cap R_1=(P_0\cap Q_0)\cap(P_1\cap Q_1)=(P_0\cap P_1)\cap(Q_0\cap Q_1)=\varnothing\;,$$
as desired. Similarly, if $x\notin Q_1$, then $x\in Q_0\setminus Q_1$, so $Q_0\ne Q_1$, and hence $R_0\cap R_1\subseteq Q_0\cap Q_1=\varnothing$. Thus, $R_0$ and $R_1$ must be disjoint.
Comment: thank you @Brian M. Scott, one question more; the last part you are proving it by contradiction, is that right? If I want to prove it by direct proof can I say that in your the last part of your formula P0 int P1=null set and Q0 int Q1=null set also, because they are disjoint, so the intersection of both will be also null set?
Comment: @Lila: You're welcome. What I did in the last part isn't actually a proof by contradiction: I proved the [*contrapositive*](https://en.wikipedia.org/wiki/Contraposition) of the desired implication. An implication $P\to Q$ is always logically equivalent to its contrapositive, $\neg Q\to\neg P$, so proving either one of them automatically proves both. A direct proof of the original implication here would require you to assume that $R_0\ne R_1$ and prove directly that $R_0\cap R_1=\varnothing$. This can be done, but it's a lot more complicated than what I actually did or what you're suggesting.
Comment: could you be so gentle to add the direct proof in the last part of your answer? @Brian M. Scott, I am really interested to see how to do it.
Comment: @Lila: I've now added it.

cross partition proof


Computing the differental of an orthogonal projection

Question: I am having trouble computing the differental of a map. This is the context:

Let $S\subset \mathbb R^3$ be a regular surface, and fix a point $p\in S$.
Let $\pi:\mathbb R^3\to T_pS$ be the orthogonal projection onto $T_pS\subset \mathbb R^3$, and let $h=\pi|_S$ be the restriction of $\pi$ to $S$. Why is $h$ differentiable? Carefully show that $dh_p$ is injective.

I said that $h$ is differentaible, because it is the restriction of a differentiable function.
Next I assume that near $p$ the surface $S$ is parametrized by some parametrization, say $X(u,v)$. Then I choose $\{X_u,X_v,n\}$ as a basis for $\mathbb R^3$. Now we see that $h(x,y,z)=(x,y)$ which would mean that $$dh_p=\begin{pmatrix}1&0&0\\0&1&0\end{pmatrix}.$$ This doesn't seem right to me, because the zero-culumn suggests tha $dh_p$ isn't injective.
Where exactly am I slipping up?
Answer: We have $h:S\rightarrow T_pS,$ or, to state it more explicitly, $h$ is defined on $S,$ and $S$ is 2-dimensional. If you want to express $dh_p$ as a matrix, you have to work with a coordinate chart for $S$ around $p.$ In more detail, this works as follows.
By applying translations in $\mathbb R^3$ and parameter space $(u,v),$ we can assume that $p = 0$ in $\mathbb R^3$ and $X(0,0) = 0.$ Denote the standard orthogonal basis in $\mathbb R^3$ by $e_1,e_2,e_3.$ By using the inverse function theorem, or the implicit function theorem, we can find a new parametrization $Y = Y(\xi,\eta)$ of $S$ given by
$$
Y(\xi,\eta) = \xi e_1 + \eta e_2 + f(\xi,\eta) e_3,
$$
where $f$ is a real-valued, smooth function with $f(0,0) = 0.$ This is a standard construction from differential geometry. Note that $Y(0,0) = 0 \in \mathbb R^3,$ $T_0S = \mathbb R e_1 + \mathbb R e_2,$ and $e_3$ is the normal at $S$ in $0.$ In the coordinates $(\xi,\eta),$ we have
$$
h:(\xi,\eta)\mapsto Y(\xi,\eta) = \xi e_1 + \eta e_2 + f(\xi,\eta) e_3 \mapsto  \xi e_1 + \eta e_2.
$$
In these coordinates, it's "obvious" that
$$
dh_0 = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix},
$$
which is very well injective, even invertible.


If a group $G$ with order $5$ acts on a set $X$ of size $10$ what are the possible orbit partitions?

Question: If a group $G$ with order $5$ acts on a set $X$ of size $10$ what are the possible orbit partitions?
The only progress I have so far is to say that using the orbit stabiliser theorem for any $x \in X$ we have $\text{Orb}(x)$ divides $|G|=5$ so $\text{Orb}(x)=1 ~\text{or}~5$. If it is $1$ then each partition consists of a single element and the action is trivial.
If it is $5$ then the $G$ orbits partition $X$ into two sets of size $5$.
My questions are this:
Is this correct and can I do anything more?
And
The question where I got this from was an old exam paper and it was one part of a question comprised of many parts. It didn't start discussing the orbit stabiliser theorem until later parts so is there a better/more direct approach to this?
Comment: For a group action two different orbits can have different sizes.
Comment: As you rightly say the parts of the partition into orbits have size $1$ or $5$. I can make $10$ in three ways using blocks of size $1$ and $5$.
Answer: Every orbit is not necessarily of the same size.
Since for $x\in X$, $|\mathcal{O} (x)|=1 $ or $5$
The possible ways to partition $X$ equal the number of ways to partition the number $10$ into sum of $1's$ or $5's$
So there are $3$ ways:
$1,1,1,1,1,1,1,1,1,1$
$5,1,1,1,1,1$
$5,5$


Como suprimir a janela de input do Oracle sem usar set define off

Question: Preciso inserir uma imagem no oracle usando php, porem depois que converto ela para inserir no banco, ela recebe alguns caracteres & no meio da string, esse caractere no Oracle dispara uma tela de input, quando é disparada essa tela de input, o php se perde e lança uma exceção, ja tentei usar set define off para suprimir a tela de input porém sem sucesso, meu usuario do oracle não tem essa permissão e não tem como eu conseguir outro usuario, qual seria o meio de contornar essa questão? a pergunta seria, como suprimir a tela de input do oracle sem usar o set define off.
Essa é a tela de input que preciso suprimir:
Comment: Você pode usar set escape?
Comment: @ROBERTOALBINOJUNIOR, Acredito que o seu problema esteja especificamente na query que faz o insert. Isto me parece um erro simples de escape de string. Normalmente o PDO escapa tudo quando utiliza PreparedStatement. Você está concatenando a query ou utilizando PreparedStatements ?
Comment: teria como postar seu código php que esta usando para inserir ?
Comment: O problema não está no insert e sim em sumprimir a tela de input sem usar o set define off, se eu postar o insert vou acabar tirando o foco da pergunta.
Comment: Eu também acho estranha a questão, eu também gostaria de ver como esta sendo executada essa linha.
Comment: Faça um teste, tente inserir em uma coluna com o tipo `varchar2(10)` em uma tabela de teste,  com o valor: `R0b&rT0` e verifique se esta inserindo. Usando PHP, claro.
Comment: Ja fiz esse teste David quando tento fazer isso o Oracle dispara a janela de input que está no print ali em cima, foi assim que descobri o erro depois de muitas tentativas, quando o php se depara com essa janela ele dispara uma exceção eu tempo de execução seria quase impossivel eu fazer o php se comunicar com essa janela em background, preciso desabilitar esse input sem usar usar o set define off
Comment: Não manjo tanto de PHP, mas acredito muito que o problema esta no seu código PHP, esta usando PDO? mysqli? Poste seu código, acredito que alguém consiga ajudar.
Comment: Não posso usar set, infelizmente.
Comment: Então, estou usando PDO sim, se fosse pra melhorar teria que ser a parte do código que transforma a foto em hexadecimal, só pq precisaria mudar o sistema inteiro, então se eu conseguisse resolver dessa maneira seria ótimo.
Comment: Pode usar outro caracter diferente de &?
Comment: Posso, só pq como esse caractere está no meio de uma foto trasnformada em hexadecimal, cada string dessa tem uns 6000 caracteres é inviavel a cada nova foto fazer a procura manual desses caracteres dentro da string.
Comment: Concatenando a query
Answer: <code>SET ESCAPE '\'

CREATE TABLE TABELA (
   C1 VARCHAR(10),
   C2 VARCHAR(10))

INSERT INTO TABELA VALUES ( 'CAR\&LOS', 'ANDOR\&INHA')
</code>
Comment: Não posso usar SET.


R: list.files returning NA instead of file name

Question: I am trying to retrieve the file name for the file "cg3-chem-djtayl18PSY101.txt" which exists in my working directory using the following commands.
regexName = "*chem-djtayl18*.txt"
fileName <- list.files(path = ".", pattern = regexName, ignore.case = TRUE)[1] # returning NA

However, it is returning the file name as NA. Although it is working for 100 other files in the same directory in the same manner. Why is it behaving this way?
Comment: puts dots before your stars, `.*` in regex.  It is not shell globs
Comment: yes, it worked. as soon as i posted it here i found the problem :)
Answer: Because your regex does not match the file name.
regexName = "*chem-djtayl18*.txt"
filename <- "cg3-chem-djtayl18PSY101.txt"
grepl(regexName, filename)
#[1] FALSE

Maybe you need the pattern.
regexName = "chem-djtayl18.*\\.txt"
grepl(regexName, filename)
#[1] TRUE


database query return an array composed of stdClass

Question: im having trouble here getting value from a record.
Here's what i want to do:
 1. Getting a record from db
 2. Convert the query result to array
 3. Display the array[0], but got error undefined offset:1
The var_dump() : array(1) { [0]=> object(stdClass)#23 (1) { ["nama"]=> string(9) "Test Name" } }
Tried the query by myself, and it return a record :
|username|nama    |
|Testuser|Testnama|
so how can i get the 'Testuser'?
model/verify_login_model
function getinfo($username) {
    $this->db->select('nama', 'username');
    $this->db->from('tb_userInfo');
    $this->db->where('username', $username);
    $this->db->limit(1);

    $result = $this->db->get();
    if($result->num_rows()==1) {
        return $result->result();

    } else {
        return false;
    }
}

controller/verify_login
public function index(){
    $this->load->model('verify_login_model');
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $result = $this->verify_login_model->verify($username, $password);
    if($result == $username) {

        $row = $this->verify_login_model->getinfo($username);
        echo var_dump($row);
        $sessiondata = array('name'=>$row[0], 'username'=>$row[1]);
        $this->session->set_userdata($sessiondata);
        $name = $sessiondata['name'];
        $this->load->view('home_view', $name);

    } else {
        redirect('login');
    }
}

view/home_view

    welcome, <?php echo $name?>

Comment: you can `echo $this->session->userdata['name']` inside of view and about model you can try and `return $result->result_array();` and then inside of controller do `$row[0]['nameofyourcolumn'];`
Comment: @MarkoKunić could you explain me about the var_dump()'s result? why am i getting that stdClass#23
Comment: Thave you tried  return $result->result_array(); instead of  return $result->result(); in model
Comment: @wolfgang1983 the result is : array(1) { [0]=> array(1) { ["nama"]=> string(9) "Test Name" } }
Answer: your model returns an array of objects, as you use
return $result->result();

in order to get the result as a plain array use:
return $result->result_array();

read more about generating query results here
Comment: yea thank you, now i stuck at this var_dump :array(1) { [0]=> array(1) { ["nama"]=> string(9) "Test Name" } }  after i changed to your suggestion. so why exactly the $row value is kinda array inception?
Comment: check here: http://www.if-not-true-then-false.com/2009/php-tip-convert-stdclass-object-to-multidimensional-array-and-convert-multidimensional-array-to-stdclass-object/
Comment: check the usage in my answer under For result_array()
Comment: Thank you for the result_array(), i think your answer is the most accurate as to the title saying about stdClass. now the problem is about the null i got for the row[1]. couldcha point the reason why ? or guess need to post another question
Comment: I think better to ask a complete new question
Answer: According to CI query result displays
https://ellislab.com/codeigniter/user-guide/database/results.html
->result() This function returns the query result as an array of objects,
What about the stdClass - check out here https://stackoverflow.com/a/931419/2513428
To get your result you have to do as following
$sessiondata = array('name'=>$row[0]->nama, 'username'=>$row[0]->yourfield);

To visualise this a bit it's like array(1) { [0]=> object(stdClass)#23 (1) { Your query result } } and to get the data you point the object $var[0]->Object. But you can also change to the result_array() and treat it as an array not an object as it is now.
For  result_array()
 $sessiondata = array('name'=>$row[0]['nama'], 'username'=>$row[0]['yourfield']);

Hope this will help you.
Comment: Thank you bro for the explanation about array[0] = object, tried your suggested code, but i think its not working.


Is practicing seventh chords ascending/descending chromatically effective?

Question: I've been practicing seventh chords on piano using a number of patterns.
I'm playing all four inversions for major, minor, half-diminished, and dominant sevenths.
One pattern I use is to play full four note voicings in each hand and ascend or descend the octave. My target speed is around eighth notes at 60 bpm.
I do a variation on this where I play each chord in three octaves before ascending/descending to the next root. That pattern is at a much slower rhythm. I also try shakes between two finders while holding the other two fingers down. Another is arpeggiating the chord along the lines of Girl With the Flaxen Hair at m. 24.
I think this is helping me get to the point where I can instantly hit just about any common chord in any voicing anywhere on the keyboard.
Any recommendations for or against these kinds of drills? Are there particular aspects to focus on?
Answer: All that is all very well. How often do you think you're going to be playing a piece where you're expected to play any seventh chord arp. and then play one a semitone up or down? Probably never? So why not reach reality and play them in a real situation, in a sequence from real songs?
Comment: Not all drills work that way. How often do you play two octave scales in contrary motion in _real_ music. I've never seen that in Mozart, Haydn, etc. I've seen other drills that move by chromatic root, but not specifically for seventh chord But I am also playing other patterns like sequences of descending fifths or fourths.
Comment: Actually, parallel-chromatically descending seventh chords are common in Blues – of course this is very easy on guitar.
Comment: @leftaroundabout, that's a good point, in the turnaround esp. parallel chords. In fact I've had trouble with those moves even though it wasn't the purpose of this exercise for me. As you mention, it's easy on guitar, but on piano there are a lot of finger adjustments. My fingers get 'tied up in knots' and I was trying to work through that.
Comment: You're right about scale playing. In the real world they generally need to be learned, thus practised, for exam purposes only! Not a lot of use for playing *real* music! Perhaps a more practical, because it happens in music, would be to go through the cycle of fourths/fifths.
Answer: I do a similar thing but without inversions. I just go across all scales and arpeggiate each of the seven diatonic seventh chords. So in major it'd be Imaj7, ii7, iii7, IVmaj7, V7, vi7, viidim7. Really try to commit all notes and especially each chord's overall sound to memory. Then after going linearly from 1-7, randomly think of a progression for example 2-5-1. As far as inversions, I find that they take care of themselves once I know the sound so I just try the different inversions when I'm playing an actual song.
Another thing I've been doing is not looking at my fingers as I play the scale or these chord based arpeggios. You can use the black keys as braille to know where you are. I'm not quite there yet but I keep practicing this. I think looking at the keys is detrimental because then you start seeing visual patterns instead of "feeling patterns". To me, muscle memory is of higher importance, much like touch typing on a computer keyboard.
As an aside, I find that if you have a miniature midi controller such as Keith McMillen's K-Board or Korg Nanokey2 it helps with practice inside of a workplace cubicle when you need a break (I'm a software engineer). Because they don't really look like standard piano keyboards, and are so tiny, nobody really notices. Funny I was practicing sevenths right when you wrote this question.
Comment: I have a few cheatsheets of harmonic sequences to practice. Ascending/descending chromatically is just one of them. These seventh chord patterns I'm trying may have some application in jazz, but I was thinking more along the lines of Satie and Debussy or neoclassical stuff.
Comment: @MichaelCurtis sequences are really cool. I heard alot about them from classical improvisation videos I've seen. but I haven't found much videos on them.
Answer: This is effective 100% as long you are reflecting what you're playing. When it becomes fully autmatisized it could be hindering the development of harmonic understanding. The controlling can be by audtive or notation or the abbreviation vor the chords.


How to Create a XMPP Chat Client in Android with Openfire?

Question: I am a newbie to Android. I wanted to create a XMPP chat client along with push notifications. I have installed openfire and the server is ready for testing on my local machine.
At this point what I am doing
1. Creating a XMPP connection in ASYNC task
2. onPost creating a chat manager
<code>protected void onPostExecute(final Boolean success) {
        if (success) {
            if (connection != null) {
                chatManager = connection.getChatManager();
                Chat newChat = chatManager.createChat("shobhit",
                         new MessageListener() {
                            public void processMessage(Chat chat, Message message) {
//Do something
                            }
                        });
            }
        }
    }
</code>
But I am totally confused if I am doing this is correctly. I read somewhere on stackoverflow that ASYNC should be used only for small duration activities and my connection can get timed out here.
I also found these as probable solutions:
Runnable, Handlers
Create a Service
Broadcast receivers
I am not sure which method should I opt. Can you guys suggest the optimum method and pointers to the example of that would be great?
Thanks
Chetan
Answer: As you said,  ASYNC should be used only for small duration activities.
Assuming that you use some version of Asmack in Android, the connection has to be in a separate thread from the activity (as a networking process) so you have to use a new thread/runnable for the connection to XMPP server. Asmack use its own threads after that, but you shouldn't worry about it.
With this template, you can create simple application which may be killed anytime by android.
If you want something to resist long-time, you should use a service for the XMPP part
Answer: Use AsynTask to create connection, In android all network related task should be different thread than UI thread so call it from doInBackground() method. If you want to keep the connection for long time put it in service.


How to programmatically get the difference between two entities of same content type?

Question: I need to implement a function that checks if there has been a change from the previous existing node. If yes, send the updated changes.
I understand that Drupal has revision system and through diff we can see the difference between two revisions.
I want similar to that, however as an API call or a logic which can facilitate getting the difference.
Comment: Could you clarify your question? "If yes, send the updated changes" Send to where? Have you tried something so far? Could you paste your code?
Comment: Tried something, but I am convinced that drupal does it better as it has a way to get difference across revisions. Tried looking for it but could not find the exact documentation on that.
Answer: Either look at:

https://www.drupal.org/project/diff
https://www.drupal.org/project/html_diff

To easily "see" if changes exist. Or look at Migrates module track_changes implementation and implement it in code between revisions. All track_changes does is hash the fields of a content type together to get a unique ID. Different revisions of a node with changes between the body field will of course hash to a different value. Be sure to exclude node fields such as NID, vid, updated_at and other fields that (may) chnage between revisions.
Sample hash code from class MigrateSource:
// When tracking changed data, We want to quietly skip (rather than
// "ignore") rows with changes. The caller needs to make that decision,
// so we need to provide them with the necessary information (before and
// after hashes).
if ($this->trackChanges) {
    $unhashed_row = clone ($row);
    // Remove all map data, otherwise we'll have a false positive on the
    // second import (attempt) on a row.
    foreach ($unhashed_row as $field => $data) {
      if (strpos($field, 'migrate_map_') === 0) {
        unset($unhashed_row->$field);
      }
    }
    $row->migrate_map_original_hash = isset($row->migrate_map_hash) ?
      $row->migrate_map_hash : '';
    $row->migrate_map_hash = $this->hash($unhashed_row);
  }
  else {
    $row->migrate_map_hash = '';
  }

Answer: I wanted to know if there were any changes whenever a node gets updated. If yes, trigger the mail. The solution below works well for me (It could be improved though). I didn't try to get the exact difference, which however can be found using field_get_items() api.
$entity_old = entity_metadata_wrapper('node', $node->original);
$entity_new = entity_metadata_wrapper('node', $node);
// Fields comprising of field names array, whose changes you want to ignore
$ignore_fields_list = ignore_fields_list();
if(!is_object($entity_old)) {
  return;
}

$data = field_info_instances('node' ,$entity_new->getBundle());
$fields_list = array_keys($data);
$diff_list =  array();
foreach ($fields_list as $key => $field_name ) {
// Ignore if field name belong to ignore list
if(in_array($field_name, $ignore_fields_list )) {
  continue;
}

$old_value = $entity_old->{$field_name}->raw();
$new_value = $entity_new->{$field_name}->raw();
// If both are empty - ignore
if(empty($old_value) && empty($new_value)) {
  continue;
}
 // If one of the value is not empty compared to the other
if( (empty($old_value) && !empty($new_value) ) || (empty($new_value) && !empty($old_value))){
  // You can use field_get_items() to get the changed value.
  $diff_list[$field_name] = $data[$field_name]['label'];
  continue;
}

if(!is_array($new_value) && $new_value != $old_value) {
  $diff_list[$field_name] = $data[$field_name]['label'];
  continue;
}

if(is_array($new_value) && is_array($old_value)) {
  $diff = array_merge(array_diff($new_value, $old_value), array_diff($old_value, $new_value));
  if(!empty($diff)) {
    $diff_list[$field_name] = $data[$field_name]['label'];
  }
}
}

return $diff_list;

Answer: Amit's answer is super helpful, thanks for that. But there is one major error:
$diff =  array_diff($new_value, $old_value);
PHP's array_diff will only tell you about values that are in the first param that are not in the second param. So, if we are updating a node and we delete (instead of add) a new value i na field, array_diff will not notice this and the node will not be marked by this code as changed (assuming that is the only change).
Instead, that line should be changed to:
$diff = array_merge(array_diff($new_value, $old_value), array_diff($old_value, $new_value));
I tested this locally, successfully.
I picked up that array_merge tidbit from https://stackoverflow.com/questions/10077840/difference-between-two-arrays
I don't have enough rep to comment on the post, but I can edit it, subject to moderation, so I will do that.


Why can I easily sing or whistle a tune I've just heard, but not as easily reproduce it on an instrument?

Question: People with perfect pitch can easily reproduce a tune they've just heard on their instrument of choice.
Most trained musicians without perfect pitch can also do this, but they would have to experiment a bit first to find the correct notes.
However most people, without perfect pitch, and even without singing experience can easily sing or whistle a tune they've just heard which they haven't heard before. Or at least find it much less difficult to do so than with an instrument.
I would have thought that this is down to relative experience between the use of vocal chords and instruments. I am much more experienced in using my vocal chords to make sounds than any other instrument because I've used them for talking every day for most of my life.
However, there seems to be a contradiction in this logic because even people with no singing experience can reproduce a tune with their voice much more easily than a professional pianist can reproduce a tune by ear on the piano (without perfect pitch).
Why do I find it easier to reproduce tunes with my voice than with an instrument? Even if I am highly trained with that instrument?
Why do I have to experiment with pitches on an instrument to reproduce a tune by ear, but I don't have to experiment with pitches when using my voice?
Comment: It is not true that most trained musicians without perfect pitch have to experiment to find the correct notes (depending on what you mean by "trained"). Experienced and skilled musicians can immediately play what they hear. Untrained singers do the same thing that untrained players of instruments to: they slide pitches around until they seem to work. Experience talking is not remotely close to experience discriminating and executing accurate pitches. Really, all of your premises seem wrong to me.
Comment: Perfect or absolute pitch has little to do with the capability of being able to reproduce a tune once it's been heard.Absolute pitch is being able to hear a sound and identify what pitch, or note it actually is. Second sentence is also not accurate. Many competent musicians who rely heavily on sight-reading to play may not be able to re-play something heard. Others, who have a 'good ear' will be able to reproduce a tune accurately.You are basically talking about a single note tune, as sing/whistle is all that can be.So anyone who knows their instrument as well as their voice will find it easy.
Comment: @AlbrechtHügli - that's as maybe. Whistling or singing produces only one note at a time, so no harmony in the question, which, to my mind, is asked using flawed premises.
Comment: I don't think people with absolute pitch would think in terms of a series of note names when trying to pick out a tune, even on a familiar instrument. I don't think it's what many folk do anyway. Absolute pitch is useful to recogise what note is being heard, not categorise a string of notes. As others say, *relative* pitch is far more useful here. And although those with a.p. probably have good r.p., it's the latter they'll use more.
Comment: What instrument do you play? From my own experience I can tell you that my relative pitch was better because ai played a brass instrument as there you always have to mind the interval ... but then playing piano I improved my knowledge of harmony that helped me to derive the chords and tones I heard.
Comment: For clarification, I do mean in all examples no polytonal tunes.
Comment: @Tim, I would have thought that naming the pitch of a heard sound and playing the pitch on an instrument without experimenting to find the note would require the same skill, ie perfect pitch.
Comment: @Karl when you are trying to find a note on an instrument when you are learning a tune, you can almost always do so *relatively* to a root note or other reference. Perfect pitch might sometimes be helpful, but usually it isn't a necessary skill.
Comment: I do not agree that "most people" can "easily" sing or whistle a tune they've heard. Most people certainly can and will *try*, but actually being able to stay on pitch isn't that common. I can't tell you how many times I'm with a friend who's singing or humming something, and I can't recognize the song because they're way off key/pitch.
Comment: I think another factor here is the (relative) simplicity of the instrument's "theory of operation." For both whistling and singing, as a first approximation, it's as simple as "flex to make the pitch higher, relax to make it lower" (with your diaphragm acting as another "knob" to control volume). On something like a piano, by contrast, you have to map pitch changes to motions of your hands and fingers in space--much more difficult. This idea would predict that it should be comparatively easy to reproduce tunes on an instrument like a slide whistle too; I don't know whether that's true or not.
Answer: Voice is an 'instrument' that many people learn in almost an ideal way. We start young, and practice with it very frequently - even speaking teaches you how to control the pitch of your voice.  And because it's an instrument that everyone has, almost everyone also learns to sing in various environments, from singing rhymes in nursery school, to singing along in school assemblies or as parts of a sports crowd - not to mention those who learn in a slightly more formal way.
Voice is also an instrument we have relatively direct control over. We don't have to worry about things like finger positions - with a moderate amount of practice, most people develop a subconscious mental map of how to control their vocal cords to hit a certain note; it almost becomes like a "thought-controlled' instrument. Due to the immediacy of control, we can also adjust very quickly, so small mistakes can be corrected less noticeably than with other instruments.
Due to all these advantages that being 'built-in' to the body gives, it's true that many - perhaps most - people do have the ability to sing back a tune.
However, I think you're underestimating how good professional musicians are at reproducing tunes by ear. As per David Bowling's comment, I'd expect most professional instrumentalists to be able to play back tunes on their instrument by ear with a similar level of accuracy. It may be that they aren't able to do so with quite as little conscious thought as someone can when they are singing, but their experience with mapping heard notes to scales, and their scales to positions on the instrument, will make up for that.

Why do I have to experiment with pitches on an instrument to reproduce a tune by ear?

Probably simply because you haven't attained enough experience in reproducing tunes by ear on an instrument! To get good at this you probably need to learn from various angles. One angle would be doing some ear training exercises to help the mapping between the sound and the notion of which note of the scale; another exercise would be to practice scales and arpeggios on the instrument to reinforce the mapping between the concept of the note and the physical finger position. Practicing improvisation will also help to make your playing more instinctive. Even some quite 'passive' exercises - like noodling on the instrument while watching on TV - will help with this.
Comment: I would probably have to play a guiding note first, then I'd be able to play what I heard (relative pitch maybe?)
Answer:
I would have thought that this is down to relative experience between the use of vocal chords and instruments. I am much more experienced in using my vocal chords to make sounds than any other instrument because I've used them for talking every day for most of my life.

As you say: even not trained people are able to reproduce a tune (singing or whistling). This must have become an unconditioned reflex by our language acquisition.
In opposition to your assumptions it can be aid that some musicians become a unison with their instrument that they can play every tune they hear without reflecting (right in the same way you are able to reproduce a tune.
To the most part of people the training of solfege and relative pitch is what they need to identify the tones of a melody.
The reflection of the names of the notes you sing or whistle will be necessary to play the right tones or keys on an instrument. It will take years of practice until this may become a conditioned  reflex.
Answer: The way we produce sound with our voice is the simplest thing on earth: if you want to sing low, you open your throat as much as possible, and then gradually close it to produce higher sounds. So all you need to sing is the ability to recognize whether you are too low or too high.
On the other hand, when you play an instrument such as the piano, you can't adjust your note as fast as you'd do when singing. So if you are playing a note which is to low, you will have to make a guess on how much it is too low, and if you don't get it right away (which will probably happen) you'll have to do it again and again. This will take way more time than adjusting your throat takes.
I think this is also why when someone starts to whistle, he gets good really fast, even though he has not been practicing since being a kid.
If you play saxophone, clarinet, bassoon, trumpet, or anything that has an embouchure, try playing a song with only your embouchure, and you'll see it's not so hard (even though some do not have a huge range, like the saxophone's embouchure in which you can barely get an octave).
So yes, I'd say it's the way the voice works which makes it so easy to use.
Answer: Singing is monophonic - only one note at a time.  Piano and guitar and drums and so forth can play lots of notes at once.  each extra note will take another human to sing it.
Also, you can feel whether the note is right or not immediately when singing and quickly glissando to the proper note if you hit it wrong.  hit the wrong note on an instrument and there's usually no saving yourself - it was just wrong and there's no hiding it.
But provided your instrument is monophonic, you'll eventually get to the point where you can "sing" with it.
With instruments that can play 2+ notes at once, you will always have to "just learn and practice it"...  It's just gonna be harder because you're doing multiple things at once.
Singers have it easy (ok ok sorry sheesh).
Answer: Think about this from a computing perspective.
Voice is your built-in default output, optimized from the ground up for power-efficiency and instruction-cycle efficiency in the operating system and hardware.
Now consider replicating music on an instrument. An instrument is external hardware that was never optimized in the operating system or hardware it's being run on. In the computing world, using new peripherals either involves loading drivers (plug-ins at the operating system level) or using a program that comes with the peripherals (application-layer interface).
People with perfect pitch could be compared to having efficient operating-system level drivers for the new peripheral (instrument). Good, although slower than optimization in hardware.
Everyone else (with no perfect pitch) could be compared to using an application-layer interface (specific program) to control the peripheral (instrument). Slow and worst performance compared to OS-level drivers or hardware optimization.
Alternately consider a data-oriented perspective.
Audio input is fundamentally analog, and for purpose of discussion assume that the brain stores audio input in a simple analog format (similar to a WAV file on computer). Voice output natively accepts the same analog format, which means there's almost no processing overhead in echoing what you just heard.
Think of musical notes as a digital (logical) format - a sequence of note begin/end markers. To play an instrument, you have to run through the following algorithm. For purposes of simplicity, assume that you're only playing 1 instrument at a time.
instrument D = getCurrentInstrument().open()
P = NoteInputStream(AnalogAudioInputStream(input song), D)
while true:
  note N = P.nextNoteMarker()
  if N == null then exit
  else if N.isBegin then D.holdNoteAfterDelay(N, N.delay)
  else if N.isEnd then D.releaseNoteAfterDelay(N, N.delay)

Seems simple enough in pseudocode. But what's really going on? The complexity is in the API functions above.
getCurrentInstrument() is a function that returns a reference to the instrument in your hands. Relatively simple. The instrument.open() function is another thing entirely. This loads the drivers for the instrument - in other terms, you have to "recall" how to play the instrument. This includes mentally mapping logical notes to whatever you have to do on the instrument to produce the note (probably a reverse lookup table). If the instrument includes holding and releasing a lot of notes at the same time (like a piano), this also includes figuring out how to optimize the fingers for holding down a set of notes. Therefore, instrument.open() takes a lot of processing power and short-term memory (RAM).
AnalogAudioInputStream(audioInput) takes analog audio input and converts it into a "stream" of data.
NoteInputStream(analogInput, instrument) takes the above-mentioned analog audio stream and an instrument, extracting the notes for the specified instrument from the analog input. This step is where perfect pitch comes in, identifying the "main" instrument and mapping its frequency to logical notes in real-time.
Each note is represented as a key, octave, delay before processing, and begin/end flag that represents if the note represents a hold-down or stop-holding-down event.
Playing back the analog input over instrument: loop over the set of extracted nodes and hold/release on the instrument as dictated. Complexity of hold/release note operations depends widely on the instrument and obviously may fail if you run out of fingers or the input is ridiculous.
Answer: With your voice, you can kind of feel the notes you sing. However, on a piano or a guitar, you can't just simply feel which notes you want to play. You have to first of all know the notes on the instrument (i.e. which key on a piano is a C), what octave to play (i.e. C1, C2, C3, etc. on a piano), then which notes you have to play to reproduce the melody.
This isn't easy if you don't have perfect pitch because you can only guess which note to play.
However, if you have good relative pitch, which means you can guess notes based off of intervals, then you could better recreate the melody if you're given the starting note.
But if you don't have perfect pitch or good relative pitch, then this is a difficult process. With your voice, you can feel the notes you want to hit because it's your body and it's natural to you. But a piano or a guitar, or any other instrument, is not a part of your body and is therefore, not natural to you. So, you can only guess which notes to play.
Your relative pitch might not be well trained. You can do simple ear-training exercises, where you're given the starting note (or chord), and then a short melody is played. Then, you have to play the melody. The RCM (Royal Conservatory of Music) has good exercises to take advantage of. You can find good books called "Four Stars". You could also look up simple ear-training exercises on the internet.
Even if you're a master at the instrument, if your relative pitch isn't very accurate and you don't have perfect pitch, then that would explain why you're having a hard time.
Answer: This is a great question one that I've asked myself. And my theory is that it comes down to muscle memory. Since you were a kid you've been practicing whistling/humming so you can translate the tone that you have in your mind to your mouth right away. It's the same as singing. Most of us can sing in key with any song on the radio.
With an instrument, it's not so much about having a perfect pitch. It's just about not having that muscle memory developed so you fumble for the correct note to make that sound that you already have in your head. But the more you play, the more you practice all scales, and especially playing by ear, the more you start remembering what that note sounds like before you even place your fingers. And after awhile, with enough practice and time, you'll be able to "whistle" with your instrument. But even those with perfect pitch would need to train their fingers with their instrument to get that muscle memory to playback in realtime what they are hearing.
Answer: It looks as though no one knows why musical individuals can instantly and accurately sing or whistle any pitch from an instrument or another voice. This is true even if a group has gone a quarter tone flat. Also, a perfect match occurs even with a note from a tempered-scale tuned instrument, such as a piano. The issue there is that no set of notes can be "correct" for any key [to produce properly matched harmonics, the fifth of every chord would have to have a frequency ratio of 6/4 to the fundamental, and the third 5/4. In a tempered scale, every half step is exactly 2^(1/12)].
Although my third grade teacher confirmed that I had perfect pitch, I have avoided practicing it because that could not produce accurate pitches in an a capella group.
Answer: It might really be linked to a theory that at least some people developed - where a child at a young enough age that is trained in a particular way to get the appropriate brain (neural) pathways appropriately configured/set-up for absolute/perfect pitch feature, then the absolute/perfect pitch features may stay around with that person for a long time. Although, it is also known that some people lose absolute pitch ability in times of old age, or older age. But - ignoring this, it may well be linked to all or most humans developing pitch control of the voice from an early age - is because pretty much most of us had to develop voice language from a young age.


create json from input type array in javascript

Question: On submitting a form I am getting a form object and making object. Now situation is I have input type array, for example I have input type "Task links" on click plus sign each time I am adding new input type text up to five.
It could be three, two, five or in case I increase up to twenty in future, how I will handle it in javascript to make object, see the code below
See screenshot for better understanding
<input type="text" name="arr[]">
<input type="text" name="arr[]">

function submit_task_form (form_obj) {

    var get_form = document.getElementById(form_obj);

    var form_data = {};
    for(var i=0; i<get_form.length; i++) {
        form_data.task_link = get_form[i];
    }

Comment: [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/)
Comment: oh ya thats right just object I mean
Comment: thank you for correcting me
Comment: I just fix it above
Comment: Are you sure you want an object rather than an array. If it's an object you want, what are the keys because all you're doing at the moment is replacing `task_link` in the object each time with the link from the next input in the iteration.
Comment: Ya I know I don't want to replace the previous one I want a new key with new value if there is
Comment: any solution you suggest
Answer: It's not really clear whether you need an object or an array, so here's a couple of examples that show both. These examples are in ES6. I can rewrite them in ES5 if you're not familiar with the syntax.
Both examples assume that there is a class called link on the input elements (to differentiate them from any other inputs you might have).
<input class="link" value="sdfs" />

1) Array DEMO
Pick up the inputs and iterate over them with map:
function getLinks() {
  const links = document.querySelectorAll('.link');
  return [...links].map(link => link.value);
}

OUTPUT
[ "sdfs", "34", "min", "987" ]

ES5 syntax DEMO
function getLinks() {
  var links = document.querySelectorAll('.link');
  var arr = [];
  for (var i = 0; i < links.length; i++) {
    arr.push(links[i].value);
  }
  return arr;
}

2) Object DEMO
This utilises a data-id attribute as the key for the link values.
<input class="link" data-id="1" value="sdfs" />

This time we create an object with reduce instead.
function getLinks() {
  const links = document.querySelectorAll('.link');
  return [...links].reduce((obj, link) => {
    const id = link.dataset.id;
    obj[id] = link.value;
    return obj;
  }, {});
}

OUTPUT
{
  1: "sdfs"
  2: "34"
  3: "min"
  4: "987"
}

ES5 Syntax DEMO
function getLinks() {
  const links = document.querySelectorAll('.link');
  var obj = {};
  for (var i = 0; i < links.length; i++) {
    let id = links[i].dataset.id;
    obj[id] = links[i].value;
  }
  return obj;
}

Comment: I didnt understand the syntax
Comment: I need an object to pass it to php via ajax at the end
Comment: data: {action: "submit_task_form_with_ajax", form_data: form_data},
Comment: or I think I can assign an array of input types to the key of object
Comment: I don't know, any suggestion :)
Comment: Dear Andy is this syntax javascript, I didn't understand const, let and query Selector()
Comment: I've added the ES5 syntax that you're probably more familiar with. You can build your own AJAX object when you decide what you want your `form_data` to be.
Comment: `querySelector` and `querySelectorAll` are just different methods of getting at DOM elements, very similar to how jQuery works. https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll


Best performance for flat file source: Single Data Conversion task with multiple columns VS multiple data conversion tasks for each column

Question: I have an SSIS package for doing ETL on a schema which has say 5 columns. Each of these columns needs to be cast to appropriate data types.
I initially did all cast inside a single data flow conversion task, which made it difficult to figure out what casting failed from the error output.
I later decided to use separate data flow conversion tasks in a row, for each column.
I want to know which approach will give me a better performance?
I get all my data from flat files(pipe separated)
Comment: I agree with below - fastest might be casting them in the source SQL query
Comment: I haven't tested but I assume there is overhead for every derived column transform because each needs an input and output buffer, so at least do _all_ the conversions in one derived column transform rather than doing multiple derived columns with a single transform expression. In all of my ETL I load into a staging table full of varchar columns, fix the data there then transfer it elsewhere. I can add as much logic as I like to identify bad columns and it's much faster than transforming in SSIS
Answer: It would really depend on how much data are you processing. What are the data types are you converting from and to? At what stage in the ETL process do you need to convert the data? The fastest method might be to cast them at source (if that's possible). If the conversion is between a database to database on the same server then doing it at the database level can also be an option.
You will need some testing to identify which method suits your process best.
Comment: All data are sourced from flat files


Dictionary - using type as key and constraint it to only to certain types

Question: Is it possible, if we use a Type as key for a dictionary, to constrain that type only to specific ones? For example:
public abstract class Base
{ }

public class InheritedObject1 : Base
{ }

public class InheritedObject2 : Base
{ }

public class Program
{
    public Dictionary<Type, string> myDictionary = new Dictionary<Type, string>();
}

So from the code given above for instance i want to constraint the Type only to : Base and every class which inherits from it. Is it possible to make such a constraint?
Answer: Just create a template class that inherits from Dictionary, as so:
class CustomDictionary<T> : Dictionary<T, string>
    where T : Base
{
}

Then you can use it in your code as required:
    public void Test()
    {
        CustomDictionary<InheritedObject1> Dict = new CustomDictionary<InheritedObject1>();

        Dict.Add(new InheritedObject1(), "value1");
        Dict.Add(new InheritedObject1(), "value2");
    }

Answer: Well if you do
public Dictionary<Base, string> myDictionary = new Dictionary<Base, string>();

then only Base and its children will be able to be used as the key (in this specific case Base is abstract so only children applies).
Comment: @Maarten Given the [response of the OP to another answer](http://stackoverflow.com/questions/27795436/dictionary-using-type-as-key-and-constraint-it-to-only-to-certain-types/27795564?noredirect=1#comment43999788_27795475) I assume it is just a miscommunication about the word `Type` being used.
Comment: This is not the same. In the question an instance of a `Type` is used as a key, while in your answer any instance of type `Base` or derived of it can be used as a key. The question is about only allowing specific types as key in the dictionary, not instances of the type.


My Script for Rock Paper Scissors isn't working. Console logs: Uncaught SyntaxError: Identifier 'playerSelection' has already been declared

Question: I just started learning javaScript and my first proyect is to make a Rock Paper Scissors game that plays on the console, the code that I wrote is:
<!DOCTYPE html>

When I try to run this on the console I get
Uncaught SyntaxError: Identifier 'playerSelection' has already been declared

Why is that?
Comment: Because it has already been declared in the function arguments
Comment: Not that it's the cause of the issue, but I think "promt" (line 8) should be "prompt".
Answer: The error is very straight forward. You are passing arguments named playerSelection and computerSelection then you immediately try to declare two local variables of the same name - however, arguments are considered local variables themselves, so you are indeed duplicating. Either pass the variables to the function as arguments or declare them in the code using let, not both.
Additionally, your code is riddled with syntax errors, you definitely need to proof-read this code because it will not run even if you fix the issue you ask about in the question.
Here is an example of what you probably want:

let RPS = function playRound() {
  let playerSelection = prompt("What do you choose?", "");
  let computerSelection = Math.random();

  if (computerSelection < 0.34) {
    computerSelection = "Rock";
  } else if (computerSelection >= 0.35 && computerSelection <= 0.66) {
    computerSelection = "Paper";
  } else {
    computerSelection = "Scissors";
  }

  if (playerSelection === "Rock") {
    if (computerSelection === "Scissors") {
      console.log("You win");
    } else {
      console.log("You lose");
    }
  }
  if (playerSelection === "Paper") {
    if (computerSelection === "Scissors") {
      console.log("You win");
    } else {
      console.log("You lose")
    }
  }
  if (playerSelection === "Scissors") {
    if (computerSelection === "Paper") {
      console.log("You win")
    } else {
      console.log("You lose")
    }
  }
}

RPS()


How to get Sub Menu to right align using CSS

Question: I've been struggling with this for a while, I have a menu for my website however I am having trouble with getting it to right align. I can get the main part of the menu to align but am having problems with getting the Sub menu to do the same.
This gives me this effect:

The HTML is:

Home

Stuff

More Stuff

Suff with Sub stuff

Sub thing 1

Sub thing 2

and the CSS is: ( I realise it may be a little messy due to me messing around to try to get it to right align)
    #nav{
    height:30px;
    width:100%;
    position:relative;
    top:-60px;
    background:#5D2C2C;

}

#nav a{
    font:"Lucida Sans Unicode", "Lucida Grande",  sans-serif;
    color:#CCC;
    text-decoration:none;
}

#nav ul{
    height:20px;
    top: 5px;
    margin:0px;
    list-style:none;
    position: relative;
    text-align:right;
}

#nav ul li{
    margin:5px;
    display: inline;
    position:relative;
    height:20px;
    height:20px;
    padding-left:10px;
    overflow:hidden;

}

#nav ul li ul li{
    list-style: none;
    position:relative;
    float:left;
    width: 200px;
    height:20px;
    margin:0;
    background:#5D2C2C;

}

#nav ul li ul{
    height:20px;
    padding: 0 0px 0 0px;
    position:relative;
    margin: 0 0 0 0;
    width: 200px;
}

#nav ul li:hover{
background:#900;
overflow:visible;
}

#nav ul li ul li:hover{
background:#000;
overflow:visible;
}

any help will be appreciated
Comment: @WillPeckham #nav ul li ul {display:none;}
#nav ul li:hover ul {display:block;} http://jsfiddle.net/NNsPd/2/
Comment: Better make a 'fiddle'; it will help us to debug and also might help you to solve the problem by yourself.
Comment: Is there any chance you could create a fiddle
Comment: http://jsfiddle.net/NNsPd/1/
Comment: I've got it working ! however I was wondering the best way to get the Sub menu to hide?
Comment: @Joseph thanks for the help everything is working now!
Answer: Without seeing a fiddle, i'd probably make the following changes:
#nav ul li ul {
    position:absolute;
    top:100%;
    left: 0;
    width:200px;
}

Answer: ...or you can try using absolute positioning for the sub element like:
#nav ul li ul{
     position:absolute;
     right:0px;
     top:25px;
 }

Answer: Try using float:right in #nav ul li ul
Answer: This is what worked for me
.dropdown-submenu {
    position: relative;
    z-index: 1100;
    padding: 0 1em;
}

.dropdown-submenu > .dropdown-menu {
    position:absolute;
    top:0;
    left: 100%;
    width:200px;
}


Two problems I can't solve when parsing the text how do i parse to the other way from right to left too?

Question: This is the class that do the parsing:
public static string[] ParseText(string text, int startPos, int endPos)
{
            List<string> parsedText = new List<string>();
            string[] entries = null;

            if (startPos >= 0 && endPos > startPos)
            {
                string images = text.Substring(startPos + 1, endPos - startPos - 1);
                entries = images.Split(new[] { ',' });
                for (var i = 0; i < entries.Length; i++)
                {
                    entries[i] = entries[i].Replace("\"", "");
                }

                for (int i = 0; i < entries.Length; i++)
                {
                    parsedText.Add(entries[i]);
                }
            }
            return entries;
}

And in Form1:
private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
{
            if (e.Button == MouseButtons.Left)
            {
                if (mouseisup == false)
                {
                    textBox1.Text = "";
                    positionToSearch = richTextBox1.GetCharIndexFromPosition(new Point(e.X, e.Y));
                    richTextBox1.SelectionStart = positionToSearch;
                    textBox1.Text = richTextBox1.Text.Substring(positionToSearch, 1);
                    previousChar = positionToSearch;
                    textBox2.Text = "";
                    mouseisup = true;
                }
                else
                {
                    currentChar = richTextBox1.GetCharIndexFromPosition(new Point(e.X, e.Y));
                    if (currentChar > previousChar + 1)//currentChar < previousChar - 1)
                    {
                        richTextBox1.SelectionStart = currentChar;
                        textBox2.Text = richTextBox1.Text.Substring(currentChar, 1);
                        button1.Enabled = true;
                    }
                    mouseisup = false;
                }
            }
}

private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
{
            if (textBox2.Text == "")
            {
                mouseisup = true;
                button1.Enabled = false;
            }
}

private void button1_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;
        string[] text = Parse_Text.ParseText(richTextBox1.Text, positionToSearch, currentChar);
        for (int i = 0; i < text.Length; i++)
        {
            richTextBox2.Text = text[i];
        }
    }

What it does now if I have a text in the richTextBox1 for example:
Daniel is greater > the the smaller < then >> higher is < Daniel

So if I click first time on the first D then I click on the second D
The text in richTextBox2 will be:
aniel is greater > the the smaller < then >> higher is <

If I click on i and then on >
So the text in richTextBox2 will be now:
s greater

Until this point everything is working good.
The problem is when I click backward for example I click on the last D of Daniel
And then i click on D of the first Daniel.
Then im getting exception in the new class since :
if (startPos >= 0 && endPos > startPos)

And then thevariable entries is null.
How do i handle this case when i try to parse backward ? In Form1 i tried some thing but i check if textBox2 is empty and set the bool to true something here stuck me.
private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (textBox2.Text == "")
            {
                mouseisup = true;
                button1.Enabled = false;
            }
        }

Since textBox2 is empty it will be always true.
But i need to check if text is null the variable text is null then do something:
private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            string[] text = Parse_Text.ParseText(richTextBox1.Text, positionToSearch, currentChar);

If i check here if text is null and then textBox2 is empty then it will be true all the time the bool variable.
Second problem is if I want to allow the user to parse from right to left ?
If I mark the first D and the last D its ok.
But if first i click on the last D and then the first D its returning null.
So the two problems:

How to handle the null entries variable if the code is as it is now? If it is null I want that the user will be start over again.
If i want to change the code and allowed to parse from right to left ? What should I change in the new class code ?

EDIT**
public static string[] ParseText(string text, int startPos, int endPos)
        {
            List<string> parsedText = new List<string>();
            string[] entries = null;
            int tempPos = 0;
            if (startPos > endPos)
            {
                tempPos = startPos;
                startPos = endPos;
                endPos = tempPos;
            }

            if (startPos >= 0 && endPos > startPos)
            {
                string images = text.Substring(startPos + 1, endPos - startPos - 1);
                entries = images.Split(new[] { ',' });
                for (var i = 0; i < entries.Length; i++)
                {
                    entries[i] = entries[i].Replace("\"", "");
                }

                for (int i = 0; i < entries.Length; i++)
                {
                    parsedText.Add(entries[i]);
                }
            }
            return entries;
        }

This is the button click event:
private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            string[] text = Parse_Text.ParseText(richTextBox1.Text, positionToSearch, currentChar);
            for (int i = 0; i < text.Length; i++)
            {
                richTextBox2.Text = text[i];
            }
        }

Comment: In `button1_Click` some code is missing.
Comment: In button click i should check for text if its null ? Tried but what to do if its null ? I want that if its null it will be like a reset so if i click on a char to the left it will add it to textBox1 and will start all over again. But since i keep clicking on the left to the left its null all the time. And since textBox2 is empty then the bool mouseisup will be true .
Comment: Current code will not compile because the variable `i` is missing in `button1_Click`. Also, last line of code is nested in braces, but is not in any kind of if-for-while-using-try statement, which is suspicious. Like some code is missing.
Comment: Dialecticus for some reason it didnt copy the complete button click event code. Im updating it now.
Answer: The answer to 2 is pretty simple, if the startPos is greater than the endPos then swap them
if(startPos > endPos)
{
    tempPos = startPos;
    startPos = endPos;
    endPos = tempPos;
}

Also do you realise in your button click you're only ever showing the last element in your parsed text. If you want to show them all on separate lines you could change it like follows
private void button1_Click(object sender, EventArgs e)
{
    button1.Enabled = false;
    string[] text = Parse_Text.ParseText(richTextBox1.Text, positionToSearch, currentChar);
    richTextBox2.Text = String.Join(Environment.NewLine, text);
}

Comment: Kev i updated my question with your answer what i did i guess its wrong. Can you show me how ot do it ?


nohup command could not generate the nohup.out file by rundeck job

Question: My rundeck job execute a simple nohup command "cd /tmp/; nohup ls -l &". the job execution log will get the command output but not generate the nohup.out file in that directory.
i used all kind of steps in rundeck workflow. all couldnot generate the nohup.out file.
Do anyone have any idea why rundeck couldnot generate the nohup.out file but send the command output to the execution logs?? thank
Answer: You didn't seem to redirect the output to a file, nohup works fine in RunDeck from my experience.
cd /tmp/; nohup ls -l > /tmp/nohup.something

Answer: I have a working theory: nohup is being consumed/interpreted by the Rundeck infrastructure and interpreted approximately as: 'run this job indefinitely in the background' without our usual understanding of 'with output to a non-tty' (i.e. both stdout/stderr to nohup.out or piped together to file).  Or at least, I am fairly certain it is not executing the version of nohup that is on my path.
Thus:

you should manually redirect all of the output (stdout and stderr) to file unless you are content to let Rundeck capture it
you do not need the &, although it does not hurt anything

In my case, I translated from:
cd tools/celery && nohup ./start.sh flower > log_name.txt &

to:
cd tools/celery && nohup ./start.sh flower > log_name.txt 2>&1


Value of a function expressed as infinite summation

Question: $f(x) = \Sigma_{n=1}^{\infty}b_nsin(nx) \ \forall x \in R$, where $R$ is the set of real numbers.
$b_n = \int_0^\pi 2e^{-4y}sin(ny)dy$
Find $f(\pi)$.
I think the answer is $0$, since
$sin(n\pi) = 0\ \forall n \in N $ where $N$ is natural numbers. So if we add $0$ how many times as we want, we'll get $0$ only. So is my answer correct?
Answer: You are correct.
For all $n \in \Bbb{Z}$ we have $b_n \in \Bbb{R}$ and $\sin(n\pi) = 0$ hence $b_n \sin(n\pi) = 0$. Therefore the series representation for $f(\pi)$ is
\begin{align*}
f(\pi) &= \sum_{n=1}^{\infty} b_n \sin(n\pi) \\
       &= \sum_{n=1}^{\infty} 0 \\
       &= 0
\end{align*}
In effect, the sequence of partial sums of the series $\displaystyle \sum_{n=1}^{\infty} 0$ is the constant sequence made up of $0$s hence the value of the series is $0$ :
\begin{align*}
\sum_{n=1}^{\infty} 0 &= \lim_{m \to \infty} \sum_{n=1}^{m} 0 && \text{by definition}\\
&= \lim_{m \to \infty} 0 && \text{finite sums of $0$s are $0$}\\
&= 0
\end{align*}


xargs does not seem to separate parameters

Question: I am trying to use xargs to set secrets in github using the gh CLI.
Given I have an .env file with the following entries
SECRET1=djfjgdfkjg
SECRET2=jbnfdgjn
SECRET3=A line of text

And the sed command sed -r 's/^([A-Za-z0-9_]*)=(.*)$/\1 -b "\2"/g' ./.env produces the following output:
SECRET1 -b "djfjgdfkjg"
SECRET2 -b "jbnfdgjn"
SECRET3 -b "A line of text"

I am unsure as to why the command:
sed -r 's/^([A-Za-z0-9_]*)=(.*)$/\1 -b "\2"/g' test.env | xargs -I {} gh secret set {}
fails for each secret with the message secret name can only contain letters, numbers, and _
Manually running gh secret set SECRET1 -b "djfjgdfkjg" works without an error.
I'm guessing that the issue is that the first arg (secret name) is being passed the value SECRET1 -b "djfjgdfkjg" rather than just SECRET1 but I'm unsure how I can fix this?
Comment: Usually, when a command is run correctly from the command line, but not from a script, the problem could come from losing the quotes. Since we can't reproduce your problem, for not having access to the command `secret`, we only can guess that you could add a backslash (or maybe two) before the quotes: `sed -r 's/^([A-Za-z0-9_]*)=(.*)$/\1 -b \\"\2\\"/g' ./.env`.
Answer: After doing a bit more digging I discovered that the problem is the use of -I and that:
sed -rn 's/^[[:space:]]*([[:alpha:]][[:alnum:]_]*)=(.*)$/\1 -b "\2"/p' .env | xargs -n 3 gh secret set

resolves the problem.


adding panel to select field in content type

Question: I created a content type for a new block. One of the fields in this needs to pull in category information from a magento site. I have code to get all of the categories and display them in a drop-down working in a panel template.
The only step I am missing is know how to access this as a field in my new content type. I have read some articles about using something called hooks for this process but I'm not fully sure about how they work.
Is a hook the best method and if so what exactly does it involve programmatically?
Comment: Do you mean ctools content types? In your edit form you need to save the value which later will be available in $conf, for a full explanation see this page for example http://www.pixelite.co.nz/article/building-custom-content-panes-aka-ctools-content-types-panels-3-and-drupal-7
Comment: It's just a regular content type. I don't think ctools content types is suitable for what I'm trying to do.
Comment: I would create a textfield in your content type. Then use hook_form_alter to change the textfield into a select field. I would use a textfield instead of list(text) because your allowed values will change depending on the response from the other site. Check out https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7 you need to change the form elements #type and add #options
Answer: As mentioned in one of the comments I used the hook_form_alter but instead of pulling in the panel I just created another function to get the information and used that as the options for my select.
<code>  function gacms_magecp_content_type_edit_form($form, &$form_state) {

   $conf = $form_state['conf'];
   $categories = gacms_magecp_categories();

    $form['magecp'] = array(
     '#type' => 'select',
     '#options' => $categories,
     '#title' => t('Mage Category Product'),
     '#default_value' => isset($conf['magecp'])?$conf['magecp']:'',
     '#format' => isset($conf['format'])?$conf['format']:'full_html',
    );

    return $form;
  }

   function gacms_magecp_categories(){
    db_set_active('magento');

    $result = db_query("SELECT entity_id, name FROM catalog_category_flat_store_1");
        while ($row = $result->fetchAssoc()) {
           $content[$row['entity_id']]= $row['name'];
        }
        db_set_active();
        return $content;
    }
</code>


Show that $\alpha(s)$ is a unit speed curve

Question: The question I am working on is the following:
Show that $\alpha(s) = (5/13 \cos s, 8/13 - \sin s, -12/13 \cos s)$ is a unit speed curve.
So my working is:
$\alpha'(s) = (-5/13 \sin s, -\cos s, 12/13 \sin s)$
$| \alpha'(s)| = 1$.
But my textbook says that a curve $\alpha$ is a unit speed curve if $|d\alpha/dt| = 1$ not $| d\alpha/ds | = 1 $.
I am really confused. What am I getting wrong?
Comment: Could you show a screenshot of the textbook? I think they assumed $\alpha$ as a function of $t$ there....
Answer: For a vector-valued function $\alpha(\cdot)$ writing it as $t\mapsto\alpha(t)$ or as $s\mapsto\alpha(s)$ are mathematically the same thing. There is a slight semantical (or mathematic-sociological) difference: If you use the letter $s$ as variable you tacitly claim that $|\alpha'(s)|=1$, and if you use some other letter this tacit understanding is absent. In the case at hand it was appropriate to use the letter $s$, since your calculation shows that indeed $|\alpha'(s)|=1$.


How to increase/decrease number when Press the button?

Question: I have two buttons: 1 and 2. The button 1 is used to increase a number from 0 to 15 and button 2 is used to decrease, with input is the current value of the number to 0.
Assume that initial value of the number is =-1. Then I press the button 1,  the number will increase to 1 value (0). If I press 5 times, the current number value is 4. Then I press the button 2, the values will decrease from 5
For example,
Button 1 press                         Button 2 press
0
1
2
3
4
                                               4
                                               3
                                               2
                                               ...

If the value is smaller than 0, then set button 2 is disabled, if the value is bigger than 15, set button 1 is disabled. I used below code but it does not work well. Could you tell me what is happen?
 int number=-1;
 public void onClickBtn1 (View v)
    {
        number++;
        btn2.setEnabled(true);
        if(number>=16) {
            number = 16;
            btn1.setEnabled(false);
        }

        if(number<=15) {
            Log.d("TAG", number);
        }
    }
    public void onClickBtn2 (View v)
    {
        btnTop.setEnabled(true);
        number--;
        if(number<=-1) {
            number =-1;
            btn2.setEnabled(false);
        }
        if(number>=0) {
            Log.d("TAG",number);
        }
    }

Update: Now, I can print as 0 to 5 (press button 1) and (5 to 0) when press button 2. But the code look complex and the button disable does not work when the number is over than 15 (<=16), and less than 0(>=-1)
My code is
int number=-1;
 public void onClickBtn1 (View v)
    {
        btn2.setEnabled(true);
        if(number<=-1) {
            number =-1;
        }
        number++;
        if(number>=16) {
            number = 16;
            btn1.setEnabled(false);
        }
        if(number<=15) {
            Log.d("TAG",number);
        }
    }
    public void onClickBtn2 (View v)
    {
        btn1.setEnabled(true);

        if(number<=-1) {
            number =-1;
            btn2.setEnabled(false);
        }
        if(number>=16) {
            number = 15;
            btn1.setEnabled(false);
        }
        if(number>=0) {
            Log.d("TAG",number);
        }
        number--;
    }

Comment: What error do you get?
Comment: Define 'does not work well'
Comment: The number show does not as my expected. It show 0....4 and 3..2...
Comment: I think it is from number --;
Comment: Are you saying that if the last number printed was 4, and you press button 2, you want it to print 4 again before it starts decreasing?
Comment: Right. It is exactly what I need. And the button enable and disable when number over 16 and 0
Comment: Then just move your `if(number>=0){...}` before `number--;`. But I don't understand why do you need that. Your code decrements the `number` variable when button2 is pressed then it compares it to 0 and executes code inside of `if`
Comment: Then just move the print line to before the decrement line in `onClickBtn2`, and it will work swimmingly.
Comment: @DavidWallace: Print line must be end sir
Comment: No, really it doesn't.
Answer: Here is simple logic.
Button add, remove;
TextView value;
int temp = 0;
int lastClicked = -1;
int ADD = 1;
int REMOVE = 2;

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (lastClicked == REMOVE) {
                lastClicked = ADD;
                return;
            }
            if (temp < 15) {
                temp++;
                add.setEnabled(true);
            } else {
                temp = 15;
            }
            if (temp == 15) {
                add.setEnabled(false);
            }
            if (temp > 0) {
                remove.setEnabled(true);
            }
            lastClicked = ADD;
            value.setText("" + temp);
        }
    });
    remove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (lastClicked == ADD) {
                lastClicked = REMOVE;
                return;
            }
            if (temp > 0) {
                temp--;
                remove.setEnabled(true);
            } else {
                temp = 0;
            }
            if (temp == 0) {
                remove.setEnabled(false);
            }
            if (temp < 15) {
                add.setEnabled(true);
            }
            lastClicked = REMOVE;
            value.setText("" + temp);
        }
    });

it should be enough for your issue.
let me know if any issue.
Comment: It is still from 0 to 5 when press button 1 and 4 to 0 when press button 2, instead of 5 to 0
Comment: I think you are understand what I need. However, when I press the button 2, the start value is still 4 to 0 instead of 5 to 0. You can download my code at https://www.dropbox.com/s/scvlzpjrcyzo36g/TestIncrease.zip?dl=0
Comment: I have updated code just 10 min ago. It works for 0 and 15. Not 1->4 and 4->1. unless you replace 15 with 4. I'll have look at your code.
Comment: Again Please check I've updated code to work with any number from 0 to 15.
Comment: Right, It is from 0 to 15 now. But the second button does not from a highest value when it decrease. For example, I am in 5, then press second button, it must show 5 and decrease from 5. You are 0,4,...
Comment: Just use two textview as my code to see what is happen.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/123513/discussion-between-deardhruv-and-user8430).
Answer: I think this is what you want to achieve. Try this.
public void onClickBtn1 (View v)
{
    number++;
    btn2.setEnabled(true);

    if(number==15) {
        btn1.setEnabled(false);
    }

    Log.d("TAG", number);
}

public void onClickBtn2 (View v)
{
    btn1.setEnabled(true);
    number--;
    if(number==0) {
        btn2.setEnabled(false);
    }

    Log.d("TAG",number);
}

Comment: It is not correct. It is from 0 to 5 but press button 2 is from 4 to 0 instead of 5 to 0
Comment: Of course thats how it works. When you press minus it should display 4 because 5-1 = 4. Its like from 100volume you press volume down, it doesnt display 100. It displays 99. Set your `number=0;` Hope that helps
Answer: public class MainActivity extends AppCompatActivity {
int number = -1;
int total;
Button plus, minus;
TextView textViewTotal;
private static String TAG="MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    plus = (Button) findViewById(R.id.btn_plus);
    minus = (Button) findViewById(R.id.btn_minus);
    textViewTotal = (TextView) findViewById(R.id.total);

    plus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            total = number;
            if(number == 15) {
                plus.setEnabled(false);
            } else {
                number++;
                plus.setEnabled(true);
                textViewTotal.setText(String.valueOf(number));
            }
            if (number > 0) {
                minus.setEnabled(true);
            }
        }
    });

    minus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            total = number;
            if(number < -1) {
                minus.setEnabled(false);
                plus.setEnabled(true);
            } else {
                minus.setEnabled(true);
                plus.setEnabled(true);
                number --;
                textViewTotal.setText(String.valueOf(number+1));
                if (total == number) {
                    number--;
                    textViewTotal.setText(String.valueOf(number));
                }
            }
        }
    });
}

}
Answer: As far as I understood your question following may be the solution
global variables
public final String BUTTON1 = "button1", BUTTON2 = "button2";
TextView button2;
int number = 0;
String lastButtonClicked = "button1";

and your buttonClickListeners
button1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        button2.setEnabled(true);
        if (lastButtonClicked.equals(BUTTON1) && number < 15)
            number++;
        lastButtonClicked = BUTTON1;
        if (number == 15) {
            button1.setEnabled(false);
        }
        Log.d("TAG", "" + number);
    }
});
button2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        button1.setEnabled(true);
        if (lastButtonClicked.equals(BUTTON2) && number > 0)
            number--;
        lastButtonClicked = BUTTON2;
        if (number == 0) {
            button2.setEnabled(false);
        }
        Log.d("TAG", "" + number);
    }
});
button2.setEnabled(false);
Log.d("TAG", "" + 0);

Comment: No, this has the same problem as the other two answers here.
Comment: @indramurari: I was busy. I am checking
Comment: @indramurari: My number start from 0. when click the button 1. Your code is from 1
Comment: @user8430 that's ok initialise number with -1
Answer: Button button1, button2;
int number = -1, initial = -1;

button2.setEnabled(false); // initially setting button2 disable

button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(number < 15) {
                number++;
            }
//this is because: If the value is smaller than 0, then set button 2 is disabled -> enabling if > 0
            if(number > 0) {
                button2.setEnabled(true);
            }

            if(number == 15){
                button1.setEnabled(false);  //because of range: from 0 to 15
            }

        }
    });

button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            button1.setEnabled(true);

// below condition is for: (Then I press the button 1, the number will increase to 1 value (0). If I press 5 times, the current number value is 4. Then I press the button 2, the values will decrease from 5)

//and initial value is -1 for once, as I think you didn't need to  check it later because range is 0-15 but initially you are taking -1.

            if(initial == -1){

                number = number - initial;
                initial = 0; // changed the value
            }

            if(number > 0) {
                number--;
            }

//as your range is 0-15, so can't be less than 0

            if(number == 0){
                button2.setEnabled(false);
            }
        }
    });