I changed my nixos channel to unstable, why are my packages still not updated?

Question: How do I update my packages from the nixos-18.09 channel to the nixos-unstable channel? I am trying to do this as I need to use updated versions of some packages.
Following the directions in the nixos manual, I have added the nixos-unstable channel https://nixos.org/channels/nixos-unstable, removed the nixos-18.09 channel https://nixos.org/channels/nixos-18.09,
and run $ nix-channel --update and $ sudo nixos-rebuild switch --upgrade.
Still, however, my installed packages are the old versions. I have also tried $ nix-env -u '*' and still have the old versions. What else do I need to do to update my packages to the nixos-unstable versions?
Answer:
I am trying to do this as I need to use updated versions of some
  packages.

You can use packages from different channels. So possibly keeping your default channel as stable, and just referencing particular packages from the unstable channel might be a better solution.
I have the following import in my config (using google-chrome from the channel I have assigned to unstable):
{ config, pkgs, ... }:

let
  unstable = import <unstable> {
    config = config.nixpkgs.config;
  };
in
{
   environment.systemPackages = with pkgs; [
     awscli
     google-cloud-sdk
     kubectl
     libreoffice
     # ...
     unstable.google-chrome
   ];
}

As to why your packages are not using the unstable channel, probably because they reference the nixos channel which you did not seem to modify (you seemed to only add a channel named nixos-unstable, but nothing referenced this channel name most probably).
Answer: To change to the unstable NixOS channel:

Become root; You want to change the root user's Nix channel: su
Remove the NixOS channel: nix-channel --remove nixos
Add the NixOS unstable channel and ensure it's named nixos: nix-channel --add nixos https://nixos.org/channels/nixos-unstable

Then you can upgrade as you normally would. For example, nixos-rebuild --upgrade boot will first update the NixOS channel and then install packages from the updated channel. Upon reboot you'd be updated.
Note: I advise against doing nixos-rebuild --upgrade switch, especially when changing channels, simply because NixOS won't restart all services anyway. Therefore the switch would be incomplete.
Answer: If you want to change all the packages to unstable
{ pkgs, ... }@args:
let
  pkgsUrl = "https://github.com/NixOS/nixpkgs-channels/archive/nixos-unstable.tar.gz";
  pkgs = import (builtins.fetchTarball pkgsUrl) {};
in
{...}


Em python, como posso simular uma propriedade somente-leitura em classes?

Question: Eu gostaria de saber como posso simular uma propriedade somente leitura em Python.
Por exemplo, eu tenho o seguinte código:
class IPInfo(object):
     def __init__(self, ip):
         self.ip = ip;

ip = IPInfo(object)

ip.ip = 'aqui é possível editar, mas quero desabilitar isso';

print ip.ip #aqui é possível imprimir, pois a leitura é permitida

Como eu poderia tornar a propriedade ip somente-leitura?
Comment: Creio que não dá, digo isto apoiado aqui: http://stackoverflow.com/questions/2682745/how-to-create-a-constant-in-python
Comment: @Miguel dá sim :p.
Comment: Ok, se for com decorators dá
Comment: Isso mesmo, hehehehe
Answer: Declare uma propriedade getter-only, usando o decorator @property
class IPInfo(object):
    def __init__(self, ip):
        self._ip = ip;

    @property
    def ip (self):
        return self._ip

ip = IPInfo(object)

ip.ip = 'aqui é possível editar, mas quero desabilitar isso';
#A linha acima vai estourar um erro - AttributeError: can't set attribute

print ip.ip

Comment: @jbueno é verdade. Quando se usa dois, você está indicando uma funcionalidade especial.
Comment: No caso não seria um duplo underline?
Comment: Em **`self._ip`**?
Comment: é ...............
Comment: Poderia dar um exmplo prático jbueno sff. Testei aqui mas não sei como definir/imprimir a 'constante', o resultado que obtenho é ``
Comment: @WallaceMaxters Na verdade, acho que não, mas não tenho certeza. Acho que seguindo a convenção de nomes do Python, é um underline só.
Comment: @Miguel Pronto, tô tentando salvar um fiddle
Comment: Obrigado jbueno


How to convert stringified surveyjs JSON-like object into actual JSON

Question: I'm working on a an application that uses the survey building library surveyjs. I'm building a tool where users can input a survey JSON from that website into a form that is then sent as a string via an ajax request that triggers an AWS Lambda function. The lambda function takes the ajax request and inserts their survey into a MongoDB instance using mongoose.
When the string comes into the lambda function, it looks like this:
"{ pages: [ { name: 'page1', elements: [ { type: 'radiogroup', name: 'question1', title: 'IS THIS A SURVEY?', choices: [ { value: 'item1', text: 'Yes' }, { value: 'item2', text: 'No' } ] } ] } ]}"
And when I try to parse that string, I get this error:
Error: JSON Parse error: Expected '}'
I think it might have something to do with the JSON keys not being strings. I've also read that my use of single quotes could potentially be the problem, but I've exhausted my knowledge base.
Overall, my question is: How can I convert that string into a JSON object?
Thanks!
Comment: Single quotes are not valid json.
Answer: JSON strings need their string properties and values to be double-quoted. Use a regular expression and replace:

const originalStr = "{ pages: [ { name: 'page1', elements: [ { type: 'radiogroup', name: 'question1', title: 'IS THIS A SURVEY?', choices: [ { value: 'item1', text: 'Yes' }, { value: 'item2', text: 'No' } ] } ] } ]}";
const finalStr = originalStr
  .replace(/'/g, '"')
  .replace(/(\w+):/g, '"$1":');
console.log(JSON.parse(finalStr).pages);

That said, it would be better to fix whatever's serving the results in the first place, if at all possible.
Comment: This worked! Thanks so much. I should've posted this hours ago. I'll accept the answer in two minutes when I can. Cheers!
Comment: @KyleFrye The above regex is fragile and will corrupt data if your JSON contains any values with single quotes in them, even if they are escaped, e.g. `{title: 'John\'s Awesome Survey'}` will become `{"title": "John"s Awesome Survey"}` which is invalid JSON and will error out if you try to parse it with JSON.parse(). Also, it will corrupt any value with a word followed by a colon, e.g. `{title: 'Puppies: Do you love them!?'}` will become `{"title": ""Puppies": Do you love them!?"}` which is also invalid and will also fail JSON.parse(). My answer handles those scenarios.
Answer: If your lambda function is written using javascript then you can make use of eval to parse malformed JSON, however the eval'd string is evaluated as actual javascript within the current context so to get the result you have to set a variable within the string. Example:
var malformedJsonString = "{unquotedName: 'single quoted value'}";
eval("var myParsedJsonObject = "+malformedJsonString+";");
// myParsedJsonObject now contains your parsed JSON object


Co-variate shift between train and test data-set

Question: What are some of the modern techniques used to detect and mitigate the covariate shift between train and test datasets?
One method I recently read involves training a classifier using Kullback-Leibler divergence loss function, this loss function is recommended since it measures the entropy or randomness. After training the classifier, test the model on the test data and calculate the Matthews correlation coefficient. As far as I know, Matthews correlation coefficient is used to estimate the quality of the classifier. Mathematically it just another measure of true/false positives and true/false negatives. How can we use this to detect the covariate shift?
If we suspect there is a co-variate shift, what are some of the recommended methods to mitigate this effect? Would a random mix of train and test set help to solve the problem? Is that a common approach?
Answer: The problem of covariate shift or concept drift is addressed in the fields of medical statistics, domain adaption, transfer learning, and online learning (learning from streams). Therefore, the literature is exhaustive. Reviews from the different domains are below:

Jiang, Jing. "A Literature Survey on Domain Adaptation of Statistical Classifiers." (2008)
Pan, Sinno Jialin, and Qiang Yang. "A Survey on Transfer Learning." (2010)
Ditzler, Gregory, et al. "Learning in nonstationary environments: A survey." (2015)
Janssen, K. J. M., et al. "Updating methods improved the performance of a clinical prediction model in new patients." (2008)
Sugiyama, Masashi, Neil D. Lawrence, and Anton Schwaighofer. Dataset shift in machine learning. The MIT Press, 2017.

Usually, some sort of re-weighting is required to compensate for covariate shift. The objective is to transform the shifted distribution in the test data to match the distribution that was observed during training. For clinical risk models, which most of the time are linear, this is called recalibration and involves re-weighting the intercept and coefficients by a factor (see review by Janssen et al.). In the machine learning domain, a popular approach is to re-weight instances and train a model on the updated data. There are a myriad of approaches to estimate these weights, importance sampling and kernel mean matching are two classical examples.
Comment: An issue is how did the training and test sets arise?  In most cases creation of such splits are not advised and a resampling validation method recommended.


Optimizing functions in Linear Programming

Question: I would like to know if it makes sense to formulate a LP problem in the following way:

Define constant coefficients of the objective function ($C_i = 1$ for all $i$)

max $x1 + x2 + ... xN$

and then define the variables as functions of theirselves in the constraints:

max $x1 + x2 + ... xN$
$s.t$
$x1 = f_1(x1)$
$x2 = f_2(x2)$
...
$xN = f_N(xN)$
In this case, all the functions $f_i(x)$ for $i=1...N$ are known.
Thank you very much :)
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: You can, but whether it makes sense is up for debate.
If you have the constraint $x_i = f(x_i)$ in a linear program, that means $f$ is affine, hence the constraints are $x_i = a + bx_i$ with solution $x_i = a/(1-b)$ meaning there is nothing to optimize.
Comment: Logarithms are not affine, so why are you talking about linear programming? If you want to maximize $\sum c_i \log(a_ix_i+b_i)$ (with non-negative $c_i$)  you have a convex nonlinear program. It has to be solved with a nonlinear programming solver (or an exponential cone solver), and the logarithmic terms should definitely not be moved to equality constraints as that renders the problem non-convex. It is an easy nonlinear program
Comment: I am not familiar with Python or R, but any nonlinear optimization framework there should work. In MATLAB it is trivial https://yalmip.github.io/tutorial/generalconvexprogramming/.
Comment: Thank you very much! Now, would it be different (and feasible) to formulate it like:   max $u1 + u2 + .... + uN$ s.t $u1 = f(x1)$; $u2 = f(x2)$ .... $uN = f(xN)$. Still the variables that  I want fo find values for are $x_i$. Thank you!
Comment: Sure you can, but without context (i.e. other constraints in the model) it is not clear why one would want to do it as you only increase the number of variables and constraints without any benefit.
Comment: Okay! The context is: I know $N$ functions $f_i(x)$ for $i=1...N$ that belong to $N$ products of a store. $f_i(x)$ returns the amount of units sold for product $i$ once I invest the amount $x$ to the product $i$. The input to the model is actually the total amount $B$ and the problem is: How do I distribute $B$ over all products to maximize the sum of the total units? So another constraint that I had not defined is that the sum of all $x_i$ is equal to $B$. I hope it is more clear now. Thank you!
Comment: So I guess you have $x\geq 0, \sum x_i = B$. It is not clear why you would want to move the terms from the objective function to the constraints, thereby increasing the number of variables and constraints at no benefit at all as I can see. The new objective in the LP will look exactly the same with same structure/sparsity. And unless I am missing something, the solution is to allocate $B$ to the $x_i$ with largest coefficients, and set all other to $0$
Comment: I understand your comments! A fix in your intuition of the problem: As $f_i(x)$ are all logarithmic  functions (I had not told that to you before), allocating $B$ to only one $x_i$ will not be optimal as I would rather prefer exploiting the beginning of the logarithmic curves for all products in some way. Although allocating $B$ to only one $x_i$ is a feasible solution, it will definately not be optimal. Note: I edited the main question to reflect that $f(x)$ is not the same for all variables, but I have $f_i(x)$ for variable $x_i$ instead.
Comment: Thank you very much for your comments. You were very helpful. By the way, do you have any recommendation for such solvers? Python or R is preferred in this case. Thank you!
Comment: Great. Another question: if instead of $sum(c_i * log(a_i*x_i + b_i))$ I had $sum( exp( c_i * log(a_i*x_i + b_i)  + C))$ would the problem still be convex?($C$ being a constant) In the case it would not be convex, exponential cone solvers would not work anymore right? So the only choice would be a general nonlinear nonconvex solver? Thank you very much
Comment: Depends on $c$. You have $\sum (a_ix_i + b_i)^{c_i}$ which is concave for $0<c_i < 1$ thus rendering the problem convex.
Comment: Actually: $c_i = 0.2$ for all $i$
Comment: So convex problem then, and also second-order cone representable, power cone representable and in exp/log form probably exponential-cone representable too. In YALMIP you would simply write cpower(A*x + b,0.2)


ShellScript for retornar valores do banco cada valor em 1 variavel diferente?

Question: Olá estou tentando retornar 1 valor para cada variavel consigo retornar porem, estou tentando criar uma condicao que valide com um for quais são verdadeiras e quais sao falsas e me exiba na tela poderiam me ajudar? abaixo meu codigo.
read numero
vartest1=`psql -X -A -d database -U usuario -h host1 -t -c "select telefone from tabela where numerodiscado = '$numero' limit 1;"`
vartest2=`psql -X -A -d database -U usuario -h host2 -t -c "select telefone from tabela where numerodiscado = '$numero' limit 1;"`
vartest3=`psql -X -A -d database -U usuario -h host3 -t -c "select telefone from tabela where numerodiscado = '$numero' limit 1;"`
vartest4=`psql -X -A -d database -U usuario -h host4 -t -c "select telefone from tabela where numerodiscado = '$numero' limit 1;"`
clear

ap1='t'
ap2='t'
ap3='t'
ap4='t'

for ((i=0; i<3; i++))
do
echo "${vetor[$i]}"
if [ $ap1 == "$vartest1" ]; then
       echo "Telefone Localizado Ap1"
     else
             echo "Não Telefone Localizado Ap1"
       sleep 1
if [ $ap2 == "vartest2" ]; then
          echo "Telefone Localizado Ap2"
               else
             echo "Não Telefone Localizado Ap2"

    if [ $ap3 == "vartest3" ]; then
           echo "Telefone Localizado Ap3"
                else
             echo "Não Telefone Localizado Ap3"

    if [ $ap4 == "vartest4" ]; then
        echo "Telefone Localizado Ap4"
             else
             echo "Não Telefone Localizado Ap4"
fi
done

Quando executo, apenas a 1 condição é validada, no caso ap1 sempre é true como poderia fazer uma cadeia de ifelse onde validaria independente da posição no caso comparia a ap1,ap2,ap3,ap4 se uma dessas fosse verdadeira me retorne na tela, caso todas sejam falsas me retorne na tela não estou conseguindo testar todas elas poderiam me ajudar.
Comment: Não é mais fácil usar o While `while [ condition ]
do
   command1
   command2
   command3
done` ? ou seja, crie duas condições while, uma para verificar os verdadeiros e outra para os falsos. Ou entao apenas um IF-ELSE, Se verdadeiro, echo verdadeiras, Senao echo falsas.
Comment: Consegui criando o while muito obrigado.
Answer: É mais fácil usar o While: while [ condition ] do command1 command2 command3 done
ou seja, crie duas condições while, uma para verificar os verdadeiros e outra para os falsos. Ou entao apenas um IF-ELSE, Se verdadeiro, echo verdadeiras, Senão echo falsa.
Answer: Após pesquisar e errar bastante consegui criar um while que atenda minha necessidade.
while [[ "$vrx" == "$num5"  ]] || [[ "$vrx" == "$num6" ]]
do
if [ $vrx == $num5 ]; then
  echo "Telefone $numero  - Status: Está Inativo"
  sleep 1
  ativa
elif [ $vrx == $num6 ]; then
  echo "Telefone $numero - Status: Está Ativo"
  sleep 1
  ativa
else
   echo "Telefone não Encontrado"
  sleep 1
  aclp
fi
done

Obrigado a todos dos stack pela ajuda.


Finding an eigenvalue and eigenfunction of $y''+\lambda y = 0$, $y(-2)=0$, $y'(2)=0$

Question: As the title says, how does one find an eigenvalue and eigenfunction of $y'' + \lambda y = 0$ when $y(-2)=0$, $y'(2)=0$? I eliminated the case of $\lambda$ being zero and negative, but I am stuck with the positive lambda.
I got $y(-2)=c_1\cos(-2\lambda)+c_2\sin(-2\lambda) = c_1\cos(2\lambda)-c_2\sin(2\lambda) = 0$ and $y'(2) = \lambda(-c_1\sin2\lambda+c_2\cos 2\lambda) = 0$
but then I am stuck here.
Comment: Shouldn't that be $\sqrt{\lambda}$?
Answer: The general solution of $y''+\lambda y=0$, for $\lambda>0$, is
$$
y(x)=c_1\cos(\sqrt{\lambda}\,x)+c_2\sin(\sqrt{\lambda}\,x),
$$
or equivalently
$$
y(x)=c_1\cos\big(\sqrt{\lambda}\,(x-2)\big)+c_2\sin\big(\sqrt{\lambda}\,(x-2)\big),
$$
If $y(-2)=y(2)=0$, then $c_1=0$, and $\,\,\sin(4\sqrt{\lambda})=0$. Thus
$$
4\sqrt{\lambda}=k\pi,\quad k\in\mathbb N,
$$
or
$$
\lambda=\frac{k^2\pi^2}{16}, \quad k\in\mathbb N,
$$
with corresponding eigenfunctions $u_k(x)=\sin \big(\frac{1}{4}k\pi (x-2)\big)$.
Comment: The question specifies $y'(2) = 0$, not $y(2) = 0$.
Answer: you get that $ \frac{c1}{c2}=\frac{c2}{c1} $ from your equation
so the eiganvalues are given by the solution of the equations
$ -1=tan(2\lambda) $
$ 1=tan(2\lambda) $
Comment: This doesn't completely answer OP's question. Where is the eigenfunction? (HINT: If x (t) is your eigenfunction then it consists of basically the general solution terms multiplied by the respective eigenvector .


how to get last record of table in sql

Question: I have three entries in the attendance table.But I need to print the last entry of the id from the attendance table.I calculated total duration in separate query and printing list in separate query.Anyone please help me to resolve this.
query to print total duration:
select SEC_TO_TIME(sum(case when a.endtime  IS NULL
                         then time_to_sec(TIMEDIFF(NOW(),a.starttime))
                         else time_to_sec(a.duration)
                       end)
                   ) as duration
from attendance a
left join staff s on a.staffid=s.id
left join company c on a.companyid=c.companyid
where DATE_FORMAT(a.createdon, '%Y/%m/%d') = DATE_FORMAT('2017-04-04', '%Y/%m/%d') and
(a.employeecode ='A101' OR 'A101'='') and
(a.companyid=0 OR 0=0)
group by a.employeecode,a.companyid order by a.id desc

Query to print the details:
select a.id,
       a.starttime,
       a.endtime,
       a.startlocation,
       a.endlocation,
       a.duration,
       a.companyid,
       a.employeecode,
       a.staffid,
       a.createdon,
       a.createdby,
       a.lastmodifiedon,
       a.reason,
       a.comments,
       s.name as staffName,
       c.company_name as companyName
from attendance a
left joinstaff s on a.staffid=s.id
left join company c on a.companyid=c.companyid
where DATE_FORMAT(a.created_on, '%Y/%m/%d') = DATE_FORMAT('2017-04-04', '%Y/%m/%d') and
(a.employeecode ='A101' OR 'A101'='') and
(a.company_id=0 OR 0=0)
group by a.employeecode,a.companyid order by a.id desc

Comment: Possible duplicate of [How to select the last record of a table in SQL?](http://stackoverflow.com/questions/5191503/how-to-select-the-last-record-of-a-table-in-sql)
Answer: I got output by setting the endtime as null.
`select SEC_TO_TIME(sum(case when a.endtime IS NULL then  time_to_sec(TIMEDIFF(NOW(),a.starttime)) else time_to_sec(a.duration) end))
from attendance a left join staff s on a.staffid=s.id
left join company c on a.companyid=c.companyid
where DATE_FORMAT(a.createdon, '%Y/%m/%d') = DATE_FORMAT('', '%Y/%m/%d') and
(a.employeecode ='' OR ''='') and
(a.companyid=0 OR 0=0)
group by a.employeecode,a.companyid order by a.id desc`

how to get last record of table in sql


How can I avoid the output "0 tries left"?

Question: My program asks the user to input how many tries/attempts they would like for answering each question. When the user runs out of tries, my program prints "0 tries left." How can I prevent this so that my program only prints "You are out of tries"?
Here is the specific function of my code:
def test_student(max_attempts, prob_spec, prob_sol):
    counter = 0
    print("The problem is:", prob_spec)
    while counter < max_attempts:
         user_answer = int(input("\t Your answer:"))
         if user_answer != int(prob_sol):
              counter = counter + 1
              print("Try again. You have", (max_attempts - counter), "tries left.")
         elif user_answer == int(prob_sol):
              print("Correct!")
              return True
              break
    if counter == max_attempts:
         print("You are out of tries. The answer was:", prob_sol)
         return False

Comment: `while counter < max_attempts - 1`
Comment: @JohnGordon that won't work. Rethink it.
Answer: Change this:
print("Try again. You have", (max_attempts - counter), "tries left.")

to this:
if max_attempts - counter != 0:
   print("Try again. You have", (max_attempts - counter), "tries left.")
else:
   break

Comment: You don't need a semicolon in python
Comment: Oop, sorry. I forgot.
Answer: Redesigned your code a little:
def test_student(max_attempts, prob_spec, prob_sol):
    counter = 0
    print("The problem is:", prob_spec)
    while True:
         user_answer = int(input("\t Your answer:"))
         if user_answer == int(prob_sol):
            print("Correct!")
            return True

        counter += 1

        if counter == max_attempts:
            print("You are out of tries. The answer was:", prob_sol)
            return False

        print("Try again. You have", (max_attempts - counter), "tries left.")

No need for break after a return.
No need to check equality and then immediately inequality, it's superfluous.
Try exiting a while loop as soon as possible if you're correct, it leads to more readable code.
As you can see, instead of checking the counter as the while condition, I check it later on. This allows you to take care of the last attempt differently.

Keep in mind you can use the max_attempts as a counter by running max_attempts -= 1 and comparing the result to 0. I chose to go with your way as it's completely reasonable.


SQL Server Query Some time take too much time with freetexttable - Looks Index Problem

Question: Following is my query, it takes some time around 1 minute and some times gives a result in a second,
problem occurred specially i execute query after some time ago, or put some new keyword in query.
It looks like some index problem, when i executed execution plan, RID Look up cost 60%. The source table have around 2-5 Lacs data and daily around 10,000-20,000 rows will be added. Please advise me. Thanks
SELECT *
FROM   (SELECT Row_number() OVER (ORDER BY rank DESC, jobid DESC) AS rnum,
               *
        FROM   (SELECT rank,
                       joblistview.*
                FROM   joblistview,
                       FREETEXTTABLE(joblistview, jobtitle, 'seo manager') f
                WHERE  joblistview.jobid = f.[key]
                       AND CONTAINS(joblistview.joblocation, 'mumbai')
                UNION
                SELECT rank,
                       joblistview.*
                FROM   joblistview,
                       FREETEXTTABLE(joblistview, jobdescription, 'seo manager')
                       f
                WHERE  joblistview.jobid = f.[key]
                       AND CONTAINS(joblistview.joblocation, 'mumbai')
                UNION
                SELECT rank,
                       joblistview.*
                FROM   joblistview,
                       FREETEXTTABLE(joblistview, company_name, 'seo manager') f
                WHERE  joblistview.jobid = f.[key]
                       AND CONTAINS(joblistview.joblocation, 'mumbai')) AS xx)AS
       tt
WHERE  rnum BETWEEN 11 AND 20

Execution Plan
Comment: You've unioned the same query three times - what gives?
Comment: They are not the same query, each query searches a different column (jobtitle, jobdescription, company_name) using the FREETEXTTABLE function.
Answer: You can specify multiple columns in a single FREETEXTTABLE search, which should eliminate the need for multiple queries with UNIONs.
SELECT *
FROM   (SELECT Row_number() OVER (ORDER BY rank DESC, jobid DESC) AS rnum,
               *
        FROM   (SELECT rank,
                       joblistview.*
                FROM   joblistview,
                       FREETEXTTABLE(joblistview, (jobtitle,jobdescription,company_name), 'seo manager') f
                WHERE  joblistview.jobid = f.[key]
                       AND CONTAINS(joblistview.joblocation, 'mumbai')
               ) AS xx
       ) AS tt
WHERE  rnum BETWEEN 11 AND 20

Comment: Hi thanks for answer..

I have already done that, but the result was coming far more better in terms of relevance with Union. Off course with multiple columns result will come fast.

With Union also result performance  is good But the problem is i think it is related to Index.. Whenever new terms come in to search it takes too much time.
Answer: Did you try to add a computed column that contains data of all your search columns? Then configure this computed column to be persisted and let it be full text indexed. You could then try
SELECT *
FROM   (SELECT Row_number() OVER (ORDER BY rank DESC, jobid DESC) AS rnum,
               *
        FROM   (SELECT rank,
                       joblistview.*
                FROM   joblistview,
                       FREETEXTTABLE(joblistview, (<<<ComputedColumn>>>), 'seo manager') f
                WHERE  joblistview.jobid = f.[key]
                       AND CONTAINS(joblistview.joblocation, 'mumbai')
               ) AS xx
       ) AS tt
WHERE  rnum BETWEEN 11 AND 20


Question on harmonizing melodies

Question: In the melody to Twinkle Twinkle Little Star there are places with two notes of the same pitch in a row. So far I have only studied harmonizing (four-part harmony) melodies without the same pitch in a row (for example, two Gs in a row).
My understanding is that the soprano stays the same for these two notes but that the ATB does not stay the same for these two notes.
Are there any rules for this!
Comment: We need an example, could we get you to provide a picture? There may be some harmony that you are not seeing.
Answer: As far as I know, you can repeat the same harmony or change it in any way compatible with good voice leading. I would suggest (on Twinkle Twinkle Little Star) to be consistent. If I remember the tune, it start with three sets of repeated notes. If you maintain the same harmony for the first, it would sound better if you maintained the same harmony for the second and third pair. If you change harmony on the first two notes, change in a similar way for the next two pairs.
Comment: The normal harmony for "Twinkle" is the tonic for the first measure (the first two pairs of notes) and the subdominant for the third pair.
Comment: Possibly first inversion tonic for the second pair.
Answer: The conventional harmony for 'Twinkle Twinkle' keeps the same chord under the repeated notes in bars 1,2,3 but often changes harmony for those in bars 5,6,7.  This isn't about any 'rule', other than a general regard for harmonic rhythm and not messing around with it carelessly.   Same idea as having a regard for harmonic texture.  It's fine to use unison texture, 2-part, 3-part..   but it's NOT fine to switch between them aimlessly.
Comment: Very interestig way of harmonizing it!
Comment: Very interestig way of harmonizing it!
We that the C note (soprano) is repeated twice and the other notes/voices also stay the same for two beats. A simmilar thing for the G and A notes. In bar three we see an E  being repeated twice but in this case you see the bass moving.
My question was not about what chords to use when harmonizing. I was actually thinking about if the four voices (SATB) should be repeated twice or do some movement like in bar three. Could you please give me some guidlines on how this works. I ask this because my textbooks only deal with a moving a soprano part.
Comment: I  considered using the same harmony but a different voicing for the second note, the fourth note etc.  But it didn't seem practical.  Bars 3 and 4 change harmony on each beat, there's more going on than just re-arranging.   As always, the aim is to make each line singable.  If you can make it interesting as well, that's a bonus, though altos accept that they're condemned to a lot of repeated notes and basses know they'll often have to jump around taking the root of chords.
Comment: We are taught 'rules' that produce nice rich 4-part harmony in a chorale style.  Remember the other options.  Unison - uveryone singing the tune - is very strong.  As is a two-part texture, particularly when you can write a strong second part with plenty of contrart motion.   Not every choir arrangement has to sound like a hymn!
Answer: Yes, there are rules for this. Very commonly, if you have a repeated note in the melody and wish to prolong the harmony, then for maximum interest, you should change the voicing of the chord.
Thus:
C E G ->
E G C
Ta-da, you've made the music more interesting.
Answer: Or why not just change the harmony under each note and throw in some accidentals for good 'measure'! The more examples, the larger your toolkit gets.
Comment: This is a really clever harmonization! I just wanted to leave a comment that it breaks many part-writing "rules," so if any future readers try to mimic this for a music-theory course, beware.
Comment: Problematic spacing between soprano and alto in the first two measures, incorrect 6/4 chords (for example, beat 2 of measure 2), parallel octaves in measure 3, odd doubling on the fourth beat of measure 3, etc. It doesn't mean it's a bad harmonization; I like it! Only that it breaks standard part-writing rules.
Comment: @Richard exactly, there is a difference between "writing good 4 part harmony" and "writing good 4 part harmony which follows the counterpoint conventions of a common practice period choral".  It's not clear whether OP is asking for advice about harmonisation in general, or about "strict" counterpoint
Comment: Besides similar movement to 5ths (which are between the bass and an inner voice), what other issues do you see?
Answer: Movement in the voices of a harmony is guided by the principles of parallel, contrary and oblique harmony. Generally, a combination of the three will work well. Parallel harmony is very common, but it can become predictable. Unless you're dealing with freak virtuosi or instruments with big ranges, you're going to run out of notes if you rely solely on contrary harmony. If you only use oblique harmony one or more of your voices will be very simple/boring. A combination of parallel, contrary and oblique harmonies is likely to be the most practical and satisfying way to move your voices.

Question on harmonizing melodies


Explicitly Release Metal Texture

Question: Simple question that I can't find an answer to, On openGL there is a glDeleteTextures(1, &t) Obviously the model is quite drastically different but i'm wondering if Metal has the same need or requirement.
Are MTLTexture's just released via reference counting or is there another way to release the texture and let the GPU clear it out of its caches as well?
Answer: MTLTexture lifetimes are managed exactly like other objects: they are dealloc'ed when their refcount reaches 0 (whether that happens automatically with ARC/Swift or MRR under Obj-C). Objects that use textures, like command buffers, may retain textures while they are in use, affecting their lifetime, but most applications can happily ignore this.

Explicitly Release Metal Texture


Changing the image path after images were uploaded

Question: I have created a image field under a custom Content Type and let the file directory setting to default, meaning the files are not uploaded to any sub directory.
As I can see now this is not a suitable situation for me and I would like to save the files in a sub directory. If I change the File Directory setting under the Field Settings will this break the paths of the files uploaded prior?
Thanks
Answer: If I change the File Directory setting under the Field Settings will this break the paths of the files uploaded prior?
Yes
As i think you need to go a two step process.

Move the images to the new folder.
Update the existing image path in database.

Before moving with any process keep all the backups.
Refer these links which may help you to move
seeking advice on changing file system path after files have been upload
Moving the files directory
Comment: Even though your answer was spot on I had done my job with [File Paths](https://www.drupal.org/project/filefield_paths). I could't work around your answer because my files were exceeding the count limit of a folder under my hosting account and therefore I had to find a way to split up my files in different folders. Thanks anyway.


Ajuda para alterar valores com onchange

Question: Boa tarde, galera!
Eu estou tentando mudar um preço de acordo com a minutagem selecionada, mas não estou conseguindo nem passar pela função. Constatei isso apos usar um alert logo após o inicio da função nomeada como treta_minutos(). O que estou fazendo de errado?
Função script que muda se for de um determinado ID e minutagem:

< script >
  function treta_minutos() {
    var id_plano = "<? echo"
    $id_plano " ?>";
    var franq_voz = tb_mobile_venda.franquia.value;

    if ((id_plano == "1") && (franq_voz == "100")) {
      document.tb_mobile_venda.assinatura.value += "8,00";
      document.getElementById("assinatura").readonly = "readonly";
    }
    if ((id_plano == "2") && (franq_voz == "100")) {
      document.tb_mobile.assinatura.value += "15,00";
      document.getElementById("assinatura").readonly = "readonly";
    }
  } < /script>

Trecho do código em PHP que cria a lista de minutagem:

if ($id_plano != "20" && $id_plano != "21" && $id_plano != "2" && $id_plano != "1") {
  echo"<input name=\"franquia\" type=\"text\" id=\"franquia\" size=\"15\" value = \"$franquia\" readonly=\"readonly\"/>Minutos	";
} else {
  if ($num_linhas_complemento != 0) {
echo "<select name=\"franquia\" id=\"franquia\" size=\"1\">
  <option value=\"$franquia\">$franquia</option>";
echo "</select> MINUTOS";
  } else {
//IMPRIMIR ITENS DO COMBO
$sql_combo_1 = "SELECT
    valor_combo
   FROM
    gpoi.tb_mobile_venda
   WHERE
    campo_flex = 'franquia'
    and cod_plano = '" . $id_plano . "'
   ORDER BY ordenacao ASC;";
  }

  $dados_select_1 = mysql_query($sql_combo_1) or die('Erro:' . mysql_error());
  $linhas_select = mysql_num_rows($dados_select_1);

  echo "<select name=\"franquia\" id=\"franquia\" size=\"1\" onchange=\"treta_oi_voz();\">
  <option value=\"ND\">Selecione...</option>";
  for ($i = 0; $i < $linhas_select; $i++) {
$item = mysql_result($dados_select_1, $i, 'valor_combo');
echo "<option value=\"$item\">$item</option>";
  }
  echo "</select>";

  echo " MINUTOS *";
}
Answer: O nome das funções na montagem do select está diferente da função que você declarou no JavaScript. Uma forma mais segura de criar um listener para um objeto é:
var select = document.getElementById("franquia");

btnEdita.addEventListener('change', treta_minutos, false);

Veja se funciona.
Comment: Muito obrigado, Celso. Eu fiz a alteração que recomendou.
E os nomes divergentes foi por um descuido meu ao tentar simplificar as funções para postar aqui no fórum.

No entanto, descobri que o erro era devido ao meu XAMP não estar habilitado para short tags. Mas já resolvi o problema.

Obrigado novamente!

Ajuda para alterar valores com onchange


Unit testing in Python

Question: This is my first project in Python and I have just learnt the unittest framework. The test module runs well when I do python test_module.py but when I want to execute a certain class or a method as said in the documentation using:
python -m unittest test_module.TestClass.test_method  # or even just test_module

I get the following error:
AttributeError: 'module' object has no attribute 'test_module'

The directory where I run the command contains graphm_test.py (I also tried to change the name to test_graphm.py), with class graphm_test(unittest.TestCase): and methods all starting with test_* and here is the command I run on the terminal:
python -m unittest test_graphm.py

I could not find a similar problem to this anywhere, it would be great to know the reason behind the error and how to run a certain class inside the module or a certain method
Comment: Consider using nosetest as your test runner instead.
Comment: Related: http://stackoverflow.com/questions/15971735/running-single-test-from-unittest-testcase-via-command-line and http://stackoverflow.com/questions/1068246/python-unittest-how-to-run-only-part-of-a-test-file
Answer: There are 2 issues: you are not calling the correct module name, and you are using the extension .py.
So you need to be in the folder with your graphm_test.py file, and run:
python -m unittest graphm_test

Unit testing in Python


Omitting certain time periods in VAR

Question: I am using a vector autoregression with a monthly lag, and wish to not include certain months, as they are outliers in my analysis and may distort findings.
Is estimating such a VAR (using OLS, then identifying the structural shocks by Cholesky decomposition and another method) with missing dates permissible?
Comment: So in order not to mess up the time dependence, would I need to feed that into the program? Or just create rows with time periods containing blanks?
Answer: You can do this, but be careful not to mess up the time dependence. You cannot just delete one or more observations from your time series. But you can construct your design matrix of lagged variables and append the dependent variables as additional columns. Then mark the outliers and delete all rows with outliers (they will be in different rows for different columns). Then split the additional columns from the rest of the columns, these will be your dependent variable and the design matrix. You can then use OLS and other least-squares based estimation methods.
Illustration with a bivariate VAR(1) for time series $x$ and $y$:
Suppose $x^\top=(x_1,x_2,NA,x_4,x_5)$ and $y^\top=(y_1,y_2,y_3,y_4,y_5)$.
Construct a matrix $A:=[x_{-1};y_{-1};x_{-5};y_{-5}]$:
$$
A=\begin{pmatrix}
x_2 & y_2 & x_1 & y_1 \\
NA  & y_3 & x_2 & y_2 \\
x_4 & y_4 & NA  & y_3 \\
x_5 & y_5 & x_4 & y_4 \\
\end{pmatrix}.
$$
Delete all rows containing NA:
$$
A'=\begin{pmatrix}
x_2 & y_2 & x_1 & y_1 \\
x_5 & y_5 & x_4 & y_4 \\
\end{pmatrix}.
$$
Your dependent variables are the first two columns of the $A'$ matrix, and your regressors are the last two columns of the $A'$ matrix: $x'=A_{\cdot 1}$, $y'=A_{\cdot 2}$, $x\text{lag}'=A_{\cdot 3}$, $y\text{lag}'=A_{\cdot 4}$. Now you can estimate the bivariate VAR(1) by, say, equation-by-equation OLS using the regular OLS routines such as lm in R. The first equation would be lm(x~xlag+ylag), the second lm(y~xlag+ylag).
Of course, in this example the sample is too small when adjusted for NAs, but with more realistic samples sizes it should work fine.
Comment: Would this work for a VAR with more lags, not just a VAR(1)?
Comment: @Student, Sure! The $A$ and $A'$ matrices would have additional columns. For VAR(2), there would be two more columns (one for lag 2 of $x$, one for lag 2 of $y$) and one fewer row (the first row of the current $A$ and $A'$ matrices would not be there).
Comment: I see what you did now, it's clear. Thanks.
Comment: @Student, you are welcome!
Comment: I do have a further question. Essentially, the unit of time in my analysis is a month from 2002 to 2014, and so the monthly VAR makes sense. From 2015 to 2018, the unit of time is now eight weeks. Is it possible to run such a VAR? At first, the lag is monthly, but now, it is every eight weeks.
Comment: @Student, this is bad news unless you assume that your data-generating process suddenly changed so that the same dynamics that applied for monthly data between 2002 and 2014 apply also for 8-weekly data in 2015-2018. A state-space approach could be helpful where the observation equation is separate from the state equation. State-space models are probably more difficult to work with than VAR, though.

Omitting certain time periods in VAR


Improvising with modes and over "advanced" chords

Question: Say I'm playing along to a jam track in C major. From my understanding, this means that C Ionian, D Dorian, E Phrygian etc. would work.
My question is: How do I bring out the flavor/characteristic of the specific mode? For example, if I wanna make my solo feel sinister, I would choose B Locrian. However, this doesn't work, as I'm still only playing the notes in C major/ionian.
Is it because that I in the given case would have to play C Locrian and not B Locrian?
And another question: To make my solos sound better, it seems that I need to emphasize the chord that is being played by playing a note from the given chord (so if D major is playing, I would play either D, F# or A). How do I achieve this effect if the chord is not a simple triad? For example, if the chord is suspended, augmented, diminished, extended etc?
Thanks in advance!
Comment: It would be best to ask each question as a separate question.
Answer: A full backing track has SO much more harmonic power, with bass and harmony instruments, it rules and bulldozes over your feeble little solo notes. Mode is not just a set of note names, because one of the notes is the King, home note, harmonic center of universe, the tonic. C Ionian and D Dorian have all the same notes, but a different center note.
<code>Mode = TONIC + intervals around it
</code>
The feeling of a mode comes from the combination of all pitches and sounds the listener hears, the "total music", which is also affected by the rhythmic placement of notes in relation to a pulse/meter. Even unpitched noises or clicks can affect the harmonic perception and weight of pitched notes, if the clicks create a rhythmic pulse grid, suggesting where the "one" is rhythmically. If your rhythmic centerpoint moves, it might move the tonal centerpoint as well! Beginners sometimes incorrectly think that to establish a modal feeling it's enough to select the right set of notes, but that's not true at all. HOW and WHEN you play the notes is extremely important, and so is what OTHER instruments are playing.
The lowest note i.e. bass is a very powerful factor in tonic-setting. If the bass plays C all the time, it will almost certainly make C the tonic note, and any modal feeling that's built by other notes above the C will be C something.
If the backing track is playing/vamping on C major, there is no way for a soloist to make it sound like D Dorian, because D Dorian would require D to be the tonic note. No can do. BUT if the backing track is playing C major and none of the backing instruments play an F note anywhere, then the soloist CAN make it sound like for example C Lydian, by playing the characteristic F# note. Or if the backing track doesn't play B, the soloist can make it C Mixolydian by playing the characteristic Bb instead of B.
If the backing track is playing/vamping a major chord, the soloist cannot make it sound like any minor mode. Minor modes are: Dorian, Phrygian, Aeolian, Locrian.
If the backing track is playing (vamping) a minor chord, the soloist cannot make it sound like any major mode. Major modes are: Ionian, Lydian, Mixolydian.
If the backing track only has a C bass note and nothing else, then you have total modal power and can make it sound like any C mode. But you cannot make it sound like e.g. D anything.
(The only real exception I can think of to push the tonic away from a fixed bass note is to utilize perfect fourths/fifths. If the bass plays C, it will set the center to C, EXCEPT maybe if you play a heavy F note and things from e.g. F major or F minor - then maybe you can convince the listener that it's just a very long held F/C or Fm/C chord, waiting to resolve home to F or Fm.)
Answer:
My question is: How do I bring out the flavor/characteristic of the specific mode?

By emphasizing characteristic notes. For modes of a major scale these are:

lydian: #4 and 7
ionian: 4 and 7 (though careful with 4!)
mixolydian: 3 and b7
dorian: b3 and 6
aeolian: 2 and b6
phrygian: b2 and 5
locrian: b2 and b5

For example, if I wanna make my solo feel sinister, I would choose B Locrian. However, this doesn't work, as I'm still only playing the notes in C major/ionian.

There are two important differences between B-locrian and C-ionian: they are different modes, but they also have different roots (tonal centers). As piiperi wrote it is unlike that you will manage to switch a tonal center when playing over a backing track. What you can do, is to change mode, e.g. play C-locrian. Of course this rises a potential problem: will C-locrian fit. Often backing track strongly suggests the scale to use – but sometimes it leaves some freedom.
To expand a bit, when you are playing accompaniment, it's your job to listen to the soloist and make sure you don't get in their way.
Answer: Say I'm playing along to a jam track in C major. From my understanding, this means that C Ionian, D Dorian, E Phrygian etc. would work.
Well, no. I mean C Ionian is CDEFGAB, D Dorian is DEFGABC, and so on, so it would be the same notes, but the chords would be different. Cmaj, Fmaj and Gmaj with would be allowable chords in D Dorian, but if they're all the chords, you clearly should be thinking C Ionian.
Answer: It's not you, it's the backing tracks! They will almost inevitably dictate what mode you'll need to play in. They will say where 'home' is - they will specify the root. Only then, when you've decided what that actually is, will you be able to play along - but in whatever mode the track is producing.
For instance, if the track starts on Dm, and there are G major chords, you'll be in with a good chance of playing D Dorian, as that track will be choosing those chords which map out D Dorian. With an Am key track, which keeps returning to that Am, you'll be good for A Aeolian.


My jQuery doesn't work

Question: I am a freshman in ICT course, and we have a project.
I am currently working for my jQuery code for add cart. When I choose how many I'll buy for example 5, when I click add cart, the total result will appear to the text field. For some reason, it won't work. I already tried JavaScript but it also won't work.
Here is my code:

 $(function() {
  var $myNumber = $("#myNumber");
  var $add = $("#add");

  $add.click(function() {
    var input = $myNumber.val();
    $('#item').val($(input).val() * $('5000').val());

  });
});

<input type="text" id="item" readonly>
  <input type="number" id="myNumber" min="1" max="5">
  <button type="button" class="button" id="add">Add Cart</button>
<button type="button" class="button" id="Reor">ReOrder</button>

For some reason the result that will come out is NaN. What did I miss? Where did I go wrong?
Comment: The best advice we can really give you is: next time plan your time better. Also look up what [`NaN`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NaN) means, and then work backwards to find out why the result is `NaN`.
Comment: Im a student and I have some minor subjects too. Here in the philippines its already the end for the 1st term . Projects has been piled up. I am working this project for almost the whole month and im close at finishing it. Just need to solve this problem then I;m already done.
Comment: `$('5000').val()` - What the heck is that? I'm guessing you don't have `<5000 />` tags. You get NaN because you multiply undefined by a string.
Comment: you dont need to do $('5000').val().You can directly give 5000
Answer: Why do have to wrap everything with $()? just

input *5000

$(function() {
  var $myNumber = $("#myNumber");
  var $add = $("#add");

  $add.click(function() {
    var input = $myNumber.val();
    $('#item').val(input * 5000);

  });
});

Answer: This is your problem:
$('#item').val($(input).val() * $('5000').val());

You don't have to use $('5000') ... just use plain integer values to make a calculation.
You already saved the value to the input variable (input contains a number already) ... you can use this variable to multiply it with 5000.
$('#item').val(input * 5000);

 $(function() {
  var $add = $("#add");

  $add.click(function() {
    var input = parseInt($("#myNumber").val(),0);
    $('#item').val(input * 5000);

  });
});

<input type="text" id="item" readonly>
  <input type="number" id="myNumber" min="1" max="5">
  <button type="button" class="button" id="add">Add Cart</button>
<button type="button" class="button" id="Reor">ReOrder</button>

edit:
Use parseInt() on your value! value is of type string.
var input = parseInt($myNumber.val(),0);

Answer: Why do you have $('5000').val(),you dont need it
check the following snippet

 $(function() {
  var $myNumber = $("#myNumber");
  var $add = $("#add");

  $add.click(function() {
    var input = parseInt($myNumber.val(),10);
    $('#item').val(input * 5000);

  });
});

<input type="text" id="item" readonly>
  <input type="number" id="myNumber" min="1" max="5">
  <button type="button" class="button" id="add">Add Cart</button>
<button type="button" class="button" id="Reor">ReOrder</button>

Use parseInt ,to convert your input to a number
Hope it helps
Answer: On input you already have the value of the #myInput element and $('5000') is not needed. Just use the number.
Try this:

 $(function() {
  var $myNumber = $("#myNumber");
  var $add = $("#add");

  $add.click(function() {
    var input = $myNumber.val();
    $('#item').val(input * 5000);

  });
});

<input type="text" id="item" readonly>
  <input type="number" id="myNumber" min="1" max="5">
  <button type="button" class="button" id="add">Add Cart</button>
<button type="button" class="button" id="Reor">ReOrder</button>

My jQuery doesn't work


Preimage of Maximal ideals

Question: It is a common fact that when F is a surjective homomorphism from a commutative ring A to another B (with 1), we have inverse images of the maximals in B maximal in A. Could anyone be so kind to me help solve the same problem without the condition of surjectivity of F but adding that A be semilocal?
 Thanks in advance.
Answer: The statement you're asking about is false; given a ring homomorphism $f:A\to B$ where $A$ is semilocal, it need not pull back a maximal ideal $M\subset B$ to a maximal ideal $f^{-1}(M)\subset A$.
For example, consider $A=\mathbb{Z}_{(2)}$ (the localization of $\mathbb{Z}$ at the ideal $(2)$, which is in fact a local ring) and $B=\mathbb{Q}$, with $f$ the inclusion map and $M=(0)$.
Comment: Is that a surjective map? Do you know under what hypothesis you can prove the preimage of maximal ideals is ideal? I'm trying to solve it. I reached a requirement to be bijective, but seems a bit much, because I needed both to be surjective and injective.

Preimage of Maximal ideals


Datagridview virtualmode with heavy data load

Question: I want to display a "lot of heavy data" inside datagridview in virtual mode.
I use a buffer where I store n (2) pages of data, initially 2 first pages are stored in buffer. When the gridview is scrolled upto a row that does not exist in buffer i load the current new page and swap it with an old page.
To simulate loading heavy data from database into the buffer, I added this line:
  System.Threading.Thread.Sleep(3000);
as the result , as the buffer update itself the grid is frozen for this period of time.
Now, as I understand adding a thread won't help here because there is only 1 operation that happens only when scroll reaches unbuffered row.
  private void dataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
    {

       e.Value = theBuffer.ReturnFromBuffer(e.RowIndex, e.ColumnIndex);
//I check there if row index is in buffer and if not i update the buffer with new page and return the value

    }

So I am thinking about adding a "spinning wheel" animation above the gird when it happens.
I tried, to send event to form to show/hide the image within the method that updates the buffer:
if (ProgressEvent != null)
     ProgressEvent(true);

System.Threading.Thread.Sleep(3000);

if (ProgressEvent != null)
     ProgressEvent(false);

and on form event handler set the visible property of the image, but the result was not as expected, i guess Sleep happened before event was handled, so the image didn't appear before the sleep.
Som I guess that a tread is still needed. But  can't figure when it sholud started and what should it do?
Update:
I tired the suggested background worker:
Inside the method that is beeing  called by  CellValueNeeded event, i check if the requested row is buffered, if not i start backgroundworker.
 if (!bgWorker.IsBusy) //otherwise worker will be started for every column of the row
 {
      bgWorker.DoWork += (sender, e) =>
         {
           UpdateBuffer(rowIndex);
          };
       bgWorker.RunWorkerAsync();
 }
 return "null";

And this:
bgWorker.RunWorkerCompleted += (sender, e) =>
{
    if (IvalidateEvent != null)
        IvalidateEvent();  //send event to form, where invalidate the gridview  dataGridView1.Invalidate();
};

it works but there a few problems with that:
1) I got many dummy results in my grid, even if it's not for long - I don't like it much.
2)it even takes more time if I just left it as is, probably because backgroundworker consumes some time and because I actually invalidate grid and call CellValueNeeded event 2 times (first onem to start backgroundworkerm second time when it finishes it's work)!
Comment: invalidating the whole grid is a bit like "overkill" ... it will also repaint all cells that have correct values, instead of only those with dummies.  another approach to avoid dummy values while scrolling through the grid would be to react on the scrolling itself. try to fetch rows that are close to the displayed rows before they are requested, in that case the values will likely be there before CellNeedsValue requests them
Comment: @DarkSquirrel42, CellNeedsValue buffers not only the needed row but a bunch of rows ahead. the only problem when I need to load new rows. I don't mind to freeze the grid, but animation must appear as it happens. without dummy values
Comment: when the datagridview raises cellvalueneeded you can specify a value to be shown in the cell. if you don't have that value, you can't specify it. so you have 2 options: 1) either provide a "loading"-message or nothing (empty string) , fill your buffer in an async operation and when the data is ready update the cell. or option 2) fill the buffer synchronously and return the desired value. of course option 2 will block the UI thread, so no loading animation, form repainting, or user interaction will be available (unless you do bad things like Application.DoEvents - that will be a pain to debug)
Comment: the problem with that is when I,for example, click on pagedown many times, so dummy value fills many rows (until data is loaded). for testing I use dataset as source and datatable that holds page in memory. Maybe other resources would work faster?
Comment: i don't think so ... try optimizing the loader process ... create a class that handles requests to the buffer that require to load data ... store such requests and when your worker thread runs, try to collect more than just one row (reduce the number of queries) ... when the worker has finished his job, have it look at the list of requests and continue using that worker instead of spawning new workers if ther's more to do... track the scroll event and make sure that the next and prevous X rows are in the buffer (so after scrolling the buffer can supply the value directly)
Comment: @DarkSquirrel42, I do not load one row, i load page (about 50 rows) every time. and buffer holds 2 page where i update the far-most page with a new one. For  the spawning new workers (actually it the same worker that restarts every time if it's not busy)m what do you mean "have it look at the list of requests", the request come as soon as CellValueNeeded event needs a value that is not buffered
Comment: sorry if my english is too bad to explain this properly: lets say that you are displaying a page located somewhere in the middle of a large result ... the displayed page is in the buffer, so your DGV can get the cell values from there without delay. expand that scheme to the following: lets say currently the rows 500 to 550 are displayed -> hold the rows 450 to 600 in your buffer ... when the user scrolls 3 rows down, drop the rows 450 to 452 from your buffer, and request the buffering ot the rows 601 to 603 in the background
Comment: what i mean with "have it look at the list of requests": the position of the currently displayed rows in the result can tell you what rows are likely to be requested next ... request those rows to be loaded in the background BEFORE your CellValueNeeded handler tries to get them from the buffer ... store those requests somewhere, and reuse your background worker thread to process them instead of creating a new thread (get rid of thread startup delay)
Comment: ok, i thought about updating buffer without CellValueNeeded asking for that but: 1)what will trigger the background buffering? background worker can't just wait fo requests, it only works if there is somthing to do...2) what if user moves the scroll to the middle? no chance to buffer this in advance
Comment: requests should trigger background buffering. it can wait for requests: give your worker an endless loop that will only be interrupted when an exit flag is set. inside that loop let your worker thread wait for a WaitHandle. when you have placed requests in the list of the worker, release the WaitHandle. requests are generated when the user scrolls. also try to cancel pending requests that are no longer needed (will happen when the user is scrolling too fast) ... you can't buffer everything in advance, but you can try to anticipate what will be needed next
Answer: when you reach an unbuffered line, call your code to get the required data in a 2nd thread (new Thread, threadpool, backgroundworker ... choose one)
after this async operation has been started make the "loading..." control visible
(here you will probably want to disable parts of your UI until the operation is completed)
for now return an empty string or some other dummy value...
your async operation should get the desired data and then invoke another method the ui thread (call Invoke(...) on your Form's object)
the invoke call is needed to avoid cross-thread UI interaction
in the invoked method you should use the fetched data to populate your buffer, hide the "loading..." control, invalidate the corresponding row(s) or cell(s) (the datagridview has methods to do this) and last but not least reenable your UI if necessary
Comment: yes, i thought about it but there is problem that I'll try to explain:  there can be a situation while new thread loads to data into the buffer user can scroll the grid again and a new thread will start!! this will cause a lot of mess. I don't think that I want to lock the scroll.
Comment: And also,CellValueNeeded waits for it's value how can it use the thread? it won't wait for thread to complete
Comment: 1st: the waiting cellValueNeeded handler ... don't let it wait ... return a dummy value, eg. "loading...". and later when the async operation has finished and the data is in your buffer, invalidate the row/cell. that will raise CellValueNeeded again, and then you can get the real value. 2nd: to have only one worker at a time you could write a class that handles requests for data. when data is requested, and no data is currently fetched, start the thread. when data is currently fetched, enqueue the request ... at the end of your fetching process check for waiting requests ...
Comment: @DarkSquirrel42, what do you mean by "invalidate the row/cell" . Alsom i do't think I can return dummy value, because it will put it inside the cell.
Comment: when a control (like a DataGridViewCell) needs to be redrawn you can invalidate it's client area, so the next time the UI thread gets into idle state it will redraw that area. usually you call Invalidate() on a control to trigger this. for a datagridview-cell/-row this is done from the datagridview-object (if i remember correctly the method is named InvalidateRow(...)/InvalidateCell(...)) in virtual mode the datagridview will raise CellValueNeeded before it can redraw a cell. so you have that dummy value in that cell while the data is fetched in the background, and then the real data appears
Comment: So after I finish loading data from thread I should call Invalidate? and what if I just start the animation from thread? (i'll start the above event via BeginInvoke)
Comment: after you finish loading data you should insert that data into your buffer, and invalidate the corresponding cell or the entire row.  be aware that you may not interact with a control from outside of your UI thread.  you need to invoke the UI thread to interact with controls


PHP Post variable loses encoding when posting to database

Question: Im sending data with android and i have a variable that have a leter "ž". when php post this into database it becomes a "?". Its not android problem bus android is sending normal value, database is utf_8 so the problem is when parsing to php.
CODE:
<code><?php
header('Content-type: application/json; charset=utf-8');
require_once('DB_connect.php');
$db = new DB_connect();
$var=0;

$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
    return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
}, $str);

$con= new mysqli ("localhost","infoizla_boris","internet1","infoizla_boris");

$place=$_POST['place'];
$name=$_POST['name'];
$number=$_POST['number'];

echo $name;

    $statement=mysqli_prepare($con,"insert into Ocjena (user,place,ocjena) values (?,?,?)");
mysqli_stmt_bind_param($statement,"sss",$name,$place,$number);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);

   if(!mysqli_stmt_execute($statement)){

    $sql="update Ocjena set ocjena='$number' where user='$name' && place='$place'";

   $rez=$con->query($sql);

   }

mysqli_close($con);

?>
</code>
Comment: You are open to SQL injections. What does `require_once('DB_connect.php');` do, I'd think the connection would be established in there..
Answer: you have to tell the connection to use utf-8 as well
<code>$con= new mysqli ("localhost","infoizla_boris","internet1","infoizla_boris");
$con->set_charset("UTF-8");
</code>


How do I upgrade from 8.4.2 to 8.4.3?

Question: I already have Drupal 8.4.2. Now I want to upgrade to 8.4.3 via commandline.
Via Drupal commands or Composer.
How to do that?
Answer: Easy way :
composer update
drush updb # or update.php via browser

Comment: It does... what did not work ? did you update your composer.json file ? (with 8.4.3)
Comment: Seems not working already tried
Answer: Using Drush:
Update Drupal 8 core drush up drupal
Update a single module drush up module_name
Update only security updates drush up --security-only
Manual Updation:
http://www.zymphonies.com/blog/update-drupal8-core
Comment: With `drush up drupal` gives `Unable to load class \Drush\VersionControl\Backup ` error
Comment: You can try manual update option also.
Answer: If you are using Drupal Console, then have a look at following command:
drupal module:update [arguments] [options]
moup

Reference: https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/module-update.html

How do I upgrade from 8.4.2 to 8.4.3?


Flutter: How to resolve Error importing package:http/http.dart

Question: I am very new to Flutter, and stuck at the following error:
package:http/http.dart That library is in a package that is not known.

Maybe you forgot to mention it in your pubspec.yaml file?
Please help in resolving this error.
Comment: that package is part of flutter and should not show an error if you import it. To help you, you should post your relevant parts of the pubspec.yaml and .dart-File
Comment: The package is not a part of flutter but it is distributed via pub.
Answer: Go to your pubspec.yaml file , and add the http dependency:
dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  http: any

Remember, the indentation must be the same as 'flutter' or 'cupertino_icons'
And don't forget to run this command in your terminal :
flutter packages get

Comment: And don't for get to `pub get` or `flutter packages get` after saving.
Comment: [https://stackoverflow.com/questions/61037356/what-is-the-difference-between-flutter-packages-get-and-flutter-pub-get](apparently) `flutter pub` is just an alias to `flutter packages`
Answer: I had the same problem. You just have to add latest http dependencies in pubspec.yaml
Here is the full code,
  dependencies:
      flutter:
        sdk: flutter

      http: ^0.12.0+1

      # The following adds the Cupertino Icons font to your application.
      # Use with the CupertinoIcons class for iOS style icons.
      cupertino_icons: ^0.1.2

Don't forget to change verson no. of http
To check latest version of http click here
If you are running app directly from command line then you could also do:
with Flutter:
$ flutter packages get

with pub:
$ pub get

Answer: I've found that, when in VS Code, you might need to restart the editor to get it to see the new http module that 'pub get' pulled in.  You can have your .dart code and pubspec.yaml exactly right but you still get the compiler/lint error.
Comment: this worked for me after installing the package using `flutter pub add http` and imported it like this: `import 'package:http/http.dart' as http;` i still get compiler error, closed my folder and open it up again in Vs Code, error's gone and editor shows warning for unused import only.
Answer: You need to import like this:
import 'package:http/http.dart' as http;

Answer: 1.Install http package
flutter pub add http

2.check pubspec.yaml file
dependencies:
  http: ^0.13.4

3.Import in file
import 'package:http/http.dart';

Reference
Answer: add below to pubspec.ymel  file
dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  http: ^0.12.0+1

use flutter pub to find the latest version
call
flutter packages get

Answer: just got to pubspec.yaml file and tweak some changes in file
dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2

 http:

under dependencies section just add http like in code description .
flutter will automatically resolve it and will add updated version of http .
Answer: You have to add the http dependency in the pubspec.yaml file as shown below:
dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  http: ^0.12.0+2

Please take note of the indentation. After doing the above, run the below command in your terminal:
flutter packages get

As at the time of writing this, the latest http version is 0.12.0+2. You can learn more by visiting this link.
Answer: this worked for me:
dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.2
  http: any

then:
flutter doctor -v

Finally:
flutter packages get

Answer: 1. Add this to your package's pubspec.yaml file:
dependencies:
   http: ^0.12.1
2. install it :
$ flutter pub get
3. Now in your Dart code, you can use:
import 'package:http/http.dart' as http;
Answer: -Just run this below command in your project directory to install http module
flutter pub add http
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Add below to pubspec.yaml file
  dependencies:
  http: ^0.12.0+1

Or Just add http
dependencies:
http:

flutter will automatically used latest version of http .

Then use pub get
Answer: version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.0
http: ^0.12.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- images/
try to update the sdk versions and then pub get or flutter pub get to get the packages get install
Answer: just add in pubspec.yaml
http: ^0.12.0+2

like as
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.3
  http: ^0.12.0+2

and run in terminal
flutter pub get

finally add in class
import 'package:http/http.dart' as http;

Answer: When I got this issue, I just close the project from Android Studio (File -> Close Project). And then open it again.
That works for me.
Simply just Restart the project.
But Make sure to add the certain dependency to the pubspec.yaml file and do pub get.
Answer: You first find 'dependencies:' in pubspec.yaml
then under 'dependencies:' type http: ^0.12.0+2 and then press ctrl + s to run get packages.
sample:
dependencies:
  http: ^0.12.0+2
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2

Answer: cupertino_icons: ^0.1.2
http: any
Answer: http:
have to be align with the other dependencies.
Comment: Your answer doesn't seem to help the OP. Please clarify and elaborate.
Answer: I had the same issue although I had the latest http package in Pubspec.yaml file. This error was still in there I did these 2 steps and error was resolved.

Remove import 'dart:_http'; if it is there
Add import 'dart:convert';


What's a good, generic name for chart of things by time of day?

Question: We're creating a chart showing traffic by time of day over a given period. So the y-axis is traffic, the x-axis is midnight, 1am, 2am, etc. It could also be days of the week. What's the generic name for this type of chart? I've come up with "cycle chart". Is that the standard? Is there one?

Update:
Just to add a bit more clarity, what's being shown in the top chart is not one day, it's an aggregation of many days. E.g. over the last month, 6am has on average been lower than noon. Similarly, in the bottom chart, over the last year, traffic dips on Saturdays.
Comment: @Charlie an alternative that is often easier to both plot and read is to repeat part of the data and plot a bit more than a complete period, e.g. to plot over 30 hours from midnight to midnight and on to 6am, so the info from midnight to 6am appears twice - much as New Zealand or Alaska appear twice on some maps. I got this idea via Stata guru Nick Cox but I can't find the ref at present. [Tukey (1972)](http://www.edwardtufte.com/tufte/tukey) favoured two complete cycles.
Comment: An aside: Sometimes it is better to plot this kind of chart around a circle. For example, there might be an interesting pattern from 10pm to 2am, but, the way that your chart is cut at midnight, you might not notice this pattern. See here: http://stackoverflow.com/questions/2076370/most-underused-data-visualization/2083230#2083230
Comment: oh, great. now the sketch is there. :)
Comment: 'Periodic chart'?
Comment: @onestop: that's a decent alternative to "cyclic". If you turn the comment into an answer, I might give it to you.
Comment: An example of some of the circle charts in R, http://goo.gl/WoyVp . I agree with onestop's point as well though and is probably just as easy if not easier to read.
Answer: Nick Cox (Stata Journal 2006, p403) calls this sort of plot a 'cycle plot', but notes that:

Cycle plots have been discussed under other names in the literature, including cycle-subseries plot, month plot, seasonal-by-month plot, and seasonal subseries plot.

(followed by a load of refs to textbooks and papers)
Many of these are clearly specific to seasonality, i.e. periods of one year. I still like the suggestion of 'periodic plot/chart' that I made in a comment to the question, but it appears the questioner's original suggestion of 'cycle plot/chart' is in fact the more standard generic term.
Comment: Even though we wound up going with histogram in case we decide to do other kinds of similar charts that aren't time related, I think this is the most direct answer to the question that I asked. (We're actually using histogram/time, but maybe I'll change it to histogram/cycle....)
Answer: What you've illustrated is a time series column (or bar) graph. The two graphs are of differing time resolution or differing time aggregation.
There may be industry specific terms for these types of charts. In finance, for example, the open-high-low-close chart is a very common time series plot:

When the x axis is time, as in your example, it's often common to illustrate the points as a line graph, instead of bars/columns. The reason for this is to put the visual emphasis on the change from one period to the next.
You might also consider graphing period-over-period. For example a year-over-year would show how the numbers for a given month (typically, although could be month or day) compare to the numbers of the prior year for the same month.

But I realize your question was about naming, not all the other cool graphs you can do ;)
Comment: The point of the question seems to be that the x-axis summarizes a *periodic* or *cyclic* variable.
Comment: @whuber: yup! (thanks for the detailed answer, though, JD)
Comment: doh! thanks @whuber, I didn't realize that.
Answer: I'd suggest "diurnal" or "circadian" rhythm chart. For weekly, the latter would be "circaseptan", "circamensual" for "monthly", and "circannual" for "yearly".
Comment: those are all cool, but I was looking for something for the whole class of charts. We went with histogram....
Answer: The type of chart you've drawn is known as a Histogram http://en.wikipedia.org/wiki/Histogram
Comment: Being picky: A histogram never has blank spaces between the bars. When it does it is called a bar chart
Comment: @os @Ralph A *histogram* represents probability (or frequency) by means of graphical *area,* whereas a "bar chart" (which is what we're looking at here) uses *length*.  Of course histograms can have blank spaces between bars, when there's no probability or frequency there!
Comment: I take back my earlier comment. Given what I now realize from the discussion, this could be a histogram showing frequency by time or day buckets.
Comment: as I said on Owe's answer, I think technically, this is correct, but a name that indicates the relationship to time would be nice.
Comment: A histogram displays the distribution of a continuous variable.  A bar chart displays the distribution of a discrete variable.
Comment: @whuber - I'm not clear. Are we being picky because the OP's diagram was drawn with no marked frequency on the y-axis? My point was that if you do a Google search, you will see many definitions of "Histogram" which adamantly insist that the bars never touch. In practice, it really does not make a difference, but most published histograms will show the bars adjacent. – Ralph Winters 0 secs ago edit
Comment: @Ralph I wouldn't waste time being picky :-).  The difference between a bar chart and a histogram is fundamental, but it's not surprising that the Web is full of confusion on this point because superficially the two look similar.  Please refer to a reputable textbook, such as the Freedman, Pisani, & Purves *Statistics* (any edition).
Answer: Short, simple, descriptive: time series plot.
Edit: In light of the discussion, I'd vote for histogram as well. At least, thats the generic name for this kind of chart, where the hours of the day are a natural division of stacks.
Comment: to me, "time series" implies either a cycle, or linear time. I'm interested in something specific to cyclic data.
Comment: Seems I misunderstood your question - so the data is aggregated over the hours of a day, or or the days of the week for a number of days or weeks? In that case it is a kind of histogram.
Comment: hmm... I think you're correct (looking at the wiki entry on histogram), but ideally something specific to time would be better.
Answer: Your charts are a diurnal hourly-average bar chart, and a one-week daily-average bar chart, respectively.


No new lines in source code with Html helpers in MVC3 :-(

Question: I am using helpers like the following:
            @Html.TextBoxFor(m => m.Login.UserName, new { @class = "adm", size = 30 })
            @Html.ValidationMessageFor(m => m.Login.UserName)

            @Html.LabelFor(m => m.Login.Password, new { @class = "adm" })
            @Html.PasswordFor(m => m.Login.Password, new { @class = "adm", size = 30 })
            @Html.ValidationMessageFor(m => m.Login.Password)

When I look at the source code it appears in one very long line with no line breaks. Is
there any way I can use the helpers and have the source code formatted a bit better? It
is just so difficult to read when in one 300 column line?
thanks
Comment: Remember that you can always add a  at the end of each line.
Answer: I wouldn't bother about the HTML source. That's for browsers to read, not humans. But if you wanted proper formatting you could wrap them in the special <text> node:
<text>
    @Html.LabelFor(m => m.Login.UserName, new { @class = "adm" })
    @Html.TextBoxFor(m => m.Login.UserName, new { @class = "adm", size = 30 })
    @Html.ValidationMessageFor(m => m.Login.UserName)
</text>

<text>
    @Html.LabelFor(m => m.Login.Password, new { @class = "adm" })
    @Html.PasswordFor(m => m.Login.Password, new { @class = "adm", size = 30 })
    @Html.ValidationMessageFor(m => m.Login.Password)
</text>

The <text> node will not be rendered in the output. Another possibility is to directly use a
 or a  because from what I can see you are applying this adm class manually to the label and the input whereas if you wrapped them in another node you could apply the class directly to this node and then define the adm rule to apply to input fields inside this wrapper node.
Comment: True. Besides...if you look at the code in a DOM inspector like the developer toolbar in a browser it organizes everything hierarchically and it becomes pretty easy to manage.


If $D(x)=2x-\sigma(x)$, then if $n>1$ is deficient which is bigger, $D(n)$ or $D(n^2)$?

Question: (In what follows, we let $\sigma(x)$ denote the sum of the divisors of $x \in \mathbb{N}$.  $I(x)=\sigma(x)/x$ is the abundancy index of $x$, while $D(x)=2x-\sigma(x)$ is the deficiency of $x$.)
From this MSE question, I have the equation
$$D(xy) - D(x)D(y) = 2xy - \sigma(xy) - (2x - \sigma(x))(2y - \sigma(y))$$
$$=2xy - \sigma(xy) - 4xy + 2y\sigma(x) + 2x\sigma(y) - \sigma(x)\sigma(y)$$
$$=-2xy - 2\sigma(x)\sigma(y) + 2y\sigma(x) + 2x\sigma(y) + (\sigma(x)\sigma(y) - \sigma(xy))$$
$$=2(x - \sigma(x))(\sigma(y) - y) + (\sigma(x)\sigma(y) - \sigma(xy)).$$
Note that, in general we have
$$2(x - \sigma(x))(\sigma(y) - y) \leq 0$$
and
$$\sigma(x)\sigma(y) - \sigma(xy) \geq 0.$$
Thus, we obtain:

Proposition: If $x$ and $y$ are relatively prime (i.e., $\gcd(x, y) = 1$), then it follows that $D(xy) \leq D(x)D(y)$.

Note that we cannot apply the preceding result to our present problem:
PROBLEM STATEMENT

If $D(x)=2x-\sigma(x)$, then if $n>1$ is deficient which is bigger, $D(n)$ or $D(n^2)$?

Nonetheless, note that we have the following partial result:
MY ATTEMPT
Since $n>1$, we obtain
$$\sqrt{I(n^2)}<I(n)<I(n^2),$$
and
$$I(n)=2-\frac{D(n)}{n}$$
$$I(n^2)=2-\frac{D(n^2)}{n^2}.$$
It follows that $D(n^2)<nD(n)$, and
$$\sqrt{2-\frac{D(n^2)}{n^2}}<2-\frac{D(n)}{n}<2-\frac{D(n^2)}{n^2}.$$
Consequently,
$$2-\frac{D(n)}{n}<2-\frac{D(n^2)}{n^2}<\bigg(2-\frac{D(n)}{n}\bigg)^2.$$
Since $n>1$ is deficient, then
$$1<2-\frac{D(n)}{n}<\bigg(2-\frac{D(n)}{n}\bigg)^2$$
so that
$$0<\bigg(2-\frac{D(n)}{n}\bigg)\bigg(1-\frac{D(n)}{n}\bigg)$$
whence it follows that
$$0<1-\frac{D(n)}{n}$$
which implies that
$$D(n)<n.$$
Consequently,
$$D(n^2)<nD(n)<n^2.$$
Alas, this is where I get stuck.
Comment: it look like the past few question are related and never answered, why not try MW instead of MSE ? (+1)
Answer: The result depends on $n$.
For example
$$D(3^k)=\frac{3^k+1}{2}<\frac{3^{2k}+1}{2}=D(3^{2k}),$$
$$D(2^k)=1=D(2^{2k}).$$
And for any prime $p\in(2^{k+1},2^{2k+1})$, we have
$$D(2^kp)=p+1-2^{k+1}>0>1+(p-2^{2k+1})(p+1)=D(2^{2k}p^2).$$
All three families give infinitely many instances.
Also, I'd like to note a fact that $D(494)=148>11=D(494^2)$, which is an instance of $D(n)>D(n^2)>0$. However, I have no idea whether there are other instances.
EDIT: More $n$ with the property $D(n)>D(n^2)>0$:
\begin{align}
&2\cdot13\cdot19\cdot44371\\
&2\cdot13\cdot19\cdot44381\\
&2\cdot13\cdot19\cdot44383\\
&2\cdot13\cdot19\cdot44371\cdot2406128687\\
&2\cdot13\cdot19\cdot44371\cdot2406128689\\
&2\cdot13\cdot19\cdot44371\cdot2406128687\cdot2466259112360839463\\
\end{align}
To get this list, I just make use the known instances of $D(n)>D(n^2)>0$ and multiply it with an appropriate prime $p$ such that $D(np)>D(n^2p^2)>0$. I believe we may obtain more instances by relax the constrains.


Connection header disapper when HTTP2

Question: In making a request to my website with curl and HTTP 1.1, I see my keep-alive connection header explicitly:
$ curl https://website.com/ -i

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 2
Connection: keep-alive

But with Chrome's developer tool and HTTP 2 the header is missing:
Content-Type: text/html; charset=utf-8
Content-Length: 2

In HTTP 2 is it normal that the connection header is not sent (and why)?
Answer: Yes, this is normal and specified by the HTTP/2 RFC.

Connection header disapper when HTTP2


Lateralus drum part

Question: I love Lateralus by Tool. But one part always confuses me. The sticking for the drum roll (with cymbals) before the 5/8 bit at 4:45.
Just to clarify, NOT the 5/8 part, but the big cresendo roll before it.
It feels like a paradiddle but I can't figure it out.
Help me, internet. You're my only hope.
Answer: The later instance looks like an ordinary single-stroke roll of six strokes with the first on the crash, or variations thereof.  You can see him playing it at 11:05-11:15 in this live video:

The earlier instance at 4:45 in the studio recording sounds like the same idea.  Without equalizing the recording or finding a clearer video, my rough guess would be six sixteenths opened with a crash, then three eighths opened with a crash or maybe those are just accents, then the same thing with two crashes, etc. You might have better accuracy if you slow the song down in Audacity.

Lateralus drum part


How do I add a skybox / 360 panorama picture to my Archilogic 3D model?

Question: I uploaded my floor plan and received my 3D model. Now I would like to add a 360 panorama picture of the exterior, so that I can see the view when I am walking in my 3D model with the "person view" perspective .
Answer: Unfortunately there is currently no special feature that would allow you to simply upload a 360° panoramic picture into the Archilogic editor to get a panoramic background view.
However, you can still create and upload your own skyboxes with a little work around, if you have a bit of experience with 3d modeling software like 3DS Max, Blender or Maya. You need to map your skybox texture spherically on to a big box or sphere object.
Make sure that the polygons of this box/sphere are facing to the inside as you won't be able to see anything otherwise (the Archilogic engine only renders forward facing surfaces, while back facing surfaces are not being rendered and are therefore transparent). If you've set up your skybox like this you can export it as an .obj file. You then can import the .obj file along with the .mtl file and the textures into Archilogic by dragging and dropping the files into the editor and use the imported object as skybox.
If you want to use the light map calculation capabilities of the Archilogic editor you have to make sure that the giant box is not interfering with the light baking process by either switching off the "bake" check box of the imported skybox object or by excluding the skybox material from being used during the light map baking process.
Due to the fact that the Archilogic editor automatically compresses and down scales all imported textures to 1024x1024 pixels it may makes sense to use several materials with different textures for the same skybox in order to increase the overall resolution of the textures instead of just using a single material with a single texture file.
I hope this helps.


How to show javascript notification during a uploading an image/File?

Question: I have a upload box which is used to upload image. I want to restrict the user to upload a particular sized image. Such as, user can't upload a image which is larger than the allowed width, height. If someone tries to select such, then i want to show him a message on client side using javascript before uploading the image.
So can you have some idea regarding this. I am using the following tools for my project

Codeigniter
Jquery

thanks in advance.
Comment: I guess if it cannot be done, its not a real question?
Answer: Its not 'exactly' what you wanted, but you can use PHP's getimagesize() function to get the dimensions after you have uploaded it. If it is too big, instead of copying it from the temp folder to the uploads folder, you can give him an error.
Searching through the StackOverflow archives, I can't seem to find a solution through Javascript.
Comment: thanks for your answer. i know this, but i need the size before uploading the file in server.
Answer: This could be with an ActiveX control or a signed Java Applet client-side, but running those require user permission.
Answer: You cannot access local files on the client side. To get the size of an image you will have to upload it one way or another. If you'd rather not reload the page, you might be able to upload it with AJAX behind the scenes, but that's the extent of it.
EDIT: For the latter, you can use something like this script. In the server side file, use $_FILES to get the file, then getimagesize() to get the size. If the size is valid, save the file and you're done with the upload. If not, echo an error message and it will be passed to the JavaScript in a callback, where you can prettify and display it.
Comment: thanks for your early response. Yea i know that we can't have the image size in client side before uploading the file. But exactly i want this. Otherwise i am ok with my task.
Answer: This isn't useful in a practical sense right now, but in the (hopefully not too distant) future you can use the HTML5 file api for something like this.
http://dev.w3.org/2006/webapi/FileAPI/
https://developer.mozilla.org/en/Using_files_from_web_applications
Answer: You can't notify them, but you can't deny bigger files on upload - thus saving bandwidth and being nicer to server:
<input type="hidden" name="MAX_FILE_SIZE" value="size-in-kb" />

than when in php going through upload, it will notice you that file wasn't even uploaded, because too big. More here:
http://forums.devshed.com/php-development-5/max-upload-size-how-to-give-notice-to-user-500259.html
Comment: No browsers implement this field. PHP will discard the file before passing control to your handler, but the browser will still fully upload it.


Set fixed page height when using MVC3

Question: I'm kind of new to MVC, and I have an issue defining fixed page height.
I will first say that I use MVC3. I have several pages, and a login page. All should have fixed height. It doesn't have to be size in pixels, it also can be in percents, but it shouldn't be affected by the content of the page.
Currently I added the "he
<code>body {
background-color: White;
font-size: .85em;
font-family: "Trebuchet MS", Verdana, Helvetica, Sans-Serif;
margin: 0;
padding: 0;
color: Black;
height: 100%;
}
</code>
and:
<code>.page {
width: 90%;
margin-left: auto;
margin-right: auto;
color: White;
height: 100%;
}
</code>
I also tried "1000px" instead of "100%", it also didn't work...
my pages' height is still defined automatically according to page's content....
EDIT:
My page code:

What am I missing?
Thanks
Answer: Try setting both the html and the body element to 100%, ie
body,html{height:100%;}
Then I guess you'll also have to cope with overflow on the elements you want to be of fixed height, so something like
.page
{overflow:hidden;}
Comment: You're going to have to post some more details then. It could be something like malformed HTML. Try putting it on jsFiddle.
Comment: Where is the element with the class 'page'? Make things easy for an old man, I beg you.
Comment: it's MVC... this page is rendered under the _Layout, it's basically something like that:

            @RenderBody() --> Here is my printscreened page

Comment: can you set this up on the internet somewhere? Or post the entire markup you get when you view page source, plus your stylesheet. Alternatively, if you're feeling frisky, open it up in Internet Explorer and press F12 to get the developer tools. Then select the 'page' class div and examine its properties to see why it's not getting what you think it should be getting. Or do the equivalent thing in Firefox, or your browser of choice.

Set fixed page height when using MVC3


In Powershell, how do I list CredSSP DelegateComputers as distinct objects?

Question: As is well known, to avoid the Powershell Second Hop problem when Powershell Remoting, one needs to set the CredSSP Client and Server settings.
e.g.
# On the client, a.k.a the First Hop Server
Enable-WSManCredSSP -Role "Client" -DelegateComputer "secondhop.example.com"

# On the server, a.k.a the Second Hop Server
Enable-WSManCredSSP -Role "Server"

And now I can PSRemote to the "client" server and from there access resources on the "server" server. All good and well.
However, the environment is largeish, and I want to know the "Client DelegateComputers" in effect on a good number of machines. How do I achieve this?
I know I can (Get-WSManCredSSP)[0] to get a list of Client DelegateComputers. But this is presented as an ugly, unwieldy string which I would very much like to not parse, given that this is Powershell and that I am in love with the object oriented approach.
I would like to think that I have been all over wsman:/ both using Get-Item and Get-WSManInstance, as well as googled through what reasonably must be all of Google.
It seems unthinkable that this is so elusive, I must have missed something embarrassingly simple.
So ServerFault, how do I Powershell natively or using a direct .NET call get a nicely presented array or similar  of CredSSP Client DelegateComputers on a given host?
I can run any version of .NET Framework and Powershell available on Win2008r2 and Win2012r2.
Comment: Some alternatives to using CredSSP are listed [here](https://blogs.technet.microsoft.com/ashleymcglone/2016/08/30/powershell-remoting-kerberos-double-hop-solved-securely/)
Comment: Very nice! If you turn it into an answer with the link and citation of the solution text I will upvote and mark it as answered.
Answer: So as it turns out, Google actually had one more page and this is where the answer was hiding.
The Client DelegateComputer list is stored in the Windows registry at:
HKLM:\software\policies\microsoft\windows\CredentialsDelegation\AllowFreshCredentials

Reading this key is not beautiful, but it's better than the alternative.
So Victor Vogelpoel, all worldly glory to him, came up with the following oneliner:
((Get-ItemProperty HKLM:\software\policies\microsoft\windows\CredentialsDelegation\AllowFreshCredentials).psobject.Properties | where { $_.Name -match "\d+"  } | select -expand value | foreach { if ($_ -like "wsman/*") { $_.substring(6) } else { $_ } })


Where is the php_error.log file in Acquia Dev Desktop?

Question: I'm having problem with a site installed with Acquia Dev Desktop, but I can't find the php_error.log file to see the errors. There is nothing inside the DevDesktop folder and I can't see anything in the Software Preference.
Where is the php_error.log file in Acquia Dev Desktop?
Comment: Have you tried looking through the error log provided by Drupal UI?
Comment: @NoSssweat the site shows the error message that only says that there is a problem in all the pages
Comment: Did you add this line `$config['system.logging']['error_level'] = 'verbose';` to your settings.php file?
Comment: If you're using XAMPP take a look at [Where does PHP's error log reside in XAMPP?](https://stackoverflow.com/questions/3719549/where-does-phps-error-log-reside-in-xampp)
Comment: @NoSssweat I come from found the answer, thanks for your time ;-)
Answer: Just checked in my installation of DevDesktop and found that my PHP logs are located in /Applications/DevDesktop/apache/logs/error_log.
Although it says Apache logs, PHP errors get logged there as well.
You can find the log locations via 'Preferences' => 'Logs'. DevDesktop version 2 (Apr 13, 2017).
Answer: I found the solution, you need to search the php.ini file inside the php version folder that you are using. Open the file and search for this line:
;error_log = php_errors.log

Delete the ; to activate the error logging, then you will have:
error_log = php_errors.log

Save the file and restart your server and the file will be created in your site root folder.


Which single player in the AFL has played for the most clubs?

Question: Which single player in AFL (Australian Football League) history has played for the most clubs/teams?
Answer: Three players have played for five different clubs in the history of the V/AFL:
Les Abbott played for Collingwood, Carlton, Richmond, Melbourne, and Sydney between 1904 and 1912.
Les Hughson played for Collingwood, Hawthorn, Carlton, St Kilda, and Fitzroy between 1927 and 1937.
Dale Kickett played for Fitzroy, West Coast, St Kilda, Essendon, and Fremantle between 1990 and 2002.
If you consider the Brisbane Bears and Brisbane Lions as distinct entities, then you can add Adrian Fletcher, who played for Geelong, St Kilda, Brisbane Bears, Brisbane Lions, and Fremantle.


What is best coding practices for providing an upgrade path to a new module version?

Question: I'm getting ready to build a new version of a module of mine. The new version can have an upgrade path from the current version to the new version that will be released, but as you know, new major verions come with database restructuring, entity refactoring, and what not.
Is there a standard practice in the way the upgrade path is provided? For instance, should I build code in the install hook of the new version, and update hook, or some stand alone script?
Suggestions welcomed.
Answer: Add the install information required for the new module version in the hook_install and hook_schema.
Users upgrading presumably won't be re-installing the module, so you'll need to use hook_update_N for those users. Check if the upgrade path is required for that installation and proceed with the update as needed.


Collation conflict between different database collation in SQL Server 2008 R2

Question: I have two different servers:
Server 1: It has database DB1 with the collation Latin1_General_CI_AS
Server 2: has DB2 with the collation SQL_Latin1_General_CP1_CI_AS
I come up with the scenario where i need to backup and restore DB1 from server 1 to server 2.
When I run a simple select statement through the linked server, I end up with an error by saying Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation.
Answer: Use : COLLATE DATABASE_DEFAULT on both sides of condition for character columns. Example below.
    select * from es
    inner join es e2
    on es.year COLLATE DATABASE_DEFAULT = e2.year COLLATE DATABASE_DEFAULT

Answer: I think a simple workaround is to restore DB1 on server1 to a new database "DB2"; then you can try to change the collation of DB2 to SQL_Latin1_General_CP1_CI_AS, and finally try to restore DB2 to server2.
I also found another answer here which might be helpful.
Comment: Creating DB2 is important to keep the origin DB unchanged to avoid any DB issues.


Discord.py | How do I get a User Tag from an ID?

Question: I am programming an entertainment bot with discord.py, and I want to code a function that allows you to look at other users' in game money and stuff with replit databases. Since making data with a user tag is inefficient since people change their usernames and tags all the time, I am using IDs. I am trying to find a way to get a user tag (eg. Dude#1234) from a user number id (eg. 871954599731396648). I couldn't find a solution. I already know how to use ctx.message.author.id but I can't find a way to make that work with every discord user.
Answer: To get the tag you can use the following method
user = await bot.fetch_user(ID) # ID must be an int and this could be could be client for you, be careful as this pings the API and can be abused if not correctly limited.

# user.discriminator will return their tag.

You can check all attributes that user can have here
Answer: To get the tag, you first have to get the user object from the id using discord.utils.get:
user_id = #insert the id of the user which you want the tag of
user = await discord.utils.get(client.get_all_members(), id =user_id)#might by something like bot.get_all_members for you
tag = user.name