Why does Uniform Distributions have no outliers?

Question: I was reading about the relation between Kurtosis and Outliers on Wiki and got across a line 'An example of a platykurtic distribution is the uniform distribution, which does not produce outliers' [here]https://en.wikipedia.org/wiki/Kurtosis
I mean it would also have some µ ± 2σ cut in probability density curve, then how can U.D not have outliers?
Comment: +1. Wikipedia is wrong here.  The intended meaning is that $\mu\pm 2\sigma$ lies outside the support of the distribution--but actual *random samples* from a uniform distribution can indeed have outliers.
Comment: For a uniform distribution on an interval of length $L,$ the mean ($\mu$) is in the middle of the interval and the standard deviation $\sigma$ is $L$ times $\sqrt{1/12}\approx  0.29.$  Thus, when you move $2\sigma L\approx 0.58L$ to either side of $\mu,$ you go beyond the endpoints, which are only $L/2 = 0.50L$ away from the middle.  The probability of observing any value beyond the endpoints of the interval is, of course, zero.
Comment: What would be an unusual value within uniform range of support?
Comment: I didn't get it. Can you elaborate more, please?
Comment: Ah! Got it. But how  μ±2σ lies outside the support of the Uniform Distribution?
Answer: Let's take a look at the uniform distribution.  Here is some R code, stuff after a # is a comment:

set.seed(1234)
random <- runif(1000, min = 0, max = 10)
sd(random) mean(random) + 2*sd(random)  #10.89 mean(random) -
  2*sd(random)  #-0.75

So, we see that there is no value in this data set that is more than 2 SD above the mean or less than 2 SD below.
This is true even for much larger N.
For a Normal distribution with large N, some values will be outside the 2 SD range, but these are not outliers. An outlier is an unexpected value. If we have a Normal distribution with a large N, then we expect some values to be beyond 2 SD. Indeed, for a perfectly Normal distribution, about 5% of the values will be outside this range.  Thus

set.seed(1234)
random <- rnorm(100000, 0, 1)
sd(random) sum(random > mean(random) + 2*sd(random))  #2389 sum(random
  < mean(random) - 2*sd(random))  #2235

and we even expect (and get) some beyond 3 SD:

sum(random > mean(random) + 3*sd(random))  #143 sum(random <
  mean(random) - 3*sd(random))  #127

The 2 SD rule worked okay as a rule of thumb in the old days, when "big data" meant a few thousand cases.
Comment: There is no one "best way". Identifying outliers requires substantive expertise. You can identify points that merit thought in various graphically ways, at least when the number of dimensions is small.
Comment: "merit" in this context means "these points are worth looking at".
Comment: This helped a lot. So, what is the best way to identify the outliers in a large dataset according to you?
Comment: who is "merit" ? Didn't get your line "You can identify points that merit thought in various graphically ways"


Add and call Function to and from Dict in Julia

Question: assume I have a Dict
acts = Dict{String, Function}()

and I have a function foo()
function foo(arg1, arg2)
  @info arg1
  @info arg2
end

First, How can I store "bar" => foo() in acts Dict?
Second, How can I call bar from acts and run it?
Answer: Should be straightforward:
julia> acts = Dict{String, Function}()
Dict{String,Function} with 0 entries

julia> function foo(arg1, arg2)
           @info arg1
           @info arg2
       end
foo (generic function with 1 method)

# add function foo to dict acts with key "bar"
julia> acts["bar"] = foo
foo (generic function with 1 method)

# check that it's there
julia> acts
Dict{String,Function} with 1 entry:
  "bar" => foo

# call the foo function from the dict by using its key
julia> acts["bar"]("hi", 2)
[ Info: hi
[ Info: 2


Spectral sequence page isomorphism

Question: Suppose we have a map of spectral sequences $\{E_{p,q}^r,d^r\}\to \{{E'}_{p,q}^r,d'^r\}$, both generated from total chain complexes, $C$ and $C'$ respectively, such that for some $r$ the map between the $r$-th pages $E_{p,q}^r\to {E'}_{p,q}^r$ is an isomorphism. Using the five lemma, we can show that for any $r'>r$, we also have an isomorphism of the $r'$ pages. Can we deduce anything about the homology of the filtered chain complexes associated with these spectral sequences?
Comment: Is the map of spectral sequences induced by a chain map between $C$ and $C'$? [This MO question](http://mathoverflow.net/questions/100157/isomorphic-spectral-sequences-quasi-isomorphic-filtered-chain-complexes) might interest you (it deals with filtered complexes though). At the very least if both spectral sequences converge, then both homologies have a graduation such that the two associated graded modules are isomorphic...
Answer: There is this comparison theorem in Weibel's book An introduction to homological algebra:

Comparison Theorem 5.2.12 Let $\{ E^r_{pq} \}$ and $\{E^{'r}_{pq} \}$ converge to $H_*$ and $H'_*$, respectively. Suppose given a map $h : H_* \to H_*'$ compatible with a morphism $f: E \to E'$ of spectral sequences. If $f^r : \{E^r_{pq}\} \to \{E^{'r}_{pq} \}$ is an isomorphism for all $p$ and $q$ and some $r$ (hence for $r = \infty$ by the Mapping Lemma), then $h : H_* \to H'_*$ is an isomorphism.

I think that's probably the best kind of result you're going to get. Of course if the spectral sequences do not converge, I don't believe it will be possible to compare the homologies. Now if they do converge, this Comparison Theorem together with your hypotheses directly imply that the homologies are isomorphic.
Note that you need the map $h : H_* \to H'_*$ from the start; so for example if your map of spectral sequences is not induced by a chain map $C \to C'$, I don't know if it will be possible to compare $H_*$ and $H'_*$.

The Exercise 5.4.4 in the aforementioned book might be useful too, and an even better result given your hypotheses actually. Suppose $f : C \to C'$ is a chain map and let $C_f$ be its mapping cone. Then the Exercise tells you that you can get a spectral sequence out of $C_f$, say $\{ E^r_p(C_f) \}$, and that it is the mapping cone of the induced map $E^r_p \to E'^r_p$. If $E^r_p \to E'^r_p$ is an isomorphism, then its mapping cone $E^r(C_f)_p$ is zero, hence $E^\infty(C_f)$ is identically zero. This implies that the mapping cone $C_f$ has trivial homology (we get convergence for free because $E^\infty = 0$!), hence that $f$ was a quasi-isomorphism.

Spectral sequence page isomorphism


redirecionamento com o mod_rewrite não funcionando no wamp

Question: O mod_rewrite já está ativado como podemos ver em www.joocebox.com/?phpinfo=1
Realizei a mudança também no arquivo httpd.conf como abaixo:
DocumentRoot "c:/wamp/www/"
<Directory />
    Order Deny,Allow
    Deny from none
    Allow from 127.0.0.1
</Directory>

<Directory "c:/wamp/www/">
   Options Indexes FollowSymLinks
   AllowOverride all
   Options FollowSymLinks
   AllowOverride all
   Order deny,allow
   Allow from all
</Directory>

E finalmente criei o arquivo .htaccess no diretorio "c:/wamp/www/" com o seguinte conteúdo:
#Ativando o mod_rewrite
RewriteEngine on
# Se o host for www.joocebox.com/trustbox
RewriteCond %{REQUEST_URI}^www.joocebox.com/trustbox$ [NC]
# A regra será a seguinte
RewriteRule ^(.*)$ http://trustbox.joocebox.com/$1 [R=301,L]

Bem, o problema é que o redirecionamento não é realizado! Retornando o erro 404.
Answer: Pessoal foi mais fácil do que eu pensei.
No meu .htaccess substitui tudo isso:
#Ativando o mod_rewrite
RewriteEngine on
# Se o host for www.joocebox.com/trustbox
RewriteCond %{REQUEST_URI}^www.joocebox.com/trustbox$ [NC]
# A regra será a seguinte
RewriteRule ^(.*)$ http://trustbox.joocebox.com/$1 [R=301,L]

Por isso:
RewriteEngine on
Redirect 301 /trustbox http://trustbox.joocebox.com

Refência: How to do a .htaccess 301 redirect


MobX observables change do not always trigger observer components render

Question: My project is built on React, and for state management Mobx is being used.
We are not using the decorators, so the components that need to observe the observables, need to be wrapped in the following way:
import React from 'react';
import {observer} from 'mobx-react';
import MyComponent from '../app/my-component.jsx';
import myFilter from './my-filters.jsx';

export default observer(() => {
  return <MyComponent filter={myFilter}/>;
});

The component MyComponent is receiving the observables as props:
static propTypes() {
    return {
      myFilter: React.PropTypes.function.isRequired
    };
  }

And it is used in the render method:
render() {
  if (this.props.myFilter.filterValue1 !== null) {
    // some code here
  }
}

myFilter in this case is the observable, which looks somehow like this:
import {observable} from 'mobx';

const myFilter = observable({
  filterValue1: null,
  filterValue2: null,
  addOrRemoveItem() {
    // some function here
  }
});

export default myFilter;

In this case, if some component alters myFilter, the observer MyComponent which receives the observable as props, does not always re-render. In some cases this can be solved by addressing the observable object by attribute before the call of the component. E.g.:
export default observer(() => {
  console.log(myFilter.filterValue1);
  return <MyComponent filter={myFilter}/>;
});

But this is not stable.
Is there a valid workaround to avoid this?
Answer: Declare MyComponent as an observer.
export in app/my-component.jsx should look like this
export default observer(MyComponent);

This piece of code
export default observer(() => {
  return <MyComponent filter={myFilter}/>;
});

turns an anonymous stateless component, not MyComponent, into an observer.
MobX documentation clearly articulates that you need to apply observer to all components that render observable data or you will encounter problems.
The other way to solve the problem would be passing plain data from this anonymous stateless component into MyComponent.
export default observer(() => {
  return <MyComponent filterValue1={myFilter.filterValue1}/>;
});

This way MyComponent will be rerendered because it receives new props each time its parent is rerendered.
Answer: Alik is right, you need MyComponent to be an observer as well.
Otherwise, your code <MyComponent filter={myFilter}/> inside the only observable you have means that you want refresh only when myFilter object (ie., reference to it) changes. It does not access any of its properties and thus refresh is not needed when those properties change. That's why your component was refreshed when you accessed the filterValue1 property in the console.log statement.
Comment: Thank you gius and Alik, that of course solves the render issue. The thinking was to put all the observing wrappers in one place for easier maintenance, thus leaving the classes as is. But probably declaring the classes observers is the only way to go.


how to write java servelt relative file path

Question: i am using SERVLET and i am reading from XML files i want to read the XML files using relative or dynamic paths , i tried the "./directoryName" and the "fileName" but non of these worked
my path now loooks like this :
public static final String DEFAULT_INFO_FILES_PATH = "D:/dev/workspace/QwiltSim/src/ps/exalt/qwilt/ui/sim/DevicesInfo.xml";

i want it to be some thing like :
 public static final String DEFAULT_INFO_FILES_PATH = SomeFolderName+"DevicesInfo.xml"

can any one help me please ?
Comment: I'd consider putting it in my classpath and reading it as a resource.
Answer: ServletContext#getRealPath() converts relative paths within your application to file system paths. If your XMLs are static and you deploy them along with your servlet application, you can store them within the WAR and resolve the path to them using this method.


Override user login form template

Question: I'm trying to customize my user login page in my custom theme using the template file page--user--login.html.twig, but am having issues accessing the different form elements. All aspects of the form are located in page.content, but I'd like to edit the content that's being outputted.
For a simple example, the base theme has Username and Password stacked vertically, where I'd like to adjust this to use bootstrap so that they are stacked horizontally on large screen and vertically on mobile.
In Drupal 7, we had a form element in the template file that allowed me to render certain form elements separately, like:

  <?php print drupal_render($form['name']); ?>

  <?php print drupal_render($form['pass']); ?>

Is there an equivalent for Drupal 8?
I attempted to create a template file for the form (form--user-login.html.twig and form--user-login-form.html.twig) to see if I could alter the form template itself instead of the page the form exists on, but didn't have any luck with that.
I'd prefer to override the current login theme instead of creating a whole new page and form and have to add all the necessary configurations so that a user lands on the correct login page, but have yet to find any way to do so, thanks in advance.
Comment: See https://drupal.stackexchange.com/questions/249856/custom-registration-twig-template
Answer: In addition to Yuseferis answer:
I'm using this function to add theme suggestions for forms in Drupal 10:
/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 *
 * Make forms themeable:
 * e.g. => form--user-login-form.html.twig
 */
function YOURTHEME_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if (!empty($variables['element']['#form_id'])) {
    $suggestions[] = 'form__' . $variables['element']['#form_id'];
  }
}

Comment: oh my god. I was banging my head as to why my Drupal 9 snippet to show form suggestions wasn't working. Thanks for the saving.
Answer: if you overrided correctly element will contain all items in form--user-login.html.twig,

    <form{{ attributes }}>

hello world

            {{ element.messages }}
            {{ element.name }} {# username element #}
            {{ element.pass }} {# password element #}

                <input id="show_password" class="show_password" type="checkbox" />
                Show password
                Forgot Password?

            {{ element.form_build_id }} {# required #}
            {{ element.form_id }} {# required #}

                {{ element.actions.submit }}

    </form>

if the template is not valid, you should try to add it.
function Yourtheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#id'])) {
    $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']['#id']);
  }
}

then create form--user-login-form.html.twig in your theme.
do not forget to clear the cache.

Override user login form template


Manter os zeros depois do ponto

Question: Bom dia a todos.
Tenho o seguinte código:
var somaR = 0;
    var somaN = 0;
    var project = [
       {part: 'Renault', partNumber: 1234, project: 'X19', gap: 15.000},
       {part: 'Renault', partNumber: 1234, project: 'X19', gap: 600},

    ]

    function groupBy(array, f) {
        var groups = {};
        array.forEach(function(o) {
            var group = JSON.stringify(f(o));
            groups[group] = groups[group] || [];
            groups[group].push(o);
        });
        return Object.keys(groups).map(function(group) {
            return groups[group];
        });
    }

    var projectIguais = groupBy(project, function(item) {
        return [item.part, item.partNumber, item.project];
    }).map(function(data){
        return {
            totalGap: data.reduce(function(total, valor){return total + valor.gap;}, 0),
            itens: data
        };
    });

    console.log(projectIguais);

    for (var i in projectIguais) {

        var partNumberItem = "Part Number: " +projectIguais[i].itens[0].partNumber;
        var projectItem = "Project: " +projectIguais[i].itens[0].project;
        var gap = "Gap: "+projectIguais[i].itens[0].gap;
        var totalGapItem = projectIguais[i].totalGap;

        console.log(partNumberItem);
        console.log(projectItem);
        console.log(gap);

        if(projectIguais[i].itens[0].part == 'Renault'){
            somaR += totalGapItem;
        }
        if(projectIguais[i].itens[0].part == 'Nissan'){
            somaN += totalGapItem;
        }
    }

    console.log("Soma Renault", somaR);
    console.log("Soma Nissan", somaN);

Dentro do array project tenho o gap 15.000 mas na hora de fazer o cálculo, o valor do gap fica 15.
Exp: O código pega dentro do array o mesmo partNumber e projeto, soma o gap e me devolve o total do gap por projeto.
No meu array tenho um gap 15.000 e outro gap 600 mas no cálculo está me retornando gap 615 porque está removendo os zeros depois do ponto.
Como faço para manter o 15.000 no cálculo?
Comment: O Json está errado, o correto de um json para numérico na casa de milhares é receber sem nenhum ponto, exp: `15000`, o `.` separa a fração, exp: `15000.58 => 15.000,58`
Answer: Resposta rápida
Escreva:
{part: 'Renault', partNumber: 1234, project: 'X19', gap: 15000},

No lugar de:
{part: 'Renault', partNumber: 1234, project: 'X19', gap: 15.000},

E na hora de mostrar o valor, ai sim você coloca os pontos e virgulas para separar milhar e decimal:
// .toLocaleString('pt-BR') vai aplicar o formato brasileiro no Number
// ou seja, um ponto var separar o milhar e uma vírgula vai separar o decimal
var gap = "Gap: " + (projectIguais[i].itens[0].gap).toLocaleString('pt-BR');

// Use em todas as saídas que quiser formatar
console.log("Soma Nissan", (somaN).toLocaleString('pt-BR'));

Explicação disso tudo
O ponto ".", na notação americana (que o javascript usa) é entendido como a nossa virgula aqui no Brasil, ou seja, ele separa o número inteiro das casas decimais, portanto escrever R$ 15.000 é igual a escrever R$ 15,000 (nós lemos isso como "quinze reais", sempre ignoramos as casas decimais quando estão ZERADAS).
Conclusão
Para trabalhar com os números no javascript não use nenhuma pontuação para separar os milhares e use o ponto (e não a virgula) para separar as casas decimais, simples assim.
Bônus
Crie uma função para facilitar a formatação (e a sua vida):
function ptbr(n) {
    // parse só pra garantir
    return Number(n).toLocaleString('pt-BR')
}

Dai você usa assim:
var gap = "Gap: " + ptbr(projectIguais[i].itens[0].gap);

Manter os zeros depois do ponto


How do you make a textview change according to an HTML document on the web

Question: A couple of friends and I are setting up a little app business, and we are creating our general app for finding out all the latest news about our other apps. But we have a small problem.
We have a layout xml file with a table row in it. In the table row we want to show two textviews. One that says Current App version (Which we have done successfully) and the other one will show a few numbers from an HTML page which is live now.
I want to know, how would be able to get the text from the HTML document on the Web to that text view, or any other thing we could use.
(We know that the manifest will have to allow the internet)
Thanks
Comment: We want it this way so we can just easily change the HTML document to change the text on the app. So we don't always have to make a new release of the app
Answer: So in this TextView, you want to show the content of the HTML page? If this is the case, the best thing you could do is to replace the TextView with a WebView, where you could load the HTML page via its url.
If not this is the case, you can make a GET request to that HTML (i.e. using an Async Task), get the results and present them in the TextView.
Hope this helps!
Comment: How would I go about setting up a Webview. We had a look at them, but had difficulty setting its URL.
The HTML page is just a very basic document with just a  tag
Comment: What problem did you have? It's quite easy indeed. You just call loadUrl in the webview object. For more info please check here: http://developer.android.com/guide/webapps/webview.html
Comment: Where do I put the WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
???
When I paste it in, it suggests to create a class called webview
Comment: In your layout xml you have to define the WebView, and in your Activity you add this code in order to get access to the WebView and use it.
Comment: When I hover over it, it suggests Create Class webView.class


Displaying multiple File entity types in a view, when they have different fields to display

Question: Working with the Media module, I want audio and video files to show (user uploaded/selected) preview images when displayed in areas throughout the site (instead of the default soundwave and film clip image.) So, I added fields to those files type entities, but since Image can be it's own preview, I didn't add that field (since it would seem odd to make the user upload/choose the image again.) This has become a GIANT pain when trying to figure out how to show all the file types together in a single view. (I want it to show field_image for audio and video, but the file for images.)
Does that sound undoable? Nothing I've been able to try with views and relationships gets me what I need. I tried customizing the preview display mode for each, then display the "rendered entity" (which got me what I needed for displaying the images), but left me with other issues, since I was displaying field_image fields for some, but file fields for others.
Slight Update: I tried adding the field_image field to the image file type, but that seems to cause some kind of infinite loop/server error when viewing/editing that file anywhere.
Answer: What I ended up doing was just add custom tpl.php files for each of the types I was interested in (audio/video/images; e.g. file--image.tpl.php). Then, in the views, just say to render the entity instead of using fields.
I'd have liked a more elegant way, since I now have 3 more tpl.php files to worry about, but it DID fit the bill.


What methods can be used to compare the consistency of the distributions sampled from independent Markov Chains?

Question: I have a set of independent random walkers on a graph that produce a distribution of the nodes in that graph. I would like to test whether the random walkers have produced a distribution which is consistent.
I thought about separating the results from the random walker into various sets, eg 4 separate groups, and using the distribution that these 4 iid groups make from the graph, use Gelman-Rubin diagnostics link to def.to test for convergence of those distributions.
I cannot use Gelman and Rubin's potential scale reduction factor directly on the independent walkers, because they are not let to run till they reach ergodic steady states.
I suppose that the reasoning behind using Gelman and Rubin still holds when comparing within $W$, and between variance $R$ of distributions from groups of these independent walkers because even a markov chain run till it is supposed to reached ergodicity is a distribution.
Is my approach valid and why? are there any references for it?
Answer: When performing Markov chain Monte Carlo, you never know when and if the ergodic steady state is reached. Gelman-Rubin statistic is a test for reaching this state.
An important assumption for the Gelman-Rubin statistic is overdispersion of the initial states. This is needed to guarantee that the between-chain variance approaches the variance of the posterior from above. Make sure that this assumption is satisfied.
Comment: can the use of multiple iid walkers be used in aggregation to approximate that state. The search is for testing the locality of a discrete distribution's consistency for the iid walkers


How to prepare USB HDD from FreeBSD CD ISO image?

Question: I have downloaded the FreeBSD 10 x86 CD ISO image file.
I have a Dell Optiplex Pentium 4 2.66Ghz PC which supports booting from USB.
I have a 500 GB external USB hard drive.
I'm using Windows 8.1 Pro on a separate laptop.
Question: How to copy the ISO image to the external hard drive so that I can use it to install FreeBSD on the PC?
Answer: dd in Linux, or unetbootin on various. platforms, also this is fairly well documented in the FreeBSD Documentation.


Digitação na TextBox

Question: Estou fazendo um projeto no visual studio e preciso de ajuda. Gostaria de saber se tem como ou como faz para fazer com que quando eu digite na textbox,isso que eu digitei comece pela frente independente da posição do cursor ou que ele va meio que excluindo até chegar na frente.A textbox seria de telefone mais ou menos assim:(__)____-____.
Comment: Vc quer usar uma mascara no campo é isso?
Answer: Você pode usar o evento Enter do MaskedTextBox que vai ser disparado sempre que o usuário clicar no componente e dentro dele usar o método Select, desta forma:
No método abaixo, também é validado se o TextBox está vazio para colocar o cursor no início.
Para usar desta forma, você precisa trocar a propriedade TextMaskFormat para ExcludePromptAndLiterals. - Isso vai fazer com que a propriedade Text do TextBox contenha apenas o texto digitado pelo usuário.
private void maskedTextBox1_Enter(object sender, EventArgs e)
{
    var txtbox = (MaskedTextBox)sender;
    if (string.IsNullOrWhiteSpace(txtbox.Text))
    {
        this.BeginInvoke((MethodInvoker)(() => txtbox.Select(0, 0)));
    }
}

Comment: Eu tenho que adicionar alguma referência? Porque algumas palavras não mudaram a cor.
Comment: Não. O que é que "não mudou a cor"?
Comment: IsNullOrWhiteSpace, Text, BeginInvoke, Select.
Comment: E não deu certo.
Comment: Tem certeza que não escreveu algo errado?
Comment: Arrumei, era um erro meu, vlw.
Comment: Certo, você pode marcar a resposta como correta se ela te ajudou clicando no **✓** abaixo das setas para votar ***=)***.

Digitação na TextBox


Start a list of processes, then terminate them

Question: Using powershell how do you start some processes running, then kill them some time later?
I start processes using the following:
ps
Start-Process "notepad.exe"

Answer: Create a file called run.ps1 with the following contents:
$apps = New-Object System.Collections.Generic.List[Object]

$app = Start-Process "notepad.exe"  -passthru
$apps.Add($app)

$app = Start-Process "notepad.exe"  -passthru
$apps.Add($app)

Write-Host "Press any key to terminate ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

#Kill the running processes
foreach ($app in $apps)
{
    Write-Host "Killing" ($app.Id -as [string])
    Stop-Process $app.Id
}

And now you can execute it using:
powershell.exe -executionpolicy remotesigned -File  ./test.ps1


Salvar campo input no banco de dados

Question: Como armazenar as ultimas 100 pesquisas feitas a um site (PHP/MYSQL) dividas por países (ex: armazenar as ultimas 100 pesquisas por livros da Macedônia). A pesquisa é um campo simples simples:
<input type="text" id="search" name="search" placeholder="Search" />

Qual a melhor forma de "coleta" desta informação que não comprometa a performance (eu julgo que a cada nova pesquisa ter de inserir no banco seja demasiadamente oneroso), e a melhor forma de estruturar esta informação em tabelas no banco? e como criar uma limitação a 100 pesquisas por país e trabalhar de forma semelhante a uma fila (mantendo sempre atualizada as 100 pesquisas)? Esta lista deve ser acessível a todos os usuários e atualizada em tempo real como fazer a nível de aplicação também.
Tabela País:
CREATE TABLE pais(
id INTEGER NOT NULL AUTO_INCREMENT,
codigo CHAR(2) NOT NULL UNIQUE,
nome VARCHAR(70) NOT NULL,
PRIMARY KEY(id));

Obs: este código é o código ISO do país.
Comment: @JorgeB. dever ser atualizado em tempo real.
Comment: Queres armazenar  `id_pais => palavra_pesquisada`?
Comment: sim seria tipo uma tabela onde uma coluna fosse o id país e na outra a palavra pesquisada, o problema que como são muitas pesquisas eu gostaria de uma forma mais eficiente de fazer a inserção no banco
Comment: Podes sempre guardar num log e ao fim do dia, numa hora morta fazer a inserção no banco. Ou tem de ser atualizado na hora?
Answer: A melhor maneira eu não se é, mas tenho algumas idéias
SOLUÇÃO 1

Criar uma TRIGGER no AFTER INSERT da sua tabela, essa trigger faz uma chamada para uma FUNCTION.
Criar a FUNCTION de forma recursiva fazendo as seguintes operações:

Fazer uma consulta que retorne quantos registros a tabela possui, leia sobre COUNT()
Fazer uma condição nessa consulta se for maior que 100, então remove o primeiro registro, leia sobre MIN()
Fazer a condição de parada, para sair da recursividade quando o resultado da consulta for menor ou igual a 100

Solução 2
fazer o delete dos registros antigos diretamente (sem recursividade)
DELETE FROM pais WHERE id NOT IN (SELECT * FROM  (SELECT id FROM pais ORDER BY id DESC LIMIT 100) alias);

solução 2 - referência: http://www.olamundo.blog.br/blog/?p=63
Comment: ,@SneepS NinjA, como estes dados terão de ser atualizados em tempo real isso não pode ser oneroso? alem desta abordagem há como fazer isto a nível de aplicação tipo fila em PHP? (a proposito muito boa sua solução)

Salvar campo input no banco de dados


biological fluorescence supervised machine learning

Question: Some general questions...
So it appears with most classification learners one must come up with a series of quantifiable variables to associate with each observation. This might include mean and std deviation intensity values, texture, and zernike polynomials. Does anyone have any other suggestions as to how one might quantify 3-dimensional fluorescence pixel data features?
Once appropriate quantification's have been acquired for a given class one can then train a classifier. My next question is - does one then have to segment test images and create a matrix of the same feature variables from that segmented image to use the classifier? Or can one use the raw image itself?
What supervised machine learning techniques will evaluate the raw image data itself - either for training or testing? Can manually annotated data sets or clustered data sets provide a direct model for training data? That is to say, are there supervised machine learning algorithms which accept pure pixel data as models for training?
Are there reliable pre-trained classifiers that are already implemented for these type of fluorescence data sets?
Any resources or advice is greatly appreciated.
Comment: Your 5 questions seem to add up to a request for a lengthy journal article.  Can you narrow down?
Comment: Fair enough.  So first.... I can do feature extraction and selection easy enough creating an arbitrary feature set in addition to common features such as those mentioned and others I've found.

So hopefully a fairly straightforward question - does one have to carry out the same feature analysis on the test data (if training a classifier)?  Does one have to carry out the same feature analysis on any future data which needs to be classified?
Answer:
What supervised machine learning techniques will evaluate the raw image data itself - either for training or testing? Can manually annotated data sets or clustered data sets provide a direct model for training data? That is to say, are there supervised machine learning algorithms which accept pure pixel data as models for training?

This is more or less the idea behind Representation Learning. For image feature extraction, Convolutional Neural Networks have established themselves as the reference.
Comment: Awesome.  This is what I was thinking. I have been trying to play around with WEKA for example to get some ideas.  I wasn't sure if they were taking the ROI information and using it as some type of truth field or if they were turning the data into some singular numeric metric.


Is XML schema validation of Citrus usable if the schemas have no target namespace?

Question: I have tried to set up an XsdSchemaRepository in Citrus that contains some XML schemas. Because these schemas have no target namespace (they are not mine, I cannot fix this), I also configured a RootQNameSchemaMappingStrategy because the default strategy to map namespaces does obviously not work.
However, I failed because of the following Exception in a Spring class:
Caused by: java.lang.IllegalArgumentException: class path resource [path to my schema file] has no targetNamespace
    at org.springframework.util.Assert.hasText(Assert.java:181)
    at org.springframework.xml.xsd.SimpleXsdSchema.loadSchema(SimpleXsdSchema.java:128)
    at org.springframework.xml.xsd.SimpleXsdSchema.afterPropertiesSet(SimpleXsdSchema.java:117)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)

Is it possible to do XML schema validation with Citrus if the schemas have no target namespace?
Answer: The target namespace restriction comes from Spring's SimpleXsdSchema implementation. You could implement your own subclass that provides a default namespace though:
public class NoTargetNamespaceXsdSchema extends SimpleXsdSchema {

    @Override
    public String getTargetNamespace() {
        return Optional.ofNullable(super.getTargetNamespace())
                       .orElse("urn:uuid:" + UUID.randomUUID());
    }
}

You can add the custom implementation to the Citrus schema repository as Spring bean reference:
<bean id="noTargetNamespaceXsdSchema" class="com.consol.citrus.xml.schema.NoTargetNamespaceXsdSchema">
  <property name="xsd" value="path/to/sample.xsd"/>
</bean>

<citrus:schema-repository id="schemaRepository">
  <citrus:schemas>
    <citrus:reference schema="noTargetNamespaceXsdSchema"/>
  </citrus:schemas>
</citrus:schema-repository>

Comment: Works perfect, except that `super.getTargetNamespace()` does not return `null` but an empty String. Thanks


jquery error TypeError: Value not an object. with .split(',')

Question: i am getting a strange error
Error: TypeError: Value not an object.
Source File: /Scripts/jquery-1.8.3.js
Line: 4

while i am trying to do a .split() with javascript.
Following is the snippet :
$("#item_qty_1").on("keydown", function (event) {

if (event.which == 13) {

    var weight_code = $("#weight_code").val();
    var qty = Number($(this).val());

    if((weight_code == "2" || weight_code == "3") && qty <= 50)
    {

        var qty_sub_val = document.getElementById('item_qty_sub').value;
        var qty_sub = "";

        console.log(typeof qty_sub_val);
        if(qty_sub_val != "" && qty_sub_val !== null)
        {
            qty_sub = qty_sub_val.split(',');
        }

        $("#test").html(qty_sub);

        for(var i=1; i<=50; i++)
        {
            if(i>qty)
            {
                $("#qty_" + i).attr("tabindex","-1").attr("readonly","readonly").removeAttr("last").css("background","#e6e6e6");
            }
            else
            {
                if(qty_sub_val != "")
                {
                    $("#qty_" + i).attr("tabindex",i).removeAttr("readonly").removeAttr("last").css("background","white").val(qty_sub[i-1]);
                }
                else
                {
                    $("#qty_" + i).attr("tabindex",i).removeAttr("readonly").removeAttr("last").css("background","white");
                }
            }
        }
        $("#qty_" + qty).attr("last","0");
        $("#unit1_list").modal();
    }

    event.preventDefault();
    return false;
}

});

it is giving error only when qty_sub_val != ""; i.e. when .split(',') is called.
Comment: What are you getting as the value of `qty_sub_val` ? Did you try alerting it ?
Comment: Why are you adding `$("#item_qty_sub").val() + "";` double quotes at last?
Comment: ``$("#item_qty_sub").val() + ""; better be: `$("#item_qty_sub").val() || "";`
Comment: working here - with 1.7.1/jquery.min.js
Comment: is `#item_qty_sub` a `` element by any chance? if so: jQ returns `null` when nothing was selected. Also `` returns an array, not a string. Best check the return value of `$.val()`, then. And as always: you haven't forgotten about `$(document).ready(function(){/*code here*/});` have you?
Comment: @EliasVanOotegem : no its a text box.
Comment: @NitinKabra: try `console.log(typeof qty_sub_val)`, and perhaps set up [a fiddle](http://jsfiddle.net/)?
Comment: @EliasVanOotegem: its string.
Comment: @NitinKabra: There's got to be something you're not telling us, or something you're missing. You've added `console.log(typeof qty_sub_val)` just above the `split` call? Does `qty_sub_val.length` cause problems, too? or `.indexOf()`? Please, set up a fiddle, or show the value of `qty_sub_val`
Answer: Please check what $("#item_qty_sub") returns. I think it is not returning the right value.
Comment: it is returning the right value. i tried printing the value in div, which is working fine.
Comment: Okay, try storing that value in a variable and do the split. For example: var str = "value of  $("#item_qty_sub")" and then do a split str.spli(',').
Comment: @user1794058: That's what he's doing: `var qty_sub_val = $('#item_qty_sub');`... and that's not working for some bizarre reason...
Comment: No, He is doing an split directly on whatever $('#item_qty_sub') returns, I want him to increase one line of code.
Comment: @user1794058: He's calling `split` on wherever `.val` returns when called on the return value of `$('#item_qty_sub')`, check the question: `var qty_sub_val = $("#item_qty_sub").val();`<-- `.val()` is there


How can I divide $x^3 \over x^2 +1$ using long division?

Question: $$x^3 \over x^2 +1$$
I have the answer as $x -{1 \over x}$ so far but I don't think that's correct.
Comment: use the fact that $x^3 = x^3 + x - x = x(x^2+1) - x$
Comment: It might make more sense to ask one somewhat general question rather than yet another isolated example.
Answer: .............................................................
Comment: Great thanks, I was trying to put the x^2 into the x and so I had x - 1/x which I see was the wrong way to go about it.
Comment: @Jay you' re welcome
Answer: As you suspected, your result is not correct. Rather, $$\frac{x^3}{x^2 +1}  = \frac{x^3 + x - x}{x^2 + 1} = \frac{x(x^2 + 1)- x}{x^2 + 1}  = x -\frac{x}{x^2 + 1}$$
Answer: Or use the Remainder theorem.
x^3 = ( Ax + B ) (x^2 +1 ) + ( Px + Q)
By equating coefficients,
A = 1
B = 0
Q = 0
A+P = 0
P = -1
x ^3 = x ( x^2 +1) - x


How to interpret results from a zero-inflated negative binomial model?

Question: I have a zero-inflated negative binomial model (ZINB) for highly skewed, high zero-count data, $n=6800$. The null model does not reject the ZINB model, and Stata count fit also indicated ZINB over other count models.
Yet, when I run the model with more than the minimum of covariates, the inflation intercept has a coefficient but no error, no $t$, no $p$-value. Does this mean the model is incorrect? Or just the zero-inflated assumptions? Any suggestions?
Answer: Are you using Stata's zinb command to run your regressions?
When there are no standard error estimates, the things that comes to mind as possible explanations are that the model may be too collinear, or that there may be zero-cells for some variables.


Problemas ao clonar um checkbox (plugin de bootstrap)

Question: http://jsfiddle.net/yusy7zr8/2/
Estou usando um plugin de bootstrap:
http://www.bootstrap-switch.org/
Estou tentando clonar este checkbox, mas o checkbox não está sendo checkado (para on e off) após ser clonado.
se eu retirar essa parte:

o clone dessa checkbox não vai funcionar normalmente.
$("[name='chk-teste']").bootstrapSwitch();

se eu retirar esse plugin, funciona (com os comboboxes regulares)
Answer: Quando você utiliza componentes Bootstrap e outros que transformam inputs HTML, eles modificam o seu DOM adicionando vários outros elementos.
Com o Bootstrap Switch você não tem mais apenas um checkbox, você tem divs para criar o efeito do switch:

        ON

        OFF
        <input type="checkbox" name="chk-teste">

Assim, você deve remover todos os divs, adicionar um novo checkbox e ativá-lo como um Bootstrap Switch. Adicionei alguns trechos no seu código existente:
var ativador = function () { $(this).bootstrapSwitch({}); };

var acao = function() {
    var campo = this;

    if (campo.value == "+") {
        var tr = campo.parentNode.parentNode;
        var novoTr = tr.cloneNode(true);
        var botoesNovos = novoTr.getElementsByClassName('btn-add');

        // Remove o DIV do checkbox bootstrap (pode dar blink na tela)
        $(novoTr).find('div').remove();

        // Adiciona um checkbox "puro"
        var $novoCheck = $('<input>', {
           "type": 'checkbox',
           "data-widget": 'bootstrap-switch'
        });
        $('td:first', $(novoTr)).append($novoCheck);
        // Transforma o checkbox em bootstrap-switch
        ativador.apply($novoCheck);

        for(var i=0;i<botoesNovos.length;i++){
            botoesNovos[i].addEventListener('click', acao, false);
        }

        tr.parentNode.insertBefore(novoTr, tr.nextSibling);
    }
};

Em funcionamento: http://jsfiddle.net/twmh7324/
Outra dica: coloque nomes únicos nos elementos clonados. Exemplo: ao clonar a linha, mude o id dela para linha-[count]. Sendo count uma variável contadora, onde você incrementa a cada clonagem.
Comment: Nota: no post original eu coloquei o link errado para o fiddle. Editei com o link correto.


Tips to find magnitude of 2 forces when given the magnitude of their resultant

Question: Forces A and B has a resultant force C with magnitude of 200N.
The magnitudes of A and B have the relation of 2||A||=3||B||.
$\theta$ is the angle between A and C, and the angle between B and C is 2$\theta$.
Determine the value of $\cos\theta$ and $\cos2\theta$.
Then find ||A|| and ||B||.
General tips to get me started on this is appreciated.
Answer: Hint:
Given the angles, the angle between $A$ and $B$ will be $3\theta$ (As $A,B,C$ must lie in a plane).
We have
$$\tag12|A|=3|B|$$
$$\tag2|C|=\sqrt{|A|^2+|B|^2+2|A||B|\cos3\theta}$$
If the angle between $A$ and $C$ is $\alpha$ and that between $A$ and $B$ is $\theta$, then
$$\tag3\tan\alpha=\frac{|B|\sin\theta}{|A|+|B|\cos\theta}$$
Here, replace $\alpha$ with $\theta$ and $\theta$ with $3\theta$.
$$\tag4|C|=200$$
Use $(1)$, $(3)$ and $(4)$ to substitute in $(2)$
Comment: Hey thanks for the hint. However, I am to find $\cos\theta$ and $\cos2\theta$ prior to finding $\cos3\theta$, and then finally ||A|| ||B||. Is there a different way to approach this question in this order?
Comment: @Yuxie In $(3)$, you can write $\cos3\theta=4\cos^3\theta-3\cos\theta$, and using that find $\cos\theta$. Then, $\cos2\theta=2\cos^2\theta-1$. Finally, you can use these values and $(1)$ iin $(2)$ to get one of $|A|$ and $|B|$. Then, substitute back in $(1)$ to get the other.
Comment: Sorry for all these questions but, how would you use $\cos3\theta = 4\cos^3\theta-3\cos\theta$ in $(3)$ to find $\cos\theta$?


Control angularjs ui switch from external event

Question: I have a angularjs material ui switch. I want to change its status when an external event happens. This external event is a mqtt message received on one of the published topic. I am using node.js mqtt client running on a browser.

        <md-switch ng-model="switch_status.sw1" aria-label="Switch"
                   ng-change="onChange(switch_status.sw1)">
                Switch: {{ switch_status.sw1 }}
        </md-switch>

The corresponding controller code;
angular.module('myApp.controllers', [])
    .controller('SWCtrl', ['$scope',
        function ($scope, ) {
            $scope.switch_status = {
                sw1: true,
            };

            var mqtt_client = mqtt.connect('ws://127.0.0.1:3000');
            mqtt_client.subscribe('hello/world');
            mqtt_client.on('connect', function () {
                console.log("MQTT connected");
            });

            mqtt_client.on("message", function(topic, payload) {
                console.log([topic, payload].join(": "));
                if (topic === "hello/world" && payload.toString() === "switch on")
                {
                    console.log("message on");
                    $scope.switch_status.sw1 = true;
                }
                else if (topic === "hello/world" && payload.toString() === "switch off")
                {
                    console.log("message off");
                    $scope.switch_status.sw1 = false;
                }
            });

            $scope.onChange = function (sw_state) {
                if (sw_state === true) {
                    mqtt_client.publish('hello/world', 'switch on');
                }
                else if (sw_state === false) {
                    mqtt_client.publish('hello/world', 'switch off');
                }
            }
        }])
;

The code segment in the controller that gave me problem is here;
        mqtt_client.on("message", function(topic, payload) {
            console.log([topic, payload].join(": "));
            if (topic === "hello/world" && payload.toString() === "switch on")
            {
                console.log("message on");
                $scope.switch_status.sw1 = true;
            }
            else if (topic === "hello/world" && payload.toString() === "switch off")
            {
                console.log("message off");
                $scope.switch_status.sw1 = false;
            }
        });

When an external event happens, I want to change the switch status. How I did it was running the line of code below;
$scope.switch_status.sw1 = true;

Unfortunately, this does not work. How to make the switch change status when the external event happens?
Answer: try $scope.$apply() after the
$scope.switch_status.sw1 = true;

basically it wasn't an angular event so angular has no idea that the variable was even change. scope.apply will force another digest cycle


how to simulate keypress for unit testing in jasmine

Question: I need to unit test function that is triggered when key pressed.
public onKeyDown(event: KeyboardEvent): void {
    if (event.ctrlKey && event.keyCode === 38) {
      console.log('increase');
    }
    if (event.ctrlKey && event.keyCode === 40) {
      console.log('decrease');
    }

    /* Prevent entering characters */
    if (event.keyCode >= 65 && event.keyCode <= 90) {
      return;
    }
  }

How can I simulate keypress to satisfy the fist condition, for example?
Comment: http://stackoverflow.com/questions/961532/firing-a-keyboard-event-in-javascript
Answer: The example code below shows how an event is created, triggered, and intercepted.
var keyPressed = null;

function keyPress(key) {
  var event = document.createEvent('Event');
  event.keyCode = key;
  event.initEvent('keydown');
  document.dispatchEvent(event);
}

document.addEventListener('keydown', function(e){
   keyPressed = e.keyCode;
});

keyPress(37)
alert(keyPressed);


Replace Exchange 2013 with 2019 servers and HWLWC

Question: My setup is hybrid with all mailboxes in O365.
On-prem we have 2 x 2013 servers used for management and mail relay.
I would like to add 2 x 2019 servers to initially run concurrently with the 2013 ones then move all apps and services that use relay from 2013 to 2019.
My question is:
Can I configure the new 2019 boxes connectors, certs etc same as the 2013 > test email relay and mailbox management > if all OK > move all apps to use 2019 as mail relay > power off 2013 servers (test nothing is pending) > and then run HWC?
Or do I need to run HWC after the new 2019 ar in coexistence?
And then run HWC again when after decommission the 2013 boxes?
HWC scares me a lot! I'm afraid to lose connection to O365…
Thanks m
Answer: You could refer to this case:How can i upgrade the Exchange Server 2013 to Exchange Server 2019 with existing Hybrid Setup
Install Exchange 2019 coexists with Exchange 2013 directly. After that, enable MRSProxy for your Exchange 2019 server:
<code>Set-WebServicesVirtualDirectory -Identity "[<Server>\]EWS (Default Web Site)" -MRSProxyEnabled $true
</code>
After that, you will could rerun HCW to choose Exchange 2019 as hybrid server. If you want to uninstall Exchange 2013, you also need to configure virtual directory for Exchange 2019 and change public DNS(such as mail.domain.com, autodiscover.domain.com) record from Exchange 2013 to Exchange 2019.
Answer: If I don't have any mailboxes on-prem do I still need to run MRSProxyEnabled command?
All my mailboxes have gone to 365 long time ago and all I use Exchange for is mail relay and management of accounts.


Access asp content from a Popup Window

Question: I want to access a asp TreeView from a Popup window. I made it public, so I can have access.
Code in Chile or Popup Page,
SomeWebPage FlViewPage = new SomeWebPage();
lblMessage.Text = FlViewPage.TreeView1.Nodes.Count.ToString();

The problem is that when I run the WebSite I got an error:
Object reference not set to an instance of an object.

WebPage (From which the Popup is called) Code the Tree is populated dynamically,
    <%@ Page Title="Folder View" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="FolderView.aspx.cs" Inherits="SwimWebFile.FolderView" %>

 <asp:Label ID="lblTitle" runat="server" Text="Documents"></asp:Label>

        Click Here for Upload

        <asp:TreeView ID="TreeViewDocuments" runat="server" ExpandDepth="0"
            ImageSet="Simple" Visible="False" onprerender="TreeView_PreRender">
            <HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
            <LeafNodeStyle NodeSpacing="10px" />
            <Nodes>
                <asp:TreeNode Text="System" Value="Systems" Expanded="False"
                    SelectAction="Expand">
                </asp:TreeNode>
                <asp:TreeNode Text="Document" Value="Documents" Expanded="False"
                    SelectAction="Expand">
                </asp:TreeNode>
            </Nodes>
            <NodeStyle Font-Names="Tahoma" Font-Size="Medium" ForeColor="Black"
                HorizontalPadding="0px" NodeSpacing="7px" VerticalPadding="0px" />
            <ParentNodeStyle Font-Bold="False" />
            <SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD"
                HorizontalPadding="0px" VerticalPadding="0px" />
        </asp:TreeView>
            <asp:Button ID="btnNewFolder" runat="server" Text="New Folder"
            onclick="btnNewFolder_Click" UseSubmitBehavior="False"/>
            <asp:Button ID="btnRenameFolder" runat="server" Text="Rename Folder" />
            <asp:Button ID="btnDeleteFolder" runat="server" Text="Delete Folder" />

Code behind,
protected void Page_Load(object sender, EventArgs e)
    {
            if (!HttpContext.Current.User.Identity.IsAuthenticated) {
                TreeViewDocuments.Visible = false;
                lblTitle.Text = "You need to be logged in.";
            }
            else
                TreeViewDocuments.Visible = true;
    }
    protected void TreeView_PreRender(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
           AddNewNode();
        }
    }
    // Some Code to pop
     protected void AddNewNode()
     {
      ...
     }
    .
    .
    .
    protected void btnNewFolder_Click(object sender, EventArgs e)
    {
Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "", "targetWin = window.open('NewFolderPopup.aspx', 'Add Folder', 'toolbar=0, location=0, directories=0, status=0, resizable= 0, menubar=0, copyhistory=no, width=460, height=150');  targetWin.moveTo((screen.height / 2) - (150/ 2), (screen.width / 2) - (460 / 2));", true);
    }

Error,
    Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 56:             FolderView FlViewPage = new FolderView();
Line 57:             lblMessage.Text = FlViewPage.TreeViewDocuments.Nodes.Count.ToString();

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   SwimWebFile.NewFolderPopup.btnCreate_Click(Object sender, EventArgs e) in C:\Users\...\NewFolderPopup.aspx.cs:57
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

Answer: there is a lot that could be null I would hook up a debugger to it and see what is null. At this point my guess is Treeview1 or FlViewPage is but I might not have the full picture as well
Comment: Yeah is confusing because, the TreeView is already populated in SomeWebPage, so I don't know why is no passing it parameters or nodes.
Comment: Can you post what somewebpage looks Luke ?
Comment: Code added. The Popup window is opened when the btnNewFolder is called from the FolderView.aspx. I want to get the TreeView nodes to this popup window.
Comment: Can you post the call stack that your getting with the exception ?
Comment: Stack trace added. I just put the '.count' to see if some value can be transfer between the web pages.
Comment: what is on line 58 ?
NewFolderPopup.aspx.cs:58
Comment: Well sorry, the line should be 57, the problem is that I was editing to remove unnecessary comments or blank spaces.
Comment: ok what I would do is set the label to  FlViewPage.tostring() if that works do  FlViewPage.TreeView1.tostring ect and figure out where your issue is
Answer: I found a work around for this problem. I used the Session method to receive just the value instead the whole TreeView.
Thanks for the advice!

Access asp content from a Popup Window


Is this pattern between Primary and Secondary chord notes important?

Question: I recently noticed a pattern between the Primary (I IV and V) Chords and Secondary (II III VI VII) chords as they are further harmonized in 3rds all the way to 13ths.
Starting with the basic triads and arranging them into a chart, I broke down note counts in the two chord categories and got this chart:

Then I noticed that the secondary chords taken together, are opposite to the primary chords, in that any note that only appears once in the primary chords, appeared twice in the secondary chords, and any note that shows up twice in the primary chords taken together, shows up only once in the secondary chords, taken together.
As the harmonization continues in 3rds, the notes in each chord category that increase with each degree of harmonization are opposite in the Primary category as opposed to the Secondary category:

I noticed how under the primary chord category, the counts for the notes A, D, and E were added to, and in the secondary chord category the counts for the notes C, F, G, and B were increased. This pattern was present through each step of harmonization in 3rds: 7ths, 9ths, 11ths and finally in the 13ths pictured above.
Is this pattern important in understanding something to do with why the I, IV and V chords ARE primary chords, and the II, III, VI, and VII chords are secondary?
P.S: I'm not sure if "Primary" and "Secondary" are the right terms to describe the 'I IV V' chords versus 'II III VI VII' chords. Sorry for any misunderstandings.
P.P.S: I know it isn't appropriate to upload pictures if the post wouldn't be clear without them, but posting these photos of the charts I made was the only way I could get the formatting right.
Comment: In RN, caps are used for majors, while lower case represents minors. Thus**I ii iii IV V vi viio**. Check out *tertiary chords*.
Comment: Given that the ii-V-I chord progression is so common, swap IV and II. Do you get the same results?
Comment: @ Dekkadeci I haven't had the opportunity to swap chords in 3rds, but I did try different chords in 2nds, 4ths, and 5ths. I found that so long as each of the 7 notes in the chosen key appeared at least once in the 3 chosen chords, then the pattern held. Please see my comment on ttw's answer below.
Comment: @Dekkadeci The ii is a viable substitute for the IV and vice verse.  Whether or not you get the same result depends on voicing.  In fact a major 6 chord and its relative minor 7 are identical (enharmonic).  The maj and min chords in a key all pair this way, (I, vi), (IV, ii) and (V, iii).
Answer: It's a counting argument. There 7 chord roots and 3 notes per chord giving. The most equal partition of 3 is 2 + 1 so some notes occur in 2 chords and some in 1. All these patterns are a consequence of laying out chords in thirds. Primary and Secondary are the correct names. Thus if a secondary chord is made into a dominant seventh type by sharpening the third and adding a minor seventh (at least in the major scales, these are names "secondary dominants." Example, D7, A7, and E7 in the key of C.)
A minor scale will show a similar pattern with the change being that the sharpened seventh is used for the V and vii chords. (The VII chord makes the minor mode a bit less symmetrical.)
Comment: It seems you're correct, ttw. This holds out even for harmony in 2nds, 4ths, and 5ths. Each one gets the same result. An aside: I don't know what primary chords or secondary chords are in anything other than 3rds, so I chose chords to use based on the results of the primary chords having all 7 notes, collectively. This pattern remains, no matter which chords are chosen, so long as all 7 notes are present at least once.


If $a>1$ and $b \mid a^2+1$ and $b>a$.Prove that $b-a > \sqrt{a}$.

Question: If $a>1$ and $b \mid a^2+1$ and $b>a$.Prove that $b-a > \sqrt{a}$.
I take $b=a+m$ where $m$ is a natural number then we have:
$b \mid a^2+1 \Rightarrow b \mid m^2+1 \Rightarrow b-1 \le m^2 \Rightarrow a \le m^2 \Rightarrow \sqrt{a} \le b-a$
But I don't know why I get the equality case with it.I can't even prove or disprove that there is an equality case.
Comment: Interesting Q!............
Answer: If you have
$$b-a=\sqrt{a}\to m=\sqrt{a}\to a=m^2\to b=m^2+m$$
once $b|a^2+1$ then
$$(m^2+m)|(m^4+1)\to m^4+1=k(m^2+m)\to m|m^4+1\to m=1$$
what is not true because $a=m^2>1$.
Answer: With $b=a+m$ we have $b| b(a-m)=(a+m)(a-m)=a^2-m^2=(a^2+1)-(m^2+1),$ so $b|m^2+1,$ so $b\leq m^2+1.$
Now if $m\leq \sqrt a$ then $a<b\leq m^2+1\leq (\sqrt a)^2+1=a+1 ,$ implying $b=a+1.$ But $a+1$ cannot divide $a^2+1.$ Otherwise $a+1| a(a+1)-(a^2+1)=a-1>0,$ which implies $a+1\leq a-1,$ a paradox. Therefore $m>\sqrt a.$


How can cross these elements so as to be responsive?

Question: I have this site:
http://avocat2.dac-proiect.ro/?page_id=25
At this point my items are centered as they wish. The only problem is that it is not responsive.
This is code HTML:

[Contact_Form_Builder id="10"]

This is code CSS:
   .container3 {
      background-color: green;
    }
    .centered {
      display: table;
      margin: 0 auto;
      background-color: red;
    }

     div[wdid="4"] {
    width: 40%;
    display: inline-block;
}

     div[wdid="22"] {
    width: 40%;
    display: inline-block;
    margin-left:-40px;
}

     div[wdid="2"] {
    width: 40%;
    display: inline-block;
}

     div[wdid="6"] {
    width: 40%;
    display: inline-block;
    margin-left:-40px;
}

If you delete this code, my elements are responsive but are not aligned properly.
 .contactform10 .wdform_column
{
width:50% !important;
}

I tried to use min-width and max width for this but does not work so take one above the other elements
Basically, my div red is divided into two equal parts, each having a width of 50%.
Can you please help me solve this problem?
Items to be displayed as they are now and be responsive.
Thanks in advance!
Comment: following the site link, and viewing source I see not only is the site using bootstrap, but it IS responsive.. perhaps you can be more specific with the question??
Comment: Are you using Bootstrap?  I see the col-md-4, col-sm-4 classes...
Comment: One problem I see on the site is that the "name" and "phone" inputs overlap, more so on narrower screens. But that's not what you're talking about, is it?
Comment: I use bootstrap, here shown when resize the window...http://i59.tinypic.com/5kr0bn.jpg
Comment: your code is a mess and to solve all your issues we would have to re-write most of it. Please read Bootstrap docs, see how the grid system works, see how you're missing the `.container` class and how you're placing `col-*` classes at random and you'll be able to sort it out. Also, unless you're looking for something really weird, if you have `overflow:hidden` .... well, when resized, any overflown element will disappear . Fix structural issues first and you'll save lots of time
Answer: Using "Push/Pull" with bootstrap will help you reposition elements in a stacked order when the screen resizes... perhaps this is what you meant?
full size:
| ITEM 1 | ITEM 2|
Smaller size:
| ITEM 1 |
| ITEM 2 |
Bootstrap discusses it here: http://getbootstrap.com/css/#grid-column-ordering

If this is the case, this question/answer may also assist you:
Bootstrap 3: Push/pull columns only on smaller screen sizes
I use foundation (not bootstrap) and to do it in that framework you simply set up as similar to this pseudo-code:

lorem ipsum

qwerty colec


4part harmony, secondary dominant's deceptive cadence

Question: Is it a rule that in a secondary dominant's deceptive cadence the root note goes upper one step to the target chord's root note and the 7th note goes down one step to the 5th note ?

Is this a rule that has to be followed ?
Answer: This is true, but think of it less as a rule and more of a byproduct of following other rules. Specifically, following these two concepts will result in what you describe:

The bass moves up by step because, typically speaking, the deceptive resolution is understood as a V moving to its related vi (or VI). There are other deceptive/evaded/attenuated resolutions, but V–vi is certainly the most common (especially in theory textbooks!).

The chordal seventh moves down because it just always does in this style (with one exception that we don't need to mention here). Anytime you have a chord with a seventh, whether it be V7 or ii7 or viio7/vi, the chordal seventh should always move down by step.

So when you follow the two above rules, the byproduct is exactly what you say: the root in the bass goes up while the seventh goes down.
Comment: But what if it was in inversion ? Will the same rule apply ? No matter whatever position the notes are on, will this rule apply the same ?
Comment: @HyunYooPark These are almost always found in root position, but if the V is inverted, the chordal seventh will still go down. The smoothest voice leading would be to have the root move up, but I guess it is possible for it to move elsewhere.
Comment: The examples shown go to ii and iii. I feel that the most common interrupted cadence is the one which goes to vi. Which is generally preceded by V or V7. How wrong am I? And - who says it's a 'rule'..?!


Grid filled with +1 or -1 is adjusted such that each cell is the product of its adjacent squares

Question: In a 9x9 grid, we fill each square with either +1 or -1. We define an adjustment of the numbers in the grid as follows:
1. For each square, we calculate the product of its 4 adjacent squares (fewer than 4 for edge or corner squares).
2. We replace the value of each square with this corresponding product.
Show if the following statement is correct:
'For any initial statement of the grid, after a sufficient (finite) number of adjustments, all the grid becomes +1.'
If correct, prove it; otherwise, give an example.
I played around with this in Python, and realized that the pattern repeats itself after every 12 iterations of the adjustment, for any starting setup, and so the statement is definitely false. However, I am unable to prove this mathematically.
Comment: So, you found a particular grid which gets in a cycle of length $12$? Then, simply writing down that grid is a sufficient disproof. Anyone who sees the grid can trivially compute the next $12$ stages, and verify that you end up in a cycle, so that is all the proof needs.
Comment: Are you trying to prove the falsity of the original statement mathematically or the specific claim that all grids repeat after 12 iterations?
Comment: I am trying to prove the falsity of the statement, I just happened to find out that the grid repeats after 12 iterations.
Comment: I am not convinced that every starting pattern repeats after 12 adjustments- are you certain?
Comment: @MikeEarnest This question popped up in an exam I had taken, and the approximate time limit for this question was approximately 25 mins. It would have been very tough, though not impossible, to start with a random setup (or a simple pattern) and run the iteration 12 times, to realise it repeats. I was trying to find the solution the examiner intended, hoping it wasn't just brute force.
Comment: @Sal Although the initial setup does not repeat in most cases, the following patterns after consecutive adjustments seem to cycle. I noticed that the 4th, 16th, 28th, etc. iterations all result in the same grid pattern.
Comment: I've put some thought in to the "invariant" strategy as @Sal suggested. You might be able to make an invariant by taking the product of the entries in some subset of the squares in the grid. If you call the squares in your subset "important" squares, then you get the following rules for what squares can be important:-Every unimportant square must  be adjacent to an even number of important squares, and every important square must be adjacent to an odd number of important square (you might want to check that these are sufficient but I'm pretty sure they're necessary).
Comment: On further thought though, that doesn't help much because exactly the same  requirements would give you a grid that get's adjusted back to itself, so the whole "look for grids that eventually go back to themselves" thing works more generally
Comment: What might help is the following: Start with $A\in \mathbb \{-1,1\} ^{9\times 9}$. Now map each cell of $A$ as follows: $1\mapsto 0, -1\mapsto 1$. If we now interpret $A$ as a matrix over $\mathbb F_2$, then one adjustment step consists of replacing the value of each cell of $A$ with the sum of its neighbor cells. With that, the adjustment rule can be written as a matrix $M$ over $\mathbb F_2$, and the statement now is that $M$ is nilpotent.
Answer: The statement is false.
A counterexample is
$$
A=\begin{array}{c|c|c|c|c|c|c|c|c}
  1 & 1 & \color{red}{-1} & 1 & 1 & 1 & \color{red}{-1} & 1 & 1 \\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1\\\hline
 \color{red}{-1} & 1 & 1 & 1 & 1 & 1 & 1 & 1 & \color{red}{-1}\\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1\\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1\\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\\hline
\color{red}{-1} & 1 & 1 & 1 & 1 & 1 & 1 & 1 & \color{red}{-1}\\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\\hline
 1 & 1 & \color{red}{-1} & 1 & 1 & 1 & \color{red}{-1} & 1 & 1
\end{array}
$$
This becomes
$$B=
\begin{array}{c|c|c|c|c|c|c|c|c}
 1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 \\\hline
 \color{red}{-1} & 1 & \color{red}{-1} & 1 & 1 & 1 & \color{red}{-1} & 1 & \color{red}{-1}\\\hline
 1 & \color{red}{-1} & 1 & 1 & 1 & 1 & 1 & \color{red}{-1} & 1\\\hline
 \color{red}{-1} & 1 & 1 & 1 & 1 & 1 & 1 & 1 & \color{red}{-1}\\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1\\\hline
\color{red}{-1} & 1 & 1 & 1 & 1 & 1 & 1 & 1 & \color{red}{-1} \\\hline
1 & \color{red}{-1} & 1 & 1 & 1 & 1 & 1 & \color{red}{-1} & 1 \\\hline
\color{red}{-1} & 1 & \color{red}{-1} & 1 & 1 & 1 & \color{red}{-1} & 1 & \color{red}{-1} \\\hline
1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 \end{array}
$$ which becomes $A$.

To find a counterexample of $9\times 9$, I first tried to find a counterexample of $4\times 4$, and got the following counterexample :
$$
C=\begin{array}{c|c|c|c}
  1 & 1 & \color{red}{-1} & 1 \\\hline
 1 & 1 & 1 & 1 \\\hline
 \color{red}{-1} & 1 & 1 & 1\\\hline
 1 & 1 & 1 & 1 \end{array}
$$
This becomes
$$
D=\begin{array}{c|c|c|c}
  1 & \color{red}{-1} & 1 & \color{red}{-1} \\\hline
 \color{red}{-1} & 1 & \color{red}{-1} & 1 \\\hline
 1 & \color{red}{-1} & 1 & 1\\\hline
 \color{red}{-1} & 1 & 1 & 1 \end{array}
$$
which becomes $C$.
From $C$, I got $A$.
Comment: Nice answer. I think, however, that OP is asking about a way to validate this without trial and error, perhaps using invariants like in the [sliding puzzle](https://en.wikipedia.org/wiki/15_puzzle?useskin=vector)
Answer: Let A be
\begin{array}{c|c|c|c|c|c|c|c|c}
  1 & \color{red}{-1} & \color{red}{-1} & 1 & 1 & 1 & \color{red}{-1} & \color{red}{-1} & 1 \\\hline
 \color{red}{-1} & 1 & 1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 & 1 & \color{red}{-1}\\\hline
 \color{red}{-1} & 1 & 1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 & 1 & \color{red}{-1}\\\hline
  1 & \color{red}{-1} & \color{red}{-1} & 1 & 1 & 1 & \color{red}{-1} & \color{red}{-1} & 1 \\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1\\\hline
  1 &\color{red}{-1} & \color{red}{-1} & 1 & 1 & 1 & \color{red}{-1} &\color{red}{-1} & 1 \\\hline
 \color{red}{-1} & 1 & 1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 & 1 & \color{red}{-1}\\\hline
 \color{red}{-1} & 1 & 1 & \color{red}{-1} & 1 & \color{red}{-1} & 1 & 1 & \color{red}{-1}\\\hline
  1 & \color{red}{-1} & \color{red}{-1} & 1 & 1 & 1 & \color{red}{-1} & \color{red}{-1} & 1
\end{array}
The grid does not change at all.
Answer: One more example. Let $a_{i, j} = -1$ if $i \in \{1, 3, 5, 7, 9\}$ and $a_{i, j} = 1$ if $i \in \{2, 4, 6, 8\}$.
A=\begin{array}{c|c|c|c|c|c|c|c|c}
  \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} \\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1\\\hline
 \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1}\\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1\\\hline
 \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1}\\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\\hline
\color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1}\\\hline
 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 \\\hline
 \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1} & \color{red}{-1}
\end{array}
The idea is that the even rows do not change, and the odd rows are changing separately. We only need to check that row of nine -1's enters period 6 after 3 iterations. Although this proof still requires some calculations.


Sistema em PHP responder em Partes

Question: Vi que é possível fazer um sistema em PHP que responde em partes, não apliquei, mas basicamente seria usar esta função:
ob_implicit_flush()
Assim qualquer saída seria enviada diretamente para o navegador do browser, ao contrário de esperar o sistema finalizar para enviar tudo para saída.
Bom, isto tem grandes impactos em desempenho, isso poderia ser ruim de alguma forma?
A ideia é listar produtos, e ir imprimindo conforme o PHP der a saída(echo), assim daria para ver alguns produtos sem precisar que todos fossem processados para sucessivamente dar a saída.
Answer: Do ponto de vista de uma conexão TCP, não há nenhum problema. O que acontece quando você envia a resposta em partes, ao invés de uma única resposta, é que a camada de transporte cria um buffer com os dados e só os dispara quando ordenado (ou seja, quando ocorre uma chamada ob_flush, por exemplo).
Acredito que o maior problema dessa prática seja a experiência do usuário, pois pode ser algo frustrante a página ir carregando, carregando, e não chegar no final do carregamento nunca. A não ser que você adote uma barra de progresso ou lhe dê algum tipo de feedback.
Também é importante tentar diagnosticar o gargalo, ou seja, porque a página está demorando tanto para carregar. Talvez seja uma boa diagnosticar suas consultas SQL, arquivos estáticos (CSS, JS), tamanho do HTML, dentre outros aspectos.

Sistema em PHP responder em Partes


A curve that starts with exponential growth and levels out

Question: I'm stuck on a mathematical problem in a small feature I'm building for a website. I need a function that starts out with exponential growth and than levels out as x grows. I've drawn this wonderful picture to communicate what I'm looking for since my math lingo isn't the best.
Any help appreciated.
Answer: I think you want a sigmoid function.
Comment: Thanks, solved my problem :)
Comment: Use these all the time for programming, easiest to use are logistic and `atan`
Comment: You say "starts out with exponential growth", so you want the logistic function.
Answer: Perhaps you are looking for something like ${\rm erf}(x-2)+1$, where erf is the error function, ${\rm erf}(x) = \frac{2}{{\sqrt \pi  }}\int_0^x {e^{ - t^2 } dt} $. You can use WolframAlpha to watch the graph: plot $f(x)={\rm erf}(x-2)+1$, say from $0$ to $5$. Further see Wikipedia's plot of the error function, here, to understand the reason for choosing ${\rm erf}(x-2)+1$.


How can I detect a "page's" content type?

Question: I have begun work on a Drupal website and unfortunately I did not have an opportunity to have them walk me through the website as is.
I'm now trying to replicate content from a development site to a live site, but there is a page which I cannot identify as a particular content type, though I know it is content, because it says on the page "Clone Content."
How can I figure out this page's content type so that I can replicate it? Is this the right question to be asking?
I apologize if this is an ambiguous question, I will clarify any detail needed.
As a side note: Is there any way to clone content between Drupal websites? Like exporting and importing? Perhaps a tutorial I should check out?
Thanks so much in advance.
Comment: Upon re-visiting this question that I asked a couple years ago, I wanted to clarify why this issue was unclear. The content type of the node had been deleted, yet the node had remained. Therefore, there was a node with no content type. If you have an issue where the option to clone it does not list the content type, one possibility is that the content type has since been deleted and the node was not deleted with the content type.
Answer: A few quick answers to your questions:

If you view source on any page, you should see a class name on the body element, something like: node-type-article. This is one way to see the content type. Also, if you edit a page, you'll see that the edit title will look something like this: Edit [content type] [title]
Alternatively, navigate to: [domain]/admin/content to see a list of all content, which includes the 'type' column
The "clone content" link content comes from a module called "node clone" https://www.drupal.org/project/node_clone, designed to allow in-place duplication of content (fields that should not be duplicated are reset to safe values)
There is another module that will allow you to export/import nodes between drupal installs: https://www.drupal.org/project/node_export It's probably not worth it to get into this unless you have quite a lot of content to move.
Comment: Thanks a lot! That's really helpful, especially since I'm still getting acclimated to using Drupal.
Comment: NP. there's plenty to get acclimated to :)


How disable all the clicks excepts particular elements using angular link function

Question: This is angular directive link function
 function link(WarningService: Warning.Service): ng.IDirectiveLinkFn {
    return ($scope: ng.IScope, element: JQuery): void => {
      element[0].addEventListener('click', () => {

      }, true);
    };
  }

I need to enable the click only Button , anchor , input, select,.nav and other item items i dont want clcikc event.
and also avoid click events for disabled elements.i did using jquery below
$('body').on('click',function(e){
  if(e.target.tagName !== " 'a' || 'button' || 'input' ||  'select' "
  || e.target.className == '.nav')
  {
      e.stopPropagation();
      e.preventDefault();
  }
})

;
Now i need help how to inclcude my jquery code to my angular directive
function link(WarningService: Warning.Service): ng.IDirectiveLinkFn {
    return ($scope: ng.IScope, element: JQuery): void => {
      element[0].addEventListener('click', (e) => {
        if(element[0].tagName !== " 'a' || 'button' || 'input' ||  'select' " || element[0].className == '.nav')
                {
                    e.stopPropagation();
                    e.preventDefault();
                }
                  else{

                  }

      }, true);
    };
  }

Answer: You can try assigning a particular class name to all DOM elements for which you want to disable click event binding . Thus simply check for the class name of the element .
Comment: I am thinking about the same, but vice versa add some class to the elements you want to handle click then select them and attach event handler
Answer: First replace that arrow function for click event handler with function.
element[0].addEventListener('click', function(){
  // here this will refer to your element[0]
  // and then check if this has the class you're looking for or
  // tag name you're looking for
}, true);

Comment: How I need to pass event inside my link function?
Comment: The same way you'd do it `element[0].addEventListener('click', function(e){`
Comment: and you don't need to pass event to your link function. It will be passed implicitly as you've bound click event handler to `element[0]` using `addEventListener`
Answer: You can add a class in top level DOM (body) say disableOthers and maintain a css like
.disableOthers *:not(button):not(a):not(button):not(select):not(nav) {
    pointer-events: none;
}

and just add/remove the class pragmatically in top level hierarchy.


postgresql 9.2.4 hstore search keys Unknown operator

Question: Can't use ?| operator. Works fine with postgresql 9.1.9 (development), fails on 9.2.4 (production)
test=# SELECT 'a=>1,b=>2'::hstore ?| ARRAY['b','c'];
ERROR:  operator does not exist: hstore ?| text[]
LINE 1: SELECT 'a=>1,b=>2'::hstore ?| ARRAY['b','c'];
                                   ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

hstore is installed
test=# create extension hstore;
ERROR:  type "hstore" already exists

Answer: The error message from create extension hstore indicates that you don't actually have the extension hstore installed, just some parts of its contents.  (Otherwise the error message would be extension "hstore" already exists.)  So I suggest you fix your hstore installation.  It might work to do CREATE EXTENSION hstore FROM unpackaged.  If not, you will have to do manual surgery to remove or add the missing parts.
Comment: CREATE EXTENSION hstore FROM unpackaged;
    ERROR:  function hstore_recv(internal) does not exist
Comment: I think it's broken after postgresql upgrade from 8.x


Troublesome two lines of Java script in a SharePoint link?

Question: I'm getting an IE error with these lines of code:
<xsl:value-of
select="@FileLeafRef" />

Error reads "'return' statement outside of function". (It's non-intrusive - just the yellow triangle in the bottom of the browser window.)
I know very little about javascript, so I'm hesistant to correct. Any thoughts, guys?
Answer: I think you want:
<a href="#" ...

Comment: Scott, thank you very much for your answer! That little tip helps me and my coworkers immensely - I hope karma rewards you well for your kindness! THANKS AGAIN!! :D
Comment: @Ryan, if that worked for you can you check the check mark next to the answer so I get credit.


Google Ads interrupt the app. Slow down fps

Question: I use AdView mAdView and the last updated libraries.
I placed the AdView into my layout (as shown in the examples):
<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>

Then I identify it and try to load a new ad in the onCreate() method:
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);

But my layout has some animated objects. This animation is freezing (skipping some frames) while new ad is become visible.
We can't catch the same problem with the disabled Internet (it disables ads and not affect lags).
I'm trying to show the problem with my own record (GIF can't show that completely):
https://www.youtube.com/watch?v=adH2Mn79O7w
How can I remove ads' lags and make the user experience better?
Comment: Need more information on what kind of Ad is loaded. {Video? Text? Image?)
Make sure you don't overlay.
Comment: @FungLAM you see it at the bottom of the second screen. It is Google's Ad. Default Ad - banner: 150x50. And what do you mean when you talking about "overlay"?
Answer: This is a known issue, which has been discussed many times on the net, is enough to search by the words "AdMob fps drop" and the like.
The root of the problem here, most likely, is that running AdMob requires significant resources, which is why the animation starts to stall. As one solution, you can show ads with some delay:
Handler handler = new Handler ();
handler.postDelayed (new Runnable () {
     @Override
     public void run () {
          AdRequest bannerRequest = new AdRequest.Builder (). Build ();
          mAdView.loadAd (bannerRequest);
     }
}, 2000);

You can make the delay not fixed, but bind it to user actions. For example, start downloading ads the moment after the user has stopped scrolling the screen.
Another solution is to disable graphics acceleration for ads by manipulating the LAYER_TYPE_SOFTWARE property.
mAdView.setAdListener(new AdListener(){
    @Override
    public void onAdLoaded(){
        runOnWebView(mAdView, new WebViewAction(){
            @Override
            public void run(WebView view){
                view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
                view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            }
        });
    }
});

For such a solution, it is necessary to implement the following interface:
private void runOnWebView (View view, WebViewAction action) {
    if (view instanceof WebView){
        action.run((WebView)view);
        return;
    }

    if (view instanceof ViewGroup) {
        final ViewGroup parent = (ViewGroup)view;

        for (int i = 0; i < parent.getChildCount(); i++) {
            runOnWebView(parent.getChildAt(i), action);
        }
    }
}

private interface WebViewAction{
    void run(WebView view);
}

Similarly, you can turn off the acceleration for some Activity:
<activity
    android:hardwareAccelerated = "false"
    android:softwareAccelerated = "false" />

Answer: As a workaround which I also have in my apps is setting a layertype:
mAdView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

or
 mAdView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

Comment: I don't think so. It is not working. I have own answer. It helped me
Comment: @EgorRandomize but you added my solution in your answer!! I think you should give me correct sign :)
Comment: Lags are actually here.
Comment: Sure! I actually don't know which part helped indeed.
Comment: view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
  view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

This part and I hope this was the main solution! :)
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/207933/discussion-between-jamil-hasnine-tamim-and-egor-randomize).
Answer: I'd think, that the advertisments shouldn't be a banner, since that is a big advertisment, and that is slowing down the performance, as you should make it small. This also could cover things in your application, (if the advertisment is on banner).
Another thing is that you could not have ads, so that performance would be better. Try any of these. Ads most of the time have very good graphics and may slow down your application. :)
Comment: I'm just can't understand what do you mean. Finally I got that you don't understand the question and AdMob. AdMob uses Google's servers, actually it is Google's subsidiary
Comment: I've to say: ads has a fixed default size: it is really small: 150*50. Graphics? No. It is GIF I guess. `Banner` is the name for ads like this. I've seen it on the AdMob.
Comment: If you have a server, like Google, then  it'd be ok to use advertisments. If not, don't put ads, and have some other way of monotization.
Answer: Place the ad view in a linear layout and implement ad listeners. In onAdLoaded() method of adListener add adView to your linear layout like linearLayout.addView(adView) and put your animation on linear layout. I hope it helps you.


How to move a Player in Vector3 using GPS coordinates? [Unity]

Question: I need to develop a Unity Android APP to help in agricultural guidance and I am facing some very especific GPS problems, let me just explain the project to you.

It needs to use accurate GPS data to guide you on the fields
It won't be able to connect the ethernet, I just get the Latitude
and Longitude, the map is just a infinite ground plane (already
made) not some real world map.
The "player" (tractor, machine,...) needs to move on the Unity
space (not the ground texture, the player itself) because I need to draw a Trail
Renderer for my planting path (already made).

So I have a very specific situation where every API I found moves the ground texture instead of the player object. I need to transform my Latitude and Longitude changes (movement) into Unity space movement, I need to accurately move (transform.Translate) my player on the Vector3 coordinates every time the GPS coordinates changes.
This code is about what I have right now.
<code>//so in the Update method
if (newLat != lastLat || newLong != lastLong){
  //what do I do here?
</code>
EDIT 1:
This guy has the same question as mine on an old post, but got no response.
Answer: After reading this code, I think you can just get the latitude and the longitude and set the position of an object, not move.
By that I mean something like this:
<code>// Get the GPS values (I'm not sure if you can do it like this, I copied it from the code you linked)
latitude = Input.location.lastData.latitude;
longitude = Input.location.lastData.longitude;

// Set the position of a GameObject using the GPS values
transform.position = new Vector3(latitude , 0, longitude);
</code>
Comment: I've tried that, my player keeps frozen at (0,0,0)
since Lat and Long need to be converted to Unity units before using, I've also tried
`code` transform.position = Quaternion.AngleAxis(longitude, -Vector3.up) * Quaternion.AngleAxis(latitude, -Vector3.right) * new Vector3(0, 0, 1);
Found this on https://answers.unity.com/questions/923182/lat-long-to-unity-world-coordinates.html
Comment: For future researchers, use this lib to convert from GPS data to Unity and vice versa
https://github.com/MichaelTaylor3D/UnityGPSConverter


Remainder of Taylor's Theorem using random variables

Question: Let $I$ be an interval and $X$ a random variable with values in I with $E(|X|^m) < \infty \forall m \in \mathbb{N}$. Also let $f: I \rightarrow \mathbb{R}$ with $f \in \mathcal{C}^{(m)}$ bounded. Let $\beta_m$ be a random variable with law beta and density function:
$$\rho_{m}=m(1-\theta)^{m-1} \quad \forall 0 \leq \theta\leq1.$$
Suppose that $X$ and $\beta_m$ be independent, then if $\mu \in I$ we have that:
$$E(f(X))-\sum_{k=0}^m\dfrac{f^{(k)}(\mu)}{k!}E((X-\mu)^k)= \dfrac{1}{m!}E((X-\mu)^m(f^{(m)}(\mu+(X-\mu)\beta_m)-f^{(m)}(\mu))$$
I was given as hints to prove this that I should use for an $x \in I$ the Taylor remainder on the integral form and the write it in terms of the $\beta_m$, then change $x$ with $X$ since it's independent with $X$ and take expectation values then use Fubini.
I'm not able to prove the result, I can make the $\beta_m$ appear by using the fact that $E(\beta_m)=\dfrac{1}{m+1}$ since the $\beta_m$ follow a $Beta(1,m)$ distribution, but I can't figure a way to get the Fubini theorem properly applied so I can compute the integral. I'd appreciate any help.
Comment: Could you provide more details on what you've gotten so far using the integral form of the error term?
Answer: I assume that $f^{(m)}$ is also bounded to ensure the integrability of the random variable $(X-\mu)^m f^{(m)}(\mu+\beta_m(X-\mu))$.
The Taylor formula with integral reminder yields for every $x \in I$
$$f(x) - \sum_{k=0}^{m-1} \frac{f^{(k)}(\mu)}{k!}(x-\mu)^k = (x-\mu)^m \int_0^1 \frac{(1-\theta)^{m-1}}{(m-1)!} f^{(m)}(\mu + \theta(x-\mu)) ~\mathrm{d}\theta.$$
Then apply this formula to $X$ instead of $x$ and take expectation of both sides. Calling $P_X$ the law of the random variable $X$, you get
\begin{eqnarray*}
E[f(X)] - \sum_{k=0}^{m-1} \frac{f^{(k)}(\mu)}{k!}E[(X-\mu)^k]
&=& E \Big[ (X-\mu)^m \int_0^1 \frac{(1-\theta)^{m-1}}{(m-1)!} f^{(m)}(\mu + \theta(X-\mu)) ~\mathrm{d}\theta \Big] \\
&=& \frac{1}{m!} \int_I \Big( \int_0^1 m(1-\theta)^{m-1} (x-\mu)^m f^{(m)}(\mu + \theta(x-\mu)) \mathrm{d}\theta \Big) \mathrm{d}P_X(x)
\end{eqnarray*}
By independence of $\beta_m$ and $X$, the double integral in the right-hand side is the expectation of $(X-\mu)^m f^{(m)}(\mu+\beta_m(X-\mu))$.
The desired formula follows by subtracking the expectation of $\frac{f^{(m)}(\mu)}{m!}(X-\mu)^m$ to both sides.
Comment: Ah man I was on the right track but I walked it backwards, I'll give you the points asap


Como simplificar o código usando um laço?

Question: Como posso simplificar o código abaixo utilizando um laço, estou na dúvida em função do nome dos labels que estão sequenciais, como coloco algo variável em NomeCampo1, NomeCampo2, ..., NomeCampoX.
lblNomeCampo1.Text = dt.Rows[1][0].ToString()+":";
lblCampo1.Text = dt.Rows[1][1].ToString();
lblNomeCampo2.Text = dt.Rows[2][0].ToString() + ":";
lblCampo2.Text = dt.Rows[2][1].ToString();
lblNomeCampo3.Text = dt.Rows[3][0].ToString() + ":";
lblCampo3.Text = dt.Rows[3][1].ToString();
lblNomeCampo4.Text = dt.Rows[4][0].ToString() + ":";
lblCampo4.Text = dt.Rows[4][1].ToString();
lblNomeCampo5.Text = dt.Rows[5][0].ToString() + ":";
lblCampo5.Text = dt.Rows[5][1].ToString();
lblNomeCampo6.Text = dt.Rows[6][0].ToString() + ":";
lblCampo6.Text = dt.Rows[6][1].ToString();
lblNomeCampo7.Text = dt.Rows[7][0].ToString() + ":";
lblCampo7.Text = dt.Rows[7][1].ToString();
lblNomeCampo8.Text = dt.Rows[8][0].ToString() + ":";
lblCampo8.Text = dt.Rows[8][1].ToString();
lblNomeCampo9.Text = dt.Rows[9][0].ToString() + ":";
lblCampo9.Text = dt.Rows[9][1].ToString();
lblNomeCampo10.Text = dt.Rows[10][0].ToString() + ":";
lblCampo10.Text = dt.Rows[10][1].ToString();

Comment: Qual linguagem? Explique melhor esse código ai.
Comment: Amigo, cada linguagem tem suas particularidades. Favor mencionar a linguagem. Isso é básico em todas as perguntas. Quantos mais detalhes, melhor.
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: Essencialmente não dá nesta forma. Daria com reflexão, mas não acho que compense.
Dá para reestruturar o formulário que lida com isto fazendo com que os campos sejam elementos de array também, aí tudo que os envolva podem ser usados com um laço. Aí poderia fazer assim:
lblNomeCampo[i].Text = dt.Rows[i][0].ToString() + ":";
lblCampo[i].Text = dt.Rows[i][1].ToString();

Coloquei no GitHub para referência futura.
Todas as vezes que tem várias variáveis com nomes que tenham uma sequencia de números como sufixo pode substituir por um array (ou estrutura semelhante) de forma simples e direta, ou seja, basta mudar o número fixo pelo índice do array.
Obviamente que tem que criar o array e criar os objetos de tela em cima dos elementos do array.
Cada elemento do array é uma variável como outra qualquer, nada muda nele exceto o fato que ela é acessada pelo conjunto do nome mais o índice. Então as trate desta forma.
Esta solução independe da linguagem, ainda que seria melhor saber qual é (pelo que entendi é C#).
Answer: Não é a melhor maneira mas poderia fazer algo assim, eu não entendo muito de C#, mas o caminho é mais ou menos este:
for (var i=1; i <= 10; i++) {
   Eval("lblNomeCampo"+i+".Text = dt.Rows["+i+"][0].ToString() + \":\";");
   Eval("lblCampo"+i+".Text = dt.Rows["+i+"][1].ToString() + \":\";");
}

Eu sugiro algo mais bem elaborado, tipo:
   foreach (int i in dt.Rows) {
       lblNomeCampo[i].Text = dt.Rows[i][0].ToString() + ":";
       lblCampo[i].Text = dt.Rows[i][1].ToString() + ":";
   }

Deixa os campos no form assim:
name="lblNomeCampo[]"

name="lblCampo[]"

Comment: Que Eval é este?
Comment: Eu estou pensando que deve haver alguma forma de converter o objeto usando eval, assim como é feito em javascript.
Comment: Mas não tem, pelo menos não de forma simples assim. E mesmo assim, não tem porque fazer desta forma quando o *array* funciona. Mesmo em JS ninguém deveria fazer isto.
Comment: Eu concordo... por isso disse que não é a melhor maneira.
Comment: talvez usando: myObject.Field = Convert.ChangeType(value, fieldType);
Comment: Não. é bem mais complicado, e vai contra a filosofia da linguagem, embora seja algo ruim em qualquer linguagem usar um recurso pior quando tem um melhor que faz a mesma coisa.
Comment: ou tipo isso: Type myTypeA = typeof(MyFieldClassA); FieldInfo myFieldInfo = myTypeA.GetField("Field");
Comment: Também não, não adianta, não está nem perto. Não vale a pena perder tempo com algo ruim assim.
Comment: Bom, eu publiquei uma segunda opção, que acredito ser a melhor... e mais elaborada. Vai da pessoa, o que ele prefere usar (não usaria, em meus códigos)... quanto a linguagem, pouco importa pra mim, não sou eu que estou escrevendo o código. Só estou mostrando opções...
Comment: Dá pra ver que o objeto em si que ele está fazendo já está dentro da proposta de XGH, pra começar...


Can we display data in html table using ng-model in angular,database is firestore

Question: I want to display my data in table format, it's coming in input fields but not in table why so? How can I solve this.
<!DOCTYPE html>

Call Details Dashboard

    Name:
    <select [(ngModel)] = "selectedLevel" (change)="selected()" >
      <option *ngFor="let post of posts | async" [ngValue]="post">{{post.user}}
      </option>
    </select>

          Name	 Duration	  Time	 Type

    {{ post.callDuration }}
    {{ post.callTime }}
    {{ post.callType }}

  //require not as per my requirement

Duration:
<input type="type"name="callDuration" [(ngModel)]="selectedLevel.callDuration"> //wokring perfect

Comment: You are missing `| async` in table.....
Comment: Yeah! thank you. That worked. But I want only that data which is selected by user through dropdown.
Comment: then you need to filter the values you want
Comment: any example of that
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Comment: no, not like this :p I want to select the value from dropdown and search that value in database.
Comment: Well then you need to make a firebase query based on what you want to filter. SO isn't really a code writing service, you should provide a [mcve] showing what you have tried and where you are facing issues. Please check [ask].
Answer: You are using input tag to display your data. You need to use table tag. Here you can see the example code for an table.
stackblitz


JavaScript loading order

Question: I've installed eu-cookie-compliance module in few projects and everywhere it worked as expected but in one project I have problems with loading JavaScript in correct order.
Even if I implement hook_js_alter and set higher weights, eu-compliance JavaScript is loaded before misc/drupal.js and misc/jquery.js. Is there any better way to reorder this JavaScript?
Answer: You could always change the group it's in:
function MYMODULE_js_alter(&$js) {
  $js['path/to/eu-cookie-compliance.js']['group'] = JS_DEFAULT;
}

Drupal's misc JS, jQuery etc, should all be in JS_SYSTEM, which has a lower weighting than JS_DEFAULT. There's also JS_THEME which has a height weighting than JS_DEFAULT.
The drupal_add_js() docs discuss the whole JS weighting thing in much greater detail.
Comment: Any chance you've got another module on that site interfering with the JS? I use that method in pretty much every site (and all of those have the eu cookie module installed) to reduce the number of aggregated JS files and it's never failed to work. You might try setting `$js['path/to/eu-cookie-compliance.js']['every_page'] = TRUE;` as a test as well
Comment: I tried everything what you wrote. I even set group and weight in drupal_add_js - no result.
Comment: No, still not working.
Comment: Have you confirmed the same behaviour on a blank install of Drupal? It would rule out your specific site instance being the problem at least
Comment: That's the oddest think, I have used this module on Drupal 6 and Drupal 7 installation, but only here eu-cookie-compliance.js is outputted at the beginning of $scripts variable.
Comment: There must be something different about the JS on that site. It's very difficult to track something like that down without disabling modules systematically :/

JavaScript loading order


Load a node content programmatically

Question: How can i load the user page (profile) in a block or in the body of a another page?
I tried to put a block in the user page but does not work.
Any ideas?
Thanks.
Comment: the user PAGE with all its associated blocks, headers, regions, markup, etc, or the user page profile NODE?
Comment: just the information of the user profile
Answer: You can print the user profile using:
<?php print render($user_profile); ?>.
You can get specific user information by
<?php print render($user_profile['user_picture']); ?>
<?php print render($user_profile['summary']); ?>

Hope this helps.
Comment: This will only work at the theme level. I'm not sure it's what the OP asks for.

Load a node content programmatically