Databinding for ExtJs Combobox from Database(Sql)

Question: How to bind data to ExtJS combo from sql database
(how to assign datatable for extjs combobox as a store)
Answer: basic example should be like this:
<code>var combo = new Ext.form.ComboBox({
  typeAhead: true,
  triggerAction: 'all',
  store: new Ext.data.JsonStore({
    reader: new Ext.data.JasonReader ( {
       fields: [ 'myId', 'displayText' ],
       root: 'rows'
     }),
     proxy: new Ext.data.HttpProxy ( {
       url: 'path/to/your/script.aspx'
     } )
  valueField: 'myId',
  displayField: 'displayText'
});
</code>
where /path/to/your/script.aspx returns data like this:
<code>{"success":true,"total":4,"rows":[
  {"myId":"1","displayText":"Option 1"},
  {"myId":"2","displayText":"Option 2"},
  {"myId":"3","displayText":"Option 3"},
  {"myId":"4","displayText":"Option 4"}
]}
</code>


Disable submissions basing on a form element value/selection

Question: I know I can turn submissions being saved in the database either on or off completely.
Is there a way I can avoid the submission is saved basing on the value selected for a form element, for example a Yes/No radio button?
Answer: You can use a WebformSettingsHandler to conditionally disable the saving of results.
Comment: Hi Jacob,
Thanks heaps for this. However, when I implement this, though the submissions are not appearing in the results view, but the count seems to be affected.
The next submission (that should be saved) does have the serial number jumped by the numbers of submissions not saved as well.
So, if last submission is No. 19, I then tested two submissions that should not have been saved, then I submitted one that should be saved but it appears with No. 22 in the view rather than the 20th submission.
Is this also fixable, otherwise it can create confusion for proper order count.
Please advise.
Comment: I can confirm that the serial incrementing is an unexpected behavior. Feel free to create a ticket in the webform module's issue queue.  This might be something we can't fix because people might be relying on this behavior. Still, it would be possible to provide a simple patch.
Comment: Thanks Jacob.
I shall.
Comment: Raised - https://www.drupal.org/project/webform/issues/3259055#comment-14377068.


Are random samples from a markov chain independent samples from the target distribution?

Question: When doing MCMC, samples are not independent. The normal strategy is to retain every Nth sample for some N. The result samples should be samples from the target distribution.
What if we kept all the samples and then at the end randomly (uniformly) sampled from those?
Would we be sampling from the target distribution?
Answer: So you have a Markov chain $M$, which converges to some stationary distribution $\mu$.  This means that $x^TM^t\approx \mu$ when $t$ is large enough. When you run MCMC, you first have to wait for convergence to the stationary distribution. After it converges sufficiently, you sample your first point. It sounds like you're suggesting to uniformly sample from the set of points you get after sufficient convergence. This would work, so long as you have plenty of samples. This is because any finite recurrent Markov chain will spend $\mu_i$ proportion of time in state $i$, so picking a point uniformly at random is equivalent to sampling from the stationary distribution. However, your samples will always be a little correlated, since if you pick two samples that occur one after the other, they are definitely correlated.
Comment: Ok, so it sounds like asymptotically both methods give you independent samples. In the non-conventional second method, the probability of selecting samples that are close to each other (with regards to the order specified by the chain) is low.  The danger of correlation is there in both methods if the number of samples is not large enough.  In retrospect, this seems self-evident. In fact, both methods may actually be equivalent in some sense. Or the second method might be considered a generalization of the conventional method. E.g/ we can add a second layer to the process of chain generation.
Comment: (continued). For each step in the chain generation process, we can with probability (for example, .001) keep the sample.  This would be a stochastic version of "keep every Nth sample"
Comment: Regarding the previous comment: this method results in a Binomial distribution over the samples rather than a uniform distribution.
Comment: you would be better off following the general practice of thinning (i.e. picking *evenly spaced* samples/samples spaced as far apart as possible), as this will generally have lower expected correlation than uniform/independent sampling.


Passing multiple data values from one JSP to another

Question: I want to pass data in multiple rows belongs to the same column id from one JSP page to another.
When i use request.getParameter("Name of the column id") it retrieves only the first row.
How can i get values entered into all rows to my second JSP page?
Answer: You can use request.getParameterValues("name") to get a String[] with all values (not just the first one.


Copiar string partindo de determinado caractere

Question: Estou desenvolvendo um programa em C, que irá trabalhar com 02 arquivos .txt
O primeiro arquivo, é um relatório, que sai direto do sistema, e nele estão informações como código do item, localização e quantidade em estoque, essas informações estão na mesma linha...
O código dos produtos, ocupa no máximo os 14 primeiros caracteres da string, e usei o seguinte código para retirar ele do .txt:
memcpy( cod, &c[0], 14);
cod[15] = '\0';

Porém, na continuação da linha, tenho mais informações que queria alocar em outras variáveis, para passá-las para o segundo arquivo .txt, o qual eu usarei como saída para uma impressora Zebra.
Como eu faço para acessar os caracteres da posição 15 em diante, e copiá-los para uma variável?
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente).
Answer: Você está no caminho certo. Não começou pegando a posição 0? Como quer pegar da posição 15 em diante, use ela. Como quer que vá até o fim, deve pegar o sizeof do texto todo e subtrair os 15 que deseja descartar.
#include <stdio.h>
#include <string.h>

int main(void) {
    char texto[] = "1234567890abcdefghijklm";
    int posicao = 15;
    int final = sizeof(texto) - posicao;
    char parte[final];
    memcpy(parte, &texto[posicao], final);
    printf("%s", parte);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Se a string não tiver o tamanho conhecido em tempo de compilação, precisaria usar um strlen() para descobrir seu tamanho. Ou strnlen() se não puder confiar que a string está bem formada.
No lugar de &texto[posicao] pode usar texto + posicao já que texto é o endereço da string, só precisa somar o número de elemento nele. Na verdade o [] é apenas açúcar sintático para essa operação aritmética de ponteiro.
Comment: Não é bem assim, concordo que há casos que precisa tomar cuidado, mas nem sempre, há exageros nesse negócio que `strlen()` não deve ser usada. Depois eu faço um adendo, tenho outras edições pra postar, não quero encavalar tudo. https://blogs.msdn.microsoft.com/larryosterman/2009/06/23/good-news-strlen-isnt-a-banned-api-after-all/
Comment: Vale notar que o "sizeof" só vai funcionar apra strings compiladas junto com o programa, como neste exemplo - nunca para dados entrados pelo usuário, ou lidos de um arquivo, ou mesmo copiadas de ma variável para outra sem tamanho pré-definido.

 Talvez seha melhor usar `strnlen` em código desse tipo - mesmo que neste exemplo funcione - por que permite que o programa seja feito de forma genérica.
Comment: @jsbueno adicionado isso. Obrigado.
Comment: (é 2017 -- vale a pena ensinar "strlen" pras pessoas, como se fosse 1985? Sabe como é...`strnlen` ajuda a prevenir "stack overflow"  :-)
Answer: Sugiro o uso de sscanf. Exemplo supondo campos de comprimento fixo 14,20,20:
#include <stdio.h>

int main(){
 char texto[] = "cod 1234567890 Joaquim da Silva    933322232";
 char a[30], b[30],c[30];
 if( sscanf(texto,"%14[^\n]%20[^\n]%[^\n]" ,a,b,c) == 3)
    printf("cod='%s' nome='%s' tel='%s'\n",a,b,c);
 return 0;
}

executando dá:
cod='cod 1234567890' nome=' Joaquim da Silva   ' tel=' 933322232'


Ansible flask tutorial unable to install

Question: I'm following this tutorial:
http://mattupstate.com/python/devops/2012/08/07/flask-wsgi-application-deployment-with-ubuntu-ansible-nginx-supervisor-and-uwsgi.html
I installed an Ubuntu image on a EC2 and trying to run playbook, I get the following error:

TASK: [install common packages needed for python application development] *****
      failed: [188.8.131.52] => (item=libpq-dev,libmysqlclient-dev,libxml2-dev,libjpeg62,libjpeg62-dev,libfreetype6,libfreetype6-dev,zlib1g-dev,mysql-client,python-dev,python-setuptools,python-imaging,python-mysqldb,python-psycopg2,git-core,nginx) => {"failed": true, "item": "libpq-dev,libmysqlclient-dev,libxml2-dev,libjpeg62,libjpeg62-dev,libfreetype6,libfreetype6-dev,zlib1g-dev,mysql-client,python-dev,python-setuptools,python-imaging,python-mysqldb,python-psycopg2,git-core,nginx"}
      msg: No package matching '$item' is available
      FATAL: all hosts have already failed -- aborting

Not sure what's wrong?
Answer: The tutorial you referenced is out of date. The syntax the Ansible playbooks use is now invalid. Try this instead
<code>- name: Install python packages
  connection: local
  hosts: 127.0.0.1
  tasks:
  - name: add nginx ppa
    apt_repository:
      repo: "ppa:nginx/stable"

  - name: install common packages needed for python application development
    apt:
      name: "{{ item }}"
    with_items:
      - libpq-dev
      - libmysqlclient-dev
      - libxml2-dev
      - libjpeg62
      - libjpeg62-dev
      - libfreetype6
      - libfreetype6-dev
      - zlib1g-dev
      - mysql-client
      - python-dev
      - python-setuptools
      - python-imaging
      - python-mysqldb
      - python-psycopg2
      - git-core
      - nginx

  - name: install pip
    easy_install:
      name: pip

  - name: install various libraries with pip
    pip:
      name: "{{ item }}"
    with_items:
      - virtualenv
      - supervisor
      - uwsgi
</code>
Comment: You need to set up the playbook also.. updated the example.
Comment: ahh figured it out, I needed to specify the servername specified in devops/hosts
Comment: I'm getting the following error with this:
ERROR: apt_repository is not a legal parameter of an Ansible Play
Comment: Make sure the indentation is correct. It should be even with `name` on the line above. `apt_repository` is a valid module so that should be fine.
Comment: but I was running via the tutorial:
ansible-playbook devops/setup_server.yml -i devops/hosts
the host is specified in devops/hosts and it's a ec2 box running Ubuntu. I cannot use localhost since I'm on Mac.


About controlling false positives

Question: Doing multiple comparisons increases the number of false positive findings. In the Bonferroni method, the adjusted critical level is $\hat{\alpha} = \frac{\large\alpha}{N}$ where $N$ is the number of tests. However, demanding this from each test increases the number of false negatives.
In the Holm-Bonferroni and FDR methods, the smallest p-values have to be likewise below $\frac{\large\alpha}{N}$. Is this some general property?
In order to control the number of false positives, when doing $N$ tests, do the smallest $p$ have to be smaller than $\alpha/N$? It seems the Holm-Bonferroni and FDR differ only with respect to the following values.
Answer: Simply put, no, it is not a general property of familywise error rate (FWER) control or of false discovery rate (FDR) control that the smallest p-value must be smaller than α/N.
The Holm-Bonferroni procedure is a "step-down" method, so the significance of each p-value depends on the lowest p-value. However, that is not the case when using "step-up" methods, such as the Hochberg procedure (for controlling the FWER) and the Benjamini-Hochberg procedure (for controlling the FDR).
For example, say you conduct 3 tests and get the following p-values: .02, .03, and .04. None of those p-values are < α/N (assuming α=.05), yet all of them would be significant using a step-up procedure such as the ones I mentioned.
Comment: Other exceptions (just to mention a FWER controlling one) would be Dunnett's test (and related test such as the one by Dunnett and Tamahane), where the threshold is a little bit higher than $\alpha/N$, weighted Bonferroni(-Holm) tests, various closed testing procedures etc. Just in case the list above may have given the impression that that the smallest p-value must be smaller than $\alpha/N$ for FWER controlling methods.
Comment: As I noted, the Hochberg method (not to be confused with the Benjamini-Hochberg method) is for controlling the FWER. But you are right that there are numerous other FWER-controlling methods that don't require p < α/N for the lowest p-value. Dunnett's is a good example.

About controlling false positives


How do I programmatically create a view whose structure is defined at runtime?

Question: I know I am able to create a view programatically here: "How do I programatically create a view?" - only this requires knowing the structure of the view (e.g. which fields / filters / relationships to use) already.
How can I dynamically create a view at runtime?  Either the view would get stored in the same place as typical views (in the views database) - or it could exist 'In code' except the code is dynamically generated.  E.g. is it possible just to create views ad hoc in hook_views_default_views()?
Comment: Yeah absolutely, the Views module isn't bothered about how you build up the objects/arrays in `hook_views_default_views()`, you can build it dynamically or statically, totally your choice
Comment: ok - but do you know if this gets cached?
Comment: I jsut checked and it does - so if I were to go down this route, I would need to be able to reset the cache somehow if my views structure changed
Comment: Exactly right, yes
Answer: Ok - no answers and I've figured out two ways to do this.
1. hook_views_default_views()
One way is to define the view in hook_views_default_views() and then to rest the cache for instance with views_invalidate_cache(). These views end up being 'in code' but not actually set.  This didn't seem like the most desirable method for my use - but might be better for some applications.
2. save the $view
Create the view e.g. $view = new view(); and fill all the fields, and then $view->save() saves it to the views database. Keeping a record of the name of the view allows you to delete it later if necessary etc.


The quartic congruence $ax^4+bx^2+c \equiv 0 \pmod {m}$ and a quadratic congruence

Question: We know that the quartic diophnatine equation $$ax^4+bx^2+c=0$$ has integer solutions if and only if the quadratic equation $$at^2+bt+c=0$$ has integer solutions. Here we set $x^2=t$
Let $m≥2$ be a positive integer. I am asking about the validity of this claim:
Claim: The quartic congruence $$ax^4+bx^2+c \equiv 0 \pmod {m}$$ has integer solutions if and only if the quadratic congruence $$at^2+bt+c \equiv 0 \pmod {m}$$ has integer solutions.
Comment: The claim in the first paragraph is obviously false. We don't know that. For example
$t^2+3t+2=0$ has integer solutions $t=-1$ and $t=-2$, but the quartic $x^4+3x^2+2=0$ obviously has no integer solutions.
Comment: I would include what you're asking in the question then. If you're asking about the validity, then the answer is no (as pointed above). From my previous comment it should be quite clear the sufficient and necessary condition is that the quadratic equation has quadratic residue solutions.
Comment: For the second statement a similar idea works. If you're mod $m$ take any two quadratic non-residues and consider the quadratic with solutions those non-residues. The quartic will have no solution. For example say $m=5$, then take $(t-2)(t-3)=t^2-5t+6$ clearly has solutions, and $x^4-5x^2+6$ won't because any solution has $2$ or $3$ as a square.
Comment: @askingquestions: I am asking if there is some sufficient and necessary conditions to get tht equivalence.
Comment: @askingquestions: Can you convert this into a clear proof.
Answer: Claim: The quartic congruence $$ax^4+bx^2+c\equiv 0 \mod m$$ has integer solutions if and only if the quadratic congruence $$at^2+bt+c\equiv 0\mod m$$ has quadratic residue solutions.
Proof: Suppose the quartic congruence has solution $x$, then $t=x^2$ is a quadratic residue mod $m$ and a solution of the quadratic. Suppose now $at^2+bt+c=(t-r^2)(t-s^2)\equiv 0\mod m$, then clearly $x=\pm r,\pm s$ are the solutions of the quartic. Done.


Cylinder geometry

Question: I want to measure the surface contour of a cylinder. I am using a laser line scanner to measure it. I am currently facing a problem with x-tilt - a misalignment caused when the measurement laser line is not parallel to the plane of rotation.
For instance, say the two points of laser line on the cylinder surface are $(x_{1},\theta_1)$ and $(x_2,\theta_2)$. If $\theta_1 = \theta_2$ then the alignment is correct. If I measure a perfectly smooth cylinder with a properly aligned sensor, z (the distance between the sensor and the cylindrical surface) as a function of x (axial length of the cylinder) would be flat line. However, if   $\theta_1 \neq \theta_2$, then z vs x would be a concave curve with peak value equal to the z_correct_aligned.
The question: How can we extract the angle by which the sensor should be rotated to ensure proper alignment when we have the curve measurement and know the radius of the cylinder?
Attached image illustrates the problem.
Answer: The laser beam when moved defines a plane. If the laser is properly aligned, the plane contains the axis of the cylinder. If it is misaligned in a way that it creates an angle with the axis, the plane it defines interescts this axis at some angle $\alpha$. Note that it is also possible to have the laser misaligned in such a way, that it defines a plane parall to the axis, but not containing it; this isn't the case you're asking about, so I won't be talking about it.
If a plane intersects the axis of a cylinder, then the crossection of the plane with the cylinder is an ellipse. It's projection on $(x,z)$ plane (which is measured) will also be an ellipse. It can be easily checked that the short axis (iun the direction $z$) of this ellipse is $R$ and the long axis (in the direction $x$) is $\frac{R}{\tan\alpha}$.
The profile you measure will be an arc of this ellipse. In a perfect situation, assuming that the maximum of the profile is at the point $(x_0,z_0)$, the profile should be given by the formula
$$ \frac{(x-x_0)^2}{R^2/\tan^2\alpha} + \frac{\big(z-(z_0-R)\big)^2}{R^2} = 1$$
that is
$$ z = z_0 + \sqrt{R^2-(x-x_0)^2\tan^2\alpha} - R$$
In a realistic situations with all possible measurement errors in the way, you don't expect full agreement with the formula, and you just need to find the value of $\alpha$ that gives the best fit. Or you can just look at $z$ around the maximum; we expect
$$ z \approx z_0 -\frac{\tan^2\alpha}{2R} (x-x_0)^2 $$
Which means that
$$ -\frac{\tan^2\alpha}{R} = z''(x_0)$$
$$ \tan^2\alpha = -R\, z''(x_0)$$
$$ \alpha = \arctan \sqrt{R\, |z''(x_0)|}$$
Fitting an ellipse to a measured profile will probably give you a better approximation for $\alpha$ than just looking at the neighbourhood of the maximum.

Cylinder geometry


Fingerstyle guitar - how to play this arpeggio?

Question: Too many notes, not enough fingers! How can I keep bass note while playing this arpeggio? ? shows the fret I cannot reach because I use index finger to play bass note. I have tried to barre index finger across frets 7 and 8 but I'm not sure if this is right approach here.

       ?
E|--10--------
B|--9----9----
G|--10-7----7-
D|------------
A|--8---------
E|------------
Comment: Keep trying with the angled barre, it is the only way to play this with the bass note sustained.
Comment: what's the source? is it from a magazine, official sheet music, on-line tab?
Comment: @Fergus I tried that, but I've got an acoustic steel string, so I found it impossible to play cleanly/without killing the D on the 3rd string.  Is it playable/clean on nylon strings?
Comment: @Fergus also, add the angled barre as an answer soon, or I'm stealing it for myself :P
Comment: @AlexanderTroup Feel free to steal it ;) I think it really comes down to how much you've practiced angled barres, the guitar (FB radius, action, string gauge etc) and to some degree your finger size/shape. I can do it comfortably on all my guitars but they are all well set up and have fret board radius (ie not classical) and I have large hands and have practiced angled barres for a few years.
Answer: I don't see any way to finger that chord other than using the index for the bass note, and I don't see any way to play the arpeggio other than using the index finger on G string fret 7, so I don't see how you could keep the bass note ringing.
If you MUSt keep the bass note and don't mind changing the octave of one of the other notes, then you could play the higher D (E string fret 10) instead of that mid D (G string fret 7), or the lower D (open D string). That way you don't even have to move your hand from the original chord position...
Answer: You could possibly use an angled barre chord, where you use your index finger on both the 8th fret on A, and the 7th fret on B.
I am aware that this is a weeeeird technique, and I'm not all that familiar with it.  I read about it in a book called Chord Chemistry by Ted Greene, and the article here even calls it the Ted Greene chord.
It is quite a tricky technique, and I think each person's individual hand proportions affects how easy they are to do, but I've asked a question to try and get some more info about them: How do you play barre chords which are at an angle?
Answer: I think the easiest (and also the most musical) way would be to leave out the high f (10th fret G string), because it's just the octave of the bass note and does not add any color to the chord. So you simply play the following chord (from low E to high E):
X 8 X 7 9 10
Then everything can ring out during the whole arpeggio (except the original high f, of course, but nobody will miss it.)


formatting of cron.allow and/or does cron need to be restarted

Question: I'm trying to setup a crontab specifically for the user that runs the web process.  I have root/sudo access so I wrote an entry for the www-data user using the -e option and here is the listing using the -l option:
<code>/etc$ sudo crontab -u www-data -l
# m h  dom mon dow   command
15,30,45 * * * * /var/www/cron/test.cli.php
</code>
The process is not running at the appointed interval however.  I'm pretty sure I have the syntax correct so this leads me to a few other possibilities
1) improperly formatted /etc/cron.allow?  I actually created this as sudo/root and all I've done is enter a line with "www-data" on it.  However, is this the correct format?  I'm having a hard time finding information on how /etc/cron.allow should be formatted, its not in the man as far as I can tell (http://linux.die.net/man/1/crontab)
2) Is /etc the correct location for cron.allow on Debian?  I googled and it mentions that it might go elsewhere under SUSE but all indications unless I'm mistaken is that under Debian /etc is the correct location.
3) Permissions for /etc/cron.allow?  I (temporarily) set them to 777, could this be too permissive?
4) Does cron need to be restarted after the creation/modification of cron.allow (or cron.deny)?
PS....since first posting this on stackoverflow (where I will now delete it) I have tried restarting cron to no avail: the task still does not run
Comment: 1) specifying (#!)/usr/bin/php would be superfluous I already begin my script that way and it runs from the command line and furthermore ....

2) I can run the task from root's crontab .... this seems to suggest that I have not properly setup the ability (via cron.allow?) for www-data to run it's own crontab
Comment: more or less identical situation (crontab for www-data user) but no solution see https://www.linuxquestions.org/questions/linux-general-1/crontab-and-process-permissions-442142/
Comment: I'm an idiot, it was a permissions problem within the script that was running.  Therefore I had actually properly setup the crontab for www-data.  Nevertheless I believe this question might be of value and will leave it stand.
Comment: It's always best to leave the questions on here, so someone in the future may benefit from what's been asked :)  Glad I could help point you in the right direction, anyway.
Answer: As Cornfed said, your .php script would have to start with #!/usr/bin/php for that to work.
1)  The cron.allow/deny files only affect a users ability to run the 'crontab' command, not the ability for a user to have a crontab.  See man crontab.
2)  Yes, also listed in man crontab.
3)  Yes, any user could add themselves to that list.  That's way too permissive.  But in most cases you do not need this file on Debian.  From man crontab:  "For standard Debian systems, all users may use this command."
4)  No, but I have noticed a delay in acceptance of new commands.  See /var/log/daemon (I think) for CRON's updating of it's internal files.
Comment: I appreciate the answer, please see the comments I've added to my question
Comment: ps....new command is accepted in a timely manner when adding to root's crontab
Comment: Thanks again, I have now actually removed the cron.allow I had previously created and crontab still runs the task for www-data, affirming what you write under #3 regarding probably not needing cron.allow on Debian
Answer: You might try "15,30,45 * * * * /usr/bin/php /var/www/cron/test.cli.php"


Is a boxplot useful, when it doesn't even look like a box?

Question: I want to visualize some data with a boxplot -- and I am wondering, if the boxplot is even the correct way for visualizing the data.
I want to compare three datasets (40 entries each) using boxplots. Basically the first two datasets are always the same numbers, the third set has only a few outliers:
<code>(geregelt: 62, 62, 62, ... 62)

(optimiert (fair): 65, 65, 65, ... 65)

(optimiert (unfair): 100, 100, 100, ... 30, 0, 0, 0, 0,)
</code>
With these data, the boxplots dont even look like boxes, just three strokes; see image:

Background:
I want to compare, how much energy electric vehicles get charged from the grid, depending on the loading strategie: controlled (geregelt), optimized (optimiert (unfair)) and optimized with constraint for fairness (optimiert (fair)).
So what I am trying to point out with these data is: with optimization the electric vehicles get charged the most, even thoug some are left without any charging. With optimization including fairness constraint, everybody gets the same amount charged. And with the controlling still everybody gets the same amount charged, but slightly less compared to the fair optimization.
actual question:
Is the boxplot the correct way of visualizing such data? Or is there a better way? Is it even useful to use boxplots when they don't even look like boxes?
Comment: A boxplot that does not look like a boxplot imposes non-needed cognitive burden on the reader, even if it is not wrong. You might consider barplots. E.g., faceted barplots.
Comment: What are the 40 columns that are all the same number?! Doesn't sounds like real data to me!?
Answer: The boxplot doesn't visualize your data effectively. (For a discussion of the advantages and disadvantages of boxplots see How should we do boxplots with small samples?
.)
Other types of graphs (except a barplot as suggested by @ Bernhard) would have trouble with you data because there is almost no variability within loading strategy; this leads to overplotting.
But since there are so few distinct values I would consider making a table instead of a graph. For example, a table with columns Loading Strategy, Target (%) and #Vehicles. Or %Vehicles since there are 40 vehicles for each strategy, so we can meaningfully compare the counts divided by 40. Rows within a table can be effectively grouped together with color highlights as well.
Answer: Visualisations need to be chosen based on the properties of the data and the message you are trying to convey. Clearly, boxplots do not communicate the distribution of this data well. Given that you have just 40 entries in each group and most values are identical, you might consider using a table, a  dotplot, or translucent histograms with appropriately chosen bin width.


OUTLOOK is telling me that the contact or group has been deleted, but that group is still in my contacts

Question: I have created a distribution group in OUTLOOk that has been working for many months.  Recently, when I go to use that group or expand the group to remove certain members, OUTLOOK alerts me with the message that "The contact or group has been deleted, and is no longer a valid address book entry," but the thing is, the group is in my address book and has not been deleted.  Am I right to understand that this can happen if a single contact from the list has been deleted from my contacts, thus making this list broken?
Answer: Yes, it can mean that a contact or a DL included by the group had been deleted. Try to open the DL and open its members one at a time until you get an error.


hook_url_outbound_alter only for links in node body

Question: I'm building a site with drafts/revisions as a major component. For now I'm using hook_url_outbound_alter to check if "/draft" is at the end of the current URL, and if so to append "/draft" to all paths. The problem is that it's also altering the Menu URLs. Is there any way that I can explicitly target links in the node body using hook_url_outbound_alter?
Comment: Thanks for the insight @Clive. I ended up using a combination of the hook and javascript: the hook to force non-aliased outbound URLs for pages with "/draft" at the end of the URL, and Javascript to append "/draft" to the appropriate links in the node content.
Comment: `hook_url_outbound_alter` responds to a request, it has no idea how that was request was invoked, much less have access to any other context...appending parameters to the URLs contained in the node body is about the only way you'd be able to pass that context through. Or do it with javascript maybe
Answer: For the googlers:
Module:
<code>/**
 * Implements hook_url_outbound_alter().
 */
function draft_links_url_outbound_alter(&$path, &$options, $original_path) {
  // Internal URLs only
  if (!$options['external']) {
    // Check if current page is draft page
    if (preg_match('|/draft(/?)$|', current_path())) {
      $options['alias'] = $path;
    }
  }
}

/**
 * Implements hook_preprocess_page().
 */
function draft_links_preprocess_page(&$variables) {
  if (preg_match('|/draft/?$|', current_path())) {
    drupal_add_js(drupal_get_path('module', 'draft_links') .'/draft_links.js');
  }
}
</code>
JavaScript:
<code>(function ($) {
    $(window).load(function() {
        $('.node__content a').each(function(){
            href = $(this).attr('href');
            // Internal URLs only.
            if (href.match(/^\/?[0-9a-zA-Z]*/) && !href.match(/^(https?:)?\/{2}/)) {
                $(this).attr('href', href+'/draft');
            };
        });
    });
})(jQuery);
</code>


Adapting Debian Sarge installation instructions (sources list) for Debian Squeeze?

Question: I'm pretty new to sysadmin, and I'm trying to install the UltraMonkey load-balancer on Debian 6.0 - Squeeze.
The installation instructions for Debian Sarge say to edit sources.list:
deb http://www.ultramonkey.org/download/3/ sarge main
deb-src http://www.ultramonkey.org/download/3 sarge main

I tried this, but when I do apt-get install ultramonkey I get Unable to locate package ultramonkey.
I then tried editing the sources to:
deb http://www.ultramonkey.org/download/3/ squeeze main
deb-src http://www.ultramonkey.org/download/3 squeeze main

But still the same issue.
Does anyone know how to adapt this for Squeeze, or is the answer basically 'You can't install UltraMonkey on Squeeze'?
Comment: A general remark only partially related to my answer: Did you issue an `apt-get update` command after editing `sources.list`? If not, apt doesn't even know about the packages from the additional repositories.
Comment: I hadn't, thanks for checking :) But I just tried it with the squeeze version of the source and got W: Failed to fetch `http://www.ultramonkey.org/download/3/dists/squeeze/main/source/Sources.gz  404  Not Found`. Then I tried editing it back to sarge, running `apt-get update` again, and got a slightly different error: `GPG error: http://www.ultramonkey.org sarge Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY XXXXX`. Do I need to do something with my public key?
Answer: Debian Sarge was 3.1, after that came 4, 5 and now 6. You shouldn't even try installing such an old package to a new system (and it's highly likely it won't work at all).
Generally, I would consider a project which has its last release in 2007 as dead and look for other alternatives.
If you insist, you will have to install it from the source code, but this is likely quite involved and nothing for a beginner.
Comment: You mean 2005. But you are absolutely right to go an alternative route.


Laravel Eloquent Self Join Parent Child

Question: Laravel Eloquent Self Join Parent Child Relationship
class Product_category extends Model
{
    //
    protected $table='PRODUCT_CATEGORIES';
    public $timestamps = false;

    public function getParentCategory() {
        return $this->hasOne(self::class, 'id', 'parent_id');
    }.

    public function getChildCategories(){
        return $this->hasMany(self::class, 'parent_id','id');
    }

I am able to retrieve all child records of table by making use of getChildeCategories but not able to retrieve Parent of particular category.
It always gives me null.
Answer: It's called one-to-many relationship, the inverse of a hasMany relationship is belongsTo method, your getParentCategory() should be:
public function getParentCategory() {
    return $this->belongsTo(self::class, 'parent_id');
}

public function getChildCategories(){
    return $this->hasMany(self::class, 'parent_id');
}

Comment: Thanks for your valuable response but it is not showing me appropriate response its giving me same record as i have given, not showing parent id record
Comment: Make sure you check on a child category, also check your database records is `parent_id` filled correctly?
Comment: Child category is working correctly but parent category does not retrieve correct response
Comment: Hmmm.. That's odd, I noticed from your question that you put two variable `(self::class, 'id', 'parent_id')` please make it exactly what you see in my answer
Comment: i have changed the function with exactly what you have specified, i want to retrieve:  suppose if particular row has parent_id as 1 then it should  give me record of id 1, that is why i have use two variables here. Is it wrong way to do?
Comment: First parameter is the model class name, the second parameter is for the foreign key of that model in your case it is `parent_id` , the third parameter is for other key: it's a column name of the value to be added as `parent_id` value on your database row, default is `id` you don't need to specify it unless you don't have `id` column.
Comment: It's also applied to `hasMany()`, except that the third parameter called local key, default value is the same: `id`.
Comment: Just wondering, what code you're using to access the parent and child category?
Comment: If you want learn more how to define one-to-many relationship, please read the [documentation](https://laravel.com/docs/5.2/eloquent-relationships#one-to-many)
Comment: Thanks for your valuable feedback.. yes you were right. code is working properly now.
Comment: Nice! Glad to hear that :)

Laravel Eloquent Self Join Parent Child


"Shortcut" to find the projection of a vector onto a subspace

Question: I understand that to project a vector $v$ onto a subspace, I must find an orthogonal basis for the subspace before projecting $v$ onto each of the orthogonal vectors and add them all up. However, for higher dimension subspaces, I find it rather cumbersome to apply the Gran Schmidt process to find the orthonormal basis.
I was wondering if there is a method to find the projection of $v$ onto a subspace?
For example:
Find the projection of $v_{1} = (-5, 3, 18)$ onto the subspace W spanned by $v_{2} = (-7, 6, 2)$ and $v_{3} = (-1, -2, 1)$
Instead of finding the orthonormal basis using the Gran Schmidt process, I simply found the cross product $v_{4} = v_{2} \times v_{3}$ and subtracted the projection of $v_{1}$ onto $v_{4}$ from $v_{1}$ to get the answer.
Are there similar shortcuts when projecting onto higher dimensions subspaces with more than two basis vectors?
Answer: What you did is actually to project $v_1$ onto the null-space of $v_2, v_3$ and deduct the projection .
You can do the same for higher dimensions and more vectors.
Answer: If the subspace is exactly $n-1$ dimensional, you can use the same trick. What you need is a generalization of the cross product. An operation that takes $n-1$ vectors of dimension $n$, and returns a single vector orthogonal to their subspace.
You write the $n-1$ vectors as row vectors of a matrix, to which you add an additional row of "free terms". Eg. in our case we have:
$$
M = \begin{pmatrix}
-7 & 6 & 2\\
-1 & -2 & 1\\
\vec{t}_{1} & \vec{t}_{2} & \vec{t}_{3}
\end{pmatrix}$$
We have: $$\det(M) = 10 \vec{t}_{1} + 5 \vec{t}_{2} + 20 \vec{t}_{3}\\
v_{2} \times v_{3} = (10, 5,20)$$
This generalizes to any number of dimensions. Ie. with $3$ vectors of dimension $4$ you can make a $M$ as a $4\times 4$ matrix.


create a custom android browser that open a url that other apps request

Question: I want to write a simple custom Android browser, like the Firefox and Chrome browsers that can be open a specific URL when other app choose my custom browser. For example, a mail app want to open a URL by sharing and then the user choose my custom browser. Or another android app runs this:
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url)); startActivity(i);

But how do my custom browser get the URL that passed from the other application?
Comment: The article here describe what I want: http://stackoverflow.com/questions/7351563/getting-data-from-an-implicit-intent
Answer: Your question isn't really clear, but if you're talking about handling intents sent from other apps to open the URL in webview this tutorial on android developers training explains it pretty well.
Comment: this is a good start as I want the general method to get the url and most text does not cover it. I still need to find where the url is stored in that intent.
Comment: It is quite hard to understand but the training documentation is very good.
Comment: My intention is to make a simple fast browser  for just one url. Not like chrome and firefox which will open unclosed past tabs, which will be very slow for some old devices.
Answer: I finally found a solution for this using intent filter:
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />

            <data android:scheme="http" />
            <data android:scheme="https" />
        </intent-filter>


Imprimir JSON.Parse

Question: Bom dia,
Tenho uma variável que armazena dados vindos de um localStorage, que por sua vez contem os dados abaixo:
Array[3]
0:"{"Token":-6742.075757575755,"Solicitacao":"3359659","Justificativa":"jjjj"}"
1:"{"Token":-57645.84848484848,"Solicitacao":"10","Justificativa":""}"
2:"{"Token":-57645.84848484848,"Solicitacao":"10","Justificativa":"asdasd"}"
length:3

Código:
    var tbHistoricos = window.localStorage.getItem("tbHistoricos");
    tbHistoricos = JSON.parse(tbHistoricos);

O que quero é imprimir o conteudo de cada linha por tag. Para cada linha eu imprimo com:
tbHistoricos[numero_que_eu_quero]

Mas não quero a linha toda, quero cada tag individual, mas da maneira abaixo não funciona:
tbHistoricos[numero_que_eu_quero].Token

Como posso fazer?
Comment: O que te dá estes logs: `console.log(typeof window.localStorage.getItem("tbHistoricos"), window.localStorage.getItem("tbHistoricos"));`?
Answer: O seu problema é porque o conteúdo de cada posição é uma string e não um objeto, por isso você não conseguiu acessar com .Token.
$ node
> var arr = [{"Token":-6742.075757575755,"Solicitacao":"3359659","Justificativa":"jjjj"},
{"Token":-57645.84848484848,"Solicitacao":"10","Justificativa":""},
{"Token":-57645.84848484848,"Solicitacao":"10","Justificativa":"asdasd"}]

> arr[0].Token
-6742.075757575755

Ai nesse caso você precisa fazer o parse de cada posição
var arr = window.localStorage.getItem("tbHistoricos");
arr = JSON.parse(arr);
arr = arr.map(i => JSON.parse(i));
console.log(arr[0].Token);

ai sim vai funcionar corretamente.

Imprimir JSON.Parse


Find $\lim_{x\to 0}\frac{(a^x-1)^3}{\sin(x\log a)\log(1+x^2\log a^2)}$

Question:
If $$f(x)= \frac{(a^x-1)^3}{\sin(x\log a)\log(1+x^2\log a^2)}$$ is continuous at $x=0$ then find $f(0)$

$$
f(0)=\lim_{x\to0}\frac{(a^x-1)^3}{\sin(x\log a)\log(1+x^2\log a^2)}\\
=\lim_{x\to0}\big[\frac{a^x-1}{x}\big]^3.\frac{x\log a}{\sin(x\log a)}.\frac{x^2}{\log a.\log(1+x^2\log a^2)}\\
=(\log a)^3.1.\lim_{x\to0}\frac{x^2}{\log a.\log(1+x^2\log a^2)}\\
=(\log a)^2.1.\lim_{x\to0}\frac{x^2}{\log(1+x^2\log a^2)}=?
$$
Can I use the fact that $\log(1+x)=x-x2/2+x^3/3-....$  but is it not for $-1<x\leq1$ ?
Comment: Does $\log a^2$ stand for $\log (a^2)$ or $(\log a)^2=\log^2a$?
Answer: We can use that
$$\frac{(a^x-1)^3}{\sin(x\log a)\log(1+x^2\log (a^2))}=\frac{(a^x-1)^3}{x^3}\frac{x^3}{\sin(x\log a)\log(1+x^2\log (a^2))}$$
and by standard limits
$$\frac{(a^x-1)^3}{x^3} \to \log^3 a$$
$$\frac{x^3}{\sin(x\log a)\log(1+x^2\log (a^2))}=\frac{x\log a}{\sin(x\log a)}\frac{x^2\log (a^2)}{\log(1+x^2\log (a^2))}\frac1{2\log^2 a} \to \frac1{2\log^2 a}$$

Edit
Yes we can also use the series expansion since $x^2\log^2 a \to 0$ and therefore eventually $0<x^2\log (a^2)<1$.
Comment: please check I have edited OP. log(1+x) can be expressed as a series for $|x|<1$ right ?
Comment: @ss1729 Yes we can also use series exapansion but in this case standard limits suffice.
Comment: it is actually $\log a^2=2\log a$. So final solution should be $\log\sqrt a$
Comment: @ss1729 Ok then I fix that!
Answer: Hint: Use the fact that $\lim_{x\to 0}\frac{\ln(x+1)}{x}=1$.
Answer: Using series expansions and $o$-notation you get for $x\to 0$:
$$\frac{(a^x-1)^3}{\sin(x\log a)\log(1+x^2\log a^2)} = \frac{(e^{x\log a}-1)^3}{(x\log a +o(x))(2x^2\log a+ o(x^3))}$$
$$= \frac{(x\log a+o(x))^3}{2x^3\log^2 a+ o(x^3)} = \frac{x^3\log^3 a+o(x^3)}{2x^3\log^2 a+ o(x^3)}$$
$$=\frac{\log^3 a+o(1)}{2\log^2 a+ o(1)} \stackrel{x\to 0}{\longrightarrow}\frac{\log a}{2}$$
Comment: @user : Yes. But the OP writes $\log a^2$ which I interpret as $2\log a$ instead of $\log^2 a$. Maybe the OP should clarify what he/she means. I know that people interpret this differently.
Comment: We have that $\log(1+x^2\log^2 a)=x^2\log^2 a +o(x^3)$
Comment: Ah ok! We can ask about that.
Comment: $\log a^2=2\log a$


What are the subfield of $\mathbb{C}$ that is $\mathbb{Q}$-isomorphic to the following

Question:
What are the subfields of $\mathbb{C}$ that are $\mathbb{Q}$-isomorphic to $\mathbb{Q}[\sqrt[6]{3}]$?

I'm guessing also 3. Itself and the 2 primitive 6th roots of unity, $e^{2\pi i/6}, e^{2\pi i\cdot5/6}$ multiplied to it.
Am I right ?
Any help or insight is appreciated
Answer: Because $X^6-3$ is irreducible over $\mathbb{Q}$, the embeddings $\mathbb{Q}[\sqrt[6]{3}] \to \mathbb{C}$ are in bijection with the roots of $X^6-3$ and so there are $6$ embeddings, corresponding to $\sqrt[6]{3} \mapsto \sqrt[6]{3}\omega^k$, for $k=0,\dots,5$, where $\omega$ is a primitive $6$-root of unity.
Let $L_k = \mathbb{Q}[\sqrt[6]{3}\omega^k]$. Because $\omega^3=-1$, we have $\omega^4=-\omega$ and $\omega^5=-\omega^2$, and so $L_0=L_3$,
 $L_1=L_4$ and $L_2=L_5$.
So, yes, you're right: there are exactly $3$ subfields of $\mathbb{C}$ isomorphic to $\mathbb{Q}[\sqrt[6]{3}]$.


iphone taking grayscale screenshot?

Question: I'm wondering if there is a SIMPLE way to take a Grayscale screenshot, i know i can take color screenshot like this:
<code>    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *data = UIImagePNGRepresentation(image);
</code>
now what i need to add in these lines of code to make the UIImage Grayscaled? thank you for reading.
Answer: Just convert your image to gray scale.
Read this post. Good luck.
Here is the method:d
<code>#pragma mark -
#pragma mark Grayscale

- (UIImage *)convertImageToGrayScale:(UIImage *)image
{
    // Create image rectangle with current image width/height
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);

    // Grayscale color space
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    // Create bitmap content with current image size and grayscale colorspace
    CGContextRef context = CGBitmapContextCreate(nil, image.size.width, image.size.height, 8, 0, colorSpace, kCGImageAlphaNone);

    // Draw image into current context, with specified rectangle
    // using previously defined context (with grayscale colorspace)
    CGContextDrawImage(context, imageRect, [image CGImage]);

    // Create bitmap image info from pixel data in current context
    CGImageRef imageRef = CGBitmapContextCreateImage(context);

    // Create a new UIImage object
    UIImage *newImage = [UIImage imageWithCGImage:imageRef];

    // Release colorspace, context and bitmap information
    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);
    CFRelease(imageRef);

    // Return the new grayscale image
    return newImage;
}
</code>
Comment: I don't now any function to to this.:D You could implement one.:D
Answer: Based on Cam's code with the ability to deal with the scale for Retina displays.
<code>- (UIImage *) toGrayscale
{
// Create image rectangle with current image width/height
CGRect imageRect = CGRectMake(0, 0, self.size.width * self.scale, self.size.height * self.scale);

int width = imageRect.size.width;
int height = imageRect.size.height;

// the pixels will be painted to this array
uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));

// clear the pixels so any transparency is preserved
memset(pixels, 0, width * height * sizeof(uint32_t));

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

// create a context with RGBA pixels
CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace,
                                         kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);

// paint the bitmap to our context which will fill in the pixels array
CGContextDrawImage(context, CGRectMake(0, 0, width, height), [self CGImage]);

for(int y = 0; y < height; y++) {
    for(int x = 0; x < width; x++) {
        uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];

        // convert to grayscale using recommended method: http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
        uint32_t gray = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];

        // set the pixels to gray
        rgbaPixel[RED] = gray;
        rgbaPixel[GREEN] = gray;
        rgbaPixel[BLUE] = gray;
    }
}

// create a new CGImageRef from our context with the modified pixels
CGImageRef image = CGBitmapContextCreateImage(context);

// we're done with the context, color space, and pixels
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
free(pixels);

// make a new UIImage to return
UIImage *resultUIImage = [UIImage imageWithCGImage:image
                                             scale:self.scale
                                       orientation:UIImageOrientationUp];

// we're done with image now too
CGImageRelease(image);

return resultUIImage;
}
</code>

iphone taking grayscale screenshot?


Inductively showing $g(s) = 3(g(s-1)+g(s-2))+1$ is odd for all $s$

Question: How would I show this equation is odd by using the induction hypothesis:
$$
g(s) = 3(g(s-1))+(g(s-2))+1
$$
I was thinking that I would prove $g(s)$ is odd by $g(s+1) = 3(g(s)+g(s-1))+1$.
How would I proceed using the induction hypothesis?
Comment: What is an "odd" equation ? $g(0)=0\land g(1)=1$ give $g(2)=4$. This is odd.
Answer: The first step is to check the hypothesis for eg. $s=0$ and $s=1$ depending on the starting condition. That is, we check if the first two values are odd.
Then we assume that $g(s)$ is odd for all $s\in\mathbb{Z}$, where $s\leq k$. This is our induction hypothesis. Like you write, we have
\begin{align*}
g(k+1)=3\big(g(k)+g(k-1)\big)+1.
\end{align*}
Can you see how we may use the induction hypothesis now?
Solution:

From the induction hypothesis, both $g(k)$ and $g(k-1)$ are odd, so $3\big(g(k)+g(k-1)\big)$ is even. Thus, $g(k+1)$ must be odd.
Comment: I can't see any starting conditions - If there were any they would have been given.
Comment: The starting conditions were g(1) = 1 and g(2) = 1
Comment: @user3472296: Then the initial step is to check that both $g(1)$ and $g(2)$ are odd (which they are).


How to insert rows in reverse order?

Question: What I'm trying to do is copy the rows of one table to another table. I have 2 choices to copy them on direct order or reverse order. I have no problem with direct order. But I couldn't insert them in reverse order. I'm trying to do it with ORDER BY DESC, but DESC isn't working with subqueries. So I'm doing it with statement. And SELECT returns me in reverse order by PRIMARY KEY. But data in DB my_db_copy inserted in direct order. How can I insert them in reverse order?
set @Query1=Concat ('INSERT INTO my_db_copy.test1 SELECT * FROM my_db.test1
ORDER BY ', (   SELECT COLUMN_NAME
FROM information_schema.COLUMNS
WHERE (TABLE_SCHEMA = 'my_db')
  AND (TABLE_NAME = 'test1')
  AND (COLUMN_KEY = 'PRI')), ' DESC');
  PREPARE stmt FROM @Query1;
  EXECUTE stmt;

Comment: What is the resulting value of `@Query1` here?  When you remove the `INSERT` clause from that resulting query and just execute the `SELECT` with its `ORDER BY`, what is the observed order of the results?  How is that different from what you're expecting?  The code you're showing us is a few steps removed from the question you're asking.
Comment: @David if I remove INSERT from set it will show the reverse order, but it won't be inserted in that reverse order.
Comment: Why do you think that?  If that's the order of the results then that's the order in which they're being used.  In what order are you later *selecting* the results of the destination table to observe them?  If you're not specifying one then no order is guaranteed.  It sounds like you're making assumptions here.
Comment: @David to see the result I select them without any order, I mean I don't do order by. what is the default order for queries without any order by?
Comment: While it's not guaranteed, the "default" order is usually very likely to be the primary key, as that's usually the clutered index and the physical order in which records are stored on the disk by the database engine.
Comment: @rdhd queries without order by return lines in any order the DBMS thinks convenient at the time of execution. It might be anything and it might even change from one execution of the query to next.
Answer: SQL tables represent unordered sets.  There is no such thing as "reversing" the order.
You can assign values to an auto-incremented column to specify a particular ordering.
If you want results in a particular order when you issue a query, then you need to explicitly include an order by.  There is no other way to guarantee a result set in a particular order.
Comment: Thank you for your answer. but if I have the table with ID 1 2 3 4 5, but if I want to copy them into another table with ID 5 4 3 2 1. How to do so?
Comment: @rdhd . . . I would suggest that you ask *another* question, with sample data and desired results.  But remember the first message here:  tables are *unordered*.

How to insert rows in reverse order?


Append to typeahead

Question: Is it possible to append some HTML to the end of a typeahead? I've tried many different things but none have worked.
What I'm trying to do is have the last result of the typeahead be Search for "< what the user typed into the input >".
Here's what I've tried on JSFiddle: http://jsfiddle.net/MgcDU/8621/
What I expected it to do was append the
 at the end of the dropdown once it's created, but it doesn't. Why?
HTML:
<input type="text" data-source="["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"]" data-items="10" data-provide="typeahead" style="margin: 0 auto;" class="span3">

jQuery:
$(".typeahead.dropdown-menu").append('
CUSTOM TEXT
');

Answer: The dropdown menu is built during the typeahead filtering process. If you inspect it "on load", you will notice it is empty.
Depending on your specific problem you're trying to solve, i can think of two possible solutions.
One solution would be to extend the typeahead plugin and provide a custom "render" function. This would allow you to modify the list rendering process and append additional
s as well as anything else you like. This is probably regarded as the "best way".
Another more hacky solution would be to place your custom value in the data source, then provide a custom "matcher" function which runs the original matcher along with an additional clause for your custom value.
Of course solutions are tied to problems and without really knowing the very specifics of what you want to do, i can't recommend which one to use. But those are your two options as far as i can think.

Append to typeahead


Que medidas podemos tomar para proteger a emissão de boletos dos malwares que alteram a linha digitável?

Question: Além de emissão em PDF, que pode dificultar alguns clientes pela falta de visualizadores de PDF, que técnicas poderíamos utilizar para proteger ou detectar que o boleto gerado foi modificado pelo malware?

Vírus que afeta boletos já infecta 192 mil computadores
Um relatório divulgado pela empresa de segurança eletrônica RSA mostra
  que pelo menos 192 mil computadores foram infectados por um vírus que
  altera a numeração de boletos bancários. Além disso, segundo a
  análise, a maioria das máquinas afetadas se encontra no Brasil.
De acordo com a RSA, o vírus é disparado por email e altera a
  numeração dos boletos bancários no momento do pagamento online,
  desviando os valores para a conta de uma gangue. A maioria das vítimas
  é da região Sudeste e já foi identificado que 75% delas utiliza o
  Windows 7 como sistema operacional. Os usuários do Hotmail são maioria
  entre os afetados pelo problema.
Segundo informações da revista Info foram gerados 496 mil boletos
  falsos, muitos deles com valores de até R$ 1,5 mil. O valor total
  estimado dos documentos fraudulentos pode chegar a R$ 8,5 bilhões. A
  RSA alerta de demora no processamento do pagamento e lentidão na
  navegação podem ser indícios que a sua máquina está comprometida.

Fonte: Tecmundo
Comment: Se entendi direito a noticia, ela fala que o número do boleto é alterado na hora do pagamento, ou seja, na hora que o cara coloca o número no site do banco, então mesmo que fosse um boleto de papel ali que o cara digitou tudo manualmente ainda seria modificado pelo malware
Comment: Na verdade o vírus altera o código html da pagina com o boleto, então mesmo que imprima e pague no caixa, vai imprimir com a linha digitavel e o código de barras dos falsários, e o dinheiro vai pra eles. fonte: http://tecnoblog.net/129088/malware-brasileiro-boletos/
Comment: uma alternativa seria montar a linha digitavel com imagens dos números, o cliente teria que digitar manualmente, mas o vírus não conseguiria modifica-la, pois nem iria detecta-la.
Answer: Poderia montar a linha digitável com imagens dos números, ou gerar "on the fly" uma imagem com todo o número, mas isso faria o cliente ter que digitar ela manualmente, sem poder copiar e colar.
Outra opção seria tentar ofuscar ela com elementos HTML ocultos como no exemplo abaixo:

041192.11800 26238.100007 19275.041424 2 61480000069739

O codigo HTML ficaria assim:

Primeira parte da numeração041192.11800 Continuação da numeração26238.100007 19275.041424 2 Ultima parte da numeração61480000069739

creio que assim o malware não conseguiria detecta-la.

Ou usando jquery:

obviamente montar o


Descobrir localidade que o usuário acessa a minha página

Question: Tenho um domínio, www.dominio.com e www.dominio.com.br, o conteúdo é o mesmo ficando a diferença no arquivo de configuração com as mensagens que serão carregadas.
Qual a melhor técnica para descobrir a localidade que o usuário está acessando? para que eu possa definir via PHP qual arquivo de configuração carregar.
Answer:

Full response:

Answer: Use o Html5, JavaScript e Jquery para fazer o reconhecimento com geolocalização de quem acessar seu dominio. estes links deverão ajuda-lo: Usando geolocalização com html5
API de Geolocalização (geolocation) do HTML5 com Javascript


How to Calculate the Amount of Floating Point Operations Needed to Train a Neural Network

Question: Assuming a model with N parameters, arranged in an arbitrary architecture, training on M training examples for E epochs, how does one calculate within an order of magnitude or (hopefully) better the number of floating point operations needed to train that model?
I an find many numbers around the web for GFLOPS needed to train, but I'm not looking for FLOPS, I want the integral of FLOPS.
Answer: tldr; this is not possible.
Essentially, you're asking how many ops it takes to do a single forward and backward pass. It's not really possible to even estimate this based on the number of parameters. As an example, suppose you want to classify (binary) 1000x1000x3 images. A single fully connected layer would have 3 million parameters and cost roughly 3 million ops. A 3-filter 3x3 conv would have 81 parameters. If you stacked 37000 of these layers followed by a global pool, you'd also end up with roughly 3 million parameters, but it would take roughly 3 trillion ops to compute the result. If you embed some turing-complete submodule in your network (e.g. suppose one of your network layers is allowed to query a python interpreter), then there is no bound on the number of ops it would take to compute a single forward pass.
Comment: So if I'm looking to get an estimate from some tensorflow/pytorch model, what's the most straightforward way to get the number of ops? Seems like you're saying it's possible to calculate given the proper info about the model. I would assume that a tensorflow model architecture json file plus info on batch size & training examples would allow one to make this calculation?
Comment: https://github.com/tensorflow/tensorflow/issues/32809 tensorflow has this built in.


Characteristic curves of a partial differantial equation

Question: I need to find the general solution of the pde:
$ x(x+y)u_{x} - y(x+y)u_{y} = -(x-y)(2x+2y+u) $
My opinion:
The characteristic equation of the pde is $ {dx \over x(x+y)}={dy \over -y(x+y)} = {du \over  -(x-y)(2x+2y+u)} $
Then firstly, use $ {dx \over x(x+y)}={dy \over -y(x+y)} \implies $ $ {dx \over x}={dy \over -y} \implies lnx=-lny+lnc_{1} \implies lnc_{1}=lnx+lny \implies xy=c_{1}:= \phi(x,y,u) $ is the first characteristic curve.
But now, I wasn't able to find a way to find the second curve. Because it seems impossible to make a relation with the $du$ part..
Answer: $x(x+y)u_x-y(x+y)u_y=-(x-y)(2x+2y+u)$
$xu_x-yu_y=-2(x-y)-\dfrac{(x-y)u}{x+y}$
Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dx}{dt}=x$ , letting $x(0)=1$ , we have $x=e^t$
$\dfrac{dy}{dt}=-y$ , letting $y(0)=y_0$ , we have $y=y_0e^{-t}=\dfrac{y_0}{x}$
$\dfrac{du}{dt}=-2(x-y)-\dfrac{(x-y)u}{x+y}=-2(e^t-y_0e^{-t})-\dfrac{(e^t-y_0e^{-t})u}{e^t+y_0e^{-t}}$
$\dfrac{du}{dt}+\dfrac{(e^t-y_0e^{-t})u}{e^t+y_0e^{-t}}=-2(e^t-y_0e^{-t})$
I.F. $=e^{\int\frac{e^t-y_0e^{-t}}{e^t+y_0e^{-t}}dt}=e^{\int\frac{d(e^t+y_0e^{-t})}{e^t+y_0e^{-t}}}=e^{\ln(e^t+y_0e^{-t})}=e^t+y_0e^{-t}$
$\therefore\dfrac{d((e^t+y_0e^{-t})u)}{dt}=-2(e^t-y_0e^{-t})(e^t+y_0e^{-t})$
$(e^t+y_0e^{-t})u=-2\int(e^{2t}-y_0^2e^{-2t})~dt$
$(e^t+y_0e^{-t})u=-e^{2t}-y_0^2e^{-2t}+f(y_0)$
$u=\dfrac{f(y_0)-e^{2t}-y_0^2e^{-2t}}{e^t+y_0e^{-t}}$
$u(x,y)=\dfrac{f(xy)-x^2-y^2}{x+y}$


Secure Pages Module or force HTTPS Across Whole Site?

Question: I understand that the Secure Pages module allows you to let some pages use http and force others to use https. Assuming that is correct, is there any reason for me to use Secure Pages if I'm already forcing all requests to my domain to use https?
More info below if you need it, some of which is platform specific for my host:
I'm getting ready to launch a production ubercart ecommerce site using the Pantheon hosting platform. I want to make sure to be secure and fully PCI compliant, so I was following these guidelines which state that I need to use secure pages.
However, before that, I followed these guidelines to force https across my entire site, for all environments including dev/test. I don't mind a slight performance hit because I would rather be as secure as possible.
To force https I have added some code to my settings.php file and I have also created a page rule on Cloudflare to force requests to my domain to use https.
It's overkill but I also used the recommended code in the Pantheon documentation link above in my settings.php file to redirect all traffic to https.
The documentation for installing secure pages also raises several red flags for me.

It involves applying core patches that have failed tests and suggests that you can do them by hand, which seems unreliable to me.
Some of the instructions lack explanation and seem somewhat unreliable. Not trying to be mean, but where this concerns security, it makes me worry. For example, they mention that you need to change the $base_url parameter in settings.php file, but then go on to say "This option may or may not be necessary. Some have reported that they need it, others have reported it breaks caching of their site." Similarly, after telling you to add the Cookie Domain they say: "Some have made comments that this is not necessary, or causes issues with their site. It's a recommended setting, but not explicitly required." Another unclear sentence in the documentation is that after applying the core patches: "If everything worked, you should see some output like "hunk succeeded" or something like that and you're good to go." The idea of changing core and then not explicitly knowing if I've done it correctly or not seems very worrying to me.
One of the instructions is "Adding the Cookie Domain" but  Pantheon documentation cited above also says that it "already handles the necessary environment settings to ensure that Drupal is aware the site is running under HTTPS and that user session cookies should be secured." So, there's no reason to worry about that step in the Secure Pages instructions, I believe.
Other instructions from Secure Pages involve changing .htaccess to force www or the bare domain, but I have already taken care of that by following the Pantheon documentation above and modifying my settings.php file. This seemed the more reliable way to go since Pantheon documentation says .htaccess is ignored by NGINX servers.

So since I am already forcing https across my entire site, and I correctly enabled credit card encryption by creating a folder outside of my document root, is that enough to be PCI compliant using the Ubercart Credit Card module without Secure Pages?
Answer: Frankly, I bypassed Secure Pages and just forced all traffic to be HTTPS via htaccess. I prefer all traffic to be forced HTTPS.
SecurePages generally works up front, but I have seen a lot of wacky behavior with it that I just don't bother anymore.
Comment: Cool, that's pretty much what I did, except that I used settings.php instead of htaccess because that is what was recommended by my host. Thanks!
Comment: Pantheon doesn't support .htaccess, nginx doesn't use it.
Answer:
... is there any reason for me to use Secure Pages ...?

No, in general, but here's one possible reason: to avoid needing your own SSL certificate and its associated cost and administration hassle. I'm currently working on a project, also hosted on Pantheon, where we do just this. We used Secure Pages to redirect the user to https for sensitive pages... user login, contact form, other forms.
So, as an example, when a user goes to https://example.com/user they get redirected to https://live-example.pantheonsite.io/user - registered users on this site are all organisation staff, or similar - it's no big deal for them to see the pantheonsite.io address.
The full implementation uses a combination of Secure Pages and some custom logic in settings.php. The latter primarily deals with overriding the configuration values for Secure Pages depending on the environment (local, dev, test, live). For example, when running on a local development machine it sets <code>$conf['securepages_enable'] = 0;</code>.
Comment: Installing the Secure Pages module does not grant you an SSL certificate, it merely has configuration and conditions under which a user is redirected to https instead of http. You still need an SSL certificate and HTTPS enabled hosting environment to actually be secure. Furthermore, it is generally advised these days to make everything HTTPS, instead of mixed. Again, this can all be achieved in .htaccess, with exclusions for local/dev urls.


create domain name like co.cc

Question: three month ago I have site registered at co.cc. I want to know how they create domain name like ".cc" not ".com". I never seen site like this and .cc is not standard domain. So my question is how they create their own domain name? can I create my own domain like www.abc.jagdish insteda of www.abc.com?
Comment: What do you mean .cc is not standard domain? Of course it is. And this has nothing to do with HTML.
Comment: See http://en.wikipedia.org/wiki/.cc.
Comment: `can I create my own domain like www.abc.jagdish insteda of www.abc.com?` nope. You'd need to be a huge entity with lots of money to even have a chance of getting your own tld
Comment: Thanks. I got my answer. It is standard domain
Answer:
I want to know how they create domain name like ".cc"

That is a (completely standard) country code top level domain, specifically the one for the Cocos (Keeling) Islands. They got the domain by being the official registrar for that country or by buying it from them.
To create your own CCTLD you would first have to found a country. That seems like an excessive expense for the purposes of having a custom TLD.
Comment: His question is to create his own extension like `www.abc.jagdish`
Comment: Thanks. I got my answer. It is standard domain
Answer: You can't create your own domain. Wait it is possible to register your own extension but it will cost roughly $300k

Management of most top-level domains is delegated to responsible
  organizations by the Internet Corporation for Assigned Names and
  Numbers (ICANN), which operates the Internet Assigned Numbers
  Authority (IANA) and is in charge of maintaining the DNS root zone.

http://www.icann.org/
http://www.iana.org/domains/root/db/
http://data.iana.org/TLD/tlds-alpha-by-domain.txt
Answer: You could apply for your own gTLD, it will cost you though. A couple of hundred thousand USD at least.
Read more: http://newgtlds.icann.org/en/

create domain name like co.cc


Fill div with text

Question: I have a div:

Using Javascript or Jquery how would I fill this with the default text:
you have no products in your shopping basket.
What I mean by default text is I would want to change the text after they clicked a product. so maybe the default text in a variable and then included in the div via JavaScript or Jquery, which would allow the variable to be manipulated.
Comment: I think reading a basic tutorial on JQuery will cover this for you.
Comment: What do you mean by default text?
Answer: You can do it using jQuery text() or javascript innerText
With jquery, using jQuery text()
$('#shoppingBasket').text("you have no products in your shopping basket.");

With Javascript, using innerText
document.getElementById("shoppingBasket").innerText = "you have no products in your shopping basket.";

Answer: With jQuery this would be:
$('#shoppingBasket').text("you have no products in your shopping basket.");

with regular javascript:
document.getElementById("shoppingBasket").innerHTML = "you have no products in your shopping basket.";

Answer: function fillwithtext(text, elementID) {
    document.getElementById(elementID).innerHTML = text;
}

How's that?

Fill div with text


IIS 7.5 (Windows 7) - HTTP Error 401.3 - Unauthorized

Question: I'm trying to test my ASP.Net website on localhost and I'm getting this error:
HTTP Error 401.3 - Unauthorized
You do not have permission to view this directory or page because of
the access control list (ACL) configuration or encryption settings for
this resource on the Web server.

I have the following users on the website application folder, with full read/write permissions:

NETWORK SERVICE
IIS_IUSRS
SYSTEM
Administrators
Nathan (me)

What can I try to fix this?
Comment: I've been chasing this issue for a couple of hours now. I already has IUSR and Server\IUSR will the Read permission. Mine problem turned out to be encrypted folders that were extracted from a Zip file. If the folder name are green, try removing the checkbox from the Advanced settings of the Property box. This fixed my issue.
Answer: IIS 7 also creates "IUSR" as default user to access files via IIS. So make user IUSR has read access to files/folders.
How to check if IUSR has read Access?
Right Click -> Folder -> Properties -> Security Tab
See if IUSR is in Group or user names list, If No.
Click Edit -> Add -> Advanced -> Find Now -> Select IUSR and click OK four times
Comment: Note: It required both IUSR and IIS_IUSRS having access for it to work on my machine.  I tried removing IIS_IUSRS after adding IUSR, thinking IUSR was all I needed, but it croaked.
Comment: Make sure you're searching from the right location. I was searching for IUSR on my work domain and finding nothing. Then I changed the location to my machine name.
Comment: It surprised me that just adding `IIS_IUSRs` wasn't enough; I also had to add `IUSR`. Worth remembering :o)
Comment: Surely the IUSR user is already a member of IIS_IUSRS by default? My server doesn't seem to mention IUSR on it's default permissions set for wwwroot.
Answer: Found this on another forum, so I cant take credit but i did it and it worked for me:
"Try changing the Anonymous authentication setting in IIS7:
Click on Authentication and click edit after choosing Anonymous Authentication. In the opening window select Application Pool identity and click OK. "
Comment: This is what did it for me.
Comment: I am using impersonation and this somehow was the issue.  Not sure why, but it worked!
Comment: This stopped me from tearing out all my hair today. Thank you.
Comment: Guess it kind of makes sense to want separate identities for "user running the app pool", and "user impersonated by app pool after 'anonymous' authentication" - but only with hindsight, and after finding this answer!
Comment: On IIS 8.5, it seems that the default for a new application is not to use the Application Pool Identity, but just IUSR. Seems like a bit gotcha to me!
Answer: I had the same issue in IIS 7.5 on Windows Server 2008. For me, the following steps worked to fix the issue:

Open IIS Manager
Click the website you want to edit
Double-click Authentication
Click Anonymous Authentication, then click Edit... under Actions
Change to use the Application pool identity credentials instead of the Specific user (mine was IUSR)

After I made this change, my 401.3 errors disappeared.
Comment: Believe it or not, it's 2020 and I'm still maintaining an ancient IIS7.5 server. This post was pretty helpful.
Answer: Are you using a login mechanism, or just anonymous auth?
If anonymous, go into IIS manager, in the Authentication icon, choose the Anonymous Auth name, then click the Edit button in Actions. Check which user is specified there and make sure it has permissions to the site files/folders.
If you have some form of login system, make sure that the user(s) you are logging in as have permissions to the files for the site, and make sure that the ID of the application pool you are running under has at least read access to the files.
Answer: By default, with IIS 7.5, the each Application Pool runs under its own "virtual identity".  The App Pool's identity is are the credentials that are used to access the file system.
I'm not sure of the mechanics of it, but Microsoft did this to increase the security of the default install while alleviating the need to create service accounts in certain installation scenarios.  Regardless, the upshot is you will have to identify this "virtual identity" account and grant it access to your directory, or change the App Pool's service account.
The App Pool virtual identities are named "IIS AppPool\", so if you are using the DefaultAppPool, its identity would be "IIS AppPool\DefaultAppPool".
See this article for more complete details.
Answer: Hi For Me on IIS 8 work :
1)Go on IIS virtual directory - 2)authentication - 3)Anonymous authentication - 4)
 set Application Pool Identity .
Comment: Both the IUSR answer and this answer are required for a complete solution in all the cases I've run into
Answer: As none of the answers above helped me I thought I'd share how I solved this issue as I bumped into it on my local machine running win7 and IIS7.

Go to IIS7 -> Application Pools
Find the application pool of your site (in my case DefaultAppPool),
right click and choose Advanced Options.
Find chapter Process Model and change the field Identity to a user
you know for sure has access to the files in your website folder (in
my case the local admin)
Answer: Answering to include info from the comments on the accepted answer.
In IIS 7.5 on Windows Server 2008r2, the IIS_IUSRS group is already included, but the separate IUSR group must still be added to permissions to allow for file access/download.
For more information on the differences in the accounts see Understanding Built-in User and Group Accounts in IIS.
Answer: Try this...
Go to Computer Management (right click on my computer and select Manage) --> Local Users and Groups --> Users --> Select IUSR_MACHINENAME --> Right click Properties --> Make sure it is a member of IIS_WPG and users and not Guests.

I am working with Server 2008 R2 and the IUser account is not available in the list.
Answer: Try installing the client side of IIS using aspnet_regiis -c and then reset IIS.
Answer: For users where this isn't quite enough:
I got it to work with this:

Open the Feature View of your website.
Go to Handler Mappings.
Find
the path for .cshtml
Right Click and Click Edit Feature Permissions
Select Execute
Hit OK.

Now try refreshing your website.


Flutter Page Navigation : Back Button to have same behaviour as Back Arrow of the AppBar

Question: I'm just starting with flutter. I found a nice example on the internet of an app. It's about navigation between widgets.
article: https://medium.com/flutter/getting-to-the-bottom-of-navigation-in-flutter-b3e440b9386
full code: https://gist.github.com/HansMuller/b189642d10fd236a41044fdf7626f7b0
the lib folder of my implementation of the app: https://github.com/Liam-Noah/myapp_navigation
my question is this:
How can I get the back button to have the same behaviour as the back arrow of the Appbar. The latter just returns to the previous screen. The backbutton exits the app entirely.
what I managed to do:
add WillPopScope at the root of the tree widget of HomePage:
WillPopScope(
        onWillPop: (){
          //return Navigator.of(context).maybePop<bool>(false);

        Navigator.pushNamed(context, "/");

          return Future.value(false);
        },

results:
this works, but returns to the first tab of the bottomNavigationBar even if you have others selected. It still doesn't behave like the back arrow of the AppBar.
I tried replacing with in the onWillPop callback:
Navigator.of(context).maybePop<bool>(false);

but with no success, it results in an endless loop. Even though the appbar actually calls this function.
Thanks for your suggestions !
Answer: try this,
Navigator.of(context).pop();

or
  Navigator.pop(context);


Input Dinâmico, Laravel, JS

Question: Olá, estou tentando fazer um input dinâmico, consiste em um botão que você adiciona dois campos de uma vez, um text e um file, porém preciso persistir isso no banco de dados, creio que preciso fazer com que os names dos inputs alterem e no controller conseguir passar todos eles.
View

          {!! Form::label('nome-anexo', 'Nome do anexo', ['class' => 'col-md-12 control-label'])!!}

          {!! Form::text('nome-anexo', null, ['class' => 'form-control input-md', 'id' => 'nome-anexo']) !!}

          {!! form::label('anexo', 'Anexo', ['class' => 'col-md-12 control-label']) !!}

            {!! Form::file('anexo', ['class' => 'input-file', 'id' => 'anexo']) !!}

        <button id="add-more" name="add-more" class="btn btn-primary">Adicionar Campo</button>

JS

Contoller
public function attach($contato){

        $contato = Contato::find($contato);

        $titulo = Request::input('titulo');
        $mensagem = Request::input('mensagem');
        $nomeAnexo = Request::input('nome-anexo');

        $anexo = Request::file('anexo');

        $contatoTimeline = ContatoTimeline::saveAnexo($contato,$titulo,$mensagem,$nomeAnexo,$anexo,true);

        $contatoTimeline->user_id = \Auth::id();
        $contatoTimeline->save();

        return redirect()->back()->with([
          'tipo' => 'success',
          'mensagem' => 'Anexo adicionado com sucesso.'
        ]);

    }

Answer: Tu podes fazer os campos adicionados com JS virarem array:
<input type="text" name="fields[]" value="">

No controller esse campo virá em formato de array.
$fields = $request->get('fields', []);

Note que passei um array vazio caso o campo não se faça presente na request.

Input Dinâmico, Laravel, JS


Calculate TS File Duration

Question: I am working on a media player application : Which plays ISDB-T audio and video.
I am using GStreamer for decoding & rendering.
For AV Sync to work perfectly, I should regulate file reads: so that data will be not be pushed to Gstreamer neither too fast nor too slow.
If I know the duration of TS file before hand, then I can regulate my reads. But how to calculate the TS file duration ?

Because, I need to verify the application with multiple TS files, cannot calculate the duration using some utility and keep changing the file reads - How can this be achieved in program?
Thanks,
Kranti
Answer: If you have sufficient knowledge in the encoding and PES layer inside the transport stream, then you can read the time-stamps within the TS and calculate it yourself.
It requires seeking to the end of the file, searching for the last time-stamp, and subtracting the first time stamp of the same program in the beginning of the file.
EDIT: In addition to the above method you need to include the last frame duration.
((last_pts - first_pts) + frame_duration) / pts_resolution
Lets say you have a 30 fps segment with a duration of 6.006s
((1081080 - 543543) + 3003) / 90000 = 6.006
Answer: in most cases, each PES header contains a PTS and/or DTS, which is measured in 90kHz frequency. so the steps may include:

find the program you need to demux from MPEG TS.
find the PID of stream.
find the first TS packet with PID found, and payload_start_indicator set to 1; that will be the starting of a PES frame, which will contain a PES header.
Parse the PES header to find the starting PTS of the stream.
parse the file backwards from end, to find a packet with same PID and payload_start_indicator set, which will contain the last PTS.
find thier difference, divide it by 90000 will give duration in Seconds

Calculate TS File Duration


How to partition by a varying expression in windows functions?

Question: Hello I have a table that looks like this:
table : user_histories

user_id
start_at
value
attribute

189
2020-12-12
88
company_id

189
2021-03-02
169
Company_Id

189
2021-12-03
142
company_id.id

189
2020-12-12
walmart
company_name

189
2021-03-02
target
Company_Name

189
2021-12-03
whole foods
company_id.name

This table defines how uses change companies. The company associated has a company id and a company name. This table holds data for multiple users and the attributes vary in the way described in the table.
Ideally I would like to write a query with the following results.

user_id
start_at
value
end_date

189
2020-12-12
88
2021-03-02

189
2021-03-02
169
2021-12-03

189
2021-12-03
142
null

189
2020-12-12
walmart
2021-03-02

189
2021-03-02
target
2021-12-03

189
2021-12-03
whole foods
null

Of course I would be close to accomplishing this by writing:
SELECT
user_id,
start_at,
value,
LEAD(start_at) OVER (PARTITION BY user_id, attribute ORDER BY start_at) AS end_date
FROM
user_histories;

But the attributes vary even though the attributes of company_id, Company_Id, and  company_id.id all mean a change in company_id. Is there anyway I can use regex to match to this specific pattern?
I am using Snowflake. Thank you!
CREATE TABLE user_histories(
  user_id int,
  start_at date,
  value varchar,
  attribute varchar
);

INSERT INTO user_histories VALUE
(189,2020-12-12,88,'company_id'),
(189,2021-03-02,169,'Company_Id'),
(189,2021-12-03,142,'company_id.id'),
(189,2020-12-12,'walmart','company_name'),
(189,2021-03-02,'target','Company_Name'),
(189,2021-12-03,'whole foods','company_id.name');

Comment: You can also do just based on start_at, unless start_at for two different companies is same.
Comment: The fact that you are considering regex makes me suspect  your sample data is not representative? does user_histories contain attributes that contain values other than company ie key value pairs and is that why you are considering regex?
Answer: You need to address the data inconsistency in the attribute column as I doubt there's any "silver bullet" for that. Below I propose a case expression to make that column consistent before using it in the over clause:
with CTE as (
    select
          user_id
        , start_at
        , value
        , case
               when lower(attribute) like '%company%name%' then 'company_name'
               when lower(attribute) like '%company%id%' then 'company_id'
               else lower(attribute)
          end as attribute
    from user_histories
    )
select
      user_id
    , start_at
    , value
    , LEAD(start_at,1) OVER (PARTITION BY user_id, attribute ORDER BY start_at) AS end_date
from CTE

result
+---------+------------+-------------+------------+
| user_id |  start_at  |    value    |  end_date  |
+---------+------------+-------------+------------+
|     189 | 2020-12-12 | 88          | 2021-03-02 |
|     189 | 2021-03-02 | 169         | 2021-12-03 |
|     189 | 2021-12-03 | 142         |            |
|     189 | 2020-12-12 | walmart     | 2021-03-02 |
|     189 | 2021-03-02 | target      | 2021-12-03 |
|     189 | 2021-12-03 | whole foods |            |
+---------+------------+-------------+------------+

see: db<>fiddle here


How to update a CursorAdapter tied to listview when number of items changes?

Question: I have a ListView backed by a custom adapter based on a CursorAdapter.
The cursor I give it is based on a list of Notes in the database (each note is a DB row).
Everything works just fine until I delete a note from the database.  I'm not sure how to properly update the cursor/adapter/listview to display the new data.
I've read conflicting posts on using adapter.notifyDataSetChanged() vs cursor.requery() to refresh the UI, but neither of them seems to work in this case.  The only way I've been able to refresh it is by creating a new cursor from a new query and calling adapter.changeCursor(newCursor).
Could someone demonstrate the proper way to update the backing data and then the UI (with psuedocode if possible).
Answer: You have to requery and then notifyDataSetChanged.
Comment: I think the requery model has been deprecated as of honeycomb (at least not recommended).  CursorLoader is the preferred method currently.
Answer: Calling requery will re-execute the exact query that was used to create the cursor - that is, it won't re-execute the actual method in your code. So if your method contains dynamic stuff such as sorting based on a preference, it won't be updated. In this case, you don't want to use the same query, you want a different one.
Answer: This is what works for me, im not sure its the best way.
c = db.rawQuery( "SELECT * FROM mytable", null); //same line of the first initialization
adapter.swapCursor(c);

I refresh the only cursor, I dont know what to do with a new one.
Also i dont understand pepole that answer with a name of a function.


REST proxy for IIS

Question: I am looking for a REST Proxy to run on IIS so that an https GET/POST/DELETE etc can be forwarded "as-is" to another REST server for fulfilment, and to return the results as-is also.
I've done a search, but cannot find anything other than people wanting to convert protocols.
What REST proxies are there available for running on IIS?
Answer: Could you use this approach?
Reverse Proxy with URL Rewrite v2 and Application Request Routing

REST proxy for IIS


ListView with an ArrayAdapter

Question: I am trying to create an ArrayAdapter for my ListView to display a list of Contacts, but it is saying that it cannot resolve the constructor for the array adapter. Please can someone help me and tell me if I need to create a custom adapter or not. I have also tried ArrayAdapter> but that doesn't resolve the constructor either. Here is my code:
package com.example.contactmanagement;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int ADDCONTACT_REQUEST_CODE = 0;
    int idCounter = 0;
    List<Bundle> contacts = new ArrayList<Bundle>();

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

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();
        contacts.add(bundle);
        String fname = bundle.getString("fname");
        String lname = bundle.getString("lname");
        String full_name = fname + " " + lname;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LinearLayout layout = (LinearLayout) findViewById(R.id.contactList);

        ArrayAdapter<List> itemsAdapter = new ArrayAdapter<List>(this, R.layout.textview, contacts);
        ListView listView = (ListView) findViewById(R.id.lv);
        listView.setAdapter(itemsAdapter);
        /*
        TextView textView = new TextView(this);
        textView.setLayoutParams(params);
        textView.setText(fname +" " + lname);
        textView.setId(idCounter);
        idCounter++;
        textView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                Intent contactDetails = new Intent("com.example.contactmanagement.ContactDetails");
                int counterID = v.getId();
                Bundle bundleToPass = contacts.get(counterID);
                contactDetails.putExtras(bundleToPass);
                startActivity(contactDetails);
            }
        });
        layout.addView(textView);
        */
    }
    public void onClick(View view) {
        Intent intent = new Intent(this, AddContact.class);
        startActivityForResult(intent, ADDCONTACT_REQUEST_CODE);
    }

}

Comment: hey try your code by declaring array adapter as string.ArrayAdapter itemsAdapter =
    new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
Answer: Change this line:
ArrayAdapter<List> itemsAdapter = new ArrayAdapter<List>(this, R.layout.textview, contacts);

to this:
ArrayAdapter<Bundle> itemsAdapter = new ArrayAdapter<Bundle>(this, R.layout.textview, contacts);

For an ArrayAdapter, the type that you place between the <> is the type that is used for your array.
In this case, your List is actually a list of Bundles, which means contacts is simply a list of type Bundle.
Therefore, the type you place in the <> has to be of type Bundle to match the type of your contacts list.
The reason for you getting that constructor error is because you wrote ArrayAdapter<List> so the constructor was expecting contacts to be an Array or List of type List.
One extra thing to note is...
Your ArrayAdapter probably won't give you the output you expect, because it doesn't know what to do with Bundle.
If it was simply a list of String, then it'll know to display that into the layout of R.layout.textview, but for type Bundle, it simply won't know what you wish to do with it unless you create a custom adapter to handle this type.
So you can either create a custom adapter to allow your ListView to know how to display the contents of your Bundle, or if your info is simple enough, like just a single String, then you can create a new List that holds only that simple String and pass that in to the constructor for the ArrayAdapter instead.
Comment: thanks! it worked perfectly. Now for the hard part of figuring out how to unpack this bundle
Comment: Please accept the answer as correct if it has answered your question.
Comment: For your hard part, this is something that can only be done through a custom adapter.

ListView with an ArrayAdapter


Android: How to share a contact via intent?

Question: how can i share a Android contact using an intent?
I tried like this, but somehow i guess i have to forward the contact id in a different way:
            Intent intent = new Intent(Intent.ACTION_SEND);
            Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(con.id));
            intent.setData(uri);
            startActivity(intent);

Answer:
how can i share a Android contact using an intent?

It is unlikely that you can. A contact is a series of database records, and as such cannot usually be shared via ACTION_SEND.
Moreover, you do not use setData() with ACTION_SEND. Usually, you set EXTRA_TEXT or EXTRA_STREAM to be the text or Uri to share, and set the MIME type of the Intent to be the MIME type of the content in EXTRA_TEXT (text/plain) or EXTRA_STREAM. You may wish to review the documentation on ACTION_SEND for other alternatives.
My guess is that few apps will agree to share a contact, and those that do will crash when they try, as the Uri in EXTRA_STREAM is supposed to represent a stream (e.g., a file served by FileProvider), not a database-style entry.
You might consider generating some text or HTML that represents the contact, then sharing it, as that is more likely to be successful (e.g., to send in an email). Or, you could try standard contact encoding formats, like vCard, and see if that works.
Comment: Somehow it has to be possible! I can choose a share action on my real device (Android 4.4.4) for each contact. If i choose 'Gmail' for example, a *.vcf file will be automatically attached to the resulting email.
Comment: @nr1: A .vcf file is a file representing a contact, not a contact itself. In particular, a .vcf file is a [vCard file](http://en.wikipedia.org/wiki/VCard), which I suggested in my answer.
Comment: @CommonsWare Can you show how to export the contact's data (whatever is possible) into VCF file, and share it? Is this a good answer: http://stackoverflow.com/questions/8701727/extract-contact-list-in-vcf-format/8701774#8701774 ?


Proof check in Linear Algebra with Diagonalizable operator

Question: Given $T : V \to V$ linear operator on $V$ space vector such that $T^2 =T$ , prove that $T$ is Diagonalizable,
What i did is $f(x) = x^2-x = x (x-1)$  and so we know that $f(T) = 0$
then it must be that $m_T (x) | f(x)$ where $m_T(x)$ is the minimal polynomial such that $m_T(T) =0$.
so $x(x-1) | m_T(x)$ and $m_T (x) | x(x-1) = f(x)$ and so $m_T(x) = x(x-1)$ and because is the multiplication of linear factors then $T$ is Diagonalizable.
is this proof correct ?!
Answer: This proof is not completely correct as $x(x-1) | m_T(x)$ is false.
For example $0$ or $\operatorname{Id}_V$ are such that $0^2=0$ and $\operatorname{Id}_V^2=\operatorname{Id}_V$ but their minimal polynomials are $x$ and $x-1$.
But the proof is almost correct as from $ m_T(x)| x(x-1) $ there is only three different cases:

$m_T(x)=x(x-1)$
$m_T(x)=x$
$m_T(x)=(x-1)$
Comment: but in every case $m_T(x)$ is multiplication of linear factors meaning that corresponding $T$ is Diagonalizable, right ?!
Comment: You are absolutely right :-)
Answer: One way to show that $T$ is diagonalizable is to show that $V$ has a basis of eigenvectors of $T$, or equivalently, that $V$ can be spanned by eigenvectors of $T$.

Here's a proof using that approach . . .

Let $A=\{a\in V\mid Ta=0\}$.

Let $B=\{b\in V\mid Tb=b\}$.

Then $A,B$ are subspaces of $V$, whose nonzero elements are eigenvectors of $T$, corresponding to the eigenvalues $0$ and $1$, respectively.

To show that $T$ is diagonalizable, it suffices to show that $V=A+B$.

Let $v\in V$.$\;\,$Claim $v\in A+B$.

Let $b'=Tv$,$\;$and let $a'=v-b'$.

Then $v=a'+b'$,$\;$and

$Ta'=T(v-b')=T(v-Tv)=Tv-T^2v=Tv-Tv=0$, so $a'\in A$.$\\[4pt]$
$Tb'=T(Tv)=T^2v=Tv=b'$, so $b'\in B$.

so $v\in A+B$, as claimed.

It follows that $V=A+B$, hence $T$ is diagonalizable
Comment: If you have that as an already proven result in the context of your course, you can use that approach; otherwise, my proof provides a first-principles approach.
Comment: That said, idempotents form such an important basic class of operators, especially from a geometric standpoint, that understanding their diagonalisability directly in terms of the eigenspaces themselves really gives the *best* proof.
Comment: I was under the impression that if the minimal polynomial is a product of distinct linear factors, then the operator is definitely diagonalisable.
Comment: ... which the OP probably has, since that is the line of argument they are trying to use!
Comment: Sure, but it's not really answering the question, which is "is this proof correct?"